path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
web-ui/src/common/link_button/link_button.js
pixelated-project/pixelated-user-agent
/* * Copyright (c) 2017 ThoughtWorks, Inc. * * Pixelated is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Pixelated 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 Pixelated. If not, see <http://www.gnu.org/licenses/>. */ import React from 'react'; import FlatButton from 'material-ui/FlatButton'; import './link_button.scss'; const labelStyle = { textTransform: 'none', color: 'inherit', fontSize: 'inherit', width: '100%', padding: '0' }; const linkButtonStyle = { color: 'inherit', borderRadius: '0', minHeight: '36px', height: 'auto', lineHeight: '20px', padding: '12px 0' }; const LinkButton = ({ buttonText, href }) => ( <div className='link-button'> <FlatButton href={href} containerElement='a' label={buttonText} labelStyle={labelStyle} hoverColor={'#ff9c00'} style={linkButtonStyle} /> </div> ); LinkButton.propTypes = { buttonText: React.PropTypes.string.isRequired, href: React.PropTypes.string.isRequired }; export default LinkButton;
client/src/app/components/navigation/components/Navigation.js
zraees/sms-project
/** * Created by griga on 11/24/15. */ import React from 'react' import {bindActionCreators} from 'redux' import {connect} from 'react-redux'; import NavMenu from './NavMenu' import MinifyMenu from './MinifyMenu' import LoginInfo from '../../user/components/LoginInfo' import AsideChat from '../../chat/components/AsideChat' import * as LayoutActions from '../../layout/LayoutActions' class Navigation extends React.Component { render() { const {lang} = this.props; // console.log(lang); return ( <aside id="left-panel"> <LoginInfo /> <nav> <NavMenu lang={lang} openedSign={'<i class="fa fa-minus-square-o"></i>'} closedSign={'<i class="fa fa-plus-square-o"></i>'} /> </nav> <MinifyMenu /> </aside> ) } } const mapStateToProps = (state, ownProps) => (state.layout); function mapDispatchToProps(dispatch) { return bindActionCreators(LayoutActions, dispatch) } export default connect(mapStateToProps, mapDispatchToProps)(Navigation);
src/svg-icons/editor/insert-emoticon.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorInsertEmoticon = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/> </SvgIcon> ); EditorInsertEmoticon = pure(EditorInsertEmoticon); EditorInsertEmoticon.displayName = 'EditorInsertEmoticon'; EditorInsertEmoticon.muiName = 'SvgIcon'; export default EditorInsertEmoticon;
src/views/Pages/Login/Login.js
Cruis-R/GestionOutil
import React, { Component } from 'react'; const urlServer = "http://vps92599.ovh.net:8082/api/session"; class Login extends Component { constructor(props){ super(props); this.state = { isLoginSuccess: true }; this.loginServerTraccar = this.loginServerTraccar.bind(this); this.restoreSession = this.restoreSession.bind(this); } componentDidMount(){ this.restoreSession(); } restoreSession(){ fetch(urlServer,{ credentials: 'include'}) .then((response)=>response.json()) .then((res)=>{ console.log(res); this.setState({ isLoginSuccess:true }); let accessString = res["email"]; window.UserEmail = accessString; window.location.href = '#/gestions/welcome?'+accessString; }) .catch((err)=>{ console.log(err); }) } loginServerTraccar(){ const queryMethod = "POST"; let email = document.getElementById('username').value; let password = document.getElementById('password').value; let formData="email="+email+"&password="+password; fetch(urlServer,{ credentials: 'include', method: queryMethod, body: formData, headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }) }) .then((response)=>response.json()) .then((res)=>{ console.log(res); this.setState({ isLoginSuccess:true }); let accessString = res["email"]; window.UserEmail = accessString; window.location.href = '#/gestions/welcome?'+accessString; }) .catch((err)=>{ this.setState({ isLoginSuccess:false }); console.log(err); }) } render() { return ( <div className="app flex-row align-items-center"> <div className="container"> <div className="row justify-content-center"> <div className="col-md-8"> <div className="card-group mb-0"> <div className="card p-4"> <div id="login-form" className="card-block"> <h1>Login</h1> <p className="text-muted">Sign In to your account</p> <div className="input-group mb-3"> <span className="input-group-addon"><i className="fa fa-user" style={{width : 30 + "px"}}></i></span> <input type="text" id="username" className="form-control" placeholder="Username"/> </div> <div className="input-group mb-4"> <span className="input-group-addon"><i className="fa fa-lock" style={{width : 30 + "px"}}></i></span> <input type="password" id="password" className="form-control" placeholder="Password"/> </div> <div className="row"> <div className="col-6"> <button type="button" className="btn btn-primary px-4" onClick={this.loginServerTraccar}>Login</button> </div> <div className="col-6 text-right"> <button type="button" className="btn btn-link px-0">Forgot password?</button> </div> </div> {!this.state.isLoginSuccess?<span className="help-block text-danger">Account Non Trouvé ou Mot de Passe Incorrecte</span>:null} </div> </div> <div className="card card-inverse card-primary py-5 d-md-down-none" style={{ width: 44 + '%' }}> <div className="card-block text-center"> <div> <h2>Sign up</h2> <p>CRUIS'R distribue et loue de nombreuses marques de véhicules électriques.</p> <button type="button" className="btn btn-primary active mt-3">Register Now!</button> </div> </div> </div> </div> </div> </div> </div> </div> ); } } export default Login;
App/Components/AccountInfo/index.spec.js
okmttdhr/YoutuVote
// @flow import test from 'ava'; import React from 'react'; import {Text} from 'react-native'; import { shallow } from 'enzyme'; import { merge } from 'lodash'; import { defaultUserMock, userActionsMock } from '../../../Tests/mock/'; import { AccountInfo } from './index'; import {DisplayName} from './DisplayName/'; test('should display name and email', (t) => { const verifiedUserMock = merge({}, defaultUserMock, {item: {emailVerified: true}}); const wrapper = shallow( <AccountInfo user={verifiedUserMock} userActions={userActionsMock} />, ); t.is(wrapper.containsMatchingElement( <DisplayName user={verifiedUserMock} updateProfile={userActionsMock.userUpdateProfile} />, ), true); t.is(wrapper.containsMatchingElement(<Text>MOCK_EMAIL</Text>), true); });
src/container/editProfile.js
thipokKub/Clique-WebFront-Personnal
import React, { Component } from 'react'; import autoBind from '../hoc/autoBind'; import Circle from '../components/circle'; import axios from 'axios'; import { getCookie } from '../actions/common'; class editProfile extends Component { constructor(props) { super(props); let config = { 'headers': { 'Authorization': ('JWT ' + getCookie('fb_sever_token')) } } // _id, firstName, lastName, picture, picture_200px, email, gender, shirt_size, phone, regId, facebookId, twitterUsername, lineId, disease, birth_day, allergy, // notification, firstNameTH, lastNameTH, major, emer_phone, admin_events, admin_channels, join_events, interest_events, subscribe_channels, already_joined_events, // tag_like, dorm_bed, dorm_building, dorm_room // // nick_name, picture, picture_200px, birth_da, twitterUsername, phone, shirt_size, allergy, disease, emer_phone, tag_like, dorm_room, dorm_building, dorm_bed, // twitterUsername, lineId, notification let _this = this; this.state = { } axios.get('http://128.199.208.0:1111/user', config).then((data) => { console.log("get!!!"); console.log(JSON.stringify(data.data.firstName)); _this.state = { 'firstName': data.data.firstName, 'lastName': data.data.lastName, 'picture': data.data.picture_200px, 'regId': data.data.regId, 'birth_day': data.data.birth_day, 'nick_name': data.data.nick_name, 'lineId': data.data.lineId, 'email': data.data.email, 'phone': data.data.phone, 'shirt_size': data.data.shirt_size, 'disease': data.data.disease, 'allergy': data.data.allergy, 'new_regId': data.data.regId, 'new_birth_day': data.data.birth_day, 'new_nick_name': data.data.nick_name, 'new_lineId': data.data.lineId, 'new_email': data.data.email, 'new_phone': data.data.phone, 'new_shirt_size': data.data.shirt_size, 'new_disease': data.data.disease, 'new_allergy': data.data.allergy, } }, (error) => { console.log("get user error"); }); this.onKeyPressed = this.onKeyPressed.bind(this); } componentWillReceiveProps(nextProps) { this.setState({updated: nextProps.updated}); } componentDidMount() { let config = { 'headers': { 'Authorization': ('JWT ' + getCookie('fb_sever_token')) } } let _this = this; axios.get('http://128.199.208.0:1111/user', config).then((data) => { console.log("get!!!"); console.log(JSON.stringify(data.data.firstName)); _this.state = { 'firstName': data.data.firstName, 'lastName': data.data.lastName, 'picture': data.data.picture_200px, 'regId': data.data.regId, 'birth_day': data.data.birth_day, 'nick_name': data.data.nick_name, 'lineId': data.data.lineId, 'email': data.data.email, 'phone': data.data.phone, 'shirt_size': data.data.shirt_size, 'disease': data.data.disease, 'allergy': data.data.allergy, 'new_regId': data.data.regId, 'new_birth_day': data.data.birth_day, 'new_nick_name': data.data.nickname, 'new_lineId': data.data.lineId, 'new_email': data.data.email, 'new_phone': data.data.phone, 'new_shirt_size': data.data.shirt_size, 'new_disease': data.data.disease, 'new_allergy': data.data.allergy, } }, (error) => { console.log("get user error"); }); } onKeyPressed() { const newState = { ...this.state, 'new_regId': this.refs.id.value, 'new_birth_day': this.refs.birth.value, 'new_nick_name': this.refs.nickname.value, 'new_lineId': this.refs.line.value, 'new_email': this.refs.email.value, 'new_phone': this.refs.mobile.value, 'new_shirt_size': this.refs.size.value, 'new_disease': this.refs.med.value, 'new_allergy': this.refs.food.value, }; this.setState(newState); } save() { const newState = { ...this.state, 'regId': this.refs.id.value, 'birth_day': this.refs.birth.value, 'nick_name': this.refs.nickname.value, 'lineId': this.refs.line.value, 'email': this.refs.email.value, 'phone': this.refs.mobile.value, 'shirt_size': this.refs.size.value, 'disease': this.refs.med.value, 'allergy': this.refs.food.value, }; this.setState(newState); let config = { 'headers': { 'Authorization': ('JWT ' + getCookie('fb_sever_token')) } } let responseBody = { 'regId': this.refs.id.value, 'birth_day': this.refs.birth.value, 'nick_name': this.refs.nickname.value, 'lineId': this.refs.line.value, 'email': this.refs.email.value, 'phone': this.refs.mobile.value, 'shirt_size': this.refs.size.value, 'disease': this.refs.med.value, 'allergy': this.refs.food.value, } axios.put('http://128.199.208.0:1111/user', responseBody, config).then((response) => { console.log("saved!!!"); return true; }, (error) => { console.log("save error"); return false; }) this.props.toggle_pop_item(); } cancel() { const newState = { ...this.state, 'new_regId': this.state.regId, 'new_birth_day': this.state.birth_day, 'new_nick_name': this.state.nick_name, 'new_lineId': this.state.lineId, 'new_email': this.state.email, 'new_phone': this.state.phone, 'new_shirt_size': this.state.shirt_size, 'new_disease': this.state.disease, 'new_allergy': this.state.allergy, }; this.setState(newState); this.props.toggle_pop_item(); } onExit() { this.props.toggle_pop_item(); } render() { if(true) {return ( <div className="modal-container"> <div className="edit-profile basic-card-no-glow modal-main mar-h-auto mar-v-40"> <section className="edit-pro-head"> <button role="exit" onClick={this.cancel.bind(this)}> <img src="../../resource/images/X.svg" /> </button> <img src={this.state.picture} alt="profile-pic" /> <div className="profile-head"> <h1 alt="profile-name">{this.state.firstName+" "+this.state.lastName}</h1> <div alt="faculty-icon" /> <p>Faculty of Engineering</p> </div> </section> <p className="hr"></p> <div className="flex"> <section className="edit-pro-left"> <img alt="id"/> <input ref="id" type="text" placeholder="Student ID" value={this.state.new_regId} onChange={this.onKeyPressed}/> <img alt="birth"/> <input ref="birth" type="text" placeholder="Birthdate" value={this.state.new_birth_day} onChange={this.onKeyPressed}/> <img alt="nickname"/> <input ref="nickname" type="text" placeholder="Nickname" value={this.state.new_nick_name} onChange={this.onKeyPressed}/> <img alt="line"/> <input ref="line" type="text" placeholder="Line ID" value={this.state.new_lineId} onChange={this.onKeyPressed}/> <img alt="email"/> <input ref="email" type="text" placeholder="Email" value={this.state.new_email} onChange={this.onKeyPressed}/> <img alt="mobile"/> <input ref="mobile" type="text" placeholder="Mobile Number" value={this.state.new_phone} onChange={this.onKeyPressed}/> <img alt="size"/> <input ref="size" type="text" placeholder="T-Shirt Size" value={this.state.new_shirt_size} onChange={this.onKeyPressed}/> <img alt="med"/> <input ref="med" type="text" placeholder="Medical Problem" value={this.state.new_disease} onChange={this.onKeyPressed}/> <img alt="food"/> <input ref="food" type="text" placeholder="Food Allergy" value={this.state.new_allergy} onChange={this.onKeyPressed}/> </section> <p className="sec-line"></p> <section className="edit-pro-right"> <div className="fb-link"> <img alt="fb-link"/> <p>{this.state.firstName+" "+this.state.lastName}</p> <button className="unlink">Unlink</button> </div> <div className="cu-link"> <img alt="cu-link"/> <p>{this.state.regId}</p> <button className="unlink">Unlink</button> </div> <div className="my-tag"> <p>YOUR INTERESTED TAG</p> <section> <Circle parent="tag" /> <Circle parent="tag" /> <Circle parent="tag" /> <Circle parent="tag" /> <Circle parent="tag" /> <Circle parent="tag" /> <Circle parent="tag" /> </section> <div><button>EDIT</button></div> </div> <div className="btn-plane"> <button className="cancel" onClick={this.cancel.bind(this)}>CANCEL</button> <button className="save" onClick={this.save.bind(this)}>SAVE</button> </div> </section> </div> </div> <div className="background-overlay" /> </div> );} } } export default autoBind(editProfile);
client/modules/Post/__tests__/components/PostCreateWidget.spec.js
pucksME/BetterBackPacking
import React from 'react'; import test from 'ava'; import sinon from 'sinon'; import { FormattedMessage } from 'react-intl'; import { PostCreateWidget } from '../../components/PostCreateWidget/PostCreateWidget'; import { mountWithIntl, shallowWithIntl } from '../../../../util/react-intl-test-helper'; const props = { addPost: () => {}, showAddPost: true, }; test('renders properly', t => { const wrapper = shallowWithIntl( <PostCreateWidget {...props} /> ); t.truthy(wrapper.hasClass('form')); t.truthy(wrapper.hasClass('appear')); t.truthy(wrapper.find('h2').first().containsMatchingElement(<FormattedMessage id="createNewPost" />)); t.is(wrapper.find('input').length, 2); t.is(wrapper.find('textarea').length, 1); }); test('hide when showAddPost is false', t => { const wrapper = mountWithIntl( <PostCreateWidget {...props} /> ); wrapper.setProps({ showAddPost: false }); t.falsy(wrapper.hasClass('appear')); }); test('has correct props', t => { const wrapper = mountWithIntl( <PostCreateWidget {...props} /> ); t.is(wrapper.prop('addPost'), props.addPost); t.is(wrapper.prop('showAddPost'), props.showAddPost); }); test('calls addPost', t => { const addPost = sinon.spy(); const wrapper = mountWithIntl( <PostCreateWidget addPost={addPost} showAddPost /> ); wrapper.ref('name').get(0).value = 'David'; wrapper.ref('title').get(0).value = 'Some Title'; wrapper.ref('content').get(0).value = 'Bla Bla Bla'; wrapper.find('a').first().simulate('click'); t.truthy(addPost.calledOnce); t.truthy(addPost.calledWith('David', 'Some Title', 'Bla Bla Bla')); }); test('empty form doesn\'t call addPost', t => { const addPost = sinon.spy(); const wrapper = mountWithIntl( <PostCreateWidget addPost={addPost} showAddPost /> ); wrapper.find('a').first().simulate('click'); t.falsy(addPost.called); });
src/svg-icons/action/system-update-alt.js
barakmitz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSystemUpdateAlt = (props) => ( <SvgIcon {...props}> <path d="M12 16.5l4-4h-3v-9h-2v9H8l4 4zm9-13h-6v1.99h6v14.03H3V5.49h6V3.5H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2v-14c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ActionSystemUpdateAlt = pure(ActionSystemUpdateAlt); ActionSystemUpdateAlt.displayName = 'ActionSystemUpdateAlt'; ActionSystemUpdateAlt.muiName = 'SvgIcon'; export default ActionSystemUpdateAlt;
files/rxjs/2.3.7/rx.all.js
2947721120/adamant-waffle
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = 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; }; // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } 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; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var s = state; var id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return Observable; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); return function () { if (promise && promise.abort) { promise.abort(); } } }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new Error('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next = it.next(); if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throw(new Error('Error')); * var res = Rx.Observable.throw(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.do(observer); * var res = observable.do(onNext); * var res = observable.do(onNext, onError); * var res = observable.do(onNext, onError, onCompleted); * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (!onError) { observer.onError(err); } else { try { onError(err); } catch (e) { observer.onError(e); } observer.onError(err); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * * @example * var res = source.takeLast(5); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } return typeof selector === 'function' ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { observer.onError(e); return; } } hashSet.push(key) && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [comparer] Used to determine whether the objects are equal. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, comparer) { return this.groupByUntil(keySelector, elementSelector, observableNever, comparer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) { var source = this; elementSelector || (elementSelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { function handleError(e) { return function (item) { item.onError(e); }; } var map = new Dictionary(0, comparer), groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var key; try { key = keySelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } var fireNewMapEntry = false, writer = map.tryGetValue(key); if (!writer) { writer = new Subject(); map.set(key, writer); fireNewMapEntry = true; } if (fireNewMapEntry) { var group = new GroupedObservable(key, writer, refCountDisposable), durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(group); var md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { map.remove(key) && writer.onCompleted(); groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe( noop, function (exn) { map.getValues().forEach(handleError(exn)); observer.onError(exn); }, expire) ); } var element; try { element = elementSelector(x); } catch (e) { map.getValues().forEach(handleError(e)); observer.onError(e); return; } writer.onNext(element); }, function (ex) { map.getValues().forEach(handleError(ex)); observer.onError(ex); }, function () { map.getValues().forEach(function (item) { item.onCompleted(); }); observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (resultSelector) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }, thisArg); } return typeof selector === 'function' ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }).mergeAll(); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (observer) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { observer.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { observer.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, observer.onError.bind(observer), function () { observer.onNext(list); observer.onCompleted(); }); }); } function firstOnly(x) { if (x.length === 0) { throw new Error(sequenceContainsNoElements); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.aggregate(function (acc, x) { return acc + x; }); * 2 - res = source.aggregate(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.aggregate = function () { var seed, hasSeed, accumulator; if (arguments.length === 2) { seed = arguments[0]; hasSeed = true; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.reduce(function (acc, x) { return acc + x; }); * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0); * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var seed, hasSeed; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @example * var result = source.any(); * var result = source.any(function (x) { return x > 3; }); * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = observableProto.any = function (predicate, thisArg) { var source = this; return predicate ? source.where(predicate, thisArg).any() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }); }; /** * Determines whether an observable sequence is empty. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().map(not); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * * 1 - res = source.all(function (value) { return value.length > 3; }); * @memberOf Observable# * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = observableProto.all = function (predicate, thisArg) { return this.where(function (v) { return !predicate(v); }, thisArg).any().select(function (b) { return !b; }); }; /** * Determines whether an observable sequence contains a specified element with an optional equality comparer. * @example * 1 - res = source.contains(42); * 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; }); * @param value The value to locate in the source sequence. * @param {Function} [comparer] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value. */ observableProto.contains = function (value, comparer) { comparer || (comparer = defaultComparer); return this.where(function (v) { return comparer(v, value); }).any(); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).count() : this.aggregate(0, function (count) { return count + 1; }); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @example * var res = source.sum(); * var res = source.sum(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).sum() : this.aggregate(0, function (prev, curr) { return prev + curr; }); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @example * var res = res = source.average(); * var res = res = source.average(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).average() : this.scan({ sum: 0, count: 0 }, function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }).finalValue().select(function (s) { if (s.count === 0) { throw new Error('The input sequence was empty'); } return s.sum / s.count; }); }; function sequenceEqualArray(first, second, comparer) { return new AnonymousObservable(function (observer) { var count = 0, len = second.length; return first.subscribe(function (value) { var equal = false; try { if (count < len) { equal = comparer(value, second[count++]); } } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } }, observer.onError.bind(observer), function () { observer.onNext(count === len); observer.onCompleted(); }); }); } /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); if (Array.isArray(second)) { return sequenceEqualArray(first, second, comparer); } return new AnonymousObservable(function (observer) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (doner) { observer.onNext(false); observer.onCompleted(); } else { ql.push(x); } }, observer.onError.bind(observer), function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (doner) { observer.onNext(true); observer.onCompleted(); } } }); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal, v; if (ql.length > 0) { v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { observer.onError(exception); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (donel) { observer.onNext(false); observer.onCompleted(); } else { qr.push(x); } }, observer.onError.bind(observer), function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (donel) { observer.onNext(true); observer.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var i = index; return source.subscribe(function (x) { if (i === 0) { observer.onNext(x); observer.onCompleted(); } i--; }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(argumentOutOfRange)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { observer.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @example * var res = res = source.single(); * var res = res = source.single(function (x) { return x === 42; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate? this.where(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue) }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { observer.onNext(x); observer.onCompleted(); }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = res = source.firstOrDefault(); * var res = res = source.firstOrDefault(function (x) { return x > 3; }); * var res = source.firstOrDefault(function (x) { return x > 3; }, 0); * var res = source.firstOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @example * var res = source.last(); * var res = source.last(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = source.lastOrDefault(); * var res = source.lastOrDefault(function (x) { return x > 3; }); * var res = source.lastOrDefault(function (x) { return x > 3; }, 0); * var res = source.lastOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { return new AnonymousObservable(function (observer) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = predicate.call(thisArg, x, i, source); } catch(e) { observer.onError(e); return; } if (shouldRun) { observer.onNext(yieldIndex ? i : x); observer.onCompleted(); } else { i++; } }, observer.onError.bind(observer), function () { observer.onNext(yieldIndex ? -1 : undefined); observer.onCompleted(); }); }); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, context, scheduler) { return observableToAsync(func, context, scheduler)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * * @example * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); * * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, context, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }; }; /** * 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); }); }; }; 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(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.subject.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var n = 2, hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(n); function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, observer.onError.bind(observer), function () { isDone = true; observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer)) ); }); } var PausableBufferedObservable = (function (_super) { inherits(PausableBufferedObservable, _super); function subscribe(observer) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.subject.distinctUntilChanged(), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { // change in shouldFire if (results.shouldFire) { while (q.length > 0) { observer.onNext(q.shift()); } } } else { // new data if (results.shouldFire) { observer.onNext(results.data); } else { q.push(results.data); } } previousShouldFire = results.shouldFire; }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); this.subject.onNext(false); return subscription; } function PausableBufferedObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return !selector ? this.multicast(new Subject()) : this.multicast(function () { return new Subject(); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); * * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish(null).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return !selector ? this.multicast(new AsyncSubject()) : this.multicast(function () { return new AsyncSubject(); }, selector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); * * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue). refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return !selector ? this.multicast(new ReplaySubject(bufferSize, window, scheduler)) : this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, _super); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { _super.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (_super) { function RemovableDisposable (subject, observer) { this.subject = subject; this.observer = observer; }; RemovableDisposable.prototype.dispose = function () { this.observer.dispose(); if (!this.subject.isDisposed) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); } }; function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = new RemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, _super); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; _super.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /* @private */ _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { var observer; checkDisposed.call(this); if (!this.isStopped) { var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onNext(value); observer.ensureActive(); } } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; } }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, subject.subscribe.bind(subject)); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); var Dictionary = (function () { var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647], noSuchkey = "no such key", duplicatekey = "duplicate key"; function isPrime(candidate) { if (candidate & 1 === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash<<5)-hash)+character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return numberHashFn(obj.valueOf()); } if (obj instanceof RegExp) { return stringHashFn(obj.toString()); } if (typeof obj.valueOf === 'function') { // Hack check for valueOf var valueOf = obj.valueOf(); if (typeof valueOf === 'number') { return numberHashFn(valueOf); } if (typeof obj === 'string') { return stringHashFn(valueOf); } } if (obj.getHashCode) { return obj.getHashCode(); } var id = 17 * uniqueIdCounter++; obj.getHashCode = function () { return id; }; return id; }; }()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } function Dictionary(capacity, comparer) { if (capacity < 0) { throw new Error('out of range'); } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; } var dictionaryProto = Dictionary.prototype; dictionaryProto._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; dictionaryProto.add = function (key, value) { return this._insert(key, value, true); }; dictionaryProto._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3, num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; dictionaryProto._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; dictionaryProto.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647, index1 = num % this.buckets.length, index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; dictionaryProto.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; dictionaryProto._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; dictionaryProto.count = function () { return this.size - this.freeCount; }; dictionaryProto.tryGetValue = function (key) { var entry = this._findEntry(key); return entry >= 0 ? this.entries[entry].value : undefined; }; dictionaryProto.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; dictionaryProto.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; dictionaryProto.set = function (key, value) { this._insert(key, value, false); }; dictionaryProto.containskey = function (key) { return this._findEntry(key) >= 0; }; return Dictionary; }()); /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var leftDone = false, rightDone = false; var leftId = 0, rightId = 0; var leftMap = new Dictionary(), rightMap = new Dictionary(); group.add(left.subscribe( function (value) { var id = leftId++; var md = new SingleAssignmentDisposable(); leftMap.add(id, value); group.add(md); var expire = function () { leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); rightMap.getValues().forEach(function (v) { var result; try { result = resultSelector(value, v); } catch (exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { leftDone = true; (rightDone || leftMap.count() === 0) && observer.onCompleted(); }) ); group.add(right.subscribe( function (value) { var id = rightId++; var md = new SingleAssignmentDisposable(); rightMap.add(id, value); group.add(md); var expire = function () { rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted(); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire)); leftMap.getValues().forEach(function (v) { var result; try { result = resultSelector(v, value); } catch(exn) { observer.onError(exn); return; } observer.onNext(result); }); }, observer.onError.bind(observer), function () { rightDone = true; (leftDone || rightMap.count() === 0) && observer.onCompleted(); }) ); return group; }); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(), rightMap = new Dictionary(); var leftId = 0, rightId = 0; function handleError(e) { return function (v) { v.onError(e); }; }; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftId++; leftMap.add(id, s); var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } observer.onNext(result); rightMap.getValues().forEach(function (v) { s.onNext(v); }); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { leftMap.remove(id) && s.onCompleted(); group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, observer.onCompleted.bind(observer)) ); group.add(right.subscribe( function (value) { var id = rightId++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( noop, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }, expire) ); leftMap.getValues().forEach(function (v) { v.onNext(value); }); }, function (e) { leftMap.getValues().forEach(handleError(e)); observer.onError(e); }) ); return r; }); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, function () { return observableEmpty(); }, function (_, window) { return window; }); } function observableWindowWithBounaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var window = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); d.add(windowBoundaries.subscribe(function (w) { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); return r; }); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var createWindowClose, m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), window = new Subject(); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); observer.onCompleted(); })); createWindowClose = function () { var m1, windowClose; try { windowClose = windowClosingSelector(); } catch (exception) { observer.onError(exception); return; } m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); createWindowClose(); })); }; createWindowClose(); return r; }); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { var published = this.publish().refCount(); return [ published.filter(predicate, thisArg), published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector) { return enumerableFor(sources, resultSelector).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler)); defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = argsOrArray(arguments, 0); return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .map(function (x) { var curr = new ChainObservable(x); chain && chain.onNext(x); chain = curr; return curr; }) .tap( noop, function (e) { chain && chain.onError(e); }, function () { chain && chain.onCompleted(); } ) .observeOn(scheduler) .map(selector); }); }; var ChainObservable = (function (__super__) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeObservable().subscribe(observer)); })); return g; } inherits(ChainObservable, __super__); function ChainObservable(head) { __super__.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwException(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = (function () { /** * @constructor * @private */ function Map() { this.keys = []; this.values = []; } /** * @private * @memberOf Map# */ Map.prototype['delete'] = function (key) { var i = this.keys.indexOf(key); if (i !== -1) { this.keys.splice(i, 1); this.values.splice(i, 1); } return i !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.get = function (key, fallback) { var i = this.keys.indexOf(key); return i !== -1 ? this.values[i] : fallback; }; /** * @private * @memberOf Map# */ Map.prototype.set = function (key, value) { var i = this.keys.indexOf(key); if (i !== -1) { this.values[i] = value; } this.values[this.keys.push(key) - 1] = value; }; /** * @private * @memberOf Map# */ Map.prototype.size = function () { return this.keys.length; }; /** * @private * @memberOf Map# */ Map.prototype.has = function (key) { return this.keys.indexOf(key) !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.getKeys = function () { return this.keys.slice(0); }; /** * @private * @memberOf Map# */ Map.prototype.getValues = function () { return this.values.slice(0); }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * * @param other Observable sequence to match in addition to the current pattern. * @return Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { var patterns = this.patterns.slice(0); patterns.push(other); return new Pattern(patterns); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.thenDo = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } // Active Plan function ActivePlan(joinObserverArray, onNext, onCompleted) { var i, joinObserver; this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (i = 0; i < this.joinObserverArray.length; i++) { joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { var values = this.joinObservers.getValues(); for (var i = 0, len = values.length; i < len; i++) { values[i].queue.shift(); } }; ActivePlan.prototype.match = function () { var firstValues, i, len, isCompleted, values, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { firstValues = []; isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); if (this.joinObserverArray[i].queue[0].kind === 'C') { isCompleted = true; } } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); values = []; for (i = 0; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; /** @private */ var JoinObserver = (function (_super) { inherits(JoinObserver, _super); /** * @constructor * @private */ function JoinObserver(source, onError) { _super.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { this.onError(notification.exception); return; } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.error = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.completed = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.removeActivePlan = function (activePlan) { var idx = this.activePlans.indexOf(activePlan); this.activePlans.splice(idx, 1); if (this.activePlans.length === 0) { this.dispose(); } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.thenDo = function (selector) { return new Pattern([this]).thenDo(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var plans = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var activePlans = [], externalSubscriptions = new Map(), group, i, len, joinObserver, joinValues, outObserver; outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { var values = externalSubscriptions.getValues(); for (var j = 0, jlen = values.length; j < jlen; j++) { values[j].onError(exception); } observer.onError(exception); }, observer.onCompleted.bind(observer)); try { for (i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); if (activePlans.length === 0) { outObserver.onCompleted(); } })); } } catch (e) { observableThrow(e).subscribe(observer); } group = new CompositeDisposable(); joinValues = externalSubscriptions.getValues(); for (i = 0, len = joinValues.length; i < len; i++) { joinObserver = joinValues[i]; joinObserver.subscribe(); group.add(joinObserver); } return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var count = 0, d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count++); self(d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * * @example * 1 - res = Rx.Observable.timer(new Date()); * 2 - res = Rx.Observable.timer(new Date(), 1000); * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); * * 5 - res = Rx.Observable.timer(5000); * 6 - res = Rx.Observable.timer(5000, 1000); * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * * @example * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; timeShiftOrScheduler == null && (timeShift = timeSpan); isScheduler(scheduler) || (scheduler = timeoutScheduler); if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (typeof timeShiftOrScheduler === 'object') { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe(function (x) { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } }, function (e) { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onError(e); } observer.onError(e); }, function () { var i, len; for (i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; isSpan && (nextSpan += timeShift); isShift && (nextShift += timeShift); m.setDisposable(scheduler.scheduleWithRelative(ts, function () { var s; if (isShift) { s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } if (isSpan) { s = q.shift(); s.onCompleted(); } createTimer(); })); } }); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @example * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items * * @memberOf Observable# * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var createTimer, groupDisposable, n = 0, refCountDisposable, s = new Subject() timerD = new SerialDisposable(), windowId = 0; groupDisposable = new CompositeDisposable(timerD); refCountDisposable = new RefCountDisposable(groupDisposable); observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe(function (x) { var newId = 0, newWindow = false; s.onNext(x); n++; if (n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } newWindow && createTimer(newId); }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); })); return refCountDisposable; function createTimer(id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { var newId; if (id !== windowId) { return; } n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); } }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.map(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * * @example * 1 - res = source.timeout(new Date()); // As a date * 2 - res = source.timeout(5000); // 5 seconds * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { other || (other = observableThrow(new Error('Timeout'))); 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); var createTimer = function () { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); }; createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { hasResult && observer.onNext(result); try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(function () { start(); }, observer.onError.bind(observer), function () { start(); })); } return new CompositeDisposable(subscription, delays); }); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * * @example * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); * * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; var firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false, setTimer = function (timeout) { var myId = id, timerWins = function () { return id === myId; }; var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } d.dispose(); }, function (e) { if (timerWins()) { observer.onError(e); } }, function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } })); }; setTimer(firstTimeout); var observerWins = function () { var res = !switched; if (res) { id++; } return res; }; original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(timeout); } }, function (e) { if (observerWins()) { observer.onError(e); } }, function () { if (observerWins()) { observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); * * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The throttled sequence. */ observableProto.throttleWithSelector = function (throttleDurationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(x); } catch (e) { observer.onError(e); return; } hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); if (hasValue) { observer.onNext(value); } observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } observer.onCompleted(); }); }); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * * @example * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { observer.onNext(next.value); } } observer.onCompleted(); }); }); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { res.push(next.value); } } observer.onNext(res); observer.onCompleted(); }); }); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler.scheduleWithRelative(duration, observer.onCompleted.bind(observer)), source.subscribe(observer)); }); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; isScheduler(scheduler) || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler.scheduleWithRelative(duration, function () { open = true; }), source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * * @example * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} scheduler Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { observer.onCompleted(); }), source.subscribe(observer)); }); }; /* * Performs a exclusive waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @returns {Observable} A exclusive observable with only the results that happen when subscribed. */ observableProto.exclusive = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasCurrent = false, isStopped = false, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); var innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); innerSubscription.setDisposable(innerSource.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (!hasCurrent && g.length === 1) { observer.onCompleted(); } })); return g; }); }; /* * Performs a exclusive map waiting for the first to finish before subscribing to another observable. * Observables that come in between subscriptions will be dropped on the floor. * @param {Function} selector Selector to invoke for every item in the current subscription. * @param {Any} [thisArg] An optional context to invoke with the selector parameter. * @returns {Observable} An exclusive observable with only the results that happen when subscribed. */ observableProto.exclusiveMap = function (selector, thisArg) { var sources = this; return new AnonymousObservable(function (observer) { var index = 0, hasCurrent = false, isStopped = true, m = new SingleAssignmentDisposable(), g = new CompositeDisposable(); g.add(m); m.setDisposable(sources.subscribe( function (innerSource) { if (!hasCurrent) { hasCurrent = true; innerSubscription = new SingleAssignmentDisposable(); g.add(innerSubscription); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { var result; try { result = selector.call(thisArg, x, index++, innerSource); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), function () { g.remove(innerSubscription); hasCurrent = false; if (isStopped && g.length === 1) { observer.onCompleted(); } })); } }, observer.onError.bind(observer), function () { isStopped = true; if (g.length === 1 && !hasCurrent) { observer.onCompleted(); } })); return g; }); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (__super__) { function notImplemented() { throw new Error('Not implemented'); } function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, __super__); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); __super__.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { var next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { this.comparer(next.dueTime, this.clock) > 0 && (this.clock = next.dueTime); next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time), dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { while (this.queue.length > 0) { var next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this; function run(scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); } var si = new ScheduledItem(this, state, run, dueTime, this.comparer); this.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (__super__) { inherits(HistoricalScheduler, __super__); /** * Creates a new historical scheduler with the specified initial clock value. * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; __super__.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
client/apps/web/components/molecules/Menu/index.js
defe266/keystone-starter
import React from 'react'//, { PropTypes } import { connect } from 'react-redux' import Link from '../../atoms/Link'; var Menu = React.createClass({ displayName: "Menu", render: function () { var props = this.props; var className = this.props.className ? this.props.className : ''; return ( <ul className={"Menu "+className}> {props.data.MenuMain.map((item) => { return <li key={item._id}><Link to={item.url.es} activeClassName="active" target={item.target} IndexLink>{item.title.es}</Link></li> })} </ul> ) } }); export default connect((state, ownProps) => { return state.menus })(Menu)
caricyno/src/main/js/modules/postModal.js
red-avtovo/caricynoVkInfo
'use strict'; import React from "react"; import client from "../client"; import EmptyPostModal from "./emptyPostModal" class PostModal extends EmptyPostModal { constructor(props) { super(props); this.state = {}; this.open =this.open.bind(this); } open(post) { client({ method: 'POST', path: '/posts/create', entity: post, headers: { 'Content-Type': 'application/json' } }) .done(response => { this.refs.modal.open(response.entity); }); } } export default PostModal;
docs/app/src/pages/guides/CurrentGame.js
tercenya/compendium
import React from 'react'; import { LanguageSelector, CodeExample, CondLang, NavMain, PageHeader, PageFooter, A } from '../../components'; import SampleCode from '../../SampleCode'; const CurrentGame = (props) => { return ( <div> <NavMain activePage="guides" /> <PageHeader title="Current Game" subTitle="How to find a match-in-progress" /> <div className="container compendium-container"> <div className="row"> <div className="col-md-12" role="main"> <div className="compendium-section"> <h2>Guide: Look up a match-in-progress</h2> <LanguageSelector> <p> Maybe you want to check in a that's currently in progress instead of something that happened long ago? There's an endpoint for that too. Again, we need a SummonerId. If you don't have it, you'll need to look it up. </p> <p> Yet again, we have a new parameter. This one isn't too hard - it's the region of the game in question. You can look them up <A href="https://developer.riotgames.com/docs/regional-endpoints">here</A>. </p> <p> This might be a good time to point out that so far, all of our examples have been against the North American region. If you want to make calls against another region (or change the region parameter), you will also need to change the URL to a different server, as noted on the document above. </p> <CondLang> <CodeExample lang='ruby' code={SampleCode.CurrentGame.id.ruby} /> <CodeExample lang='php' code={SampleCode.CurrentGame.id.php} /> <CodeExample lang='node' code={SampleCode.CurrentGame.id.node} /> </CondLang> <p> Now comes the time when our knowledge of HTTP status comes in handy. This route can (and frequently does) return a 404. That means there's no game in progress for that user. We will need to check for that status in our code. </p> <CondLang> <CodeExample lang='ruby' code={SampleCode.CurrentGame.status.ruby} /> <CodeExample lang='php' code={SampleCode.CurrentGame.status.php} /> <CodeExample lang='node' code={SampleCode.CurrentGame.status.node} /> </CondLang> <p>If we were succesful, we get a response that looks like this.</p> <CodeExample lang='jsx' code={SampleCode.CurrentGame.json} /> <p>Let's try the output.</p> <CondLang> <div lang='ruby'> <CodeExample lang='shell' code={SampleCode.CurrentGame.fullOutput.ruby} /> </div> <div lang='php'> <CodeExample lang='shell' code={SampleCode.CurrentGame.fullOutput.php} /> </div> <div lang='node'> <CodeExample lang='shell' code={SampleCode.CurrentGame.fullOutput.node} /> </div> </CondLang> <p> Ah, well, that's to be expected. I'm writing guides on how to use the Riot API instead of playing League of Legends. </p> </LanguageSelector> </div> </div> </div> </div> </div> ); }; export default CurrentGame;
test/Footer.js
jamesmcewan/jmce-react
import React from 'react'; import { beforeEach, describe, it } from 'mocha'; import { expect } from 'chai'; import { render } from 'enzyme'; import Footer from '../app/components/modules/Footer/Footer'; const items = { 0: { name: 'test', link: 'http://test.com', path: 'path', }, 1: { name: 'test2', link: 'http://test2.com', path: 'path', }, }; describe('Footer', () => { let result; beforeEach(() => { result = render(<Footer items={items} />); }); it('renders a footer tag', () => { expect(result.find('footer').length).to.equal(1); }); it('contains the css class .footer', () => { expect(result.find('.footer').length).to.equal(1); }); describe('Footer Container', () => { it('renders a div tag', () => { expect(result.find('div').length).to.equal(1); }); it('contains the css class .footer-container', () => { expect(result.find('.footer-container').length).to.equal(1); }); describe('Footer Social', () => { it('renders a ul tag', () => { expect(result.find('ul').length).to.equal(1); }); it('contains the css class .footer-social', () => { expect(result.find('.footer-social').length).to.equal(1); }); }); }); });
react/features/participants-pane/components/breakout-rooms/components/web/CollapsibleRoom.js
gpolitis/jitsi-meet
// @flow import { makeStyles } from '@material-ui/styles'; import clsx from 'clsx'; import React, { useCallback, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { useSelector } from 'react-redux'; import { ListItem } from '../../../../../base/components'; import { Icon, IconArrowDown, IconArrowUp } from '../../../../../base/icons'; import { ACTION_TRIGGER } from '../../../../constants'; import { participantMatchesSearch } from '../../../../functions'; import ParticipantItem from '../../../web/ParticipantItem'; type Props = { /** * Type of trigger for the breakout room actions. */ actionsTrigger?: string, /** * React children. */ children: React$Node, /** * Is this item highlighted/raised. */ isHighlighted?: boolean, /** * Callback to raise menu. Used to raise menu on mobile long press. */ onRaiseMenu: Function, /** * Callback for when the mouse leaves this component. */ onLeave?: Function, /** * Room reference. */ room: Object, /** * Participants search string. */ searchString: string } const useStyles = makeStyles(theme => { return { container: { boxShadow: 'none' }, roomName: { overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', ...theme.typography.labelButton, lineHeight: `${theme.typography.labelButton.lineHeight}px`, padding: '12px 0' }, arrowContainer: { backgroundColor: theme.palette.ui03, width: '24px', height: '24px', borderRadius: '6px', marginRight: '16px', display: 'flex', alignItems: 'center', justifyContent: 'center' } }; }); export const CollapsibleRoom = ({ actionsTrigger = ACTION_TRIGGER.HOVER, children, isHighlighted, onRaiseMenu, onLeave, room, searchString }: Props) => { const { t } = useTranslation(); const styles = useStyles(); const [ collapsed, setCollapsed ] = useState(false); const toggleCollapsed = useCallback(() => { setCollapsed(!collapsed); }, [ collapsed ]); const raiseMenu = useCallback(target => { onRaiseMenu(target); }, [ onRaiseMenu ]); const { defaultRemoteDisplayName } = useSelector(state => state['features/base/config']); const arrow = (<div className = { styles.arrowContainer }> <Icon size = { 14 } src = { collapsed ? IconArrowDown : IconArrowUp } /> </div>); const roomName = (<span className = { styles.roomName }> {`${room.name || t('breakoutRooms.mainRoom')} (${Object.keys(room?.participants || {}).length})`} </span>); return ( <> <ListItem actions = { children } className = { clsx(styles.container, 'breakout-room-container') } icon = { arrow } isHighlighted = { isHighlighted } onClick = { toggleCollapsed } onLongPress = { raiseMenu } onMouseLeave = { onLeave } testId = { room.id } textChildren = { roomName } trigger = { actionsTrigger } /> {!collapsed && room?.participants && Object.values(room?.participants || {}).map((p: Object) => participantMatchesSearch(p, searchString) && ( <ParticipantItem displayName = { p.displayName || defaultRemoteDisplayName } key = { p.jid } local = { false } participantID = { p.jid } /> )) } </> ); };
node_modules/react/lib/onlyChild.js
louisiaegerv/zephyr
/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var _prodInvariant = require('./reactProdInvariant'); var ReactElement = require('./ReactElement'); var invariant = require('fbjs/lib/invariant'); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. * * See https://facebook.github.io/react/docs/top-level-api.html#react.children.only * * The current implementation of this function assumes that a single child gets * passed without a wrapper, but the purpose of this helper function is to * abstract away the particular structure of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { !ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React.Children.only expected to receive a single React element child.') : _prodInvariant('143') : void 0; return children; } module.exports = onlyChild;
file-manager/src/views/App.js
adamantius/react-redux-file-manager
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import FileManager from './FileManager'; export default class App extends Component { static propTypes = { baseRoots: PropTypes.array }; render() { return ( <FileManager baseRoots={ this.props.baseRoots }/> ); } }
src/components/common/svg-icons/editor/vertical-align-bottom.js
abzfarah/Pearson.NAPLAN.GnomeH
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorVerticalAlignBottom = (props) => ( <SvgIcon {...props}> <path d="M16 13h-3V3h-2v10H8l4 4 4-4zM4 19v2h16v-2H4z"/> </SvgIcon> ); EditorVerticalAlignBottom = pure(EditorVerticalAlignBottom); EditorVerticalAlignBottom.displayName = 'EditorVerticalAlignBottom'; EditorVerticalAlignBottom.muiName = 'SvgIcon'; export default EditorVerticalAlignBottom;
packages/material-ui-icons/src/VpnLockTwoTone.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M12 8h-2v2c0 .55-.45 1-1 1H7v2h6c.55 0 1 .45 1 1v3h1c.9 0 1.64.58 1.9 1.39C18.2 16.97 19 15.08 19 13c0-.34-.04-.67-.08-1H17c-1.65 0-3-1.35-3-3V6c0 1.1-.9 2-2 2zM8 17v-1l-4.79-4.79C3.08 11.79 3 12.38 3 13c0 4.08 3.05 7.44 7 7.93V19c-1.1 0-2-.9-2-2z" opacity=".3" /><path d="M18.92 12c.04.33.08.66.08 1 0 2.08-.8 3.97-2.1 5.39-.26-.81-1-1.39-1.9-1.39h-1v-3c0-.55-.45-1-1-1H7v-2h2c.55 0 1-.45 1-1V8h2c1.1 0 2-.9 2-2V5 3.46c-.95-.3-1.95-.46-3-.46C5.48 3 1 7.48 1 13s4.48 10 10 10 10-4.48 10-10c0-.34-.02-.67-.05-1h-2.03zM10 20.93c-3.95-.49-7-3.85-7-7.93 0-.62.08-1.21.21-1.79L8 16v1c0 1.1.9 2 2 2v1.93z" /><path d="M22 4v-.5C22 2.12 20.88 1 19.5 1S17 2.12 17 3.5V4c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h5c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zm-1 0h-3v-.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5V4z" /></g></React.Fragment> , 'VpnLockTwoTone');
js/pages/iptt_report/components/report/buttons.js
mercycorps/TolaActivity
import React from 'react'; import ReactDOM from 'react-dom'; import { inject, observer } from 'mobx-react'; import { BootstrapPopoverButton } from '../../../../components/helpPopover'; @observer class PinPopover extends React.Component { NOT_SENT = 0; SENDING = 1; SENT = 2; FAILED = 3; constructor(props) { super(props); this.state = { reportName: '', status: this.NOT_SENT }; } handleChange = (e) => { this.setState({reportName: e.target.value}); } isDisabled = () => { return !this.props.rootStore.pinAPI.pinReady || !this.state.reportName; } handleClick = () => { this.setState({status: this.SENDING}); this.props.rootStore.pinAPI.savePin({ name: this.state.reportName, ...this.props.rootStore.pinParams }).then( () => { this.setState({status: this.SENT}); this.props.updatePosition(); }).catch( () => { this.setState({status: this.FAILED}); console.log("ajax error:", ev); }); } render() { return ( <React.Fragment> {(() => { switch(this.state.status) { case this.SENT: return ( <div className="form-group"> <p><span> {/* # Translators: The user has successfully "pinned" a report link to a program page for quick access to the report */} {gettext('Success! This report is now pinned to the program page')} </span></p> <p><a href={ this.props.rootStore.pinAPI.programPageUrl }> {/* # Translators: This is not really an imperative, it's an option that is available once you have pinned a report to a certain web page */} {gettext('Visit the program page now.')} </a></p> </div> ); case this.FAILED: return ( <div className="form-group"> <p><span> { gettext('Something went wrong when attempting to pin this report') } </span></p> </div> ); case this.NOT_SENT: return ( <React.Fragment> <div className="form-group"> <label className=""> { /* # Translators: a field where users can name their newly created report */ gettext('Report name') } </label> <input type="text" className="form-control" value={ this.state.reportName } onChange={ this.handleChange } disabled={ this.state.sending }/> </div> <button type="button" onClick={ this.handleClick } disabled={ this.isDisabled() } className="btn btn-primary btn-block"> { gettext('Pin to program page') } </button> </React.Fragment> ); case this.SENDING: return ( <div className="btn btn-primary" disabled> <img src='/static/img/ajax-loader.gif' />&nbsp; { gettext('Sending') } </div> ); } })()} </React.Fragment> ); } } @inject('rootStore') @observer export class PinButton extends BootstrapPopoverButton { popoverName = 'pin'; getPopoverContent = () => { return ( <PinPopover rootStore={ this.props.rootStore } updatePosition={() => {$(this.refs.target).popover('update');}} /> ); } render() { return ( <React.Fragment> <button href="#" className="btn btn-sm btn-secondary" ref="target"> <i className="fas fa-thumbtack"></i> { /* # Translators: a button that lets a user "pin" (verb) a report to their home page */ gettext('Pin') } </button> </React.Fragment> ); } } @observer class ExcelPopover extends React.Component { getCurrent = () => { if (this.props.excelUrl) { window.open(this.props.excelUrl, '_blank'); } } getAll = () => { if (this.props.fullExcelUrl) { window.open(this.props.fullExcelUrl, '_blank'); } } render() { return ( <div> <button type="button" className="btn btn-primary btn-block" onClick={ this.getCurrent }> { /* # Translators: a download button for a report containing just the data currently displayed */ gettext('Current view') } </button> <button type="button" className="btn btn-primary btn-block" onClick={ this.getAll }> { /* # Translators: a download button for a report containing all available data */ gettext('All program data') } </button> </div> ); } } @observer export class ExcelPopoverButton extends BootstrapPopoverButton { popoverName = 'excel'; getPopoverContent = () => { return ( <ExcelPopover { ...this.props } /> ); } render() { return ( <React.Fragment> <button type="button" className="btn btn-sm btn-secondary" ref="target"> <i className="fas fa-download"></i> Excel </button> </React.Fragment> ); } } @observer export class ExcelButton extends React.Component { handleClick = () => { if (this.props.excelUrl) { window.open(this.props.excelUrl, '_blank'); } } render() { return ( <React.Fragment> <button type="button" className="btn btn-sm btn-secondary" onClick={this.handleClick }> <i className="fas fa-download"></i> Excel </button> </React.Fragment> ); } }
node_modules/react-icons/md/cloud-circle.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const MdCloudCircle = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m27.5 26.6c2.3 0 4.1-1.8 4.1-4.1s-1.8-4.1-4.1-4.1h-0.9c0-3.7-2.9-6.8-6.6-6.8-3.1 0-5.7 2.2-6.4 5.1l-0.2-0.1c-2.8 0-5 2.3-5 5s2.2 5 5 5h14.1z m-7.5-23.2c9.2 0 16.6 7.4 16.6 16.6s-7.4 16.6-16.6 16.6-16.6-7.4-16.6-16.6 7.4-16.6 16.6-16.6z"/></g> </Icon> ) export default MdCloudCircle
app/component/blogs.js
smay1227/winterfellapp
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { AppRegistry, StyleSheet, Text, View, ListView, RefreshControl, TouchableOpacity, InteractionManager } from 'react-native'; import StaticContainer from 'react-static-container'; import {blogList} from '../actions/blogListAction'; import * as Api from '../constant/api'; import ToolBar from '../widget/ToolBar'; import { blogsStyle } from '../style/blogsStyle'; import LoadingMoreFooter from '../widget/LoadMoreFooter'; import {getNavigator} from '../route'; /** * 初始化状态 */ let isLoading = true; let isLoadMore = false; let isRefresh = false; let isFirstLoad = true; class blogs extends Component { constructor(props) { super(props); console.info('blogs constructor'); this.state = { dataSource: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2 }) } } // 拉取网络数据 componentDidMount() { InteractionManager.runAfterInteractions(() => { console.info('blogs componentDidMount 拉取数据'); const {blogList} = this.props; blogList(Api.API_BLOG_LIST, isLoading, isLoadMore, isRefresh); }); } render() { const {BlogReducer} = this.props; let blogList = BlogReducer.blogs; console.info('lenght', blogList.length); if (blogList.length) { isFirstLoad = false; } return ( <View style={blogsStyle.container}> <ToolBar title="winterfell" titleStyle={{ textAlign: 'center' }} /> <ListView dataSource={this.state.dataSource.cloneWithRows(blogList)} style={blogsStyle.listview} onEndReachedThreshold={10} enableEmptySections={true} showsVerticalScrollIndicator={false} renderRow={this._renderRow.bind(this)} /*onEndReached={this._onEndReach.bind(this)} renderFooter={this._renderFooter.bind(this)}*/ refreshControl={ <RefreshControl refreshing={false} onRefresh={this._onRefresh.bind(this)} colors={["#F70938"]} /> } /> </View> ) } /** * listview item */ _renderRow(rowData, sectionId, rowId) { return( <TouchableOpacity activeOpacity={0.8} onPress={this._onPressRow.bind(this, rowData, rowId)}> <View style={blogsStyle.listitem}> <Text style={blogsStyle.title}>{rowData.title}</Text> <Text style={blogsStyle.blogdate}>{rowData.date}</Text> </View> </TouchableOpacity> ) } /** * 下拉刷新 */ _onRefresh() { isRefresh = true; isLoading = false; isLoadMore = false; const {blogList} = this.props; blogList(Api.API_BLOG_LIST, isLoading, isLoadMore, isRefresh); } /** * 加载更多 */ _onEndReach() { if (!isFirstLoad) { isLoadMore = true; isRefresh = false; isLoading = false; const {blogList} = this.props; blogList(Api.API_BLOG_LIST, isLoading, isLoadMore, isRefresh); } } /** * 底部 */ _renderFooter() { const {BlogReducer} = this.props; console.info('BlogReducer.isLoadMore', BlogReducer.isLoadMore); console.info('BlogReducer.blogs.length', BlogReducer.blogs.length); if (BlogReducer.isLoadMore && BlogReducer.blogs.length > 0) { return <StaticContainer> <LoadingMoreFooter /> </StaticContainer> } } /** * item click */ _onPressRow(rowData, rowId) { //跳转 getNavigator().push({ name: 'Blog', params: { title: rowData.title, year: rowData.year, month: rowData.month, day: rowData.day, urlname: rowData.urlname } }); } } export default connect((state) => { const {BlogReducer} = state; // => var Main = state.Main;调用rootReducer中声明的reducer return { BlogReducer// 1.相当于返回Main:Main,当key和value相同时,可省略key ==> es6(即可通过this.props.Main获取state中的状态值) } }, { blogList } // 2.注入action,即可调用action中声明的方法,(即可通过this.props.main获取,用于调用main中的方法) )(blogs) // 3.将组件注入
src/button.js
ju5td0m7m1nd/guidejs
import React from 'react' import PlayFont from 'react-icons/lib/fa/play-circle-o' import StopFont from 'react-icons/lib/fa/pause' import ReactFont from 'react-icons/lib/fa/video-camera' import QuestionFont from 'react-icons/lib/fa/question' const styles = { btn: { display:'flex', justifyContent:'center', alignItems:'center', position:'fixed', right:'10%', bottom:'10%', boxShadow:'0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12)', cursor:'pointer', fontWeight:'bold', width:'3em', height:'3em', borderRadius:'50%', zIndex: '9998', transition:'all .3s ease-in', }, startBtn: { background:'rgba(255,255,255,1)', color:'rgba(230,0,0,1)', }, endBtn: { background:'rgba(230,0,0,1)', color:'#FFF', }, qBtn: { background:'rgba(255,255,255,1)', color:'#222', }, playBtn: { color:'rgba(0,230,0,1)', background:'rgba(255,255,255,1)', }, } class RecordBtn extends React.Component{ constructor(props){ super(props); this.state= { openPos: '20', open: false, start: false, } this.openBtn = this.openBtn.bind(this); this.startRecord = this.startRecord.bind(this); } openBtn () { this.setState({open: !this.state.open}); } startRecord() { this.props.handleRecord(); this.setState({start: !this.state.start}); } render() { let recordBtnStyle = Object.assign({},styles.btn,styles.startBtn); recordBtnStyle = this.state.start ? Object.assign({}, recordBtnStyle, styles.PauseBtn): Object.assign({}, recordBtnStyle, styles.StartBtn); recordBtnStyle = this.state.open ? Object.assign({},recordBtnStyle,{'right':`${this.state.openPos}%`}) : recordBtnStyle; console.log(this.props.mode); recordBtnStyle = this.props.mode !== 'dev' ? Object.assign({},recordBtnStyle,{'visibility':'hidden'}): recordBtnStyle; return <div className="start-btn" onClick={this.startRecord} style={recordBtnStyle} > { this.state.start ? <StopFont height="1.5em" width="1.5em" />: <ReactFont height="1.5em" width="1.5em" /> } </div> } } class PlayBtn extends React.Component{ constructor(props){ super(props); this.state= { openPos: '15', open:false, } this.openBtn = this.openBtn.bind(this); } openBtn () { this.setState({open: !this.state.open}); } render() { let playBtnStyle = Object.assign({},styles.btn,styles.playBtn); playBtnStyle = this.state.open ? Object.assign({},playBtnStyle,{'right':`${this.state.openPos}%`}) : playBtnStyle; return <div className="play-btn" onClick={this.props.handleReplay} style={playBtnStyle}> <PlayFont height="2em" width="2em"/></div> } } class QuestionBtn extends React.Component{ constructor(props){ super(props); this.state= { openPos: this.props.mode === 'dev' ? 25 : 20, open:false, } this.openBtn = this.openBtn.bind(this); this.visitGuideJs = this.visitGuideJs.bind(this); } openBtn () { this.setState({open: !this.state.open}); } visitGuideJs() { window.open("https://www.npmjs.com/package/guidejs"); } render() { let qBtnStyle = Object.assign({},styles.btn,styles.qBtn); qBtnStyle = this.state.open ? Object.assign({},qBtnStyle,{'right':`${this.state.openPos}%`}) : qBtnStyle; return <div className="question-btn" onClick={this.visitGuideJs} style={qBtnStyle}> <QuestionFont height="2em" width="2em"/></div> } } export {RecordBtn, PlayBtn, QuestionBtn}
frontend/Stories/Sections/DeleteButton.js
fdemian/Morpheus
import React from 'react'; import IconButton from 'material-ui/IconButton'; import DeleteIcon from 'material-ui/svg-icons/action/delete'; const DeleteButton = ({deleteFn, story, loggedIn}) => { if(loggedIn){ return( <span onClick={() => deleteFn(story.id)}> <IconButton tooltip="Delete"> <DeleteIcon color='#3b5998' /> </IconButton> </span> ); } else return null; } export default DeleteButton;
src/components/MarkdownViewer.js
Charlie9830/pounder
import React, { Component } from 'react'; import { ListItem, ListItemText, List, withTheme, Typography } from '@material-ui/core'; import ReactMarkdown from 'react-markdown'; let TableHead = (props) => { return null; } let TableCell = (props) => { let { theme } = props; return ( <td style={{ ...theme.typography.body1, background: theme.palette.background.paper, border: `1px solid ${theme.palette.divider}`, padding: '16px' }}> {props.children} </td> ) } let Strong = (props) => { let { theme } = props; return ( <span style={{ ...theme.typography.body1, fontWeight: 'bold', color: theme.palette.secondary.light, }}> {props.children} </span> ) } let Root = (props) => { return ( <div style={{ width: '100%', height: '100%', padding: '8px' }}> {props.children} </div> ) } let MDListItem = (props) => { let { theme } = props; return ( <div style={{ ...theme.typography.body1, }}> - {props.children} </div> ) } let Heading = (props) => { let level = props.level + 2; level = level > 6 ? 6 : level; return ( <Typography style={{ marginTop: '16px', marginBottom: '16px' }} variant={`h${level}`}> {props.children} </Typography> ) } let Paragraph = (props) => { return ( <Typography> {props.children} </Typography> ) } let Credit = (props) => { let { theme } = props; return ( <span style={{ ...theme.typography.body1, color: theme.palette.secondary.main, }}> [Thanks {props.children}] </span> ) } let ExampleContainer = (props) => { let { theme } = props; let style = { ...theme.typography.body1, background: theme.palette.background.paper, color: theme.palette.text.primary, border: theme.palette.divider, width: 'fit-content', height: 'fit-content', padding: '8px', marginBottom: '8px', } return ( <div style={style}> {props.value} </div> ) } let renderers = { root: Root, heading: Heading, paragraph: Paragraph, inlineCode: withTheme()(Credit), listItem: withTheme()(MDListItem), strong: withTheme()(Strong), tableHead: TableHead, tableCell: withTheme()(TableCell), code: withTheme()(ExampleContainer), } const MarkdownViewer = (props) => { return ( <ReactMarkdown source={props.source} renderers={renderers} /> ); } export default MarkdownViewer;
ajax/libs/material-ui/5.0.0-alpha.12/esm/List/ListContext.js
cdnjs/cdnjs
import * as React from 'react'; /** * @ignore - internal component. */ var ListContext = /*#__PURE__*/React.createContext({}); if (process.env.NODE_ENV !== 'production') { ListContext.displayName = 'ListContext'; } export default ListContext;
src/parser/shared/modules/items/bfa/raids/uldir/TwitchingTentacleofXalzaix.js
fyruna/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import ITEMS from 'common/ITEMS'; import { formatPercentage, formatNumber } from 'common/format'; import { calculatePrimaryStat } from 'common/stats'; import ItemStatistic from 'interface/statistics/ItemStatistic'; import BoringItemValueText from 'interface/statistics/components/BoringItemValueText'; import IntellectIcon from 'interface/icons/Intellect'; import UptimeIcon from 'interface/icons/Uptime'; import StatTracker from 'parser/shared/modules/StatTracker'; import Analyzer from 'parser/core/Analyzer'; /** * Twitching Tentacle of Xalzaix - * Equip: Your spells have a chance to grant you the Lingering Power of Xalzaix for 30 sec. * When it reaches 5 charges the power is released, increasing your Intellect by 159 for 12 sec. * * Test Log: /report/ABH7D8W1Qaqv96mt/2-Mythic+Taloc+-+Kill+(4:12)/Halshuggen/statistics * * @property {StatTracker} statTracker */ class TwitchingTentacleofXalzaix extends Analyzer { static dependencies = { statTracker: StatTracker, }; _item = null; statBuff = 0; constructor(...args) { super(...args); this._item = this.selectedCombatant.getTrinket(ITEMS.TWITCHING_TENTACLE_OF_XALZAIX.id); this.active = !!this._item; if (this.active) { this.statBuff = calculatePrimaryStat(340, 850, this._item.itemLevel); this.statTracker.add(SPELLS.UNCONTAINED_POWER.id, { intellect: this.statBuff, }); } } get totalBuffUptime() { return this.selectedCombatant.getBuffUptime(SPELLS.UNCONTAINED_POWER.id) / this.owner.fightDuration; } statistic() { return ( <ItemStatistic size="flexible" > <BoringItemValueText item={ITEMS.TWITCHING_TENTACLE_OF_XALZAIX}> <UptimeIcon /> {formatPercentage(this.totalBuffUptime, 0)}% <small>uptime</small> <br /> <IntellectIcon /> {formatNumber(this.totalBuffUptime * this.statBuff)} <small>average {this.selectedCombatant.spec.primaryStat} gained</small> </BoringItemValueText> </ItemStatistic> ); } } export default TwitchingTentacleofXalzaix;
packages/example-react-native-expo/App.js
s-i18n/s-i18n
import React from 'react'; import { StyleSheet, Text, View, Alert, TouchableOpacity } from 'react-native'; import { translator, _ } from './locale'; import { Greeting } from './greeting'; import { ButtonGroup, Button } from 'react-native-elements'; export default class App extends React.Component { constructor(props) { super(props); this.state = { selectedIndex: 0 }; this.updateIndex = this.updateIndex.bind(this); } updateIndex(selectedIndex) { const codes = ['fr', 'en', 'es', 'debug']; const lang = codes[selectedIndex]; if (lang === 'debug') { translator.config.debug = !translator.config.debug; this.setState(this.state); } else { this.setState({ selectedIndex }); translator.setLanguage(lang); } } componentDidMount() { this.updateIndex(0); } render() { const buttons = ['Français', 'English', 'Español', 'Debug']; const { selectedIndex } = this.state; return ( <View style={styles.container}> <ButtonGroup onPress={this.updateIndex} selectedIndex={selectedIndex} buttons={buttons} containerStyle={{ height: 100 }} /> <View style={{ padding: 20 }}> {_('Started react-native when {user} made {repository} public', { user: 'Houssein', //repository: "gitpoint/git-point" repository: ( <Text style={{ color: '#ff0000' }} onPress={() => Alert.alert('you clicked')} > gitpoint/git-point </Text> ) })} {_( 'This string is not translated and will automatically fallback to {language}', { language: 'English' } )} {_('This string should not trigger placeholders processing')} {_('This string uses {nested}', { nested: _('nested translating!') })} <Text>I forgot to run this sentence through _() 😮</Text> {_('Oops, I forgot to pass my {placeholder}', {})} {_('A simple sentence without placeholders')} {_('Two {consecutive} {placeholders}', { consecutive: _('consecutive'), placeholders: _('placeholders') })} {_('A sentence {0} using {1} numerical {0} placeholders', [ '-foo-', '-bar-' ])} {_( 'A simple sentence with only one placeholder passed as a {0} without wrapping it in an array', 'string' )} {_( 'There {n,plural,=0{are no cats} =1{is one cat} =*{are # cats}}!', { n: 0 } )} {_( 'There {n,plural,=0{are no cats} =1{is one cat} =*{are # cats}}!', { n: 1 } )} {_( 'There {n,plural,=0{are no cats} =1{is one cat} =*{are # cats}}!', { n: 42 } )} <Greeting name="s-i18n" /> </View> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff' // alignItems: 'center', //justifyContent: 'center', } });
app/routes.js
oeb25/colio
import React from 'react'; import { Route } from 'react-router'; import LandingContainer from './containers/LandingContainer'; import RoomContainer from './containers/RoomContainer'; import CreateRoom from './components/CreateRoom'; const routes = ( <Route> <Route path="/" component={LandingContainer}/> <Route path="/room" component={CreateRoom} /> <Route path="/room/:id" component={RoomContainer} /> </Route> ); export default routes;
src/js/MaterialLoader.js
alamarre/math-exercises
import React from 'react' import { Link } from 'react-router' var material = require("./material.json"); var renderers = {"multiple choice": require("./activities/MultipleChoiceRenderer")}; for(var grade in material.grades) { var gradeData = material.grades[grade].exercises; for(var i=0; i<gradeData.length; i++) { gradeData[i].actualSource = require("./material/grades/"+grade+"/"+gradeData[i].source); gradeData[i].actualMode = require("./gamemodes/"+gradeData[i].mode); } } const MaterialLoader = React.createClass({ render() { var grade = this.props.params.grade; var materialNumber = this.props.params.material;; var links = []; var gradeData = material.grades[grade].exercises; var materialData = gradeData[materialNumber]; var result = React.createElement(materialData.actualMode, {material: materialData, questionRenderer: renderers[materialData.type], problemGenerator: materialData.actualSource , grade: grade}); return ( <div> {result} </div> ) } }) module.exports = MaterialLoader
monkey/monkey_island/cc/ui/src/components/report-components/AttackReport.js
guardicore/monkey
import React from 'react'; import {Col, Button} from 'react-bootstrap'; import '../../styles/components/Collapse.scss'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import {faCircle} from '@fortawesome/free-solid-svg-icons/faCircle'; import {faRadiation} from '@fortawesome/free-solid-svg-icons/faRadiation'; import {faEye} from '@fortawesome/free-solid-svg-icons/faEye'; import {faEyeSlash} from '@fortawesome/free-solid-svg-icons/faEyeSlash'; import {faToggleOff} from '@fortawesome/free-solid-svg-icons/faToggleOff'; import {marked} from 'marked'; import ReportHeader, {ReportTypes} from './common/ReportHeader'; import {ScanStatus} from '../attack/techniques/Helpers'; import Matrix from './attack/ReportMatrixComponent'; import SelectedTechnique from './attack/SelectedTechnique'; import TechniqueDropdowns from './attack/TechniqueDropdowns'; import ReportLoader from './common/ReportLoader'; const techComponents = getAllAttackModules(); function getAllAttackModules() { let context = require.context('../attack/techniques/', false, /\.js$/); let obj = {}; context.keys().forEach(function (key) { let techName = key.replace(/\.js/, ''); techName = String(techName.replace(/\.\//, '')); obj[techName] = context(key).default; }); return obj; } class AttackReport extends React.Component { constructor(props) { super(props); this.state = { selectedTechnique: false, collapseOpen: '' }; if (typeof this.props.report.schema !== 'undefined' && typeof this.props.report.techniques !== 'undefined'){ this.state['schema'] = this.props.report['schema']; this.state['techniques'] = AttackReport.modifyTechniqueData(this.props.report['schema'], this.props.report['techniques']); } } componentDidUpdate(prevProps) { if (this.props.report !== prevProps.report) { this.setState({schema: this.props.report['schema'], techniques: AttackReport.modifyTechniqueData(this.props.report['schema'], this.props.report['techniques'])}) } } onTechniqueSelect = (technique, _) => { let selectedTechnique = this.getTechniqueByTitle(technique); if (selectedTechnique === false){ return; } this.setState({selectedTechnique: selectedTechnique.tech_id}) }; static getComponentClass(tech_id, techniques) { switch (techniques[tech_id].status) { case ScanStatus.SCANNED: return 'collapse-warning'; case ScanStatus.USED: return 'collapse-danger'; case ScanStatus.DISABLED: return 'collapse-disabled'; default: return 'collapse-default'; } } static getStatusIcon(tech_id, techniques){ switch (techniques[tech_id].status){ case ScanStatus.SCANNED: return <FontAwesomeIcon icon={faEye} className={'technique-status-icon'}/>; case ScanStatus.USED: return <FontAwesomeIcon icon={faRadiation} className={'technique-status-icon'}/>; case ScanStatus.DISABLED: return <FontAwesomeIcon icon={faToggleOff} className={'technique-status-icon'}/>; default: return <FontAwesomeIcon icon={faEyeSlash} className={'technique-status-icon'}/>; } } renderLegend() { return (<div id='header' className='row justify-content-between attack-legend'> <Col xs={3}> <FontAwesomeIcon icon={faCircle} className='technique-disabled'/> <span> - Disabled</span> </Col> <Col xs={3}> <FontAwesomeIcon icon={faCircle} className='technique-not-attempted'/> <span> - Not attempted</span> </Col> <Col xs={3}> <FontAwesomeIcon icon={faCircle} className='technique-attempted'/> <span> - Tried (but failed)</span> </Col> <Col xs={3}> <FontAwesomeIcon icon={faCircle} className='technique-used'/> <span> - Successfully used</span> </Col> </div>) } generateReportContent() { return ( <div> <p> This report shows information about <Button variant={'link'} href={'https://attack.mitre.org/'} size={'lg'} className={'attack-link'} target={'_blank'}> Mitre ATT&CK™ </Button> techniques used by Infection Monkey. </p> {this.renderLegend()} <Matrix techniques={this.state.techniques} schema={this.state.schema} onClick={this.onTechniqueSelect}/> <SelectedTechnique techComponents={techComponents} techniques={this.state.techniques} selected={this.state.selectedTechnique}/> <TechniqueDropdowns techniques={this.state.techniques} techComponents={techComponents} schema={this.state.schema}/> <br/> </div> ) } getTechniqueByTitle(title){ for (const tech_id in this.state.techniques){ if (! Object.prototype.hasOwnProperty.call(this.state.techniques, tech_id)) {return false;} let technique = this.state.techniques[tech_id]; if (technique.title === title){ technique['tech_id'] = tech_id; return technique } } return false; } static modifyTechniqueData(schema, techniques){ // add links to techniques schema = schema.properties; for(const type in schema){ if (! Object.prototype.hasOwnProperty.call(schema, type)) {return false;} let typeTechniques = schema[type].properties; for(const tech_id in typeTechniques){ if (! Object.prototype.hasOwnProperty.call(typeTechniques, tech_id)) {return false;} if (typeTechniques[tech_id] !== undefined){ techniques[tech_id]['link'] = typeTechniques[tech_id].link } } } // compiles techniques' message string from markdown to HTML for (const tech_id in techniques){ techniques[tech_id]['message_html'] = <div dangerouslySetInnerHTML={{__html: marked(techniques[tech_id]['message'])}} />; } return techniques } render() { let content = {}; if (typeof this.state.schema === 'undefined' || typeof this.state.techniques === 'undefined') { content = <ReportLoader/>; } else { content = <div> {this.generateReportContent()}</div>; } return ( <div id='attack' className='attack-report report-page'> <ReportHeader report_type={ReportTypes.attack}/> <hr/> {content} </div>) } } export default AttackReport;
ajax/libs/ember-data.js/1.0.0-beta.6/ember-data.js
gagan-bansal/cdnjs
/*! * @overview Ember Data * @copyright Copyright 2011-2014 Tilde Inc. and contributors. * Portions Copyright 2011 LivingSocial Inc. * @license Licensed under MIT license (see license.js) * @version 1.0.0-beta.6 */ (function() { var define, requireModule; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requireModule = function(name) { if (seen[name]) { return seen[name]; } seen[name] = {}; var mod, deps, callback, reified , exports; mod = registry[name]; if (!mod) { throw new Error("Module '" + name + "' not found."); } deps = mod.deps; callback = mod.callback; reified = []; exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(deps[i])); } } var value = callback.apply(this, reified); return seen[name] = exports || value; }; })(); (function() { /** @module ember-data */ /** All Ember Data methods and functions are defined inside of this namespace. @class DS @static */ var DS; if ('undefined' === typeof DS) { /** @property VERSION @type String @default '1.0.0-beta.6' @static */ DS = Ember.Namespace.create({ VERSION: '1.0.0-beta.6' }); if ('undefined' !== typeof window) { window.DS = DS; } if (Ember.libraries) { Ember.libraries.registerCoreLibrary('Ember Data', DS.VERSION); } } })(); (function() { /** This is used internally to enable deprecation of container paths and provide a decent message to the user indicating how to fix the issue. @class ContainerProxy @namespace DS @private */ var ContainerProxy = function (container){ this.container = container; }; ContainerProxy.prototype.aliasedFactory = function(path, preLookup) { var _this = this; return {create: function(){ if (preLookup) { preLookup(); } return _this.container.lookup(path); }}; }; ContainerProxy.prototype.registerAlias = function(source, dest, preLookup) { var factory = this.aliasedFactory(dest, preLookup); return this.container.register(source, factory); }; ContainerProxy.prototype.registerDeprecation = function(deprecated, valid) { var preLookupCallback = function(){ Ember.deprecate("You tried to look up '" + deprecated + "', " + "but this has been deprecated in favor of '" + valid + "'.", false); }; return this.registerAlias(deprecated, valid, preLookupCallback); }; ContainerProxy.prototype.registerDeprecations = function(proxyPairs) { for (var i = proxyPairs.length; i > 0; i--) { var proxyPair = proxyPairs[i - 1], deprecated = proxyPair['deprecated'], valid = proxyPair['valid']; this.registerDeprecation(deprecated, valid); } }; DS.ContainerProxy = ContainerProxy; })(); (function() { var get = Ember.get, set = Ember.set, isNone = Ember.isNone; // Simple dispatcher to support overriding the aliased // method in subclasses. function aliasMethod(methodName) { return function() { return this[methodName].apply(this, arguments); }; } /** In Ember Data a Serializer is used to serialize and deserialize records when they are transferred in and out of an external source. This process involves normalizing property names, transforming attribute values and serializing relationships. For maximum performance Ember Data recommends you use the [RESTSerializer](DS.RESTSerializer.html) or one of its subclasses. `JSONSerializer` is useful for simpler or legacy backends that may not support the http://jsonapi.org/ spec. @class JSONSerializer @namespace DS */ DS.JSONSerializer = Ember.Object.extend({ /** The primaryKey is used when serializing and deserializing data. Ember Data always uses the `id` property to store the id of the record. The external source may not always follow this convention. In these cases it is useful to override the primaryKey property to match the primaryKey of your external store. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ primaryKey: '_id' }); ``` @property primaryKey @type {String} @default 'id' */ primaryKey: 'id', /** Given a subclass of `DS.Model` and a JSON object this method will iterate through each attribute of the `DS.Model` and invoke the `DS.Transform#deserialize` method on the matching property of the JSON object. This method is typically called after the serializer's `normalize` method. @method applyTransforms @private @param {subclass of DS.Model} type @param {Object} data The data to transform @return {Object} data The transformed data object */ applyTransforms: function(type, data) { type.eachTransformedAttribute(function(key, type) { var transform = this.transformFor(type); data[key] = transform.deserialize(data[key]); }, this); return data; }, /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. Example ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ normalize: function(type, hash) { var fields = Ember.get(type, 'fields'); fields.forEach(function(field) { var payloadField = Ember.String.underscore(field); if (field === payloadField) { return; } hash[field] = hash[payloadField]; delete hash[payloadField]; }); return this._super.apply(this, arguments); } }); ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @return {Object} */ normalize: function(type, hash) { if (!hash) { return hash; } this.applyTransforms(type, hash); return hash; }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```javascript App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```javascript { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(post, options) { var json = { POST_TTL: post.get('title'), POST_BDY: post.get('body'), POST_CMS: post.get('comments').mapProperty('id') } if (options.includeId) { json.POST_ID_ = post.get('id'); } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachAttribute(function(name) { json[serverAttributeName(name)] = record.get(name); }) record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = record.get(name).mapBy('id'); } }); if (options.includeId) { json.ID_ = record.get('id'); } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```javascript { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serialize: function(record, options) { var json = this._super.apply(this, arguments); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param {subclass of DS.Model} record @param {Object} options @return {Object} json */ serialize: function(record, options) { var json = {}; if (options && options.includeId) { var id = get(record, 'id'); if (id) { json[get(this, 'primaryKey')] = id; } } record.eachAttribute(function(key, attribute) { this.serializeAttribute(record, json, key, attribute); }, this); record.eachRelationship(function(key, relationship) { if (relationship.kind === 'belongsTo') { this.serializeBelongsTo(record, json, relationship); } else if (relationship.kind === 'hasMany') { this.serializeHasMany(record, json, relationship); } }, this); return json; }, /** `serializeAttribute` can be used to customize how `DS.attr` properties are serialized For example if you wanted to ensure all you attributes were always serialized as properties on an `attributes` object you could write: ```javascript App.ApplicationSerializer = DS.JSONSerializer.extend({ serializeAttribute: function(record, json, key, attributes) { json.attributes = json.attributes || {}; this._super(record, json.attributes, key, attributes); } }); ``` @method serializeAttribute @param {DS.Model} record @param {Object} json @param {String} key @param {Object} attribute */ serializeAttribute: function(record, json, key, attribute) { var attrs = get(this, 'attrs'); var value = get(record, key), type = attribute.type; if (type) { var transform = this.transformFor(type); value = transform.serialize(value); } // if provided, use the mapping provided by `attrs` in // the serializer key = attrs && attrs[key] || (this.keyForAttribute ? this.keyForAttribute(key) : key); json[key] = value; }, /** `serializeBelongsTo` can be used to customize how `DS.belongsTo` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeBelongsTo: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; json[key] = Ember.isNone(belongsTo) ? belongsTo : belongsTo.toJSON(); } }); ``` @method serializeBelongsTo @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeBelongsTo: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; if (isNone(belongsTo)) { json[key] = belongsTo; } else { json[key] = get(belongsTo, 'id'); } if (relationship.options.polymorphic) { this.serializePolymorphicType(record, json, relationship); } }, /** `serializeHasMany` can be used to customize how `DS.hasMany` properties are serialized. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ serializeHasMany: function(record, json, relationship) { var key = relationship.key; if (key === 'comments') { return; } else { this._super.apply(this, arguments); } } }); ``` @method serializeHasMany @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializeHasMany: function(record, json, relationship) { var key = relationship.key; var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship); if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') { json[key] = get(record, key).mapBy('id'); // TODO support for polymorphic manyToNone and manyToMany relationships } }, /** You can use this method to customize how polymorphic objects are serialized. Objects are considered to be polymorphic if `{polymorphic: true}` is pass as the second argument to the `DS.belongsTo` function. Example ```javascript App.CommentSerializer = DS.JSONSerializer.extend({ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; json[key + "_type"] = belongsTo.constructor.typeKey; } }); ``` @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializePolymorphicType: Ember.K, // EXTRACT /** The `extract` method is used to deserialize payload data from the server. By default the `JSONSerializer` does not push the records into the store. However records that subclass `JSONSerializer` such as the `RESTSerializer` may push records into the store as part of the extract call. This method delegates to a more specific extract method based on the `requestType`. Example ```javascript var get = Ember.get; socket.on('message', function(message) { var modelName = message.model; var data = message.data; var type = store.modelFor(modelName); var serializer = store.serializerFor(type.typeKey); var record = serializer.extract(store, type, data, get(data, 'id'), 'single'); store.push(modelName, record); }); ``` @method extract @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String or Number} id @param {String} requestType @return {Object} json The deserialized payload */ extract: function(store, type, payload, id, requestType) { this.extractMeta(store, type, payload); var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1); return this[specificExtract](store, type, payload, id, requestType); }, /** `extractFindAll` is a hook into the extract method used when a call is made to `DS.Store#findAll`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindAll @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindAll: aliasMethod('extractArray'), /** `extractFindQuery` is a hook into the extract method used when a call is made to `DS.Store#findQuery`. By default this method is an alias for [extractArray](#method_extractArray). @method extractFindQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindQuery: aliasMethod('extractArray'), /** `extractFindMany` is a hook into the extract method used when a call is made to `DS.Store#findMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindMany: aliasMethod('extractArray'), /** `extractFindHasMany` is a hook into the extract method used when a call is made to `DS.Store#findHasMany`. By default this method is alias for [extractArray](#method_extractArray). @method extractFindHasMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractFindHasMany: aliasMethod('extractArray'), /** `extractCreateRecord` is a hook into the extract method used when a call is made to `DS.Store#createRecord`. By default this method is alias for [extractSave](#method_extractSave). @method extractCreateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractCreateRecord: aliasMethod('extractSave'), /** `extractUpdateRecord` is a hook into the extract method used when a call is made to `DS.Store#update`. By default this method is alias for [extractSave](#method_extractSave). @method extractUpdateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractUpdateRecord: aliasMethod('extractSave'), /** `extractDeleteRecord` is a hook into the extract method used when a call is made to `DS.Store#deleteRecord`. By default this method is alias for [extractSave](#method_extractSave). @method extractDeleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractDeleteRecord: aliasMethod('extractSave'), /** `extractFind` is a hook into the extract method used when a call is made to `DS.Store#find`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFind @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractFind: aliasMethod('extractSingle'), /** `extractFindBelongsTo` is a hook into the extract method used when a call is made to `DS.Store#findBelongsTo`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractFindBelongsTo @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractFindBelongsTo: aliasMethod('extractSingle'), /** `extractSave` is a hook into the extract method used when a call is made to `DS.Model#save`. By default this method is alias for [extractSingle](#method_extractSingle). @method extractSave @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractSave: aliasMethod('extractSingle'), /** `extractSingle` is used to deserialize a single record returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractSingle: function(store, type, payload) { payload.comments = payload._embedded.comment; delete payload._embedded; return this._super(store, type, payload); }, }); ``` @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Object} json The deserialized payload */ extractSingle: function(store, type, payload) { return this.normalize(type, payload); }, /** `extractArray` is used to deserialize an array of records returned from the adapter. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractArray: function(store, type, payload) { return payload.map(function(json) { return this.extractSingle(json); }, this); } }); ``` @method extractArray @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @return {Array} array An array of deserialized objects */ extractArray: function(store, type, payload) { return this.normalize(type, payload); }, /** `extractMeta` is used to deserialize any meta information in the adapter payload. By default Ember Data expects meta information to be located on the `meta` property of the payload object. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ extractMeta: function(store, type, payload) { if (payload && payload._pagination) { store.metaForType(type, payload._pagination); delete payload._pagination; } } }); ``` @method extractMeta @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload */ extractMeta: function(store, type, payload) { if (payload && payload.meta) { store.metaForType(type, payload.meta); delete payload.meta; } }, /** `keyForAttribute` can be used to define rules for how to convert an attribute name in your model to a key in your JSON. Example ```javascript App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` @method keyForAttribute @param {String} key @return {String} normalized key */ /** `keyForRelationship` can be used to define a custom key when serializing relationship properties. By default `JSONSerializer` does not provide an implementation of this method. Example ```javascript App.PostSerializer = DS.JSONSerializer.extend({ keyForRelationship: function(key, relationship) { return 'rel_' + Ember.String.underscore(key); } }); ``` @method keyForRelationship @param {String} key @param {String} relationship type @return {String} normalized key */ // HELPERS /** @method transformFor @private @param {String} attributeType @param {Boolean} skipAssertion @return {DS.Transform} transform */ transformFor: function(attributeType, skipAssertion) { var transform = this.container.lookup('transform:' + attributeType); Ember.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform); return transform; } }); })(); (function() { /** @module ember-data */ var get = Ember.get, capitalize = Ember.String.capitalize, underscore = Ember.String.underscore, DS = window.DS ; /** Extend `Ember.DataAdapter` with ED specific code. @class DebugAdapter @namespace DS @extends Ember.DataAdapter @private */ DS.DebugAdapter = Ember.DataAdapter.extend({ getFilters: function() { return [ { name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' } ]; }, detect: function(klass) { return klass !== DS.Model && DS.Model.detect(klass); }, columnsForType: function(type) { var columns = [{ name: 'id', desc: 'Id' }], count = 0, self = this; get(type, 'attributes').forEach(function(name, meta) { if (count++ > self.attributeLimit) { return false; } var desc = capitalize(underscore(name).replace('_', ' ')); columns.push({ name: name, desc: desc }); }); return columns; }, getRecords: function(type) { return this.get('store').all(type); }, getRecordColumnValues: function(record) { var self = this, count = 0, columnValues = { id: get(record, 'id') }; record.eachAttribute(function(key) { if (count++ > self.attributeLimit) { return false; } var value = get(record, key); columnValues[key] = value; }); return columnValues; }, getRecordKeywords: function(record) { var keywords = [], keys = Ember.A(['id']); record.eachAttribute(function(key) { keys.push(key); }); keys.forEach(function(key) { keywords.push(get(record, key)); }); return keywords; }, getRecordFilterValues: function(record) { return { isNew: record.get('isNew'), isModified: record.get('isDirty') && !record.get('isNew'), isClean: !record.get('isDirty') }; }, getRecordColor: function(record) { var color = 'black'; if (record.get('isNew')) { color = 'green'; } else if (record.get('isDirty')) { color = 'blue'; } return color; }, observeRecord: function(record, recordUpdated) { var releaseMethods = Ember.A(), self = this, keysToObserve = Ember.A(['id', 'isNew', 'isDirty']); record.eachAttribute(function(key) { keysToObserve.push(key); }); keysToObserve.forEach(function(key) { var handler = function() { recordUpdated(self.wrapRecord(record)); }; Ember.addObserver(record, key, handler); releaseMethods.push(function() { Ember.removeObserver(record, key, handler); }); }); var release = function() { releaseMethods.forEach(function(fn) { fn(); } ); }; return release; } }); })(); (function() { /** The `DS.Transform` class is used to serialize and deserialize model attributes when they are saved or loaded from an adapter. Subclassing `DS.Transform` is useful for creating custom attributes. All subclasses of `DS.Transform` must implement a `serialize` and a `deserialize` method. Example ```javascript App.RawTransform = DS.Transform.extend({ deserialize: function(serialized) { return serialized; }, serialize: function(deserialized) { return deserialized; } }); ``` Usage ```javascript var attr = DS.attr; App.Requirement = DS.Model.extend({ name: attr('string'), optionsArray: attr('raw') }); ``` @class Transform @namespace DS */ DS.Transform = Ember.Object.extend({ /** When given a deserialized value from a record attribute this method must return the serialized value. Example ```javascript serialize: function(deserialized) { return Ember.isEmpty(deserialized) ? null : Number(deserialized); } ``` @method serialize @param deserialized The deserialized value @return The serialized value */ serialize: Ember.required(), /** When given a serialize value from a JSON object this method must return the deserialized value for the record attribute. Example ```javascript deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); } ``` @method deserialize @param serialized The serialized value @return The deserialized value */ deserialize: Ember.required() }); })(); (function() { /** The `DS.BooleanTransform` class is used to serialize and deserialize boolean attributes on Ember Data record objects. This transform is used when `boolean` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.User = DS.Model.extend({ isAdmin: attr('boolean'), name: attr('string'), email: attr('string') }); ``` @class BooleanTransform @extends DS.Transform @namespace DS */ DS.BooleanTransform = DS.Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "boolean") { return serialized; } else if (type === "string") { return serialized.match(/^true$|^t$|^1$/i) !== null; } else if (type === "number") { return serialized === 1; } else { return false; } }, serialize: function(deserialized) { return Boolean(deserialized); } }); })(); (function() { /** The `DS.DateTransform` class is used to serialize and deserialize date attributes on Ember Data record objects. This transform is used when `date` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. ```javascript var attr = DS.attr; App.Score = DS.Model.extend({ value: attr('number'), player: DS.belongsTo('player'), date: attr('date') }); ``` @class DateTransform @extends DS.Transform @namespace DS */ DS.DateTransform = DS.Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "string") { return new Date(Ember.Date.parse(serialized)); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is not present in the data, // return undefined, not null. return serialized; } else { return null; } }, serialize: function(date) { if (date instanceof Date) { // Serialize it as a number to maintain millisecond precision return Number(date); } else { return null; } } }); })(); (function() { var empty = Ember.isEmpty; /** The `DS.NumberTransform` class is used to serialize and deserialize numeric attributes on Ember Data record objects. This transform is used when `number` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.Score = DS.Model.extend({ value: attr('number'), player: DS.belongsTo('player'), date: attr('date') }); ``` @class NumberTransform @extends DS.Transform @namespace DS */ DS.NumberTransform = DS.Transform.extend({ deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); }, serialize: function(deserialized) { return empty(deserialized) ? null : Number(deserialized); } }); })(); (function() { var none = Ember.isNone; /** The `DS.StringTransform` class is used to serialize and deserialize string attributes on Ember Data record objects. This transform is used when `string` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```javascript var attr = DS.attr; App.User = DS.Model.extend({ isAdmin: attr('boolean'), name: attr('string'), email: attr('string') }); ``` @class StringTransform @extends DS.Transform @namespace DS */ DS.StringTransform = DS.Transform.extend({ deserialize: function(serialized) { return none(serialized) ? null : String(serialized); }, serialize: function(deserialized) { return none(deserialized) ? null : String(deserialized); } }); })(); (function() { })(); (function() { /** @module ember-data */ var set = Ember.set; /* This code registers an injection for Ember.Application. If an Ember.js developer defines a subclass of DS.Store on their application, this code will automatically instantiate it and make it available on the router. Additionally, after an application's controllers have been injected, they will each have the store made available to them. For example, imagine an Ember.js application with the following classes: App.Store = DS.Store.extend({ adapter: 'custom' }); App.PostsController = Ember.ArrayController.extend({ // ... }); When the application is initialized, `App.Store` will automatically be instantiated, and the instance of `App.PostsController` will have its `store` property set to that instance. Note that this code will only be run if the `ember-application` package is loaded. If Ember Data is being used in an environment other than a typical application (e.g., node.js where only `ember-runtime` is available), this code will be ignored. */ Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "store", initialize: function(container, application) { application.register('store:main', application.Store || DS.Store); // allow older names to be looked up var proxy = new DS.ContainerProxy(container); proxy.registerDeprecations([ {deprecated: 'serializer:_default', valid: 'serializer:-default'}, {deprecated: 'serializer:_rest', valid: 'serializer:-rest'}, {deprecated: 'adapter:_rest', valid: 'adapter:-rest'} ]); // new go forward paths application.register('serializer:-default', DS.JSONSerializer); application.register('serializer:-rest', DS.RESTSerializer); application.register('adapter:-rest', DS.RESTAdapter); // Eagerly generate the store so defaultStore is populated. // TODO: Do this in a finisher hook container.lookup('store:main'); } }); Application.initializer({ name: "transforms", before: "store", initialize: function(container, application) { application.register('transform:boolean', DS.BooleanTransform); application.register('transform:date', DS.DateTransform); application.register('transform:number', DS.NumberTransform); application.register('transform:string', DS.StringTransform); } }); Application.initializer({ name: "data-adapter", before: "store", initialize: function(container, application) { application.register('data-adapter:main', DS.DebugAdapter); } }); Application.initializer({ name: "injectStore", before: "store", initialize: function(container, application) { application.inject('controller', 'store', 'store:main'); application.inject('route', 'store', 'store:main'); application.inject('serializer', 'store', 'store:main'); application.inject('data-adapter', 'store', 'store:main'); } }); }); })(); (function() { /** @module ember-data */ /** Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601> © 2011 Colin Snover <http://zetafleet.com> Released under MIT license. @class Date @namespace Ember @static */ Ember.Date = Ember.Date || {}; var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ]; /** @method parse @param date */ Ember.Date.parse = function (date) { var timestamp, struct, minutesOffset = 0; // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string // before falling back to any implementation-specific date parsing, so that’s what we do, even if native // implementations could be faster // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; (k = numericKeys[i]); ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); } else { timestamp = origParse ? origParse(date) : NaN; } return timestamp; }; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) { Date.parse = Ember.Date.parse; } })(); (function() { })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; /** A record array is an array that contains records of a certain type. The record array materializes records as needed when they are retrieved for the first time. You should not create record arrays yourself. Instead, an instance of `DS.RecordArray` or its subclasses will be returned by your application's store in response to queries. @class RecordArray @namespace DS @extends Ember.ArrayProxy @uses Ember.Evented */ DS.RecordArray = Ember.ArrayProxy.extend(Ember.Evented, { /** The model type contained by this record array. @property type @type DS.Model */ type: null, /** The array of client ids backing the record array. When a record is requested from the record array, the record for the client id at the same index is materialized, if necessary, by the store. @property content @private @type Ember.Array */ content: null, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all(App.Person); people.get('isLoaded'); // true ``` @property isLoaded @type Boolean */ isLoaded: false, /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.all(App.Person); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @property isUpdating @type Boolean */ isUpdating: false, /** The store that created this record array. @property store @private @type DS.Store */ store: null, /** Retrieves an object from the content by index. @method objectAtContent @private @param {Number} index @return {DS.Model} record */ objectAtContent: function(index) { var content = get(this, 'content'); return content.objectAt(index); }, /** Used to get the latest version of all of the records in this array from the adapter. Example ```javascript var people = store.all(App.Person); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @method update */ update: function() { if (get(this, 'isUpdating')) { return; } var store = get(this, 'store'), type = get(this, 'type'); return store.fetchAll(type, this); }, /** Adds a record to the `RecordArray`. @method addRecord @private @param {DS.Model} record */ addRecord: function(record) { get(this, 'content').addObject(record); }, /** Removes a record to the `RecordArray`. @method removeRecord @private @param {DS.Model} record */ removeRecord: function(record) { get(this, 'content').removeObject(record); }, /** Saves all of the records in the `RecordArray`. Example ```javascript var messages = store.all(App.Message); messages.forEach(function(message) { message.set('hasBeenSeen', true); }); messages.save(); ``` @method save @return {DS.PromiseArray} promise */ save: function() { var promiseLabel = "DS: RecordArray#save " + get(this, 'type'); var promise = Ember.RSVP.all(this.invoke("save"), promiseLabel).then(function(array) { return Ember.A(array); }, null, "DS: RecordArray#save apply Ember.NativeArray"); return DS.PromiseArray.create({ promise: promise }); } }); })(); (function() { /** @module ember-data */ var get = Ember.get; /** Represents a list of records whose membership is determined by the store. As records are created, loaded, or modified, the store evaluates them to determine if they should be part of the record array. @class FilteredRecordArray @namespace DS @extends DS.RecordArray */ DS.FilteredRecordArray = DS.RecordArray.extend({ /** The filterFunction is a function used to test records from the store to determine if they should be part of the record array. Example ```javascript var allPeople = store.all('person'); allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"] var people = store.filter('person', function(person) { if (person.get('name').match(/Katz$/)) { return true; } }); people.mapBy('name'); // ["Yehuda Katz"] var notKatzFilter = function(person) { return !person.get('name').match(/Katz$/); }; people.set('filterFunction', notKatzFilter); people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"] ``` @method filterFunction @param {DS.Model} record @return {Boolean} `true` if the record should be in the array */ filterFunction: null, isLoaded: true, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a client-side filter (on " + type + ") is immutable."); }, /** @method updateFilter @private */ updateFilter: Ember.observer(function() { var manager = get(this, 'manager'); manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction')); }, 'filterFunction') }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; /** Represents an ordered list of records whose order and membership is determined by the adapter. For example, a query sent to the adapter may trigger a search on the server, whose results would be loaded into an instance of the `AdapterPopulatedRecordArray`. @class AdapterPopulatedRecordArray @namespace DS @extends DS.RecordArray */ DS.AdapterPopulatedRecordArray = DS.RecordArray.extend({ query: null, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, /** @method load @private @param {Array} data */ load: function(data) { var store = get(this, 'store'), type = get(this, 'type'), records = store.pushMany(type, data), meta = store.metadataFor(type); this.setProperties({ content: Ember.A(records), isLoaded: true, meta: meta }); // TODO: does triggering didLoad event should be the last action of the runLoop? Ember.run.once(this, 'trigger', 'didLoad'); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var map = Ember.EnumerableUtils.map; /** A `ManyArray` is a `RecordArray` that represents the contents of a has-many relationship. The `ManyArray` is instantiated lazily the first time the relationship is requested. ### Inverses Often, the relationships in Ember Data applications will have an inverse. For example, imagine the following models are defined: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` If you created a new instance of `App.Post` and added a `App.Comment` record to its `comments` has-many relationship, you would expect the comment's `post` property to be set to the post that contained the has-many. We call the record to which a relationship belongs the relationship's _owner_. @class ManyArray @namespace DS @extends DS.RecordArray */ DS.ManyArray = DS.RecordArray.extend({ init: function() { this._super.apply(this, arguments); this._changesToSync = Ember.OrderedSet.create(); }, /** The property name of the relationship @property {String} name @private */ name: null, /** The record to which this relationship belongs. @property {DS.Model} owner @private */ owner: null, /** `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} isPolymorphic @private */ isPolymorphic: false, // LOADING STATE isLoaded: false, /** Used for async `hasMany` arrays to keep track of when they will resolve. @property {Ember.RSVP.Promise} promise @private */ promise: null, /** @method loadingRecordsCount @param {Number} count @private */ loadingRecordsCount: function(count) { this.loadingRecordsCount = count; }, /** @method loadedRecord @private */ loadedRecord: function() { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { set(this, 'isLoaded', true); this.trigger('didLoad'); } }, /** @method fetch @private */ fetch: function() { var records = get(this, 'content'), store = get(this, 'store'), owner = get(this, 'owner'), resolver = Ember.RSVP.defer("DS: ManyArray#fetch " + get(this, 'type')); var unloadedRecords = records.filterProperty('isEmpty', true); store.fetchMany(unloadedRecords, owner, resolver); }, // Overrides Ember.Array's replace method to implement replaceContent: function(index, removed, added) { // Map the array of record objects into an array of client ids. added = map(added, function(record) { Ember.assert("You cannot add '" + record.constructor.typeKey + "' records to this relationship (only '" + this.type.typeKey + "' allowed)", !this.type || record instanceof this.type); return record; }, this); this._super(index, removed, added); }, arrangedContentDidChange: function() { Ember.run.once(this, 'fetch'); }, arrayContentWillChange: function(index, removed, added) { var owner = get(this, 'owner'), name = get(this, 'name'); if (!owner._suspendedRelationships) { // This code is the first half of code that continues inside // of arrayContentDidChange. It gets or creates a change from // the child object, adds the current owner as the old // parent if this is the first time the object was removed // from a ManyArray, and sets `newParent` to null. // // Later, if the object is added to another ManyArray, // the `arrayContentDidChange` will set `newParent` on // the change. for (var i=index; i<index+removed; i++) { var record = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner, record, get(this, 'store'), { parentType: owner.constructor, changeType: "remove", kind: "hasMany", key: name }); this._changesToSync.add(change); } } return this._super.apply(this, arguments); }, arrayContentDidChange: function(index, removed, added) { this._super.apply(this, arguments); var owner = get(this, 'owner'), name = get(this, 'name'), store = get(this, 'store'); if (!owner._suspendedRelationships) { // This code is the second half of code that started in // `arrayContentWillChange`. It gets or creates a change // from the child object, and adds the current owner as // the new parent. for (var i=index; i<index+added; i++) { var record = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner, record, store, { parentType: owner.constructor, changeType: "add", kind:"hasMany", key: name }); change.hasManyName = name; this._changesToSync.add(change); } // We wait until the array has finished being // mutated before syncing the OneToManyChanges created // in arrayContentWillChange, so that the array // membership test in the sync() logic operates // on the final results. this._changesToSync.forEach(function(change) { change.sync(); }); this._changesToSync.clear(); } }, /** Create a child record within the owner @method createRecord @private @param {Object} hash @return {DS.Model} record */ createRecord: function(hash) { var owner = get(this, 'owner'), store = get(owner, 'store'), type = get(this, 'type'), record; Ember.assert("You cannot add '" + type.typeKey + "' records to this polymorphic relationship.", !get(this, 'isPolymorphic')); record = store.createRecord.call(store, type, hash); this.pushObject(record); return record; } }); })(); (function() { /** @module ember-data */ })(); (function() { /*globals Ember*/ /*jshint eqnull:true*/ /** @module ember-data */ var get = Ember.get, set = Ember.set; var once = Ember.run.once; var isNone = Ember.isNone; var forEach = Ember.EnumerableUtils.forEach; var indexOf = Ember.EnumerableUtils.indexOf; var map = Ember.EnumerableUtils.map; var resolve = Ember.RSVP.resolve; var copy = Ember.copy; // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. These are always coerced to be strings // before being used internally. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +reference+ means a record reference object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a subclass of DS.Model. // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`), // it is important that internally we use strings, since IDs may be serialized // and lose type information. For example, Ember's router may put a record's // ID into the URL, and if we later try to deserialize that URL and find the // corresponding record, we will not know if it is a string or a number. var coerceId = function(id) { return id == null ? null : id+''; }; /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of `DS.Model` that wrap the individual data for a record, so that they can be bound to in your Handlebars templates. Define your application's store like this: ```javascript MyApp.Store = DS.Store.extend(); ``` Most Ember.js applications will only have a single `DS.Store` that is automatically created by their `Ember.Application`. You can retrieve models from the store in several ways. To retrieve a record for a specific id, use `DS.Store`'s `find()` method: ```javascript var person = store.find('person', 123); ``` If your application has multiple `DS.Store` instances (an unusual case), you can specify which store should be used: ```javascript var person = store.find(App.Person, 123); ``` By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: ```javascript MyApp.store = DS.Store.create({ adapter: 'MyApp.CustomAdapter' }); ``` You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. @class Store @namespace DS @extends Ember.Object */ DS.Store = Ember.Object.extend({ /** @method init @private */ init: function() { // internal bookkeeping; not observable this.typeMaps = {}; this.recordArrayManager = DS.RecordArrayManager.create({ store: this }); this._relationshipChanges = {}; this._pendingSave = []; }, /** The adapter to use to communicate to a backend server or other persistence layer. This can be specified as an instance, class, or string. If you want to specify `App.CustomAdapter` as a string, do: ```js adapter: 'custom' ``` @property adapter @default DS.RESTAdapter @type {DS.Adapter|String} */ adapter: '-rest', /** Returns a JSON representation of the record using a custom type-specific serializer, if one exists. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @method serialize @private @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function(record, options) { return this.serializerFor(record.constructor.typeKey).serialize(record, options); }, /** This property returns the adapter, after resolving a possible string key. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @property defaultAdapter @private @returns DS.Adapter */ defaultAdapter: Ember.computed('adapter', function() { var adapter = get(this, 'adapter'); Ember.assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name or a factory', !(adapter instanceof DS.Adapter)); if (typeof adapter === 'string') { adapter = this.container.lookup('adapter:' + adapter) || this.container.lookup('adapter:application') || this.container.lookup('adapter:-rest'); } if (DS.Adapter.detect(adapter)) { adapter = adapter.create({ container: this.container }); } return adapter; }), // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. To create a new instance of `App.Post`: ```js store.createRecord('post', { title: "Rails is omakase" }); ``` @method createRecord @param {String} type @param {Object} properties a hash of properties to set on the newly created record. @returns {DS.Model} record */ createRecord: function(type, properties) { type = this.modelFor(type); properties = copy(properties) || {}; // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if (isNone(properties.id)) { properties.id = this._generateId(type); } // Coerce ID to a string properties.id = coerceId(properties.id); var record = this.buildRecord(type, properties.id); // Move the record out of its initial `empty` state into // the `loaded` state. record.loadedData(); // Set the properties specified on the record. record.setProperties(properties); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method _generateId @private @param {String} type @returns {String} if the adapter can generate one, an ID */ _generateId: function(type) { var adapter = this.adapterFor(type); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this); } return null; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. Example ```javascript var post = store.createRecord('post', { title: "Rails is omakase" }); store.deleteRecord(post); ``` @method deleteRecord @param {DS.Model} record */ deleteRecord: function(record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. Only non-dirty records can be unloaded. Example ```javascript store.find('post', 1).then(function(post) { store.unloadRecord(post); }); ``` @method unloadRecord @param {DS.Model} record */ unloadRecord: function(record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** This is the main entry point into finding records. The first parameter to this method is the model's name as a string. --- To find a record by ID, pass the `id` as the second parameter: ```javascript store.find('person', 1); ``` The `find` method will always return a **promise** that will be resolved with the record. If the record was already in the store, the promise will be resolved immediately. Otherwise, the store will ask the adapter's `find` method to find the necessary data. The `find` method will always resolve its promise with the same object for a given type and `id`. --- To find all records for a type, call `find` with no additional parameters: ```javascript store.find('person'); ``` This will ask the adapter's `findAll` method to find the records for the given type, and return a promise that will be resolved once the server returns the values. --- To find a record by a query, call `find` with a hash as the second parameter: ```javascript store.find(App.Person, { page: 1 }); ``` This will ask the adapter's `findQuery` method to find the records for the query, and return a promise that will be resolved once the server responds. @method find @param {String or subclass of DS.Model} type @param {Object|String|Integer|null} id @return {Promise} promise */ find: function(type, id) { if (id === undefined) { return this.findAll(type); } // We are passed a query instead of an id. if (Ember.typeOf(id) === 'object') { return this.findQuery(type, id); } return this.findById(type, coerceId(id)); }, /** This method returns a record for a given type and id combination. @method findById @private @param {String or subclass of DS.Model} type @param {String|Integer} id @return {Promise} promise */ findById: function(type, id) { type = this.modelFor(type); var record = this.recordForId(type, id); var promise = this.fetchRecord(record) || resolve(record, "DS: Store#findById " + type + " with id: " + id); return promiseObject(promise); }, /** This method makes a series of requests to the adapter's `find` method and returns a promise that resolves once they are all loaded. @private @method findByIds @param {String} type @param {Array} ids @returns {Promise} promise */ findByIds: function(type, ids) { var store = this; var promiseLabel = "DS: Store#findByIds " + type; return promiseArray(Ember.RSVP.all(map(ids, function(id) { return store.findById(type, id); })).then(Ember.A, null, "DS: Store#findByIds of " + type + " complete")); }, /** This method is called by `findById` if it discovers that a particular type/id pair hasn't been loaded yet to kick off a request to the adapter. @method fetchRecord @private @param {DS.Model} record @returns {Promise} promise */ fetchRecord: function(record) { if (isNone(record)) { return null; } if (record._loadingPromise) { return record._loadingPromise; } if (!get(record, 'isEmpty')) { return null; } var type = record.constructor, id = get(record, 'id'); var adapter = this.adapterFor(type); Ember.assert("You tried to find a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to find a record but your adapter (for " + type + ") does not implement 'find'", adapter.find); var promise = _find(adapter, this, type, id); record.loadingData(promise); return promise; }, /** Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it's available. Otherwise, it will return null. ```js var post = store.getById('post', 1); ``` @method getById @param {String or subclass of DS.Model} type @param {String|Integer} id @param {DS.Model} record */ getById: function(type, id) { if (this.hasRecordForId(type, id)) { return this.recordForId(type, id); } else { return null; } }, /** This method is called by the record's `reload` method. This method calls the adapter's `find` method, which returns a promise. When **that** promise resolves, `reloadRecord` will resolve the promise returned by the record's `reload`. @method reloadRecord @private @param {DS.Model} record @return {Promise} promise */ reloadRecord: function(record) { var type = record.constructor, adapter = this.adapterFor(type), id = get(record, 'id'); Ember.assert("You cannot reload a record without an ID", id); Ember.assert("You tried to reload a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to reload a record but your adapter does not implement `find`", adapter.find); return _find(adapter, this, type, id); }, /** This method takes a list of records, groups the records by type, converts the records into IDs, and then invokes the adapter's `findMany` method. The records are grouped by type to invoke `findMany` on adapters for each unique type in records. It is used both by a brand new relationship (via the `findMany` method) or when the data underlying an existing relationship changes. @method fetchMany @private @param {Array} records @param {DS.Model} owner @param {Resolver} resolver */ fetchMany: function(records, owner, resolver) { if (!records.length) { return; } // Group By Type var recordsByTypeMap = Ember.MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); forEach(records, function(record) { recordsByTypeMap.get(record.constructor).push(record); }); forEach(recordsByTypeMap, function(type, records) { var ids = records.mapProperty('id'), adapter = this.adapterFor(type); Ember.assert("You tried to load many records but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load many records but your adapter does not implement `findMany`", adapter.findMany); resolver.resolve(_findMany(adapter, this, type, ids, owner)); }, this); }, /** Returns true if a record for a given type and ID is already loaded. @method hasRecordForId @param {String or subclass of DS.Model} type @param {String|Integer} id @returns {Boolean} */ hasRecordForId: function(type, id) { id = coerceId(id); type = this.modelFor(type); return !!this.typeMapFor(type).idToRecord[id]; }, /** Returns id record for a given type and ID. If one isn't already loaded, it builds a new record and leaves it in the `empty` state. @method recordForId @private @param {String or subclass of DS.Model} type @param {String|Integer} id @returns {DS.Model} record */ recordForId: function(type, id) { type = this.modelFor(type); id = coerceId(id); var record = this.typeMapFor(type).idToRecord[id]; if (!record) { record = this.buildRecord(type, id); } return record; }, /** @method findMany @private @param {DS.Model} owner @param {Array} records @param {String or subclass of DS.Model} type @param {Resolver} resolver @return {DS.ManyArray} records */ findMany: function(owner, records, type, resolver) { type = this.modelFor(type); records = Ember.A(records); var unloadedRecords = records.filterProperty('isEmpty', true), manyArray = this.recordArrayManager.createManyArray(type, records); forEach(unloadedRecords, function(record) { record.loadingData(); }); manyArray.loadingRecordsCount = unloadedRecords.length; if (unloadedRecords.length) { forEach(unloadedRecords, function(record) { this.recordArrayManager.registerWaitingRecordArray(record, manyArray); }, this); this.fetchMany(unloadedRecords, owner, resolver); } else { if (resolver) { resolver.resolve(); } manyArray.set('isLoaded', true); Ember.run.once(manyArray, 'trigger', 'didLoad'); } return manyArray; }, /** If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched. The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants. The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship. @method findHasMany @private @param {DS.Model} owner @param {any} link @param {String or subclass of DS.Model} type @param {Resolver} resolver @return {DS.ManyArray} */ findHasMany: function(owner, link, relationship, resolver) { var adapter = this.adapterFor(owner.constructor); Ember.assert("You tried to load a hasMany relationship but you have no adapter (for " + owner.constructor + ")", adapter); Ember.assert("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", adapter.findHasMany); var records = this.recordArrayManager.createManyArray(relationship.type, Ember.A([])); resolver.resolve(_findHasMany(adapter, this, owner, link, relationship)); return records; }, /** @method findBelongsTo @private @param {DS.Model} owner @param {any} link @param {Relationship} relationship @param {Resolver} resolver */ findBelongsTo: function(owner, link, relationship, resolver) { var adapter = this.adapterFor(owner.constructor); Ember.assert("You tried to load a belongsTo relationship but you have no adapter (for " + owner.constructor + ")", adapter); Ember.assert("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", adapter.findBelongsTo); resolver.resolve(_findBelongsTo(adapter, this, owner, link, relationship)); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. This method returns a promise, which is resolved with a `RecordArray` once the server returns. @method findQuery @private @param {String or subclass of DS.Model} type @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ findQuery: function(type, query) { type = this.modelFor(type); var array = this.recordArrayManager .createAdapterPopulatedRecordArray(type, query); var adapter = this.adapterFor(type), promiseLabel = "DS: Store#findQuery " + type, resolver = Ember.RSVP.defer(promiseLabel); Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", adapter.findQuery); resolver.resolve(_findQuery(adapter, this, type, query, array)); return promiseArray(resolver.promise); }, /** This method returns an array of all records adapter can find. It triggers the adapter's `findAll` method to give it an opportunity to populate the array with records of that type. @method findAll @private @param {String or subclass of DS.Model} type @return {DS.AdapterPopulatedRecordArray} */ findAll: function(type) { type = this.modelFor(type); return this.fetchAll(type, this.all(type)); }, /** @method fetchAll @private @param {DS.Model} type @param {DS.RecordArray} array @returns {Promise} promise */ fetchAll: function(type, array) { var adapter = this.adapterFor(type), sinceToken = this.typeMapFor(type).metadata.since; set(array, 'isUpdating', true); Ember.assert("You tried to load all records but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load all records but your adapter does not implement `findAll`", adapter.findAll); return promiseArray(_findAll(adapter, this, type, sinceToken)); }, /** @method didUpdateAll @param {DS.Model} type */ didUpdateAll: function(type) { var findAllCache = this.typeMapFor(type).findAllCache; set(findAllCache, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type. Note that because it's just a filter, it will have any locally created records of the type. Also note that multiple calls to `all` for a given type will always return the same RecordArray. Example ```javascript var local_posts = store.all(App.Post); ``` @method all @param {String or subclass of DS.Model} type @return {DS.RecordArray} */ all: function(type) { type = this.modelFor(type); var typeMap = this.typeMapFor(type), findAllCache = typeMap.findAllCache; if (findAllCache) { return findAllCache; } var array = this.recordArrayManager.createRecordArray(type); typeMap.findAllCache = array; return array; }, /** This method unloads all of the known records for a given type. ```javascript store.unloadAll(App.Post); ``` @method unloadAll @param {String or subclass of DS.Model} type */ unloadAll: function(type) { type = this.modelFor(type); var typeMap = this.typeMapFor(type), records = typeMap.records.splice(0), record; while(record = records.pop()) { record.unloadRecord(); } typeMap.findAllCache = null; }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The callback function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. Optionally you can pass a query which will be triggered at first. The results returned by the server could then appear in the filter if they match the filter function. Example ```javascript store.filter(App.Post, {unread: true}, function(post) { return post.get('unread'); }).then(function(unreadPosts) { unreadPosts.get('length'); // 5 var unreadPost = unreadPosts.objectAt(0); unreadPost.set('unread', false); unreadPosts.get('length'); // 4 }); ``` @method filter @param {String or subclass of DS.Model} type @param {Object} query optional query @param {Function} filter @return {DS.PromiseArray} */ filter: function(type, query, filter) { var promise; // allow an optional server query if (arguments.length === 3) { promise = this.findQuery(type, query); } else if (arguments.length === 2) { filter = query; } type = this.modelFor(type); var array = this.recordArrayManager .createFilteredRecordArray(type, filter); promise = promise || resolve(array); return promiseArray(promise.then(function() { return array; }, null, "DS: Store#filter of " + type)); }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit. Example ```javascript store.recordIsLoaded(App.Post, 1); // false store.find(App.Post, 1).then(function() { store.recordIsLoaded(App.Post, 1); // true }); ``` @method recordIsLoaded @param {String or subclass of DS.Model} type @param {string} id @return {boolean} */ recordIsLoaded: function(type, id) { if (!this.hasRecordForId(type, id)) { return false; } return !get(this.recordForId(type, id), 'isEmpty'); }, /** This method returns the metadata for a specific type. @method metadataFor @param {String or subclass of DS.Model} type @return {object} */ metadataFor: function(type) { type = this.modelFor(type); return this.typeMapFor(type).metadata; }, // ............ // . UPDATING . // ............ /** If the adapter updates attributes or acknowledges creation or deletion, the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @method dataWasUpdated @private @param {Class} type @param {DS.Model} record */ dataWasUpdated: function(type, record) { this.recordArrayManager.recordDidChange(record); }, // .............. // . PERSISTING . // .............. /** This method is called by `record.save`, and gets passed a resolver for the promise that `record.save` returns. It schedules saving to happen at the end of the run loop. @method scheduleSave @private @param {DS.Model} record @param {Resolver} resolver */ scheduleSave: function(record, resolver) { record.adapterWillCommit(); this._pendingSave.push([record, resolver]); once(this, 'flushPendingSave'); }, /** This method is called at the end of the run loop, and flushes any records passed into `scheduleSave` @method flushPendingSave @private */ flushPendingSave: function() { var pending = this._pendingSave.slice(); this._pendingSave = []; forEach(pending, function(tuple) { var record = tuple[0], resolver = tuple[1], adapter = this.adapterFor(record.constructor), operation; if (get(record, 'isNew')) { operation = 'createRecord'; } else if (get(record, 'isDeleted')) { operation = 'deleteRecord'; } else { operation = 'updateRecord'; } resolver.resolve(_commit(adapter, this, operation, record)); }, this); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is resolved. If the data provides a server-generated ID, it will update the record and the store's indexes. @method didSaveRecord @private @param {DS.Model} record the in-flight record @param {Object} data optional data (see above) */ didSaveRecord: function(record, data) { if (data) { // normalize relationship IDs into records data = normalizeRelationships(this, record.constructor, data, record); this.updateId(record, data); } record.adapterDidCommit(data); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected with a `DS.InvalidError`. @method recordWasInvalid @private @param {DS.Model} record @param {Object} errors */ recordWasInvalid: function(record, errors) { record.adapterDidInvalidate(errors); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected (with anything other than a `DS.InvalidError`). @method recordWasError @private @param {DS.Model} record */ recordWasError: function(record) { record.adapterDidError(); }, /** When an adapter's `createRecord`, `updateRecord` or `deleteRecord` resolves with data, this method extracts the ID from the supplied data. @method updateId @private @param {DS.Model} record @param {Object} data */ updateId: function(record, data) { var oldId = get(record, 'id'), id = coerceId(data.id); Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId); this.typeMapFor(record.constructor).idToRecord[id] = record; set(record, 'id', id); }, /** Returns a map of IDs to client IDs for a given type. @method typeMapFor @private @param type @return {Object} typeMap */ typeMapFor: function(type) { var typeMaps = get(this, 'typeMaps'), guid = Ember.guidFor(type), typeMap; typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: {}, records: [], metadata: {} }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {String or subclass of DS.Model} type @param {Object} data @param {Boolean} partial the data should be merged into the existing data, not replace it. */ _load: function(type, data, partial) { var id = coerceId(data.id), record = this.recordForId(type, id); record.setupData(data, partial); this.recordArrayManager.recordDidChange(record); return record; }, /** Returns a model class for a particular key. Used by methods that take a type key (like `find`, `createRecord`, etc.) @method modelFor @param {String or subclass of DS.Model} key @returns {subclass of DS.Model} */ modelFor: function(key) { var factory; if (typeof key === 'string') { var normalizedKey = this.container.normalize('model:' + key); factory = this.container.lookupFactory(normalizedKey); if (!factory) { throw new Ember.Error("No model was found for '" + key + "'"); } factory.typeKey = normalizedKey.split(':', 2)[1]; } else { // A factory already supplied. factory = key; } factory.store = this; return factory; }, /** Push some data for a given type into the store. This method expects normalized data: * The ID is a key named `id` (an ID is mandatory) * The names of attributes are the ones you used in your model's `DS.attr`s. * Your relationships must be: * represented as IDs or Arrays of IDs * represented as model instances * represented as URLs, under the `links` key For this model: ```js App.Person = DS.Model.extend({ firstName: DS.attr(), lastName: DS.attr(), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { id: 1, firstName: "Tom", lastName: "Dale", children: [1, 2, 3] } ``` To represent the children relationship as a URL: ```js { id: 1, firstName: "Tom", lastName: "Dale", links: { children: "/people/1/children" } } ``` If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. This method can be used both to push in brand new records, as well as to update existing records. @method push @param {String or subclass of DS.Model} type @param {Object} data @returns {DS.Model} the record that was created or updated. */ push: function(type, data, _partial) { // _partial is an internal param used by `update`. // If passed, it means that the data should be // merged into the existing data, not replace it. Ember.assert("You must include an `id` in a hash passed to `push`", data.id != null); type = this.modelFor(type); // normalize relationship IDs into records data = normalizeRelationships(this, type, data); this._load(type, data, _partial); return this.recordForId(type, data.id); }, /** Push some raw data into the store. The data will be automatically deserialized using the serializer for the `type` param. This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer. ```js App.ApplicationSerializer = DS.ActiveModelSerializer; var pushData = { posts: [ {id: 1, post_title: "Great post", comment_ids: [2]} ], comments: [ {id: 2, comment_body: "Insightful comment"} ] } store.pushPayload('post', pushData); ``` @method pushPayload @param {String} type @param {Object} payload @return {DS.Model} the record that was created or updated. */ pushPayload: function (type, payload) { var serializer; if (!payload) { payload = type; serializer = defaultSerializer(this.container); Ember.assert("You cannot use `store#pushPayload` without a type unless your default serializer defines `pushPayload`", serializer.pushPayload); } else { serializer = this.serializerFor(type); } serializer.pushPayload(this, payload); }, update: function(type, data) { Ember.assert("You must include an `id` in a hash passed to `update`", data.id != null); return this.push(type, data, true); }, /** If you have an Array of normalized data to push, you can call `pushMany` with the Array, and it will call `push` repeatedly for you. @method pushMany @param {String or subclass of DS.Model} type @param {Array} datas @return {Array} */ pushMany: function(type, datas) { return map(datas, function(data) { return this.push(type, data); }, this); }, /** If you have some metadata to set for a type you can call `metaForType`. @method metaForType @param {String or subclass of DS.Model} type @param {Object} metadata */ metaForType: function(type, metadata) { type = this.modelFor(type); Ember.merge(this.typeMapFor(type).metadata, metadata); }, /** Build a brand new record for a given type, ID, and initial data. @method buildRecord @private @param {subclass of DS.Model} type @param {String} id @param {Object} data @returns {DS.Model} record */ buildRecord: function(type, id, data) { var typeMap = this.typeMapFor(type), idToRecord = typeMap.idToRecord; Ember.assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]); // lookupFactory should really return an object that creates // instances with the injections applied var record = type._create({ id: id, store: this, container: this.container }); if (data) { record.setupData(data); } // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToRecord[id] = record; } typeMap.records.push(record); return record; }, // ............... // . DESTRUCTION . // ............... /** When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed. @method dematerializeRecord @private @param {DS.Model} record */ dematerializeRecord: function(record) { var type = record.constructor, typeMap = this.typeMapFor(type), id = get(record, 'id'); record.updateRecordArrays(); if (id) { delete typeMap.idToRecord[id]; } var loc = indexOf(typeMap.records, record); typeMap.records.splice(loc, 1); }, // ........................ // . RELATIONSHIP CHANGES . // ........................ addRelationshipChangeFor: function(childRecord, childKey, parentRecord, parentKey, change) { var clientId = childRecord.clientId, parentClientId = parentRecord ? parentRecord : parentRecord; var key = childKey + parentKey; var changes = this._relationshipChanges; if (!(clientId in changes)) { changes[clientId] = {}; } if (!(parentClientId in changes[clientId])) { changes[clientId][parentClientId] = {}; } if (!(key in changes[clientId][parentClientId])) { changes[clientId][parentClientId][key] = {}; } changes[clientId][parentClientId][key][change.changeType] = change; }, removeRelationshipChangeFor: function(clientRecord, childKey, parentRecord, parentKey, type) { var clientId = clientRecord.clientId, parentClientId = parentRecord ? parentRecord.clientId : parentRecord; var changes = this._relationshipChanges; var key = childKey + parentKey; if (!(clientId in changes) || !(parentClientId in changes[clientId]) || !(key in changes[clientId][parentClientId])){ return; } delete changes[clientId][parentClientId][key][type]; }, relationshipChangePairsFor: function(record){ var toReturn = []; if( !record ) { return toReturn; } //TODO(Igor) What about the other side var changesObject = this._relationshipChanges[record.clientId]; for (var objKey in changesObject){ if(changesObject.hasOwnProperty(objKey)){ for (var changeKey in changesObject[objKey]){ if(changesObject[objKey].hasOwnProperty(changeKey)){ toReturn.push(changesObject[objKey][changeKey]); } } } } return toReturn; }, // ...................... // . PER-TYPE ADAPTERS // ...................... /** Returns the adapter for a given type. @method adapterFor @private @param {subclass of DS.Model} type @returns DS.Adapter */ adapterFor: function(type) { var container = this.container, adapter; if (container) { adapter = container.lookup('adapter:' + type.typeKey) || container.lookup('adapter:application'); } return adapter || get(this, 'defaultAdapter'); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. /** Returns an instance of the serializer for a given type. For example, `serializerFor('person')` will return an instance of `App.PersonSerializer`. If no `App.PersonSerializer` is found, this method will look for an `App.ApplicationSerializer` (the default serializer for your entire application). If no `App.ApplicationSerializer` is found, it will fall back to an instance of `DS.JSONSerializer`. @method serializerFor @private @param {String} type the record to serialize @return {DS.Serializer} */ serializerFor: function(type) { type = this.modelFor(type); var adapter = this.adapterFor(type); return serializerFor(this.container, type.typeKey, adapter && adapter.defaultSerializer); } }); function normalizeRelationships(store, type, data, record) { type.eachRelationship(function(key, relationship) { // A link (usually a URL) was already provided in // normalized form if (data.links && data.links[key]) { if (record && relationship.options.async) { record._relationships[key] = null; } return; } var kind = relationship.kind, value = data[key]; if (value == null) { return; } if (kind === 'belongsTo') { deserializeRecordId(store, data, key, relationship, value); } else if (kind === 'hasMany') { deserializeRecordIds(store, data, key, relationship, value); addUnsavedRecords(record, key, value); } }); return data; } function deserializeRecordId(store, data, key, relationship, id) { if (isNone(id) || id instanceof DS.Model) { return; } var type; if (typeof id === 'number' || typeof id === 'string') { type = typeFor(relationship, key, data); data[key] = store.recordForId(type, id); } else if (typeof id === 'object') { // polymorphic data[key] = store.recordForId(id.type, id.id); } } function typeFor(relationship, key, data) { if (relationship.options.polymorphic) { return data[key + "Type"]; } else { return relationship.type; } } function deserializeRecordIds(store, data, key, relationship, ids) { for (var i=0, l=ids.length; i<l; i++) { deserializeRecordId(store, ids, i, relationship, ids[i]); } } // If there are any unsaved records that are in a hasMany they won't be // in the payload, so add them back in manually. function addUnsavedRecords(record, key, data) { if(record) { data.pushObjects(record.get(key).filterBy('isNew')); } } // Delegation to the adapter and promise management /** A `PromiseArray` is an object that acts like both an `Ember.Array` and a promise. When the promise is resolved the the resulting value will be set to the `PromiseArray`'s `content` property. This makes it easy to create data bindings with the `PromiseArray` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseArray = DS.PromiseArray.create({ promise: $.getJSON('/some/remote/data.json') }); promiseArray.get('length'); // 0 promiseArray.then(function() { promiseArray.get('length'); // 100 }); ``` @class PromiseArray @namespace DS @extends Ember.ArrayProxy @uses Ember.PromiseProxyMixin */ DS.PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin); /** A `PromiseObject` is an object that acts like both an `Ember.Object` and a promise. When the promise is resolved the the resulting value will be set to the `PromiseObject`'s `content` property. This makes it easy to create data bindings with the `PromiseObject` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript var promiseObject = DS.PromiseObject.create({ promise: $.getJSON('/some/remote/data.json') }); promiseObject.get('name'); // null promiseObject.then(function() { promiseObject.get('name'); // 'Tomster' }); ``` @class PromiseObject @namespace DS @extends Ember.ObjectProxy @uses Ember.PromiseProxyMixin */ DS.PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin); function promiseObject(promise) { return DS.PromiseObject.create({ promise: promise }); } function promiseArray(promise) { return DS.PromiseArray.create({ promise: promise }); } function isThenable(object) { return object && typeof object.then === 'function'; } function serializerFor(container, type, defaultSerializer) { return container.lookup('serializer:'+type) || container.lookup('serializer:application') || container.lookup('serializer:' + defaultSerializer) || container.lookup('serializer:-default'); } function defaultSerializer(container) { return container.lookup('serializer:application') || container.lookup('serializer:-default'); } function serializerForAdapter(adapter, type) { var serializer = adapter.serializer, defaultSerializer = adapter.defaultSerializer, container = adapter.container; if (container && serializer === undefined) { serializer = serializerFor(container, type.typeKey, defaultSerializer); } if (serializer === null || serializer === undefined) { serializer = { extract: function(store, type, payload) { return payload; } }; } return serializer; } function _find(adapter, store, type, id) { var promise = adapter.find(store, type, id), serializer = serializerForAdapter(adapter, type); return resolve(promise, "DS: Handle Adapter#find of " + type + " with id: " + id).then(function(payload) { Ember.assert("You made a request for a " + type.typeKey + " with id " + id + ", but the adapter's response did not have any data", payload); payload = serializer.extract(store, type, payload, id, 'find'); return store.push(type, payload); }, function(error) { var record = store.getById(type, id); record.notFound(); throw error; }, "DS: Extract payload of '" + type + "'"); } function _findMany(adapter, store, type, ids, owner) { var promise = adapter.findMany(store, type, ids, owner), serializer = serializerForAdapter(adapter, type); return resolve(promise, "DS: Handle Adapter#findMany of " + type).then(function(payload) { payload = serializer.extract(store, type, payload, null, 'findMany'); Ember.assert("The response from a findMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); store.pushMany(type, payload); }, null, "DS: Extract payload of " + type); } function _findHasMany(adapter, store, record, link, relationship) { var promise = adapter.findHasMany(store, record, link, relationship), serializer = serializerForAdapter(adapter, relationship.type); return resolve(promise, "DS: Handle Adapter#findHasMany of " + record + " : " + relationship.type).then(function(payload) { payload = serializer.extract(store, relationship.type, payload, null, 'findHasMany'); Ember.assert("The response from a findHasMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); var records = store.pushMany(relationship.type, payload); record.updateHasMany(relationship.key, records); }, null, "DS: Extract payload of " + record + " : hasMany " + relationship.type); } function _findBelongsTo(adapter, store, record, link, relationship) { var promise = adapter.findBelongsTo(store, record, link, relationship), serializer = serializerForAdapter(adapter, relationship.type); return resolve(promise, "DS: Handle Adapter#findBelongsTo of " + record + " : " + relationship.type).then(function(payload) { payload = serializer.extract(store, relationship.type, payload, null, 'findBelongsTo'); var record = store.push(relationship.type, payload); record.updateBelongsTo(relationship.key, record); return record; }, null, "DS: Extract payload of " + record + " : " + relationship.type); } function _findAll(adapter, store, type, sinceToken) { var promise = adapter.findAll(store, type, sinceToken), serializer = serializerForAdapter(adapter, type); return resolve(promise, "DS: Handle Adapter#findAll of " + type).then(function(payload) { payload = serializer.extract(store, type, payload, null, 'findAll'); Ember.assert("The response from a findAll must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); store.pushMany(type, payload); store.didUpdateAll(type); return store.all(type); }, null, "DS: Extract payload of findAll " + type); } function _findQuery(adapter, store, type, query, recordArray) { var promise = adapter.findQuery(store, type, query, recordArray), serializer = serializerForAdapter(adapter, type); return resolve(promise, "DS: Handle Adapter#findQuery of " + type).then(function(payload) { payload = serializer.extract(store, type, payload, null, 'findQuery'); Ember.assert("The response from a findQuery must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); recordArray.load(payload); return recordArray; }, null, "DS: Extract payload of findQuery " + type); } function _commit(adapter, store, operation, record) { var type = record.constructor, promise = adapter[operation](store, type, record), serializer = serializerForAdapter(adapter, type); Ember.assert("Your adapter's '" + operation + "' method must return a promise, but it returned " + promise, isThenable(promise)); return promise.then(function(payload) { if (payload) { payload = serializer.extract(store, type, payload, get(record, 'id'), operation); } store.didSaveRecord(record, payload); return record; }, function(reason) { if (reason instanceof DS.InvalidError) { store.recordWasInvalid(record, reason.errors); } else { store.recordWasError(record, reason); } throw reason; }, "DS: Extract and notify about " + operation + " completion of " + record); } })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; /* This file encapsulates the various states that a record can transition through during its lifecycle. */ /** ### State Each record has a `currentState` property that explicitly tracks what state a record is in at any given time. For instance, if a record is newly created and has not yet been sent to the adapter to be saved, it would be in the `root.loaded.created.uncommitted` state. If a record has had local modifications made to it that are in the process of being saved, the record would be in the `root.loaded.updated.inFlight` state. (These state paths will be explained in more detail below.) Events are sent by the record or its store to the record's `currentState` property. How the state reacts to these events is dependent on which state it is in. In some states, certain events will be invalid and will cause an exception to be raised. States are hierarchical and every state is a substate of the `RootState`. For example, a record can be in the `root.deleted.uncommitted` state, then transition into the `root.deleted.inFlight` state. If a child state does not implement an event handler, the state manager will attempt to invoke the event on all parent states until the root state is reached. The state hierarchy of a record is described in terms of a path string. You can determine a record's current state by getting the state's `stateName` property: ```javascript record.get('currentState.stateName'); //=> "root.created.uncommitted" ``` The hierarchy of valid states that ship with ember data looks like this: ```text * root * deleted * saved * uncommitted * inFlight * empty * loaded * created * uncommitted * inFlight * saved * updated * uncommitted * inFlight * loading ``` The `DS.Model` states are themselves stateless. What we mean is that, the hierarchical states that each of *those* points to is a shared data structure. For performance reasons, instead of each record getting its own copy of the hierarchy of states, each record points to this global, immutable shared instance. How does a state know which record it should be acting on? We pass the record instance into the state's event handlers as the first argument. The record passed as the first parameter is where you should stash state about the record if needed; you should never store data on the state object itself. ### Events and Flags A state may implement zero or more events and flags. #### Events Events are named functions that are invoked when sent to a record. The record will first look for a method with the given name on the current state. If no method is found, it will search the current state's parent, and then its grandparent, and so on until reaching the top of the hierarchy. If the root is reached without an event handler being found, an exception will be raised. This can be very helpful when debugging new features. Here's an example implementation of a state with a `myEvent` event handler: ```javascript aState: DS.State.create({ myEvent: function(manager, param) { console.log("Received myEvent with", param); } }) ``` To trigger this event: ```javascript record.send('myEvent', 'foo'); //=> "Received myEvent with foo" ``` Note that an optional parameter can be sent to a record's `send()` method, which will be passed as the second parameter to the event handler. Events should transition to a different state if appropriate. This can be done by calling the record's `transitionTo()` method with a path to the desired state. The state manager will attempt to resolve the state path relative to the current state. If no state is found at that path, it will attempt to resolve it relative to the current state's parent, and then its parent, and so on until the root is reached. For example, imagine a hierarchy like this: * created * uncommitted <-- currentState * inFlight * updated * inFlight If we are currently in the `uncommitted` state, calling `transitionTo('inFlight')` would transition to the `created.inFlight` state, while calling `transitionTo('updated.inFlight')` would transition to the `updated.inFlight` state. Remember that *only events* should ever cause a state transition. You should never call `transitionTo()` from outside a state's event handler. If you are tempted to do so, create a new event and send that to the state manager. #### Flags Flags are Boolean values that can be used to introspect a record's current state in a more user-friendly way than examining its state path. For example, instead of doing this: ```javascript var statePath = record.get('stateManager.currentPath'); if (statePath === 'created.inFlight') { doSomething(); } ``` You can say: ```javascript if (record.get('isNew') && record.get('isSaving')) { doSomething(); } ``` If your state does not set a value for a given flag, the value will be inherited from its parent (or the first place in the state hierarchy where it is defined). The current set of flags are defined below. If you want to add a new flag, in addition to the area below, you will also need to declare it in the `DS.Model` class. * [isEmpty](DS.Model.html#property_isEmpty) * [isLoading](DS.Model.html#property_isLoading) * [isLoaded](DS.Model.html#property_isLoaded) * [isDirty](DS.Model.html#property_isDirty) * [isSaving](DS.Model.html#property_isSaving) * [isDeleted](DS.Model.html#property_isDeleted) * [isNew](DS.Model.html#property_isNew) * [isValid](DS.Model.html#property_isValid) @namespace DS @class RootState */ var hasDefinedProperties = function(object) { // Ignore internal property defined by simulated `Ember.create`. var names = Ember.keys(object); var i, l, name; for (i = 0, l = names.length; i < l; i++ ) { name = names[i]; if (object.hasOwnProperty(name) && object[name]) { return true; } } return false; }; var didSetProperty = function(record, context) { if (context.value === context.originalValue) { delete record._attributes[context.name]; record.send('propertyWasReset', context.name); } else if (context.value !== context.oldValue) { record.send('becomeDirty'); } record.updateRecordArraysLater(); }; // Implementation notes: // // Each state has a boolean value for all of the following flags: // // * isLoaded: The record has a populated `data` property. When a // record is loaded via `store.find`, `isLoaded` is false // until the adapter sets it. When a record is created locally, // its `isLoaded` property is always true. // * isDirty: The record has local changes that have not yet been // saved by the adapter. This includes records that have been // created (but not yet saved) or deleted. // * isSaving: The record has been committed, but // the adapter has not yet acknowledged that the changes have // been persisted to the backend. // * isDeleted: The record was marked for deletion. When `isDeleted` // is true and `isDirty` is true, the record is deleted locally // but the deletion was not yet persisted. When `isSaving` is // true, the change is in-flight. When both `isDirty` and // `isSaving` are false, the change has persisted. // * isError: The adapter reported that it was unable to save // local changes to the backend. This may also result in the // record having its `isValid` property become false if the // adapter reported that server-side validations failed. // * isNew: The record was created on the client and the adapter // did not yet report that it was successfully saved. // * isValid: No client-side validations have failed and the // adapter did not report any server-side validation failures. // The dirty state is a abstract state whose functionality is // shared between the `created` and `updated` states. // // The deleted state shares the `isDirty` flag with the // subclasses of `DirtyState`, but with a very different // implementation. // // Dirty states have three child states: // // `uncommitted`: the store has not yet handed off the record // to be saved. // `inFlight`: the store has handed off the record to be saved, // but the adapter has not yet acknowledged success. // `invalid`: the record has invalid information and cannot be // send to the adapter yet. var DirtyState = { initialState: 'uncommitted', // FLAGS isDirty: true, // SUBSTATES // When a record first becomes dirty, it is `uncommitted`. // This means that there are local pending changes, but they // have not yet begun to be saved, and are not invalid. uncommitted: { // EVENTS didSetProperty: didSetProperty, propertyWasReset: function(record, name) { var stillDirty = false; for (var prop in record._attributes) { stillDirty = true; break; } if (!stillDirty) { record.send('rolledBack'); } }, pushedData: Ember.K, becomeDirty: Ember.K, willCommit: function(record) { record.transitionTo('inFlight'); }, reloadRecord: function(record, resolve) { resolve(get(record, 'store').reloadRecord(record)); }, rolledBack: function(record) { record.transitionTo('loaded.saved'); }, becameInvalid: function(record) { record.transitionTo('invalid'); }, rollback: function(record) { record.rollback(); } }, // Once a record has been handed off to the adapter to be // saved, it is in the 'in flight' state. Changes to the // record cannot be made during this window. inFlight: { // FLAGS isSaving: true, // EVENTS didSetProperty: didSetProperty, becomeDirty: Ember.K, pushedData: Ember.K, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { var dirtyType = get(this, 'dirtyType'); record.transitionTo('saved'); record.send('invokeLifecycleCallbacks', dirtyType); }, becameInvalid: function(record) { record.transitionTo('invalid'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // A record is in the `invalid` state when its client-side // invalidations have failed, or if the adapter has indicated // the the record failed server-side invalidations. invalid: { // FLAGS isValid: false, // EVENTS deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }, didSetProperty: function(record, context) { get(record, 'errors').remove(context.name); didSetProperty(record, context); }, becomeDirty: Ember.K, rolledBack: function(record) { get(record, 'errors').clear(); }, becameValid: function(record) { record.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('becameInvalid', record); } } }; // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. function deepClone(object) { var clone = {}, value; for (var prop in object) { value = object[prop]; if (value && typeof value === 'object') { clone[prop] = deepClone(value); } else { clone[prop] = value; } } return clone; } function mixin(original, hash) { for (var prop in hash) { original[prop] = hash[prop]; } return original; } function dirtyState(options) { var newState = deepClone(DirtyState); return mixin(newState, options); } var createdState = dirtyState({ dirtyType: 'created', // FLAGS isNew: true }); createdState.uncommitted.rolledBack = function(record) { record.transitionTo('deleted.saved'); }; var updatedState = dirtyState({ dirtyType: 'updated' }); createdState.uncommitted.deleteRecord = function(record) { record.clearRelationships(); record.transitionTo('deleted.saved'); }; createdState.uncommitted.rollback = function(record) { DirtyState.uncommitted.rollback.apply(this, arguments); record.transitionTo('deleted.saved'); }; createdState.uncommitted.propertyWasReset = Ember.K; updatedState.uncommitted.deleteRecord = function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }; var RootState = { // FLAGS isEmpty: false, isLoading: false, isLoaded: false, isDirty: false, isSaving: false, isDeleted: false, isNew: false, isValid: true, // DEFAULT EVENTS // Trying to roll back if you're not in the dirty state // doesn't change your state. For example, if you're in the // in-flight state, rolling back the record doesn't move // you out of the in-flight state. rolledBack: Ember.K, propertyWasReset: Ember.K, // SUBSTATES // A record begins its lifecycle in the `empty` state. // If its data will come from the adapter, it will // transition into the `loading` state. Otherwise, if // the record is being created on the client, it will // transition into the `created` state. empty: { isEmpty: true, // EVENTS loadingData: function(record, promise) { record._loadingPromise = promise; record.transitionTo('loading'); }, loadedData: function(record) { record.transitionTo('loaded.created.uncommitted'); record.suspendRelationshipObservers(function() { record.notifyPropertyChange('data'); }); }, pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); } }, // A record enters this state when the store asks // the adapter for its data. It remains in this state // until the adapter provides the requested data. // // Usually, this process is asynchronous, using an // XHR to retrieve the data. loading: { // FLAGS isLoading: true, exit: function(record) { record._loadingPromise = null; }, // EVENTS pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); set(record, 'isError', false); }, becameError: function(record) { record.triggerLater('becameError', record); }, notFound: function(record) { record.transitionTo('empty'); } }, // A record enters this state when its data is populated. // Most of a record's lifecycle is spent inside substates // of the `loaded` state. loaded: { initialState: 'saved', // FLAGS isLoaded: true, // SUBSTATES // If there are no local changes to a record, it remains // in the `saved` state. saved: { setup: function(record) { var attrs = record._attributes, isDirty = false; for (var prop in attrs) { if (attrs.hasOwnProperty(prop)) { isDirty = true; break; } } if (isDirty) { record.adapterDidDirty(); } }, // EVENTS didSetProperty: didSetProperty, pushedData: Ember.K, becomeDirty: function(record) { record.transitionTo('updated.uncommitted'); }, willCommit: function(record) { record.transitionTo('updated.inFlight'); }, reloadRecord: function(record, resolve) { resolve(get(record, 'store').reloadRecord(record)); }, deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }, unloadRecord: function(record) { // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); record.transitionTo('deleted.saved'); }, didCommit: function(record) { record.send('invokeLifecycleCallbacks', get(record, 'lastDirtyType')); }, // loaded.saved.notFound would be triggered by a failed // `reload()` on an unchanged record notFound: Ember.K }, // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: createdState, // A record is in this state if it has already been // saved to the server, but there are new local changes // that have not yet been saved. updated: updatedState }, // A record is in this state if it was deleted from the store. deleted: { initialState: 'uncommitted', dirtyType: 'deleted', // FLAGS isDeleted: true, isLoaded: true, isDirty: true, // TRANSITIONS setup: function(record) { record.updateRecordArrays(); }, // SUBSTATES // When a record is deleted, it enters the `start` // state. It will exit this state when the record // starts to commit. uncommitted: { // EVENTS willCommit: function(record) { record.transitionTo('inFlight'); }, rollback: function(record) { record.rollback(); }, becomeDirty: Ember.K, deleteRecord: Ember.K, rolledBack: function(record) { record.transitionTo('loaded.saved'); } }, // After a record starts committing, but // before the adapter indicates that the deletion // has saved to the server, a record is in the // `inFlight` substate of `deleted`. inFlight: { // FLAGS isSaving: true, // EVENTS // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { record.transitionTo('saved'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: { // FLAGS isDirty: false, setup: function(record) { var store = get(record, 'store'); store.dematerializeRecord(record); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('didDelete', record); record.triggerLater('didCommit', record); } } }, invokeLifecycleCallbacks: function(record, dirtyType) { if (dirtyType === 'created') { record.triggerLater('didCreate', record); } else { record.triggerLater('didUpdate', record); } record.triggerLater('didCommit', record); } }; function wireState(object, parent, name) { /*jshint proto:true*/ // TODO: Use Object.create and copy instead object = mixin(parent ? Ember.create(parent) : {}, object); object.parentState = parent; object.stateName = name; for (var prop in object) { if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; } if (typeof object[prop] === 'object') { object[prop] = wireState(object[prop], object, name + "." + prop); } } return object; } RootState = wireState(RootState, null, "root"); DS.RootState = RootState; })(); (function() { var get = Ember.get, isEmpty = Ember.isEmpty; /** @module ember-data */ /** Holds validation errors for a given record organized by attribute names. @class Errors @namespace DS @extends Ember.Object @uses Ember.Enumerable @uses Ember.Evented */ DS.Errors = Ember.Object.extend(Ember.Enumerable, Ember.Evented, { /** Register with target handler @method registerHandlers @param {Object} target @param {Function} becameInvalid @param {Function} becameValid */ registerHandlers: function(target, becameInvalid, becameValid) { this.on('becameInvalid', target, becameInvalid); this.on('becameValid', target, becameValid); }, /** @property errorsByAttributeName @type {Ember.MapWithDefault} @private */ errorsByAttributeName: Ember.reduceComputed("content", { initialValue: function() { return Ember.MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); }, addedItem: function(errors, error) { errors.get(error.attribute).pushObject(error); return errors; }, removedItem: function(errors, error) { errors.get(error.attribute).removeObject(error); return errors; } }), /** Returns errors for a given attribute @method errorsFor @param {String} attribute @returns {Array} */ errorsFor: function(attribute) { return get(this, 'errorsByAttributeName').get(attribute); }, /** */ messages: Ember.computed.mapBy('content', 'message'), /** @property content @type {Array} @private */ content: Ember.computed(function() { return Ember.A(); }), /** @method unknownProperty @private */ unknownProperty: function(attribute) { var errors = this.errorsFor(attribute); if (isEmpty(errors)) { return null; } return errors; }, /** @method nextObject @private */ nextObject: function(index, previousObject, context) { return get(this, 'content').objectAt(index); }, /** Total number of errors. @property length @type {Number} @readOnly */ length: Ember.computed.oneWay('content.length').readOnly(), /** @property isEmpty @type {Boolean} @readOnly */ isEmpty: Ember.computed.not('length').readOnly(), /** Adds error messages to a given attribute and sends `becameInvalid` event to the record. @method add @param {String} attribute @param {Array|String} messages */ add: function(attribute, messages) { var wasEmpty = get(this, 'isEmpty'); messages = this._findOrCreateMessages(attribute, messages); get(this, 'content').addObjects(messages); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (wasEmpty && !get(this, 'isEmpty')) { this.trigger('becameInvalid'); } }, /** @method _findOrCreateMessages @private */ _findOrCreateMessages: function(attribute, messages) { var errors = this.errorsFor(attribute); return Ember.makeArray(messages).map(function(message) { return errors.findBy('message', message) || { attribute: attribute, message: message }; }); }, /** Removes all error messages from the given attribute and sends `becameValid` event to the record if there no more errors left. @method remove @param {String} attribute */ remove: function(attribute) { if (get(this, 'isEmpty')) { return; } var content = get(this, 'content').rejectBy('attribute', attribute); get(this, 'content').setObjects(content); this.notifyPropertyChange(attribute); this.enumerableContentDidChange(); if (get(this, 'isEmpty')) { this.trigger('becameValid'); } }, /** Removes all error messages and sends `becameValid` event to the record. @method clear */ clear: function() { if (get(this, 'isEmpty')) { return; } get(this, 'content').clear(); this.enumerableContentDidChange(); this.trigger('becameValid'); }, /** Checks if there is error messages for the given attribute. @method has @param {String} attribute @returns {Boolean} true if there some errors on given attribute */ has: function(attribute) { return !isEmpty(this.errorsFor(attribute)); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set, merge = Ember.merge; var retrieveFromCurrentState = Ember.computed('currentState', function(key, value) { return get(get(this, 'currentState'), key); }).readOnly(); /** The model class that all Ember Data records descend from. @class Model @namespace DS @extends Ember.Object @uses Ember.Evented */ DS.Model = Ember.Object.extend(Ember.Evented, { /** If this property is `true` the record is in the `empty` state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the `loading` state if data needs to be fetched from the server or the `created` state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record. @property isEmpty @type {Boolean} @readOnly */ isEmpty: retrieveFromCurrentState, /** If this property is `true` the record is in the `loading` state. A record enters this state when the store asks the adapter for its data. It remains in this state until the adapter provides the requested data. @property isLoading @type {Boolean} @readOnly */ isLoading: retrieveFromCurrentState, /** If this property is `true` the record is in the `loaded` state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the `loaded` state. Example ```javascript var record = store.createRecord(App.Model); record.get('isLoaded'); // true store.find('model', 1).then(function(model) { model.get('isLoaded'); // true }); ``` @property isLoaded @type {Boolean} @readOnly */ isLoaded: retrieveFromCurrentState, /** If this property is `true` the record is in the `dirty` state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted. Example ```javascript var record = store.createRecord(App.Model); record.get('isDirty'); // true store.find('model', 1).then(function(model) { model.get('isDirty'); // false model.set('foo', 'some value'); model.set('isDirty'); // true }); ``` @property isDirty @type {Boolean} @readOnly */ isDirty: retrieveFromCurrentState, /** If this property is `true` the record is in the `saving` state. A record enters the saving state when `save` is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend. Example ```javascript var record = store.createRecord(App.Model); record.get('isSaving'); // false var promise = record.save(); record.get('isSaving'); // true promise.then(function() { record.get('isSaving'); // false }); ``` @property isSaving @type {Boolean} @readOnly */ isSaving: retrieveFromCurrentState, /** If this property is `true` the record is in the `deleted` state and has been marked for deletion. When `isDeleted` is true and `isDirty` is true, the record is deleted locally but the deletion was not yet persisted. When `isSaving` is true, the change is in-flight. When both `isDirty` and `isSaving` are false, the change has persisted. Example ```javascript var record = store.createRecord(App.Model); record.get('isDeleted'); // false record.deleteRecord(); record.get('isDeleted'); // true ``` @property isDeleted @type {Boolean} @readOnly */ isDeleted: retrieveFromCurrentState, /** If this property is `true` the record is in the `new` state. A record will be in the `new` state when it has been created on the client and the adapter has not yet report that it was successfully saved. Example ```javascript var record = store.createRecord(App.Model); record.get('isNew'); // true record.save().then(function(model) { model.get('isNew'); // false }); ``` @property isNew @type {Boolean} @readOnly */ isNew: retrieveFromCurrentState, /** If this property is `true` the record is in the `valid` state. A record will be in the `valid` state when no client-side validations have failed and the adapter did not report any server-side validation failures. @property isValid @type {Boolean} @readOnly */ isValid: retrieveFromCurrentState, /** If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are: - `created` The record has been created by the client and not yet saved to the adapter. - `updated` The record has been updated by the client and not yet saved to the adapter. - `deleted` The record has been deleted by the client and not yet saved to the adapter. Example ```javascript var record = store.createRecord(App.Model); record.get('dirtyType'); // 'created' ``` @property dirtyType @type {String} @readOnly */ dirtyType: retrieveFromCurrentState, /** If `true` the adapter reported that it was unable to save local changes to the backend. This may also result in the record having its `isValid` property become false if the adapter reported that server-side validations failed. Example ```javascript record.get('isError'); // false record.set('foo', 'invalid value'); record.save().then(null, function() { record.get('isError'); // true }); ``` @property isError @type {Boolean} @readOnly */ isError: false, /** If `true` the store is attempting to reload the record form the adapter. Example ```javascript record.get('isReloading'); // false record.reload(); record.get('isReloading'); // true ``` @property isReloading @type {Boolean} @readOnly */ isReloading: false, /** The `clientId` property is a transient numerical identifier generated at runtime by the data store. It is important primarily because newly created objects may not yet have an externally generated id. @property clientId @private @type {Number|String} */ clientId: null, /** All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute. ```javascript var record = store.createRecord(App.Model); record.get('id'); // null store.find('model', 1).then(function(model) { model.get('id'); // '1' }); ``` @property id @type {String} */ id: null, transaction: null, /** @property currentState @private @type {Object} */ currentState: null, /** When the record is in the `invalid` state this object will contain any errors returned by the adapter. When present the errors hash typically contains keys corresponding to the invalid property names and values which are an array of error messages. ```javascript record.get('errors.length'); // 0 record.set('foo', 'invalid value'); record.save().then(null, function() { record.get('errors').get('foo'); // ['foo should be a number.'] }); ``` @property errors @type {Object} */ errors: null, /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. `serialize` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method serialize @param {Object} options @returns {Object} an object whose values are primitive JSON values only */ serialize: function(options) { var store = get(this, 'store'); return store.serialize(this, options); }, /** Use [DS.JSONSerializer](DS.JSONSerializer.html) to get the JSON representation of a record. `toJSON` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method toJSON @param {Object} options @returns {Object} A JSON representation of the object. */ toJSON: function(options) { // container is for lazy transform lookups var serializer = DS.JSONSerializer.create({ container: this.container }); return serializer.serialize(this, options); }, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: Ember.K, /** Fired when the record is updated. @event didUpdate */ didUpdate: Ember.K, /** Fired when the record is created. @event didCreate */ didCreate: Ember.K, /** Fired when the record is deleted. @event didDelete */ didDelete: Ember.K, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: Ember.K, /** Fired when the record enters the error state. @event becameError */ becameError: Ember.K, /** @property data @private @type {Object} */ data: Ember.computed(function() { this._data = this._data || {}; return this._data; }).property(), _data: null, init: function() { set(this, 'currentState', DS.RootState.empty); var errors = DS.Errors.create(); errors.registerHandlers(this, function() { this.send('becameInvalid'); }, function() { this.send('becameValid'); }); set(this, 'errors', errors); this._super(); this._setup(); }, _setup: function() { this._changesToSync = {}; this._deferredTriggers = []; this._data = {}; this._attributes = {}; this._inFlightAttributes = {}; this._relationships = {}; }, /** @method send @private @param {String} name @param {Object} context */ send: function(name, context) { var currentState = get(this, 'currentState'); if (!currentState[name]) { this._unhandledEvent(currentState, name, context); } return currentState[name](this, context); }, /** @method transitionTo @private @param {String} name */ transitionTo: function(name) { // POSSIBLE TODO: Remove this code and replace with // always having direct references to state objects var pivotName = name.split(".", 1), currentState = get(this, 'currentState'), state = currentState; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state.hasOwnProperty(pivotName)); var path = name.split("."); var setups = [], enters = [], i, l; for (i=0, l=path.length; i<l; i++) { state = state[path[i]]; if (state.enter) { enters.push(state); } if (state.setup) { setups.push(state); } } for (i=0, l=enters.length; i<l; i++) { enters[i].enter(this); } set(this, 'currentState', state); for (i=0, l=setups.length; i<l; i++) { setups[i].setup(this); } this.updateRecordArraysLater(); }, _unhandledEvent: function(state, name, context) { var errorMessage = "Attempted to handle event `" + name + "` "; errorMessage += "on " + String(this) + " while in state "; errorMessage += state.stateName + ". "; if (context !== undefined) { errorMessage += "Called with " + Ember.inspect(context) + "."; } throw new Ember.Error(errorMessage); }, withTransaction: function(fn) { var transaction = get(this, 'transaction'); if (transaction) { fn(transaction); } }, /** @method loadingData @private @param {Promise} promise */ loadingData: function(promise) { this.send('loadingData', promise); }, /** @method loadedData @private */ loadedData: function() { this.send('loadedData'); }, /** @method notFound @private */ notFound: function() { this.send('notFound'); }, /** @method pushedData @private */ pushedData: function() { this.send('pushedData'); }, /** Marks the record as deleted but does not save it. You must call `save` afterwards if you want to persist it. You might use this method if you want to allow the user to still `rollback()` a delete after it was made. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { softDelete: function() { this.get('model').deleteRecord(); }, confirm: function() { this.get('model').save(); }, undo: function() { this.get('model').rollback(); } } }); ``` @method deleteRecord */ deleteRecord: function() { this.send('deleteRecord'); }, /** Same as `deleteRecord`, but saves the record immediately. Example ```javascript App.ModelDeleteRoute = Ember.Route.extend({ actions: { delete: function() { var controller = this.controller; this.get('model').destroyRecord().then(function() { controller.transitionToRoute('model.index'); }); } } }); ``` @method destroyRecord @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ destroyRecord: function() { this.deleteRecord(); return this.save(); }, /** @method unloadRecord @private */ unloadRecord: function() { Ember.assert("You can only unload a loaded, non-dirty record.", !get(this, 'isDirty')); this.send('unloadRecord'); }, /** @method clearRelationships @private */ clearRelationships: function() { this.eachRelationship(function(name, relationship) { if (relationship.kind === 'belongsTo') { set(this, name, null); } else if (relationship.kind === 'hasMany') { var hasMany = this._relationships[relationship.name]; if (hasMany) { hasMany.clear(); } } }, this); }, /** @method updateRecordArrays @private */ updateRecordArrays: function() { this._updatingRecordArraysLater = false; get(this, 'store').dataWasUpdated(this.constructor, this); }, /** Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. Example ```javascript App.Mascot = DS.Model.extend({ name: attr('string') }); var person = store.createRecord('person'); person.changedAttributes(); // {} person.set('name', 'Tomster'); person.changedAttributes(); // {name: [undefined, 'Tomster']} ``` @method changedAttributes @return {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function() { var oldData = get(this, '_data'), newData = get(this, '_attributes'), diffData = {}, prop; for (prop in newData) { diffData[prop] = [oldData[prop], newData[prop]]; } return diffData; }, /** @method adapterWillCommit @private */ adapterWillCommit: function() { this.send('willCommit'); }, /** If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. @method adapterDidCommit */ adapterDidCommit: function(data) { set(this, 'isError', false); if (data) { this._data = data; } else { Ember.mixin(this._data, this._inFlightAttributes); } this._inFlightAttributes = {}; this.send('didCommit'); this.updateRecordArraysLater(); if (!data) { return; } this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, /** @method adapterDidDirty @private */ adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, dataDidChange: Ember.observer(function() { this.reloadHasManys(); }, 'data'), reloadHasManys: function() { var relationships = get(this.constructor, 'relationshipsByName'); this.updateRecordArraysLater(); relationships.forEach(function(name, relationship) { if (this._data.links && this._data.links[name]) { return; } if (relationship.kind === 'hasMany') { this.hasManyDidChange(relationship.key); } }, this); }, hasManyDidChange: function(key) { var hasMany = this._relationships[key]; if (hasMany) { var records = this._data[key] || []; set(hasMany, 'content', Ember.A(records)); set(hasMany, 'isLoaded', true); hasMany.trigger('didLoad'); } }, /** @method updateRecordArraysLater @private */ updateRecordArraysLater: function() { // quick hack (something like this could be pushed into run.once if (this._updatingRecordArraysLater) { return; } this._updatingRecordArraysLater = true; Ember.run.schedule('actions', this, this.updateRecordArrays); }, /** @method setupData @private @param {Object} data @param {Boolean} partial the data should be merged into the existing data, not replace it. */ setupData: function(data, partial) { if (partial) { Ember.merge(this._data, data); } else { this._data = data; } var relationships = this._relationships; this.eachRelationship(function(name, rel) { if (data.links && data.links[name]) { return; } if (rel.options.async) { relationships[name] = null; } }); if (data) { this.pushedData(); } this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, materializeId: function(id) { set(this, 'id', id); }, materializeAttributes: function(attributes) { Ember.assert("Must pass a hash of attributes to materializeAttributes", !!attributes); merge(this._data, attributes); }, materializeAttribute: function(name, value) { this._data[name] = value; }, /** @method updateHasMany @private @param {String} name @param {Array} records */ updateHasMany: function(name, records) { this._data[name] = records; this.hasManyDidChange(name); }, /** @method updateBelongsTo @private @param {String} name @param {DS.Model} record */ updateBelongsTo: function(name, record) { this._data[name] = record; }, /** If the model `isDirty` this function will discard any unsaved changes Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollback(); record.get('name'); // 'Untitled Document' ``` @method rollback */ rollback: function() { this._attributes = {}; if (get(this, 'isError')) { this._inFlightAttributes = {}; set(this, 'isError', false); } if (!get(this, 'isValid')) { this._inFlightAttributes = {}; } this.send('rolledBack'); this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, toStringExtension: function() { return get(this, 'id'); }, /** The goal of this method is to temporarily disable specific observers that take action in response to application changes. This allows the system to make changes (such as materialization and rollback) that should not trigger secondary behavior (such as setting an inverse relationship or marking records as dirty). The specific implementation will likely change as Ember proper provides better infrastructure for suspending groups of observers, and if Array observation becomes more unified with regular observers. @method suspendRelationshipObservers @private @param callback @param binding */ suspendRelationshipObservers: function(callback, binding) { var observers = get(this.constructor, 'relationshipNames').belongsTo; var self = this; try { this._suspendedRelationships = true; Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() { Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() { callback.call(binding || self); }); }); } finally { this._suspendedRelationships = false; } }, /** Save the record and persist any changes to the record to an extenal source via the adapter. Example ```javascript record.set('name', 'Tomster'); record.save().then(function(){ // Success callback }, function() { // Error callback }); ``` @method save @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ save: function() { var promiseLabel = "DS: Model#save " + this; var resolver = Ember.RSVP.defer(promiseLabel); this.get('store').scheduleSave(this, resolver); this._inFlightAttributes = this._attributes; this._attributes = {}; return DS.PromiseObject.create({ promise: resolver.promise }); }, /** Reload the record from the adapter. This will only work if the record has already finished loading and has not yet been modified (`isLoaded` but not `isDirty`, or `isSaving`). Example ```javascript App.ModelViewRoute = Ember.Route.extend({ actions: { reload: function() { this.get('model').reload(); } } }); ``` @method reload @return {Promise} a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error. */ reload: function() { set(this, 'isReloading', true); var record = this; var promiseLabel = "DS: Model#reload of " + this; var promise = new Ember.RSVP.Promise(function(resolve){ record.send('reloadRecord', resolve); }, promiseLabel).then(function() { record.set('isReloading', false); record.set('isError', false); return record; }, function(reason) { record.set('isError', true); throw reason; }, "DS: Model#reload complete, update flags"); return DS.PromiseObject.create({ promise: promise }); }, // FOR USE DURING COMMIT PROCESS adapterDidUpdateAttribute: function(attributeName, value) { // If a value is passed in, update the internal attributes and clear // the attribute cache so it picks up the new value. Otherwise, // collapse the current value into the internal attributes because // the adapter has acknowledged it. if (value !== undefined) { this._data[attributeName] = value; this.notifyPropertyChange(attributeName); } else { this._data[attributeName] = this._inFlightAttributes[attributeName]; } this.updateRecordArraysLater(); }, /** @method adapterDidInvalidate @private */ adapterDidInvalidate: function(errors) { var recordErrors = get(this, 'errors'); function addError(name) { if (errors[name]) { recordErrors.add(name, errors[name]); } } this.eachAttribute(addError); this.eachRelationship(addError); }, /** @method adapterDidError @private */ adapterDidError: function() { this.send('becameError'); set(this, 'isError', true); }, /** Override the default event firing from Ember.Evented to also call methods with the given name. @method trigger @private @param name */ trigger: function(name) { Ember.tryInvoke(this, name, [].slice.call(arguments, 1)); this._super.apply(this, arguments); }, triggerLater: function() { if (this._deferredTriggers.push(arguments) !== 1) { return; } Ember.run.schedule('actions', this, '_triggerDeferredTriggers'); }, _triggerDeferredTriggers: function() { for (var i=0, l=this._deferredTriggers.length; i<l; i++) { this.trigger.apply(this, this._deferredTriggers[i]); } this._deferredTriggers.length = 0; } }); DS.Model.reopenClass({ /** Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model instances from within the store, but if end users accidentally call `create()` (instead of `createRecord()`), we can raise an error. @method _create @private @static */ _create: DS.Model.create, /** Override the class' `create()` method to raise an error. This prevents end users from inadvertently calling `create()` instead of `createRecord()`. The store is still able to create instances by calling the `_create()` method. To create an instance of a `DS.Model` use [store.createRecord](DS.Store.html#method_createRecord). @method create @private @static */ create: function() { throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); } }); })(); (function() { /** @module ember-data */ var get = Ember.get; /** @class Model @namespace DS */ DS.Model.reopenClass({ /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are the meta object for the property. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); var attributes = Ember.get(App.Person, 'attributes') attributes.forEach(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @property attributes @static @type {Ember.Map} @readOnly */ attributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isAttribute) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id'); meta.name = name; map.set(name, meta); } }); return map; }), /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); var transformedAttributes = Ember.get(App.Person, 'transformedAttributes') transformedAttributes.forEach(function(field, type) { console.log(field, type); }); // prints: // lastName string // birthday date ``` @property transformedAttributes @static @type {Ember.Map} @readOnly */ transformedAttributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachAttribute(function(key, meta) { if (meta.type) { map.set(key, meta.type); } }); return map; }), /** Iterates through the attributes of the model, calling the passed function on each attribute. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, meta); ``` - `name` the name of the current property in the iteration - `meta` the meta object for the attribute property in the iteration Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr('string'), lastName: attr('string'), birthday: attr('date') }); App.Person.eachAttribute(function(name, meta) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @method eachAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachAttribute: function(callback, binding) { get(this, 'attributes').forEach(function(name, meta) { callback.call(binding, name, meta); }, binding); }, /** Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type. The callback method you provide should have the following signature (all parameters are optional): ```javascript function(name, type); ``` - `name` the name of the current property in the iteration - `type` a string containing the name of the type of transformed applied to the attribute Note that in addition to a callback, you can also pass an optional target object that will be set as `this` on the context. Example ```javascript App.Person = DS.Model.extend({ firstName: attr(), lastName: attr('string'), birthday: attr('date') }); App.Person.eachTransformedAttribute(function(name, type) { console.log(name, type); }); // prints: // lastName string // birthday date ``` @method eachTransformedAttribute @param {Function} callback The callback to execute @param {Object} [target] The target object to use @static */ eachTransformedAttribute: function(callback, binding) { get(this, 'transformedAttributes').forEach(function(name, type) { callback.call(binding, name, type); }); } }); DS.Model.reopen({ eachAttribute: function(callback, binding) { this.constructor.eachAttribute(callback, binding); } }); function getDefaultValue(record, options, key) { if (typeof options.defaultValue === "function") { return options.defaultValue(); } else { return options.defaultValue; } } function hasValue(record, key) { return record._attributes.hasOwnProperty(key) || record._inFlightAttributes.hasOwnProperty(key) || record._data.hasOwnProperty(key); } function getValue(record, key) { if (record._attributes.hasOwnProperty(key)) { return record._attributes[key]; } else if (record._inFlightAttributes.hasOwnProperty(key)) { return record._inFlightAttributes[key]; } else { return record._data[key]; } } /** `DS.attr` defines an attribute on a [DS.Model](DS.Model.html). By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed. Ember Data ships with four basic transform types: `string`, `number`, `boolean` and `date`. You can define your own transforms by subclassing [DS.Transform](DS.Transform.html). `DS.attr` takes an optional hash as a second parameter, currently supported options are: - `defaultValue`: Pass a string or a function to be called to set the attribute to a default value if none is supplied. Example ```javascript var attr = DS.attr; App.User = DS.Model.extend({ username: attr('string'), email: attr('string'), verified: attr('boolean', {defaultValue: false}) }); ``` @namespace @method attr @for DS @param {String} type the attribute type @param {Object} options a hash of options @return {Attribute} */ DS.attr = function(type, options) { options = options || {}; var meta = { type: type, isAttribute: true, options: options }; return Ember.computed(function(key, value) { if (arguments.length > 1) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id'); var oldValue = this._attributes[key] || this._inFlightAttributes[key] || this._data[key]; this.send('didSetProperty', { name: key, oldValue: oldValue, originalValue: this._data[key], value: value }); this._attributes[key] = value; return value; } else if (hasValue(this, key)) { return getValue(this, key); } else { return getDefaultValue(this, options, key); } // `data` is never set directly. However, it may be // invalidated from the state manager's setData // event. }).property('data').meta(meta); }; })(); (function() { /** @module ember-data */ })(); (function() { /** @module ember-data */ /** An AttributeChange object is created whenever a record's attribute changes value. It is used to track changes to a record between transaction commits. @class AttributeChange @namespace DS @private @constructor */ var AttributeChange = DS.AttributeChange = function(options) { this.record = options.record; this.store = options.store; this.name = options.name; this.value = options.value; this.oldValue = options.oldValue; }; AttributeChange.createChange = function(options) { return new AttributeChange(options); }; AttributeChange.prototype = { sync: function() { if (this.value !== this.oldValue) { this.record.send('becomeDirty'); this.record.updateRecordArraysLater(); } // TODO: Use this object in the commit process this.destroy(); }, /** If the AttributeChange is destroyed (either by being rolled back or being committed), remove it from the list of pending changes on the record. @method destroy */ destroy: function() { delete this.record._changesToSync[this.name]; } }; })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var forEach = Ember.EnumerableUtils.forEach; /** @class RelationshipChange @namespace DS @private @constructor */ DS.RelationshipChange = function(options) { this.parentRecord = options.parentRecord; this.childRecord = options.childRecord; this.firstRecord = options.firstRecord; this.firstRecordKind = options.firstRecordKind; this.firstRecordName = options.firstRecordName; this.secondRecord = options.secondRecord; this.secondRecordKind = options.secondRecordKind; this.secondRecordName = options.secondRecordName; this.changeType = options.changeType; this.store = options.store; this.committed = {}; }; /** @class RelationshipChangeAdd @namespace DS @private @constructor */ DS.RelationshipChangeAdd = function(options){ DS.RelationshipChange.call(this, options); }; /** @class RelationshipChangeRemove @namespace DS @private @constructor */ DS.RelationshipChangeRemove = function(options){ DS.RelationshipChange.call(this, options); }; DS.RelationshipChange.create = function(options) { return new DS.RelationshipChange(options); }; DS.RelationshipChangeAdd.create = function(options) { return new DS.RelationshipChangeAdd(options); }; DS.RelationshipChangeRemove.create = function(options) { return new DS.RelationshipChangeRemove(options); }; DS.OneToManyChange = {}; DS.OneToNoneChange = {}; DS.ManyToNoneChange = {}; DS.OneToOneChange = {}; DS.ManyToManyChange = {}; DS.RelationshipChange._createChange = function(options){ if(options.changeType === "add"){ return DS.RelationshipChangeAdd.create(options); } if(options.changeType === "remove"){ return DS.RelationshipChangeRemove.create(options); } }; DS.RelationshipChange.determineRelationshipType = function(recordType, knownSide){ var knownKey = knownSide.key, key, otherKind; var knownKind = knownSide.kind; var inverse = recordType.inverseFor(knownKey); if (inverse){ key = inverse.name; otherKind = inverse.kind; } if (!inverse){ return knownKind === "belongsTo" ? "oneToNone" : "manyToNone"; } else{ if(otherKind === "belongsTo"){ return knownKind === "belongsTo" ? "oneToOne" : "manyToOne"; } else{ return knownKind === "belongsTo" ? "oneToMany" : "manyToMany"; } } }; DS.RelationshipChange.createChange = function(firstRecord, secondRecord, store, options){ // Get the type of the child based on the child's client ID var firstRecordType = firstRecord.constructor, changeType; changeType = DS.RelationshipChange.determineRelationshipType(firstRecordType, options); if (changeType === "oneToMany"){ return DS.OneToManyChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToOne"){ return DS.OneToManyChange.createChange(secondRecord, firstRecord, store, options); } else if (changeType === "oneToNone"){ return DS.OneToNoneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToNone"){ return DS.ManyToNoneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "oneToOne"){ return DS.OneToOneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToMany"){ return DS.ManyToManyChange.createChange(firstRecord, secondRecord, store, options); } }; DS.OneToNoneChange.createChange = function(childRecord, parentRecord, store, options) { var key = options.key; var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, store: store, changeType: options.changeType, firstRecordName: key, firstRecordKind: "belongsTo" }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.ManyToNoneChange.createChange = function(childRecord, parentRecord, store, options) { var key = options.key; var change = DS.RelationshipChange._createChange({ parentRecord: childRecord, childRecord: parentRecord, secondRecord: childRecord, store: store, changeType: options.changeType, secondRecordName: options.key, secondRecordKind: "hasMany" }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.ManyToManyChange.createChange = function(childRecord, parentRecord, store, options) { // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. var key = options.key; var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "hasMany", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.OneToOneChange.createChange = function(childRecord, parentRecord, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; } else if (options.key) { key = options.key; } else { Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false); } var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "belongsTo", secondRecordKind: "belongsTo", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.OneToOneChange.maintainInvariant = function(options, store, childRecord, key){ if (options.changeType === "add" && store.recordIsMaterialized(childRecord)) { var oldParent = get(childRecord, key); if (oldParent){ var correspondingChange = DS.OneToOneChange.createChange(childRecord, oldParent, store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childRecord, key, options.parentRecord , null, correspondingChange); correspondingChange.sync(); } } }; DS.OneToManyChange.createChange = function(childRecord, parentRecord, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; DS.OneToManyChange.maintainInvariant( options, store, childRecord, key ); } else if (options.key) { key = options.key; } else { Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false); } var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "belongsTo", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, change.getSecondRecordName(), change); return change; }; DS.OneToManyChange.maintainInvariant = function(options, store, childRecord, key){ if (options.changeType === "add" && childRecord) { var oldParent = get(childRecord, key); if (oldParent){ var correspondingChange = DS.OneToManyChange.createChange(childRecord, oldParent, store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childRecord, key, options.parentRecord, correspondingChange.getSecondRecordName(), correspondingChange); correspondingChange.sync(); } } }; /** @class RelationshipChange @namespace DS */ DS.RelationshipChange.prototype = { getSecondRecordName: function() { var name = this.secondRecordName, parent; if (!name) { parent = this.secondRecord; if (!parent) { return; } var childType = this.firstRecord.constructor; var inverse = childType.inverseFor(this.firstRecordName); this.secondRecordName = inverse.name; } return this.secondRecordName; }, /** Get the name of the relationship on the belongsTo side. @method getFirstRecordName @return {String} */ getFirstRecordName: function() { var name = this.firstRecordName; return name; }, /** @method destroy @private */ destroy: function() { var childRecord = this.childRecord, belongsToName = this.getFirstRecordName(), hasManyName = this.getSecondRecordName(), store = this.store; store.removeRelationshipChangeFor(childRecord, belongsToName, this.parentRecord, hasManyName, this.changeType); }, getSecondRecord: function(){ return this.secondRecord; }, /** @method getFirstRecord @private */ getFirstRecord: function() { return this.firstRecord; }, coalesce: function(){ var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecord); forEach(relationshipPairs, function(pair){ var addedChange = pair["add"]; var removedChange = pair["remove"]; if(addedChange && removedChange) { addedChange.destroy(); removedChange.destroy(); } }); } }; DS.RelationshipChangeAdd.prototype = Ember.create(DS.RelationshipChange.create({})); DS.RelationshipChangeRemove.prototype = Ember.create(DS.RelationshipChange.create({})); // the object is a value, and not a promise function isValue(object) { return typeof object === 'object' && (!object.then || typeof object.then !== 'function'); } DS.RelationshipChangeAdd.prototype.changeType = "add"; DS.RelationshipChangeAdd.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); if (secondRecord instanceof DS.Model && firstRecord instanceof DS.Model) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, firstRecord); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ var relationship = get(secondRecord, secondRecordName); if (isValue(relationship)) { relationship.addObject(firstRecord); } }); } } if (firstRecord instanceof DS.Model && secondRecord instanceof DS.Model && get(firstRecord, firstRecordName) !== secondRecord) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, secondRecord); }); } else if(this.firstRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ var relationship = get(firstRecord, firstRecordName); if (isValue(relationship)) { relationship.addObject(secondRecord); } }); } } this.coalesce(); }; DS.RelationshipChangeRemove.prototype.changeType = "remove"; DS.RelationshipChangeRemove.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); if (secondRecord instanceof DS.Model && firstRecord instanceof DS.Model) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, null); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ var relationship = get(secondRecord, secondRecordName); if (isValue(relationship)) { relationship.removeObject(firstRecord); } }); } } if (firstRecord instanceof DS.Model && get(firstRecord, firstRecordName)) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, null); }); } else if(this.firstRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ var relationship = get(firstRecord, firstRecordName); if (isValue(relationship)) { relationship.removeObject(secondRecord); } }); } } this.coalesce(); }; })(); (function() { /** @module ember-data */ })(); (function() { var get = Ember.get, set = Ember.set, isNone = Ember.isNone; /** @module ember-data */ function asyncBelongsTo(type, options, meta) { return Ember.computed(function(key, value) { var data = get(this, 'data'), store = get(this, 'store'), promiseLabel = "DS: Async belongsTo " + this + " : " + key; if (arguments.length === 2) { Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof store.modelFor(type)); return value === undefined ? null : DS.PromiseObject.create({ promise: Ember.RSVP.resolve(value, promiseLabel) }); } var link = data.links && data.links[key], belongsTo = data[key]; if(!isNone(belongsTo)) { var promise = store.fetchRecord(belongsTo) || Ember.RSVP.resolve(belongsTo, promiseLabel); return DS.PromiseObject.create({ promise: promise}); } else if (link) { var resolver = Ember.RSVP.defer("DS: Async belongsTo (link) " + this + " : " + key); store.findBelongsTo(this, link, meta, resolver); return DS.PromiseObject.create({ promise: resolver.promise }); } else { return null; } }).property('data').meta(meta); } /** `DS.belongsTo` is used to define One-To-One and One-To-Many relationships on a [DS.Model](DS.Model.html). `DS.belongsTo` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses) #### One-To-One To declare a one-to-one relationship between two models, use `DS.belongsTo`: ```javascript App.User = DS.Model.extend({ profile: DS.belongsTo('profile') }); App.Profile = DS.Model.extend({ user: DS.belongsTo('user') }); ``` #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` @namespace @method belongsTo @for DS @param {String or DS.Model} type the model type of the relationship @param {Object} options a hash of options @return {Ember.computed} relationship */ DS.belongsTo = function(type, options) { if (typeof type === 'object') { options = type; type = undefined; } else { Ember.assert("The first argument DS.belongsTo must be a model type or string, like DS.belongsTo(App.Person)", !!type && (typeof type === 'string' || DS.Model.detect(type))); } options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo' }; if (options.async) { return asyncBelongsTo(type, options, meta); } return Ember.computed(function(key, value) { var data = get(this, 'data'), store = get(this, 'store'), belongsTo, typeClass; if (typeof type === 'string') { typeClass = store.modelFor(type); } else { typeClass = type; } if (arguments.length === 2) { Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof typeClass); return value === undefined ? null : value; } belongsTo = data[key]; if (isNone(belongsTo)) { return null; } store.fetchRecord(belongsTo); return belongsTo; }).property('data').meta(meta); }; /** These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. @class Model @namespace DS */ DS.Model.reopen({ /** @method belongsToWillChange @private @static @param record @param key */ belongsToWillChange: Ember.beforeObserver(function(record, key) { if (get(record, 'isLoaded')) { var oldParent = get(record, key); if (oldParent) { var store = get(record, 'store'), change = DS.RelationshipChange.createChange(record, oldParent, store, { key: key, kind: "belongsTo", changeType: "remove" }); change.sync(); this._changesToSync[key] = change; } } }), /** @method belongsToDidChange @private @static @param record @param key */ belongsToDidChange: Ember.immediateObserver(function(record, key) { if (get(record, 'isLoaded')) { var newParent = get(record, key); if (newParent) { var store = get(record, 'store'), change = DS.RelationshipChange.createChange(record, newParent, store, { key: key, kind: "belongsTo", changeType: "add" }); change.sync(); } } delete this._changesToSync[key]; }) }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set, setProperties = Ember.setProperties; function asyncHasMany(type, options, meta) { return Ember.computed(function(key, value) { var relationship = this._relationships[key], promiseLabel = "DS: Async hasMany " + this + " : " + key; if (!relationship) { var resolver = Ember.RSVP.defer(promiseLabel); relationship = buildRelationship(this, key, options, function(store, data) { var link = data.links && data.links[key]; var rel; if (link) { rel = store.findHasMany(this, link, meta, resolver); } else { rel = store.findMany(this, data[key], meta.type, resolver); } // cache the promise so we can use it // when we come back and don't need to rebuild // the relationship. set(rel, 'promise', resolver.promise); return rel; }); } var promise = relationship.get('promise').then(function() { return relationship; }, null, "DS: Async hasMany records received"); return DS.PromiseArray.create({ promise: promise }); }).property('data').meta(meta); } function buildRelationship(record, key, options, callback) { var rels = record._relationships; if (rels[key]) { return rels[key]; } var data = get(record, 'data'), store = get(record, 'store'); var relationship = rels[key] = callback.call(record, store, data); return setProperties(relationship, { owner: record, name: key, isPolymorphic: options.polymorphic }); } function hasRelationship(type, options) { options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany' }; if (options.async) { return asyncHasMany(type, options, meta); } return Ember.computed(function(key, value) { return buildRelationship(this, key, options, function(store, data) { var records = data[key]; Ember.assert("You looked up the '" + key + "' relationship on '" + this + "' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", Ember.A(records).everyProperty('isEmpty', false)); return store.findMany(this, data[key], meta.type); }); }).property('data').meta(meta); } /** `DS.hasMany` is used to define One-To-Many and Many-To-Many relationships on a [DS.Model](DS.Model.html). `DS.hasMany` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model. #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); ``` #### Many-To-Many To declare a many-to-many relationship between two models, use `DS.hasMany`: ```javascript App.Post = DS.Model.extend({ tags: DS.hasMany('tag') }); App.Tag = DS.Model.extend({ posts: DS.hasMany('post') }); ``` #### Explicit Inverses Ember Data will do its best to discover which relationships map to one another. In the one-to-many code above, for example, Ember Data can figure out that changing the `comments` relationship should update the `post` relationship on the inverse because post is the only relationship to that model. However, sometimes you may have multiple `belongsTo`/`hasManys` for the same type. You can specify which property on the related model is the inverse using `DS.hasMany`'s `inverse` option: ```javascript var belongsTo = DS.belongsTo, hasMany = DS.hasMany; App.Comment = DS.Model.extend({ onePost: belongsTo('post'), twoPost: belongsTo('post'), redPost: belongsTo('post'), bluePost: belongsTo('post') }); App.Post = DS.Model.extend({ comments: hasMany('comment', { inverse: 'redPost' }) }); ``` You can also specify an inverse on a `belongsTo`, which works how you'd expect. @namespace @method hasMany @for DS @param {String or DS.Model} type the model type of the relationship @param {Object} options a hash of options @return {Ember.computed} relationship */ DS.hasMany = function(type, options) { if (typeof type === 'object') { options = type; type = undefined; } return hasRelationship(type, options); }; })(); (function() { var get = Ember.get, set = Ember.set; /** @module ember-data */ /* This file defines several extensions to the base `DS.Model` class that add support for one-to-many relationships. */ /** @class Model @namespace DS */ DS.Model.reopen({ /** This Ember.js hook allows an object to be notified when a property is defined. In this case, we use it to be notified when an Ember Data user defines a belongs-to relationship. In that case, we need to set up observers for each one, allowing us to track relationship changes and automatically reflect changes in the inverse has-many array. This hook passes the class being set up, as well as the key and value being defined. So, for example, when the user does this: ```javascript DS.Model.extend({ parent: DS.belongsTo('user') }); ``` This hook would be called with "parent" as the key and the computed property returned by `DS.belongsTo` as the value. @method didDefineProperty @param proto @param key @param value */ didDefineProperty: function(proto, key, value) { // Check if the value being set is a computed property. if (value instanceof Ember.Descriptor) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value.meta(); if (meta.isRelationship && meta.kind === 'belongsTo') { Ember.addObserver(proto, key, null, 'belongsToDidChange'); Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange'); } meta.parentType = proto.constructor; } } }); /* These DS.Model extensions add class methods that provide relationship introspection abilities about relationships. A note about the computed properties contained here: **These properties are effectively sealed once called for the first time.** To avoid repeatedly doing expensive iteration over a model's fields, these values are computed once and then cached for the remainder of the runtime of your application. If your application needs to modify a class after its initial definition (for example, using `reopen()` to add additional attributes), make sure you do it before using your model with the store, which uses these properties extensively. */ DS.Model.reopenClass({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: ```javascript App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); ``` Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. @method typeForRelationship @static @param {String} name the name of the relationship @return {subclass of DS.Model} the type of the relationship, or undefined */ typeForRelationship: function(name) { var relationship = get(this, 'relationshipsByName').get(name); return relationship && relationship.type; }, inverseFor: function(name) { var inverseType = this.typeForRelationship(name); if (!inverseType) { return null; } var options = this.metaForProperty(name).options; if (options.inverse === null) { return null; } var inverseName, inverseKind; if (options.inverse) { inverseName = options.inverse; inverseKind = Ember.get(inverseType, 'relationshipsByName').get(inverseName).kind; } else { var possibleRelationships = findPossibleInverses(this, inverseType); if (possibleRelationships.length === 0) { return null; } Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ". Look at http://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", possibleRelationships.length === 1); inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } function findPossibleInverses(type, inverseType, possibleRelationships) { possibleRelationships = possibleRelationships || []; var relationshipMap = get(inverseType, 'relationships'); if (!relationshipMap) { return; } var relationships = relationshipMap.get(type); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationshipMap.get(type)); } if (type.superclass) { findPossibleInverses(type.superclass, inverseType, possibleRelationships); } return possibleRelationships; } return { type: inverseType, name: inverseName, kind: inverseKind }; }, /** The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type. For example, given the following model definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This computed property would return a map describing these relationships, like this: ```javascript var relationships = Ember.get(App.Blog, 'relationships'); relationships.get(App.User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(App.Post); //=> [ { name: 'posts', kind: 'hasMany' } ] ``` @property relationships @static @type Ember.Map @readOnly */ relationships: Ember.computed(function() { var map = new Ember.MapWithDefault({ defaultValue: function() { return []; } }); // Loop through each computed property on the class this.eachComputedProperty(function(name, meta) { // If the computed property is a relationship, add // it to the map. if (meta.isRelationship) { if (typeof meta.type === 'string') { meta.type = this.store.modelFor(meta.type); } var relationshipsForType = map.get(meta.type); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }), /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipNames = Ember.get(App.Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] ``` @property relationshipNames @static @type Object @readOnly */ relationshipNames: Ember.computed(function() { var names = { hasMany: [], belongsTo: [] }; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { names[meta.kind].push(name); } }); return names; }), /** An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relatedTypes = Ember.get(App.Blog, 'relatedTypes'); //=> [ App.User, App.Post ] ``` @property relatedTypes @static @type Ember.Array @readOnly */ relatedTypes: Ember.computed(function() { var type, types = Ember.A(); // Loop through each computed property on the class, // and create an array of the unique types involved // in relationships this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { type = meta.type; if (typeof type === 'string') { type = get(this, type, false) || this.store.modelFor(type); } Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", type); if (!types.contains(type)) { Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!type); types.push(type); } } }); return types; }), /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: App.User } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: App.User } ``` @property relationshipsByName @static @type Ember.Map @readOnly */ relationshipsByName: Ember.computed(function() { var map = Ember.Map.create(), type; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; type = meta.type; if (!type && meta.kind === 'hasMany') { type = Ember.String.singularize(name); } else if (!type) { type = name; } if (typeof type === 'string') { meta.type = this.store.modelFor(type); } map.set(name, meta); } }); return map; }), /** A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships. For example: ```javascript App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post'), title: DS.attr('string') }); var fields = Ember.get(App.Blog, 'fields'); fields.forEach(function(field, kind) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute ``` @property fields @static @type Ember.Map @readOnly */ fields: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { map.set(name, meta.kind); } else if (meta.isAttribute) { map.set(name, 'attribute'); } }); return map; }), /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { get(this, 'relationshipsByName').forEach(function(name, relationship) { callback.call(binding, name, relationship); }); }, /** Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model. @method eachRelatedType @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelatedType: function(callback, binding) { get(this, 'relatedTypes').forEach(function(type) { callback.call(binding, type); }); } }); DS.Model.reopen({ /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { this.constructor.eachRelationship(callback, binding); } }); })(); (function() { /** @module ember-data */ })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var forEach = Ember.EnumerableUtils.forEach; /** @class RecordArrayManager @namespace DS @private @extends Ember.Object */ DS.RecordArrayManager = Ember.Object.extend({ init: function() { this.filteredRecordArrays = Ember.MapWithDefault.create({ defaultValue: function() { return []; } }); this.changedRecords = []; }, recordDidChange: function(record) { if (this.changedRecords.push(record) !== 1) { return; } Ember.run.schedule('actions', this, this.updateRecordArrays); }, recordArraysForRecord: function(record) { record._recordArrays = record._recordArrays || Ember.OrderedSet.create(); return record._recordArrays; }, /** This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter, or when a record has changed. It updates all record arrays that a record belongs to. To avoid thrashing, it only runs at most once per run loop. @method updateRecordArrays @param {Class} type @param {Number|String} clientId */ updateRecordArrays: function() { forEach(this.changedRecords, function(record) { if (get(record, 'isDeleted')) { this._recordWasDeleted(record); } else { this._recordWasChanged(record); } }, this); this.changedRecords.length = 0; }, _recordWasDeleted: function (record) { var recordArrays = record._recordArrays; if (!recordArrays) { return; } forEach(recordArrays, function(array) { array.removeRecord(record); }); }, _recordWasChanged: function (record) { var type = record.constructor, recordArrays = this.filteredRecordArrays.get(type), filter; forEach(recordArrays, function(array) { filter = get(array, 'filterFunction'); this.updateRecordArray(array, filter, type, record); }, this); // loop through all manyArrays containing an unloaded copy of this // clientId and notify them that the record was loaded. var manyArrays = record._loadingRecordArrays; if (manyArrays) { for (var i=0, l=manyArrays.length; i<l; i++) { manyArrays[i].loadedRecord(); } record._loadingRecordArrays = []; } }, /** Update an individual filter. @method updateRecordArray @param {DS.FilteredRecordArray} array @param {Function} filter @param {Class} type @param {Number|String} clientId */ updateRecordArray: function(array, filter, type, record) { var shouldBeInArray; if (!filter) { shouldBeInArray = true; } else { shouldBeInArray = filter(record); } var recordArrays = this.recordArraysForRecord(record); if (shouldBeInArray) { recordArrays.add(array); array.addRecord(record); } else if (!shouldBeInArray) { recordArrays.remove(array); array.removeRecord(record); } }, /** This method is invoked if the `filterFunction` property is changed on a `DS.FilteredRecordArray`. It essentially re-runs the filter from scratch. This same method is invoked when the filter is created in th first place. @method updateFilter @param array @param type @param filter */ updateFilter: function(array, type, filter) { var typeMap = this.store.typeMapFor(type), records = typeMap.records, record; for (var i=0, l=records.length; i<l; i++) { record = records[i]; if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) { this.updateRecordArray(array, filter, type, record); } } }, /** Create a `DS.ManyArray` for a type and list of record references, and index the `ManyArray` under each reference. This allows us to efficiently remove records from `ManyArray`s when they are deleted. @method createManyArray @param {Class} type @param {Array} references @return {DS.ManyArray} */ createManyArray: function(type, records) { var manyArray = DS.ManyArray.create({ type: type, content: records, store: this.store }); forEach(records, function(record) { var arrays = this.recordArraysForRecord(record); arrays.add(manyArray); }, this); return manyArray; }, /** Create a `DS.RecordArray` for a type and register it for updates. @method createRecordArray @param {Class} type @return {DS.RecordArray} */ createRecordArray: function(type) { var array = DS.RecordArray.create({ type: type, content: Ember.A(), store: this.store, isLoaded: true }); this.registerFilteredRecordArray(array, type); return array; }, /** Create a `DS.FilteredRecordArray` for a type and register it for updates. @method createFilteredRecordArray @param {Class} type @param {Function} filter @return {DS.FilteredRecordArray} */ createFilteredRecordArray: function(type, filter) { var array = DS.FilteredRecordArray.create({ type: type, content: Ember.A(), store: this.store, manager: this, filterFunction: filter }); this.registerFilteredRecordArray(array, type, filter); return array; }, /** Create a `DS.AdapterPopulatedRecordArray` for a type with given query. @method createAdapterPopulatedRecordArray @param {Class} type @param {Object} query @return {DS.AdapterPopulatedRecordArray} */ createAdapterPopulatedRecordArray: function(type, query) { return DS.AdapterPopulatedRecordArray.create({ type: type, query: query, content: Ember.A(), store: this.store }); }, /** Register a RecordArray for a given type to be backed by a filter function. This will cause the array to update automatically when records of that type change attribute values or states. @method registerFilteredRecordArray @param {DS.RecordArray} array @param {Class} type @param {Function} filter */ registerFilteredRecordArray: function(array, type, filter) { var recordArrays = this.filteredRecordArrays.get(type); recordArrays.push(array); this.updateFilter(array, type, filter); }, // Internally, we maintain a map of all unloaded IDs requested by // a ManyArray. As the adapter loads data into the store, the // store notifies any interested ManyArrays. When the ManyArray's // total number of loading records drops to zero, it becomes // `isLoaded` and fires a `didLoad` event. registerWaitingRecordArray: function(record, array) { var loadingRecordArrays = record._loadingRecordArrays || []; loadingRecordArrays.push(array); record._loadingRecordArrays = loadingRecordArrays; } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var map = Ember.ArrayPolyfills.map; var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; /** A `DS.InvalidError` is used by an adapter to signal the external API was unable to process a request because the content was not semantically correct or meaningful per the API. Usually this means a record failed some form of server side validation. When a promise from an adapter is rejected with a `DS.InvalidError` the record will transition to the `invalid` state and the errors will be set to the `errors` property on the record. Example ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"]; return new DS.InvalidError(jsonErrors); } else { return error; } } }); ``` @class InvalidError @namespace DS */ DS.InvalidError = function(errors) { var tmp = Error.prototype.constructor.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors)); this.errors = errors; for (var i=0, l=errorProps.length; i<l; i++) { this[errorProps[i]] = tmp[errorProps[i]]; } }; DS.InvalidError.prototype = Ember.create(Error.prototype); /** An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. Typically the adapter is not invoked directly instead its functionality is accessed through the `store`. ### Creating an Adapter First, create a new subclass of `DS.Adapter`: ```javascript App.MyAdapter = DS.Adapter.extend({ // ...your code here }); ``` To tell your store which adapter to use, set its `adapter` property: ```javascript App.store = DS.Store.create({ adapter: 'MyAdapter' }); ``` `DS.Adapter` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `find()` * `createRecord()` * `updateRecord()` * `deleteRecord()` * `findAll()` * `findQuery()` To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods: * `findMany()` For an example implementation, see `DS.RESTAdapter`, the included REST adapter. @class Adapter @namespace DS @extends Ember.Object */ DS.Adapter = Ember.Object.extend({ /** If you would like your adapter to use a custom serializer you can set the `defaultSerializer` property to be the name of the custom serializer. Note the `defaultSerializer` serializer has a lower priority then a model specific serializer (i.e. `PostSerializer`) or the `application` serializer. ```javascript var DjangoAdapter = DS.Adapter.extend({ defaultSerializer: 'django' }); ``` @property defaultSerializer @type {String} */ /** The `find()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `find()` being called, you should query your persistence layer for a record with the given ID. Once found, you can asynchronously call the store's `push()` method to push the record into the store. Here is an example `find` implementation: ```javascript App.ApplicationAdapter = DS.Adapter.extend({ find: function(store, type, id) { var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @return {Promise} promise */ find: Ember.required(Function), /** The `findAll()` method is called when you call `find` on the store without an ID (i.e. `store.find('post')`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findAll: function(store, type, sinceToken) { var url = type; var query = { since: sinceToken }; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: null, /** This method is called when you call `find` on the store with a query object as the second parameter (i.e. `store.find('person', { page: 1 })`). Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findQuery: function(store, type, query) { var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, query).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: null, /** If the globally unique IDs for your records should be generated on the client, implement the `generateIdForRecord()` method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's `primaryKey`. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls `didCreateRecord()`. Only implement this method if you intend to generate record IDs on the client-side. The `generateIdForRecord()` method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter: ```javascript generateIdForRecord: function(store, record) { var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision(); return uuid; } ``` @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record @return {String|Number} id */ generateIdForRecord: null, /** Proxies to the serializer's `serialize` method. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var url = type; // ... } }); ``` @method serialize @param {DS.Model} record @param {Object} options @return {Object} serialized record */ serialize: function(record, options) { return get(record, 'store').serializerFor(record.constructor.typeKey).serialize(record, options); }, /** Implement this method in a subclass to handle the creation of new records. Serializes the record and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ createRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'POST', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ createRecord: Ember.required(Function), /** Implement this method in a subclass to handle the updating of a record. Serializes the record update and send it to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ updateRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var id = record.get('id'); var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'PUT', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ updateRecord: Ember.required(Function), /** Implement this method in a subclass to handle the deletion of a record. Sends a delete request for the record to the server. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ deleteRecord: function(store, type, record) { var data = this.serialize(record, { includeId: true }); var id = record.get('id'); var url = [type, id].join('/'); return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.ajax({ type: 'DELETE', url: url, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record @return {Promise} promise */ deleteRecord: Ember.required(Function), /** Find multiple records at once. By default, it loops over the provided ids and calls `find` on each. May be overwritten to improve performance and reduce the number of server requests. Example ```javascript App.ApplicationAdapter = DS.Adapter.extend({ findMany: function(store, type, ids) { var url = type; return new Ember.RSVP.Promise(function(resolve, reject) { jQuery.getJSON(url, {ids: ids}).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method findMany @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the records @param {Array} ids @return {Promise} promise */ findMany: function(store, type, ids) { var promises = map.call(ids, function(id) { return this.find(store, type, id); }, this); return Ember.RSVP.all(promises); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, fmt = Ember.String.fmt, indexOf = Ember.EnumerableUtils.indexOf; var counter = 0; /** `DS.FixtureAdapter` is an adapter that loads records from memory. Its primarily used for development and testing. You can also use `DS.FixtureAdapter` while working on the API but are not ready to integrate yet. It is a fully functioning adapter. All CRUD methods are implemented. You can also implement query logic that a remote system would do. Its possible to do develop your entire application with `DS.FixtureAdapter`. For information on how to use the `FixtureAdapter` in your application please see the [FixtureAdapter guide](/guides/models/the-fixture-adapter/). @class FixtureAdapter @namespace DS @extends DS.Adapter */ DS.FixtureAdapter = DS.Adapter.extend({ // by default, fixtures are already in normalized form serializer: null, /** If `simulateRemoteResponse` is `true` the `FixtureAdapter` will wait a number of milliseconds before resolving promises with the fixture values. The wait time can be configured via the `latency` property. @property simulateRemoteResponse @type {Boolean} @default true */ simulateRemoteResponse: true, /** By default the `FixtureAdapter` will simulate a wait of the `latency` milliseconds before resolving promises with the fixture values. This behavior can be turned off via the `simulateRemoteResponse` property. @property latency @type {Number} @default 50 */ latency: 50, /** Implement this method in order to provide data associated with a type @method fixturesForType @param {Subclass of DS.Model} type @return {Array} */ fixturesForType: function(type) { if (type.FIXTURES) { var fixtures = Ember.A(type.FIXTURES); return fixtures.map(function(fixture){ var fixtureIdType = typeof fixture.id; if(fixtureIdType !== "number" && fixtureIdType !== "string"){ throw new Error(fmt('the id property must be defined as a number or string for fixture %@', [fixture])); } fixture.id = fixture.id + ''; return fixture; }); } return null; }, /** Implement this method in order to query fixtures data @method queryFixtures @param {Array} fixture @param {Object} query @param {Subclass of DS.Model} type @return {Promise|Array} */ queryFixtures: function(fixtures, query, type) { Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.'); }, /** @method updateFixtures @param {Subclass of DS.Model} type @param {Array} fixture */ updateFixtures: function(type, fixture) { if(!type.FIXTURES) { type.FIXTURES = []; } var fixtures = type.FIXTURES; this.deleteLoadedFixture(type, fixture); fixtures.push(fixture); }, /** Implement this method in order to provide json for CRUD methods @method mockJSON @param {Subclass of DS.Model} type @param {DS.Model} record */ mockJSON: function(store, type, record) { return store.serializerFor(type).serialize(record, { includeId: true }); }, /** @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record @return {String} id */ generateIdForRecord: function(store) { return "fixture-" + counter++; }, /** @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @return {Promise} promise */ find: function(store, type, id) { var fixtures = this.fixturesForType(type), fixture; Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); if (fixtures) { fixture = Ember.A(fixtures).findProperty('id', id); } if (fixture) { return this.simulateRemoteCall(function() { return fixture; }, this); } }, /** @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @return {Promise} promise */ findMany: function(store, type, ids) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); if (fixtures) { fixtures = fixtures.filter(function(item) { return indexOf(ids, item.id) !== -1; }); } if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @return {Promise} promise */ findAll: function(store, type) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); return this.simulateRemoteCall(function() { return fixtures; }, this); }, /** @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ findQuery: function(store, type, query, array) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); fixtures = this.queryFixtures(fixtures, query, type); if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ createRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ updateRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @return {Promise} promise */ deleteRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.deleteLoadedFixture(type, fixture); return this.simulateRemoteCall(function() { // no payload in a deletion return null; }); }, /* @method deleteLoadedFixture @private @param type @param record */ deleteLoadedFixture: function(type, record) { var existingFixture = this.findExistingFixture(type, record); if(existingFixture) { var index = indexOf(type.FIXTURES, existingFixture); type.FIXTURES.splice(index, 1); return true; } }, /* @method findExistingFixture @private @param type @param record */ findExistingFixture: function(type, record) { var fixtures = this.fixturesForType(type); var id = get(record, 'id'); return this.findFixtureById(fixtures, id); }, /* @method findFixtureById @private @param fixtures @param id */ findFixtureById: function(fixtures, id) { return Ember.A(fixtures).find(function(r) { if(''+get(r, 'id') === ''+id) { return true; } else { return false; } }); }, /* @method simulateRemoteCall @private @param callback @param context */ simulateRemoteCall: function(callback, context) { var adapter = this; return new Ember.RSVP.Promise(function(resolve) { if (get(adapter, 'simulateRemoteResponse')) { // Schedule with setTimeout Ember.run.later(function() { resolve(callback.call(context)); }, get(adapter, 'latency')); } else { // Asynchronous, but at the of the runloop with zero latency Ember.run.schedule('actions', null, function() { resolve(callback.call(context)); }); } }, "DS: FixtureAdapter#simulateRemoteCall"); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var forEach = Ember.ArrayPolyfills.forEach; var map = Ember.ArrayPolyfills.map; function coerceId(id) { return id == null ? null : id+''; } /** Normally, applications will use the `RESTSerializer` by implementing the `normalize` method and individual normalizations under `normalizeHash`. This allows you to do whatever kind of munging you need, and is especially useful if your server is inconsistent and you need to do munging differently for many different kinds of responses. See the `normalize` documentation for more information. ## Across the Board Normalization There are also a number of hooks that you might find useful to defined across-the-board rules for your payload. These rules will be useful if your server is consistent, or if you're building an adapter for an infrastructure service, like Parse, and want to encode service conventions. For example, if all of your keys are underscored and all-caps, but otherwise consistent with the names you use in your models, you can implement across-the-board rules for how to convert an attribute name in your model to a key in your JSON. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` You can also implement `keyForRelationship`, which takes the name of the relationship as the first parameter, and the kind of relationship (`hasMany` or `belongsTo`) as the second parameter. @class RESTSerializer @namespace DS @extends DS.JSONSerializer */ DS.RESTSerializer = DS.JSONSerializer.extend({ /** If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, given the following json where the the `IDs` under `"comments"` are provided as `_id` instead of `id`. ```javascript { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "_id": 1, "body": "FIRST" }, { "_id": 2, "body": "Rails is unagi" }] } ``` You use `normalizeHash` to normalize just the comments: ```javascript App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is usually just the original key that was in the original payload. However, key names will be impacted by any modifications done in the `normalizePayload` method. The `DS.RESTSerializer`'s default implementation makes no changes to the payload keys. @property normalizeHash @type {Object} @default undefined */ /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. For example, if you have a payload that looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "id": 1, "body": "FIRST" }, { "id": 2, "body": "Rails is unagi" }] } ``` The `normalize` method will be called three times: * With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }` * With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }` * With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }` You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, if the `IDs` under `"comments"` are provided as `_id` instead of `id`, you can specify how to normalize just the comments: ```js App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is just the original key that was in the original payload. @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @returns {Object} */ normalize: function(type, hash, prop) { this.normalizeId(hash); this.normalizeAttributes(type, hash); this.normalizeRelationships(type, hash); this.normalizeUsingDeclaredMapping(type, hash); if (this.normalizeHash && this.normalizeHash[prop]) { this.normalizeHash[prop](hash); } return this._super(type, hash, prop); }, /** You can use this method to normalize all payloads, regardless of whether they represent single records or an array. For example, you might want to remove some extraneous data from the payload: ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ normalizePayload: function(type, payload) { delete payload.version; delete payload.status; return payload; } }); ``` @method normalizePayload @param {subclass of DS.Model} type @param {Object} hash @returns {Object} the normalized payload */ normalizePayload: function(type, payload) { return payload; }, /** @method normalizeId @private */ normalizeId: function(hash) { var primaryKey = get(this, 'primaryKey'); if (primaryKey === 'id') { return; } hash.id = hash[primaryKey]; delete hash[primaryKey]; }, /** @method normalizeUsingDeclaredMapping @private */ normalizeUsingDeclaredMapping: function(type, hash) { var attrs = get(this, 'attrs'), payloadKey, key; if (attrs) { for (key in attrs) { payloadKey = attrs[key]; if (payloadKey && payloadKey.key) { payloadKey = payloadKey.key; } if (typeof payloadKey === 'string') { hash[key] = hash[payloadKey]; delete hash[payloadKey]; } } } }, /** @method normalizeAttributes @private */ normalizeAttributes: function(type, hash) { var payloadKey, key; if (this.keyForAttribute) { type.eachAttribute(function(key) { payloadKey = this.keyForAttribute(key); if (key === payloadKey) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { var payloadKey, key; if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { payloadKey = this.keyForRelationship(key, relationship.kind); if (key === payloadKey) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** Called when the server has returned a payload representing a single record, such as in response to a `find` or `save`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for post 1: ```js { "id": 1, "title": "Rails is omakase", "_embedded": { "comment": [{ "_id": 1, "comment_title": "FIRST" }, { "_id": 2, "comment_title": "Rails is unagi" }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type extractSingle: function(store, type, payload, id, requestType) { var comments = payload._embedded.comment; delete payload._embedded; payload = { comments: comments, post: payload }; return this._super(store, type, payload, id, requestType); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractSingle`, the built-in implementation will find the primary record in your normalized payload and push the remaining records into the store. The primary record is the single hash found under `post` or the first element of the `posts` array. The primary record has special meaning when the record is being created for the first time or updated (`createRecord` or `updateRecord`). In particular, it will update the properties of the record that was saved. @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String} id @param {'find'|'createRecord'|'updateRecord'|'deleteRecord'} requestType @returns {Object} the primary response to the original request */ extractSingle: function(store, primaryType, payload, recordId, requestType) { payload = this.normalizePayload(primaryType, payload); var primaryTypeName = primaryType.typeKey, primaryRecord; for (var prop in payload) { var typeName = this.typeForRoot(prop), type = store.modelFor(typeName), isPrimary = type.typeKey === primaryTypeName; // legacy support for singular resources if (isPrimary && Ember.typeOf(payload[prop]) !== "array" ) { primaryRecord = this.normalize(primaryType, payload[prop], prop); continue; } /*jshint loopfunc:true*/ forEach.call(payload[prop], function(hash) { var typeName = this.typeForRoot(prop), type = store.modelFor(typeName), typeSerializer = store.serializerFor(type); hash = typeSerializer.normalize(type, hash, prop); var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord, isUpdatedRecord = isPrimary && coerceId(hash.id) === recordId; // find the primary record. // // It's either: // * the record with the same ID as the original request // * in the case of a newly created record that didn't have an ID, the first // record in the Array if (isFirstCreatedRecord || isUpdatedRecord) { primaryRecord = hash; } else { store.push(typeName, hash); } }, this); } return primaryRecord; }, /** Called when the server has returned a payload representing multiple records, such as in response to a `findAll` or `findQuery`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for all posts: ```js { "_embedded": { "post": [{ "id": 1, "title": "Rails is omakase" }, { "id": 2, "title": "The Parley Letter" }], "comment": [{ "_id": 1, "comment_title": "Rails is unagi" "post_id": 1 }, { "_id": 2, "comment_title": "Don't tread on me", "post_id": 2 }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type // and the comments are listed under a post's `comments` key. extractArray: function(store, type, payload, id, requestType) { var posts = payload._embedded.post; var comments = []; var postCache = {}; posts.forEach(function(post) { post.comments = []; postCache[post.id] = post; }); payload._embedded.comment.forEach(function(comment) { comments.push(comment); postCache[comment.post_id].comments.push(comment); delete comment.post_id; } payload = { comments: comments, posts: payload }; return this._super(store, type, payload, id, requestType); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractArray`, the built-in implementation will find the primary array in your normalized payload and push the remaining records into the store. The primary array is the array found under `posts`. The primary record has special meaning when responding to `findQuery` or `findHasMany`. In particular, the primary array will become the list of records in the record array that kicked off the request. If your primary array contains secondary (embedded) records of the same type, you cannot place these into the primary array `posts`. Instead, place the secondary items into an underscore prefixed property `_posts`, which will push these items into the store and will not affect the resulting query. @method extractArray @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {'findAll'|'findMany'|'findHasMany'|'findQuery'} requestType @returns {Array} The primary array that was returned in response to the original query. */ extractArray: function(store, primaryType, payload) { payload = this.normalizePayload(primaryType, payload); var primaryTypeName = primaryType.typeKey, primaryArray; for (var prop in payload) { var typeKey = prop, forcedSecondary = false; if (prop.charAt(0) === '_') { forcedSecondary = true; typeKey = prop.substr(1); } var typeName = this.typeForRoot(typeKey), type = store.modelFor(typeName), typeSerializer = store.serializerFor(type), isPrimary = (!forcedSecondary && (type.typeKey === primaryTypeName)); /*jshint loopfunc:true*/ var normalizedArray = map.call(payload[prop], function(hash) { return typeSerializer.normalize(type, hash, prop); }, this); if (isPrimary) { primaryArray = normalizedArray; } else { store.pushMany(typeName, normalizedArray); } } return primaryArray; }, /** This method allows you to push a payload containing top-level collections of records organized per type. ```js { "posts": [{ "id": "1", "title": "Rails is omakase", "author", "1", "comments": [ "1" ] }], "comments": [{ "id": "1", "body": "FIRST" }], "users": [{ "id": "1", "name": "@d2h" }] } ``` It will first normalize the payload, so you can use this to push in data streaming in from your server structured the same way that fetches and saves are structured. @method pushPayload @param {DS.Store} store @param {Object} payload */ pushPayload: function(store, payload) { payload = this.normalizePayload(null, payload); for (var prop in payload) { var typeName = this.typeForRoot(prop), type = store.modelFor(typeName); /*jshint loopfunc:true*/ var normalizedArray = map.call(Ember.makeArray(payload[prop]), function(hash) { return this.normalize(type, hash, prop); }, this); store.pushMany(typeName, normalizedArray); } }, /** You can use this method to normalize the JSON root keys returned into the model type expected by your store. For example, your server may return underscored root keys rather than the expected camelcased versions. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ typeForRoot: function(root) { var camelized = Ember.String.camelize(root); return Ember.String.singularize(camelized); } }); ``` @method typeForRoot @param {String} root @returns {String} the model's typeKey */ typeForRoot: function(root) { return Ember.String.singularize(root); }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```js App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```js { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(post, options) { var json = { POST_TTL: post.get('title'), POST_BDY: post.get('body'), POST_CMS: post.get('comments').mapProperty('id') } if (options.includeId) { json.POST_ID_ = post.get('id'); } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachAttribute(function(name) { json[serverAttributeName(name)] = record.get(name); }) record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = record.get(name).mapBy('id'); } }); if (options.includeId) { json.ID_ = record.get('id'); } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```js { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = this._super(record, options); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param record @param options */ serialize: function(record, options) { return this._super.apply(this, arguments); }, /** You can use this method to customize the root keys serialized into the JSON. By default the REST Serializer sends camelized root keys. For example, your server may expect underscored root objects. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(hash, type, record, options) { var root = Ember.String.camelize(type.typeKey); hash[root] = this.serialize(record, options); }, /** You can use this method to customize how polymorphic objects are serialized. By default the JSON Serializer creates the key by appending `Type` to the attribute and value from the model's camelcased model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param {Object} relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; json[key + "Type"] = Ember.String.camelize(belongsTo.constructor.typeKey); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var forEach = Ember.ArrayPolyfills.forEach; /** The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter. This adapter is designed around the idea that the JSON exchanged with the server should be conventional. ## JSON Structure The REST adapter expects the JSON returned from your server to follow these conventions. ### Object Root The JSON payload should be an object that contains the record inside a root property. For example, in response to a `GET` request for `/posts/1`, the JSON should look like this: ```js { "post": { "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" } } ``` ### Conventional Names Attribute names in your JSON payload should be the camelCased versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "person": { "firstName": "Barack", "lastName": "Obama", "occupation": "President" } } ``` ## Customization ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```js DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Person` would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```js DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` ### Headers customization Some APIs require HTTP headers, e.g. to provide an API key. An array of headers can be added to the adapter which are passed with every request: ```js DS.RESTAdapter.reopen({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter */ DS.RESTAdapter = DS.Adapter.extend({ defaultSerializer: '-rest', /** Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```javascript DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Post` would now target `/api/1/post/`. @property namespace @type {String} */ /** An adapter can target other hosts by setting the `host` property. ```javascript DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` Requests for `App.Post` would now target `https://api.example.com/post/`. @property host @type {String} */ /** Some APIs require HTTP headers, e.g. to provide an API key. An array of headers can be added to the adapter which are passed with every request: ```javascript DS.RESTAdapter.reopen({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "Some header value" } }); ``` @property headers @type {Object} */ /** Called by the store in order to fetch the JSON for a given type and ID. The `find` method makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. This method performs an HTTP `GET` request with the id provided as part of the query string. @method find @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @returns {Promise} promise */ find: function(store, type, id) { return this.ajax(this.buildURL(type.typeKey, id), 'GET'); }, /** Called by the store in order to fetch a JSON array for all of the records for a given type. The `findAll` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @private @method findAll @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @returns {Promise} promise */ findAll: function(store, type, sinceToken) { var query; if (sinceToken) { query = { since: sinceToken }; } return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The `findQuery` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. The `query` argument is a simple JavaScript object that will be passed directly to the server as parameters. @private @method findQuery @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @returns {Promise} promise */ findQuery: function(store, type, query) { return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as IDs. For example, if the original payload looks like: ```js { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2, 3 ] } ``` The IDs will be passed as a URL-encoded Array of IDs, in this form: ``` ids[]=1&ids[]=2&ids[]=3 ``` Many servers, such as Rails and PHP, will automatically convert this URL-encoded array into an Array for you on the server-side. If you want to encode the IDs, differently, just override this (one-line) method. The `findMany` method makes an Ajax (HTTP GET) request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findMany @param {DS.Store} store @param {subclass of DS.Model} type @param {Array} ids @returns {Promise} promise */ findMany: function(store, type, ids) { return this.ajax(this.buildURL(type.typeKey), 'GET', { data: { ids: ids } }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "comments": "/posts/1/comments" } } } ``` This method will be called with the parent record and `/posts/1/comments`. The `findHasMany` method will make an Ajax (HTTP GET) request to the originally specified URL. If the URL is host-relative (starting with a single slash), the request will use the host specified on the adapter (if any). @method findHasMany @param {DS.Store} store @param {DS.Model} record @param {String} url @returns {Promise} promise */ findHasMany: function(store, record, url) { var host = get(this, 'host'), id = get(record, 'id'), type = record.constructor.typeKey; if (host && url.charAt(0) === '/' && url.charAt(1) !== '/') { url = host + url; } return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a belongs-to relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "person": { "id": 1, "name": "Tom Dale", "links": { "group": "/people/1/group" } } } ``` This method will be called with the parent record and `/people/1/group`. The `findBelongsTo` method will make an Ajax (HTTP GET) request to the originally specified URL. @method findBelongsTo @param {DS.Store} store @param {DS.Model} record @param {String} url @returns {Promise} promise */ findBelongsTo: function(store, record, url) { var id = get(record, 'id'), type = record.constructor.typeKey; return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store when a newly created record is saved via the `save` method on a model record instance. The `createRecord` method serializes the record and makes an Ajax (HTTP POST) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @returns {Promise} promise */ createRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record, { includeId: true }); return this.ajax(this.buildURL(type.typeKey), "POST", { data: data }); }, /** Called by the store when an existing record is saved via the `save` method on a model record instance. The `updateRecord` method serializes the record and makes an Ajax (HTTP PUT) request to a URL computed by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @returns {Promise} promise */ updateRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record); var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id), "PUT", { data: data }); }, /** Called by the store when a record is deleted. The `deleteRecord` method makes an Ajax (HTTP DELETE) request to a URL computed by `buildURL`. @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @returns {Promise} promise */ deleteRecord: function(store, type, record) { var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id), "DELETE"); }, /** Builds a URL for a given type and optional ID. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). To override the pluralization see [pathForType](#method_pathForType). If an ID is specified, it adds the ID to the path generated for the type, separated by a `/`. @method buildURL @param {String} type @param {String} id @returns {String} url */ buildURL: function(type, id) { var url = [], host = get(this, 'host'), prefix = this.urlPrefix(); if (type) { url.push(this.pathForType(type)); } if (id) { url.push(id); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url) { url = '/' + url; } return url; }, /** @method urlPrefix @private @param {String} path @param {String} parentUrl @return {String} urlPrefix */ urlPrefix: function(path, parentURL) { var host = get(this, 'host'), namespace = get(this, 'namespace'), url = []; if (path) { // Absolute path if (path.charAt(0) === '/') { if (host) { path = path.slice(1); url.push(host); } // Relative path } else if (!/^http(s)?:\/\//.test(path)) { url.push(parentURL); } } else { if (host) { url.push(host); } if (namespace) { url.push(namespace); } } if (path) { url.push(path); } return url.join('/'); }, /** Determines the pathname for a given type. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). ### Pathname customization For example if you have an object LineItem with an endpoint of "/line_items/". ```js DS.RESTAdapter.reopen({ pathForType: function(type) { var decamelized = Ember.String.decamelize(type); return Ember.String.pluralize(decamelized); }; }); ``` @method pathForType @param {String} type @returns {String} path **/ pathForType: function(type) { var camelized = Ember.String.camelize(type); return Ember.String.pluralize(camelized); }, /** Takes an ajax response, and returns a relevant error. Returning a `DS.InvalidError` from this method will cause the record to transition into the `invalid` state and make the `errors` object available on the record. ```javascript App.ApplicationAdapter = DS.RESTAdapter.extend({ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"]; return new DS.InvalidError(jsonErrors); } else { return error; } } }); ``` Note: As a correctness optimization, the default implementation of the `ajaxError` method strips out the `then` method from jquery's ajax response (jqXHR). This is important because the jqXHR's `then` method fulfills the promise with itself resulting in a circular "thenable" chain which may cause problems for some promise libraries. @method ajaxError @param {Object} jqXHR @return {Object} jqXHR */ ajaxError: function(jqXHR) { if (jqXHR) { jqXHR.then = null; } return jqXHR; }, /** Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. When the server responds with a payload, Ember Data will call into `extractSingle` or `extractArray` (depending on whether the original query was for one record or many records). By default, `ajax` method has the following behavior: * It sets the response `dataType` to `"json"` * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be `application/json; charset=utf-8` * If the HTTP method is not `"GET"`, it stringifies the data passed in. The data is the serialized record in the case of a save. * Registers success and failure handlers. @method ajax @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} hash @return {Promise} promise */ ajax: function(url, type, hash) { var adapter = this; return new Ember.RSVP.Promise(function(resolve, reject) { hash = adapter.ajaxOptions(url, type, hash); hash.success = function(json) { Ember.run(null, resolve, json); }; hash.error = function(jqXHR, textStatus, errorThrown) { Ember.run(null, reject, adapter.ajaxError(jqXHR)); }; Ember.$.ajax(hash); }, "DS: RestAdapter#ajax " + type + " to " + url); }, /** @method ajaxOptions @private @param {String} url @param {String} type The request type GET, POST, PUT, DELETE etc. @param {Object} hash @return {Object} hash */ ajaxOptions: function(url, type, hash) { hash = hash || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = this; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } if (this.headers !== undefined) { var headers = this.headers; hash.beforeSend = function (xhr) { forEach.call(Ember.keys(headers), function(key) { xhr.setRequestHeader(key, headers[key]); }); }; } return hash; } }); })(); (function() { /** @module ember-data */ })(); (function() { DS.Model.reopen({ /** Provides info about the model for debugging purposes by grouping the properties into more semantic groups. Meant to be used by debugging tools such as the Chrome Ember Extension. - Groups all attributes in "Attributes" group. - Groups all belongsTo relationships in "Belongs To" group. - Groups all hasMany relationships in "Has Many" group. - Groups all flags in "Flags" group. - Flags relationship CPs as expensive properties. @method _debugInfo @for DS.Model @private */ _debugInfo: function() { var attributes = ['id'], relationships = { belongsTo: [], hasMany: [] }, expensiveProperties = []; this.eachAttribute(function(name, meta) { attributes.push(name); }, this); this.eachRelationship(function(name, relationship) { relationships[relationship.kind].push(name); expensiveProperties.push(name); }); var groups = [ { name: 'Attributes', properties: attributes, expand: true }, { name: 'Belongs To', properties: relationships.belongsTo, expand: true }, { name: 'Has Many', properties: relationships.hasMany, expand: true }, { name: 'Flags', properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid'] } ]; return { propertyInfo: { // include all other mixins / properties (not just the grouped ones) includeOtherProperties: true, groups: groups, // don't pre-calculate unless cached expensiveProperties: expensiveProperties } }; } }); })(); (function() { /** @module ember-data */ })(); (function() { /** Ember Data @module ember-data @main ember-data */ })(); (function() { Ember.String.pluralize = function(word) { return Ember.Inflector.inflector.pluralize(word); }; Ember.String.singularize = function(word) { return Ember.Inflector.inflector.singularize(word); }; })(); (function() { var BLANK_REGEX = /^\s*$/; function loadUncountable(rules, uncountable) { for (var i = 0, length = uncountable.length; i < length; i++) { rules.uncountable[uncountable[i].toLowerCase()] = true; } } function loadIrregular(rules, irregularPairs) { var pair; for (var i = 0, length = irregularPairs.length; i < length; i++) { pair = irregularPairs[i]; rules.irregular[pair[0].toLowerCase()] = pair[1]; rules.irregularInverse[pair[1].toLowerCase()] = pair[0]; } } /** Inflector.Ember provides a mechanism for supplying inflection rules for your application. Ember includes a default set of inflection rules, and provides an API for providing additional rules. Examples: Creating an inflector with no rules. ```js var inflector = new Ember.Inflector(); ``` Creating an inflector with the default ember ruleset. ```js var inflector = new Ember.Inflector(Ember.Inflector.defaultRules); inflector.pluralize('cow') //=> 'kine' inflector.singularize('kine') //=> 'cow' ``` Creating an inflector and adding rules later. ```javascript var inflector = Ember.Inflector.inflector; inflector.pluralize('advice') // => 'advices' inflector.uncountable('advice'); inflector.pluralize('advice') // => 'advice' inflector.pluralize('formula') // => 'formulas' inflector.irregular('formula', 'formulae'); inflector.pluralize('formula') // => 'formulae' // you would not need to add these as they are the default rules inflector.plural(/$/, 's'); inflector.singular(/s$/i, ''); ``` Creating an inflector with a nondefault ruleset. ```javascript var rules = { plurals: [ /$/, 's' ], singular: [ /\s$/, '' ], irregularPairs: [ [ 'cow', 'kine' ] ], uncountable: [ 'fish' ] }; var inflector = new Ember.Inflector(rules); ``` @class Inflector @namespace Ember */ function Inflector(ruleSet) { ruleSet = ruleSet || {}; ruleSet.uncountable = ruleSet.uncountable || {}; ruleSet.irregularPairs = ruleSet.irregularPairs || {}; var rules = this.rules = { plurals: ruleSet.plurals || [], singular: ruleSet.singular || [], irregular: {}, irregularInverse: {}, uncountable: {} }; loadUncountable(rules, ruleSet.uncountable); loadIrregular(rules, ruleSet.irregularPairs); } Inflector.prototype = { /** @method plural @param {RegExp} regex @param {String} string */ plural: function(regex, string) { this.rules.plurals.push([regex, string.toLowerCase()]); }, /** @method singular @param {RegExp} regex @param {String} string */ singular: function(regex, string) { this.rules.singular.push([regex, string.toLowerCase()]); }, /** @method uncountable @param {String} regex */ uncountable: function(string) { loadUncountable(this.rules, [string.toLowerCase()]); }, /** @method irregular @param {String} singular @param {String} plural */ irregular: function (singular, plural) { loadIrregular(this.rules, [[singular, plural]]); }, /** @method pluralize @param {String} word */ pluralize: function(word) { return this.inflect(word, this.rules.plurals, this.rules.irregular); }, /** @method singularize @param {String} word */ singularize: function(word) { return this.inflect(word, this.rules.singular, this.rules.irregularInverse); }, /** @protected @method inflect @param {String} word @param {Object} typeRules @param {Object} irregular */ inflect: function(word, typeRules, irregular) { var inflection, substitution, result, lowercase, isBlank, isUncountable, isIrregular, isIrregularInverse, rule; isBlank = BLANK_REGEX.test(word); if (isBlank) { return word; } lowercase = word.toLowerCase(); isUncountable = this.rules.uncountable[lowercase]; if (isUncountable) { return word; } isIrregular = irregular && irregular[lowercase]; if (isIrregular) { return isIrregular; } for (var i = typeRules.length, min = 0; i > min; i--) { inflection = typeRules[i-1]; rule = inflection[0]; if (rule.test(word)) { break; } } inflection = inflection || []; rule = inflection[0]; substitution = inflection[1]; result = word.replace(rule, substitution); return result; } }; Ember.Inflector = Inflector; })(); (function() { Ember.Inflector.defaultRules = { plurals: [ [/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes'] ], singular: [ [/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1'] ], irregularPairs: [ ['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies'] ], uncountable: [ 'equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police' ] }; })(); (function() { if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} @method pluralize @for String */ String.prototype.pluralize = function() { return Ember.String.pluralize(this); }; /** See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} @method singularize @for String */ String.prototype.singularize = function() { return Ember.String.singularize(this); }; } })(); (function() { Ember.Inflector.inflector = new Ember.Inflector(Ember.Inflector.defaultRules); })(); (function() { })(); (function() { /** @module ember-data */ var get = Ember.get, forEach = Ember.EnumerableUtils.forEach, camelize = Ember.String.camelize, capitalize = Ember.String.capitalize, decamelize = Ember.String.decamelize, singularize = Ember.String.singularize, underscore = Ember.String.underscore; DS.ActiveModelSerializer = DS.RESTSerializer.extend({ // SERIALIZE /** Converts camelcased attributes to underscored when serializing. @method keyForAttribute @param {String} attribute @returns String */ keyForAttribute: function(attr) { return decamelize(attr); }, /** Underscores relationship names and appends "_id" or "_ids" when serializing relationship keys. @method keyForRelationship @param {String} key @param {String} kind @returns String */ keyForRelationship: function(key, kind) { key = decamelize(key); if (kind === "belongsTo") { return key + "_id"; } else if (kind === "hasMany") { return singularize(key) + "_ids"; } else { return key; } }, /** Does not serialize hasMany relationships by default. */ serializeHasMany: Ember.K, /** Underscores the JSON root keys when serializing. @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(data, type, record, options) { var root = underscore(decamelize(type.typeKey)); data[root] = this.serialize(record, options); }, /** Serializes a polymorphic type as a fully capitalized model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute(key); json[key + "_type"] = capitalize(camelize(belongsTo.constructor.typeKey)); }, // EXTRACT /** Extracts the model typeKey from underscored root objects. @method typeForRoot @param {String} root @returns String the model's typeKey */ typeForRoot: function(root) { var camelized = camelize(root); return singularize(camelized); }, /** Add extra step to `DS.RESTSerializer.normalize` so links are normalized. If your payload looks like this ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flagged_comments": "api/comments/flagged" } } } ``` The normalized version would look like this ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "flaggedComments": "api/comments/flagged" } } } ``` @method normalize @param {subclass of DS.Model} type @param {Object} hash @param {String} prop @returns Object */ normalize: function(type, hash, prop) { this.normalizeLinks(hash); return this._super(type, hash, prop); }, /** Convert `snake_cased` links to `camelCase` @method normalizeLinks @param {Object} hash */ normalizeLinks: function(data){ if (data.links) { var links = data.links; for (var link in links) { var camelizedLink = camelize(link); if (camelizedLink !== link) { links[camelizedLink] = links[link]; delete links[link]; } } } }, /** Normalize the polymorphic type from the JSON. Normalize: ```js { id: "1" minion: { type: "evil_minion", id: "12"} } ``` To: ```js { id: "1" minion: { type: "evilMinion", id: "12"} } ``` @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { var payloadKey, payload; if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { if (relationship.options.polymorphic) { payloadKey = this.keyForAttribute(key); payload = hash[payloadKey]; if (payload && payload.type) { payload.type = this.typeForRoot(payload.type); } else if (payload && relationship.kind === "hasMany") { var self = this; forEach(payload, function(single) { single.type = self.typeForRoot(single.type); }); } } else { payloadKey = this.keyForRelationship(key, relationship.kind); payload = hash[payloadKey]; } hash[key] = payload; if (key !== payloadKey) { delete hash[payloadKey]; } }, this); } } }); })(); (function() { var get = Ember.get; var forEach = Ember.EnumerableUtils.forEach; /** The EmbeddedRecordsMixin allows you to add embedded record support to your serializers. To set up embedded records, you include the mixin into the serializer and then define your embedded relations. ```js App.PostSerializer = DS.ActiveModelSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: {embedded: 'always'} } }) ``` Currently only `{embedded: 'always'}` records are supported. @class EmbeddedRecordsMixin @namespace DS */ DS.EmbeddedRecordsMixin = Ember.Mixin.create({ /** Serialize has-may relationship when it is configured as embedded objects. @method serializeHasMany */ serializeHasMany: function(record, json, relationship) { var key = relationship.key, attrs = get(this, 'attrs'), embed = attrs && attrs[key] && attrs[key].embedded === 'always'; if (embed) { json[this.keyForAttribute(key)] = get(record, key).map(function(relation) { var data = relation.serialize(), primaryKey = get(this, 'primaryKey'); data[primaryKey] = get(relation, primaryKey); return data; }, this); } }, /** Extract embedded objects out of the payload for a single object and add them as sideloaded objects instead. @method extractSingle */ extractSingle: function(store, primaryType, payload, recordId, requestType) { var root = this.keyForAttribute(primaryType.typeKey), partial = payload[root]; updatePayloadWithEmbedded(store, this, primaryType, partial, payload); return this._super(store, primaryType, payload, recordId, requestType); }, /** Extract embedded objects out of a standard payload and add them as sideloaded objects instead. @method extractArray */ extractArray: function(store, type, payload) { var root = this.keyForAttribute(type.typeKey), partials = payload[Ember.String.pluralize(root)]; forEach(partials, function(partial) { updatePayloadWithEmbedded(store, this, type, partial, payload); }, this); return this._super(store, type, payload); } }); function updatePayloadWithEmbedded(store, serializer, type, partial, payload) { var attrs = get(serializer, 'attrs'); if (!attrs) { return; } type.eachRelationship(function(key, relationship) { var expandedKey, embeddedTypeKey, attribute, ids, config = attrs[key], serializer = store.serializerFor(relationship.type.typeKey), primaryKey = get(serializer, "primaryKey"); if (relationship.kind !== "hasMany") { return; } if (config && (config.embedded === 'always' || config.embedded === 'load')) { // underscore forces the embedded records to be side loaded. // it is needed when main type === relationship.type embeddedTypeKey = '_' + Ember.String.pluralize(relationship.type.typeKey); expandedKey = this.keyForRelationship(key, relationship.kind); attribute = this.keyForAttribute(key); ids = []; if (!partial[attribute]) { return; } payload[embeddedTypeKey] = payload[embeddedTypeKey] || []; forEach(partial[attribute], function(data) { var embeddedType = store.modelFor(relationship.type.typeKey); updatePayloadWithEmbedded(store, serializer, embeddedType, data, payload); ids.push(data[primaryKey]); payload[embeddedTypeKey].push(data); }); partial[expandedKey] = ids; delete partial[attribute]; } }, serializer); } })(); (function() { /** @module ember-data */ var forEach = Ember.EnumerableUtils.forEach; var decamelize = Ember.String.decamelize, underscore = Ember.String.underscore, pluralize = Ember.String.pluralize; /** The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate with a JSON API that uses an underscored naming convention instead of camelcasing. It has been designed to work out of the box with the [active_model_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. This adapter extends the DS.RESTAdapter by making consistent use of the camelization, decamelization and pluralization methods to normalize the serialized JSON into a format that is compatible with a conventional Rails backend and Ember Data. ## JSON Structure The ActiveModelAdapter expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` @class ActiveModelAdapter @constructor @namespace DS @extends DS.Adapter **/ DS.ActiveModelAdapter = DS.RESTAdapter.extend({ defaultSerializer: '-active-model', /** The ActiveModelAdapter overrides the `pathForType` method to build underscored URLs by decamelizing and pluralizing the object type name. ```js this.pathForType("famousPerson"); //=> "famous_people" ``` @method pathForType @param {String} type @returns String */ pathForType: function(type) { var decamelized = decamelize(type); var underscored = underscore(decamelized); return pluralize(underscored); }, /** The ActiveModelAdapter overrides the `ajaxError` method to return a DS.InvalidError for all 422 Unprocessable Entity responses. A 422 HTTP response from the server generally implies that the request was well formed but the API was unable to process it because the content was not semantically correct or meaningful per the API. For more information on 422 HTTP Error code see 11.2 WebDAV RFC 4918 https://tools.ietf.org/html/rfc4918#section-11.2 @method ajaxError @param jqXHR @returns error */ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var response = Ember.$.parseJSON(jqXHR.responseText), errors = {}; if (response.errors !== undefined) { var jsonErrors = response.errors; forEach(Ember.keys(jsonErrors), function(key) { errors[Ember.String.camelize(key)] = jsonErrors[key]; }); } return new DS.InvalidError(errors); } else { return error; } } }); })(); (function() { })(); (function() { Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "activeModelAdapter", initialize: function(container, application) { var proxy = new DS.ContainerProxy(container); proxy.registerDeprecations([ {deprecated: 'serializer:_ams', valid: 'serializer:-active-model'}, {deprecated: 'adapter:_ams', valid: 'adapter:-active-model'} ]); application.register('serializer:-active-model', DS.ActiveModelSerializer); application.register('adapter:-active-model', DS.ActiveModelAdapter); } }); }); })(); (function() { })(); })();
tests/site6/src/category/category_sections.js
dominikwilkowski/cuttlebelle
import PropTypes from 'prop-types'; import Slugify from 'slugify'; import React from 'react'; /** * The sections component */ const CategorySections = ( page ) => { const sections = []; page.sections.map( ( section ) => sections.push({ link: Slugify( section ).toLowerCase(), title: section, })); return ( <div className="uikit-body uikit-grid category-sections"> <div className="category-sections__wrapper js-sections"> <ul className="category-sections__list"> { page.sections.map( ( section, i ) => ( <li key={ i } className="category-sections__list__item__wrapper"> <div className="category-sections__list__item"> <a className="category-sections__list__link" href={`#${ Slugify( section ).toLowerCase() }`}>{ section }</a> </div>{ ' ' } </li> )) } </ul> </div> </div> ); }; CategorySections.propTypes = { /** * sections: * - Why * - When * - How * - Support */ sections: PropTypes.array.isRequired, }; CategorySections.defaultProps = {}; export default CategorySections;
src/App.js
grommet/grommet-docs
import React from 'react'; import { IntlProvider, addLocaleData } from 'react-intl'; import en from 'react-intl/locale-data/en'; import routes from './routes'; import { Router, useRouterHistory } from 'react-router'; import { createHistory } from 'history'; import { logPageView } from './utils/analytics'; addLocaleData(en); import { getCurrentLocale, getLocaleData } from 'grommet/utils/Locale'; const onRouteUpdate = () => { logPageView(); window.scrollTo(0, 0); document.getElementById('content').focus(); }; const THEMES = ['vanilla', 'aruba', 'dxc', 'hpe', 'hpinc']; function basenameForTheme (theme) { let basename; if ('vanilla' === theme || THEMES.indexOf(theme) === -1) { basename = '/'; } else { basename = `/${theme}`; } return basename; } let history; if (typeof document !== 'undefined') { const firstPathElement = window.location.pathname.split('/')[1]; const theme = (THEMES.indexOf(firstPathElement) === -1 ? 'vanilla' : firstPathElement); require(`./scss/index-${theme}`); if (__DEV_MODE__) { var themeLink = document.getElementById('theme-link'); var themeUrl = `/assets/css/index-${theme}.css`; if (themeLink) { themeLink.setAttribute('href', themeUrl); } } const basename = basenameForTheme(theme); let historyOptions = {}; if ('/' !== basename) { historyOptions.basename = basename; } history = useRouterHistory(createHistory)(historyOptions); } const locale = getCurrentLocale(); const localeData = getLocaleData({}, locale); export default (props) => { let body = ( <Router onUpdate={onRouteUpdate} routes={routes} history={history} /> ); if (props.children) { body = props.children; } return ( <IntlProvider locale={localeData.locale} messages={localeData.messages}> {body} </IntlProvider> ); };
ajax/libs/analytics.js/2.3.9/analytics.min.js
mitsuruog/cdnjs
(function outer(modules,cache,entries){var global=function(){return this}();function require(name,jumped){if(cache[name])return cache[name].exports;if(modules[name])return call(name,require);throw new Error('cannot find module "'+name+'"')}function call(id,require){var m=cache[id]={exports:{}};var mod=modules[id];var name=mod[2];var fn=mod[0];fn.call(m.exports,function(req){var dep=modules[id][1][req];return require(dep?dep:req)},m,m.exports,outer,modules,cache,entries);if(name)cache[name]=cache[id];return cache[id].exports}for(var id in entries){if(entries[id]){global[entries[id]]=require(id)}else{require(id)}}require.duo=true;require.cache=cache;require.modules=modules;return require})({1:[function(require,module,exports){var Integrations=require("analytics.js-integrations");var Analytics=require("./analytics");var each=require("each");var analytics=module.exports=exports=new Analytics;analytics.require=require;exports.VERSION=require("./version");each(Integrations,function(name,Integration){analytics.use(Integration)})},{"./analytics":2,"./version":3,"analytics.js-integrations":4,each:5}],2:[function(require,module,exports){var after=require("after");var bind=require("bind");var callback=require("callback");var canonical=require("canonical");var clone=require("clone");var cookie=require("./cookie");var debug=require("debug");var defaults=require("defaults");var each=require("each");var Emitter=require("emitter");var group=require("./group");var is=require("is");var isEmail=require("is-email");var isMeta=require("is-meta");var newDate=require("new-date");var on=require("event").bind;var prevent=require("prevent");var querystring=require("querystring");var size=require("object").length;var store=require("./store");var url=require("url");var user=require("./user");var Facade=require("facade");var Identify=Facade.Identify;var Group=Facade.Group;var Alias=Facade.Alias;var Track=Facade.Track;var Page=Facade.Page;exports=module.exports=Analytics;exports.cookie=cookie;exports.store=store;function Analytics(){this.Integrations={};this._integrations={};this._readied=false;this._timeout=300;this._user=user;bind.all(this);var self=this;this.on("initialize",function(settings,options){if(options.initialPageview)self.page()});this.on("initialize",function(){self._parseQuery()})}Emitter(Analytics.prototype);Analytics.prototype.use=function(plugin){plugin(this);return this};Analytics.prototype.addIntegration=function(Integration){var name=Integration.prototype.name;if(!name)throw new TypeError("attempted to add an invalid integration");this.Integrations[name]=Integration;return this};Analytics.prototype.init=Analytics.prototype.initialize=function(settings,options){settings=settings||{};options=options||{};this._options(options);this._readied=false;var self=this;each(settings,function(name){var Integration=self.Integrations[name];if(!Integration)delete settings[name]});each(settings,function(name,opts){var Integration=self.Integrations[name];var integration=new Integration(clone(opts));self.add(integration)});var integrations=this._integrations;user.load();group.load();var ready=after(size(integrations),function(){self._readied=true;self.emit("ready")});each(integrations,function(name,integration){if(options.initialPageview&&integration.options.initialPageview===false){integration.page=after(2,integration.page)}integration.analytics=self;integration.once("ready",ready);integration.initialize()});this.initialized=true;this.emit("initialize",settings,options);return this};Analytics.prototype.add=function(integration){this._integrations[integration.name]=integration;return this};Analytics.prototype.identify=function(id,traits,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=user.id();user.identify(id,traits);id=user.id();traits=user.traits();this._invoke("identify",message(Identify,{options:options,traits:traits,userId:id}));this.emit("identify",id,traits,options);this._callback(fn);return this};Analytics.prototype.user=function(){return user};Analytics.prototype.group=function(id,traits,options,fn){if(0===arguments.length)return group;if(is.fn(options))fn=options,options=null;if(is.fn(traits))fn=traits,options=null,traits=null;if(is.object(id))options=traits,traits=id,id=group.id();group.identify(id,traits);id=group.id();traits=group.traits();this._invoke("group",message(Group,{options:options,traits:traits,groupId:id}));this.emit("group",id,traits,options);this._callback(fn);return this};Analytics.prototype.track=function(event,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=null,properties=null;this._invoke("track",message(Track,{properties:properties,options:options,event:event}));this.emit("track",event,properties,options);this._callback(fn);return this};Analytics.prototype.trackClick=Analytics.prototype.trackLink=function(links,event,properties){if(!links)return this;if(is.element(links))links=[links];var self=this;each(links,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackLink`.");on(el,"click",function(e){var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);if(el.href&&el.target!=="_blank"&&!isMeta(e)){prevent(e);self._callback(function(){window.location.href=el.href})}})});return this};Analytics.prototype.trackSubmit=Analytics.prototype.trackForm=function(forms,event,properties){if(!forms)return this;if(is.element(forms))forms=[forms];var self=this;each(forms,function(el){if(!is.element(el))throw new TypeError("Must pass HTMLElement to `analytics.trackForm`.");function handler(e){prevent(e);var ev=is.fn(event)?event(el):event;var props=is.fn(properties)?properties(el):properties;self.track(ev,props);self._callback(function(){el.submit()})}var $=window.jQuery||window.Zepto;if($){$(el).submit(handler)}else{on(el,"submit",handler)}});return this};Analytics.prototype.page=function(category,name,properties,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(properties))fn=properties,options=properties=null;if(is.fn(name))fn=name,options=properties=name=null;if(is.object(category))options=name,properties=category,name=category=null;if(is.object(name))options=properties,properties=name,name=null;if(is.string(category)&&!is.string(name))name=category,category=null;var defs={path:canonicalPath(),referrer:document.referrer,title:document.title,search:location.search};if(name)defs.name=name;if(category)defs.category=category;properties=clone(properties)||{};defaults(properties,defs);properties.url=properties.url||canonicalUrl(properties.search);this._invoke("page",message(Page,{properties:properties,category:category,options:options,name:name}));this.emit("page",category,name,properties,options);this._callback(fn);return this};Analytics.prototype.pageview=function(url,options){var properties={};if(url)properties.path=url;this.page(properties);return this};Analytics.prototype.alias=function(to,from,options,fn){if(is.fn(options))fn=options,options=null;if(is.fn(from))fn=from,options=null,from=null;if(is.object(from))options=from,from=null;this._invoke("alias",message(Alias,{options:options,from:from,to:to}));this.emit("alias",to,from,options);this._callback(fn);return this};Analytics.prototype.ready=function(fn){if(!is.fn(fn))return this;this._readied?callback.async(fn):this.once("ready",fn);return this};Analytics.prototype.timeout=function(timeout){this._timeout=timeout};Analytics.prototype.debug=function(str){if(0==arguments.length||str){debug.enable("analytics:"+(str||"*"))}else{debug.disable()}};Analytics.prototype._options=function(options){options=options||{};cookie.options(options.cookie);store.options(options.localStorage);user.options(options.user);group.options(options.group);return this};Analytics.prototype._callback=function(fn){callback.async(fn,this._timeout);return this};Analytics.prototype._invoke=function(method,facade){var options=facade.options();this.emit("invoke",facade);each(this._integrations,function(name,integration){if(!facade.enabled(name))return;integration.invoke.call(integration,method,facade)});return this};Analytics.prototype.push=function(args){var method=args.shift();if(!this[method])return;this[method].apply(this,args)};Analytics.prototype._parseQuery=function(){var q=querystring.parse(window.location.search);if(q.ajs_uid)this.identify(q.ajs_uid);if(q.ajs_event)this.track(q.ajs_event);return this};function canonicalPath(){var canon=canonical();if(!canon)return window.location.pathname;var parsed=url.parse(canon);return parsed.pathname}function canonicalUrl(search){var canon=canonical();if(canon)return~canon.indexOf("?")?canon:canon+search;var url=window.location.href;var i=url.indexOf("#");return-1==i?url:url.slice(0,i)}function message(Type,msg){var ctx=msg.options||{};if(ctx.timestamp||ctx.integrations||ctx.context){msg=defaults(ctx,msg);delete msg.options}return new Type(msg)}},{"./cookie":6,"./group":7,"./store":8,"./user":9,after:10,bind:11,callback:12,canonical:13,clone:14,debug:15,defaults:16,each:5,emitter:17,is:18,"is-email":19,"is-meta":20,"new-date":21,event:22,prevent:23,querystring:24,object:25,url:26,facade:27}],6:[function(require,module,exports){var debug=require("debug")("analytics.js:cookie");var bind=require("bind");var cookie=require("cookie");var clone=require("clone");var defaults=require("defaults");var json=require("json");var topDomain=require("top-domain");function Cookie(options){this.options(options)}Cookie.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};var domain="."+topDomain(window.location.href);this._options=defaults(options,{maxage:31536e6,path:"/",domain:domain});this.set("ajs:test",true);if(!this.get("ajs:test")){debug("fallback to domain=null");this._options.domain=null}this.remove("ajs:test")};Cookie.prototype.set=function(key,value){try{value=json.stringify(value);cookie(key,value,clone(this._options));return true}catch(e){return false}};Cookie.prototype.get=function(key){try{var value=cookie(key);value=value?json.parse(value):null;return value}catch(e){return null}};Cookie.prototype.remove=function(key){try{cookie(key,null,clone(this._options));return true}catch(e){return false}};module.exports=bind.all(new Cookie);module.exports.Cookie=Cookie},{debug:15,bind:11,cookie:28,clone:14,defaults:16,json:29,"top-domain":30}],15:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":31,"./debug":32}],31:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],32:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],11:[function(require,module,exports){try{var bind=require("bind")}catch(e){var bind=require("bind-component")}var bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:33,"bind-all":34}],33:[function(require,module,exports){var slice=[].slice;module.exports=function(obj,fn){if("string"==typeof fn)fn=obj[fn];if("function"!=typeof fn)throw new Error("bind() requires a function");var args=slice.call(arguments,2);return function(){return fn.apply(obj,args.concat(slice.call(arguments)))}}},{}],34:[function(require,module,exports){try{var bind=require("bind");var type=require("type")}catch(e){var bind=require("bind-component");var type=require("type-component")}module.exports=function(obj){for(var key in obj){var val=obj[key];if(type(val)==="function")obj[key]=bind(obj,obj[key])}return obj}},{bind:33,type:35}],35:[function(require,module,exports){var toString=Object.prototype.toString;module.exports=function(val){switch(toString.call(val)){case"[object Function]":return"function";case"[object Date]":return"date";case"[object RegExp]":return"regexp";case"[object Arguments]":return"arguments";case"[object Array]":return"array";case"[object String]":return"string"}if(val===null)return"null";if(val===undefined)return"undefined";if(val&&val.nodeType===1)return"element";if(val===Object(val))return"object";return typeof val}},{}],28:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;module.exports=function(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:return get(name);default:return all()}};function set(name,value,options){options=options||{};var str=encode(name)+"="+encode(value);if(null==value)options.maxage=-1;if(options.maxage){options.expires=new Date(+new Date+options.maxage)}if(options.path)str+="; path="+options.path;if(options.domain)str+="; domain="+options.domain;if(options.expires)str+="; expires="+options.expires.toGMTString();if(options.secure)str+="; secure";document.cookie=str}function all(){return parse(document.cookie)}function get(name){return all()[name]}function parse(str){var obj={};var pairs=str.split(/ *; */);var pair;if(""==pairs[0])return obj;for(var i=0;i<pairs.length;++i){pair=pairs[i].split("=");obj[decode(pair[0])]=decode(pair[1])}return obj}},{}],14:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{type:35}],16:[function(require,module,exports){"use strict";var defaults=function(dest,src,recursive){for(var prop in src){if(recursive&&dest[prop]instanceof Object&&src[prop]instanceof Object){dest[prop]=defaults(dest[prop],src[prop],true)}else if(!(prop in dest)){dest[prop]=src[prop]}}return dest};module.exports=defaults},{}],29:[function(require,module,exports){var json=window.JSON||{};var stringify=json.stringify;var parse=json.parse;module.exports=parse&&stringify?JSON:require("json-fallback")},{"json-fallback":36}],36:[function(require,module,exports){(function(){"use strict";var JSON=module.exports={};function f(n){return n<10?"0"+n:n}if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(){return this.valueOf()}}var cx,escapable,gap,indent,meta,rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==="string"?c:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==="object"&&typeof value.toJSON==="function"){value=value.toJSON(key)}if(typeof rep==="function"){value=rep.call(holder,key,value)}switch(typeof value){case"string":return quote(value);case"number":return isFinite(value)?String(value):"null";case"boolean":case"null":return String(value);case"object":if(!value){return"null"}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==="[object Array]"){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||"null"}v=partial.length===0?"[]":gap?"[\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"]":"["+partial.join(",")+"]";gap=mind;return v}if(rep&&typeof rep==="object"){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==="string"){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?": ":":")+v)}}}}v=partial.length===0?"{}":gap?"{\n"+gap+partial.join(",\n"+gap)+"\n"+mind+"}":"{"+partial.join(",")+"}";gap=mind;return v}}if(typeof JSON.stringify!=="function"){escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;meta={"\b":"\\b"," ":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};JSON.stringify=function(value,replacer,space){var i;gap="";indent="";if(typeof space==="number"){for(i=0;i<space;i+=1){indent+=" "}}else if(typeof space==="string"){indent=space}rep=replacer;if(replacer&&typeof replacer!=="function"&&(typeof replacer!=="object"||typeof replacer.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":value})}}if(typeof JSON.parse!=="function"){cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g;JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==="object"){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v}else{delete value[k]}}}}return reviver.call(holder,key,value)}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()},{}],30:[function(require,module,exports){var parse=require("url").parse;module.exports=domain;var regexp=/[a-z0-9][a-z0-9\-]*[a-z0-9]\.[a-z\.]{2,6}$/i;function domain(url){var host=parse(url).hostname;var match=host.match(regexp);return match?match[0]:""}},{url:26}],26:[function(require,module,exports){exports.parse=function(url){var a=document.createElement("a");a.href=url;return{href:a.href,host:a.host,port:a.port,hash:a.hash,hostname:a.hostname,pathname:a.pathname,protocol:a.protocol,search:a.search,query:a.search.slice(1)}};exports.isAbsolute=function(url){if(0==url.indexOf("//"))return true;if(~url.indexOf("://"))return true;return false};exports.isRelative=function(url){return!exports.isAbsolute(url)};exports.isCrossDomain=function(url){url=exports.parse(url);return url.hostname!=location.hostname||url.port!=location.port||url.protocol!=location.protocol}},{}],7:[function(require,module,exports){var debug=require("debug")("analytics:group");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");Group.defaults={persist:true,cookie:{key:"ajs_group_id"},localStorage:{key:"ajs_group_properties"}};function Group(options){this.defaults=Group.defaults;this.debug=debug;Entity.call(this,options)}inherit(Group,Entity);module.exports=bind.all(new Group);module.exports.Group=Group},{"./entity":37,debug:15,inherit:38,bind:11}],37:[function(require,module,exports){var traverse=require("isodate-traverse");var defaults=require("defaults");var cookie=require("./cookie");var store=require("./store");var extend=require("extend");var clone=require("clone");module.exports=Entity;function Entity(options){this.options(options)}Entity.prototype.options=function(options){if(arguments.length===0)return this._options;options||(options={});defaults(options,this.defaults||{});this._options=options};Entity.prototype.id=function(id){switch(arguments.length){case 0:return this._getId();case 1:return this._setId(id)}};Entity.prototype._getId=function(){var ret=this._options.persist?cookie.get(this._options.cookie.key):this._id;return ret===undefined?null:ret};Entity.prototype._setId=function(id){if(this._options.persist){cookie.set(this._options.cookie.key,id)}else{this._id=id}};Entity.prototype.properties=Entity.prototype.traits=function(traits){switch(arguments.length){case 0:return this._getTraits();case 1:return this._setTraits(traits)}};Entity.prototype._getTraits=function(){var ret=this._options.persist?store.get(this._options.localStorage.key):this._traits;return ret?traverse(clone(ret)):{}};Entity.prototype._setTraits=function(traits){traits||(traits={});if(this._options.persist){store.set(this._options.localStorage.key,traits)}else{this._traits=traits}};Entity.prototype.identify=function(id,traits){traits||(traits={});var current=this.id();if(current===null||current===id)traits=extend(this.traits(),traits);if(id)this.id(id);this.debug("identify %o, %o",id,traits);this.traits(traits);this.save()};Entity.prototype.save=function(){if(!this._options.persist)return false;cookie.set(this._options.cookie.key,this.id());store.set(this._options.localStorage.key,this.traits());return true};Entity.prototype.logout=function(){this.id(null);this.traits({});cookie.remove(this._options.cookie.key);store.remove(this._options.localStorage.key)};Entity.prototype.reset=function(){this.logout();this.options({})};Entity.prototype.load=function(){this.id(cookie.get(this._options.cookie.key));this.traits(store.get(this._options.localStorage.key))}},{"./cookie":6,"./store":8,"isodate-traverse":39,defaults:16,extend:40,clone:14}],8:[function(require,module,exports){var bind=require("bind");var defaults=require("defaults");var store=require("store.js");function Store(options){this.options(options)}Store.prototype.options=function(options){if(arguments.length===0)return this._options;options=options||{};defaults(options,{enabled:true});this.enabled=options.enabled&&store.enabled;this._options=options};Store.prototype.set=function(key,value){if(!this.enabled)return false;return store.set(key,value)};Store.prototype.get=function(key){if(!this.enabled)return null;return store.get(key)};Store.prototype.remove=function(key){if(!this.enabled)return false;return store.remove(key)};module.exports=bind.all(new Store);module.exports.Store=Store},{bind:11,defaults:16,"store.js":41}],41:[function(require,module,exports){var json=require("json"),store={},win=window,doc=win.document,localStorageName="localStorage",namespace="__storejs__",storage;store.disabled=false;store.set=function(key,value){};store.get=function(key){};store.remove=function(key){};store.clear=function(){};store.transact=function(key,defaultVal,transactionFn){var val=store.get(key);if(transactionFn==null){transactionFn=defaultVal;defaultVal=null}if(typeof val=="undefined"){val=defaultVal||{}}transactionFn(val);store.set(key,val)};store.getAll=function(){};store.serialize=function(value){return json.stringify(value)};store.deserialize=function(value){if(typeof value!="string"){return undefined}try{return json.parse(value)}catch(e){return value||undefined}};function isLocalStorageNameSupported(){try{return localStorageName in win&&win[localStorageName]}catch(err){return false}}if(isLocalStorageNameSupported()){storage=win[localStorageName];store.set=function(key,val){if(val===undefined){return store.remove(key)}storage.setItem(key,store.serialize(val));return val};store.get=function(key){return store.deserialize(storage.getItem(key))};store.remove=function(key){storage.removeItem(key)};store.clear=function(){storage.clear()};store.getAll=function(){var ret={};for(var i=0;i<storage.length;++i){var key=storage.key(i);ret[key]=store.get(key)}return ret}}else if(doc.documentElement.addBehavior){var storageOwner,storageContainer;try{storageContainer=new ActiveXObject("htmlfile");storageContainer.open();storageContainer.write("<s"+"cript>document.w=window</s"+'cript><iframe src="/favicon.ico"></iframe>');storageContainer.close();storageOwner=storageContainer.w.frames[0].document;storage=storageOwner.createElement("div")}catch(e){storage=doc.createElement("div");storageOwner=doc.body}function withIEStorage(storeFunction){return function(){var args=Array.prototype.slice.call(arguments,0);args.unshift(storage);storageOwner.appendChild(storage);storage.addBehavior("#default#userData");storage.load(localStorageName);var result=storeFunction.apply(store,args);storageOwner.removeChild(storage);return result}}var forbiddenCharsRegex=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");function ieKeyFix(key){return key.replace(forbiddenCharsRegex,"___")}store.set=withIEStorage(function(storage,key,val){key=ieKeyFix(key);if(val===undefined){return store.remove(key)}storage.setAttribute(key,store.serialize(val));storage.save(localStorageName);return val});store.get=withIEStorage(function(storage,key){key=ieKeyFix(key);return store.deserialize(storage.getAttribute(key))});store.remove=withIEStorage(function(storage,key){key=ieKeyFix(key);storage.removeAttribute(key);storage.save(localStorageName)});store.clear=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;storage.load(localStorageName);for(var i=0,attr;attr=attributes[i];i++){storage.removeAttribute(attr.name)}storage.save(localStorageName)});store.getAll=withIEStorage(function(storage){var attributes=storage.XMLDocument.documentElement.attributes;var ret={};for(var i=0,attr;attr=attributes[i];++i){var key=ieKeyFix(attr.name);ret[attr.name]=store.deserialize(storage.getAttribute(key))}return ret})}try{store.set(namespace,namespace);if(store.get(namespace)!=namespace){store.disabled=true}store.remove(namespace)}catch(e){store.disabled=true}store.enabled=!store.disabled;module.exports=store},{json:29}],39:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var each;try{each=require("each")}catch(err){each=require("each-component")}module.exports=traverse;function traverse(input,strict){if(strict===undefined)strict=true;if(is.object(input))return object(input,strict);if(is.array(input))return array(input,strict);return input}function object(obj,strict){each(obj,function(key,val){if(isodate.is(val,strict)){obj[key]=isodate.parse(val)}else if(is.object(val)||is.array(val)){traverse(val,strict)}});return obj}function array(arr,strict){each(arr,function(val,x){if(is.object(val)){traverse(val,strict)}else if(isodate.is(val,strict)){arr[x]=isodate.parse(val)}});return arr}},{is:42,isodate:43,each:5}],42:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":44,type:35,"component-type":35}],44:[function(require,module,exports){module.exports=isEmpty;var has=Object.prototype.hasOwnProperty;function isEmpty(val){if(null==val)return true;if("number"==typeof val)return 0===val;if(undefined!==val.length)return 0===val.length;for(var key in val)if(has.call(val,key))return false;return true}},{}],43:[function(require,module,exports){var matcher=/^(\d{4})(?:-?(\d{2})(?:-?(\d{2}))?)?(?:([ T])(\d{2}):?(\d{2})(?::?(\d{2})(?:[,\.](\d{1,}))?)?(?:(Z)|([+\-])(\d{2})(?::?(\d{2}))?)?)?$/;exports.parse=function(iso){var numericKeys=[1,5,6,7,11,12];var arr=matcher.exec(iso);var offset=0;if(!arr)return new Date(iso);for(var i=0,val;val=numericKeys[i];i++){arr[val]=parseInt(arr[val],10)||0}arr[2]=parseInt(arr[2],10)||1;arr[3]=parseInt(arr[3],10)||1;arr[2]--;arr[8]=arr[8]?(arr[8]+"00").substring(0,3):0;if(arr[4]==" "){offset=(new Date).getTimezoneOffset()}else if(arr[9]!=="Z"&&arr[10]){offset=arr[11]*60+arr[12];if("+"==arr[10])offset=0-offset}var millis=Date.UTC(arr[1],arr[2],arr[3],arr[5],arr[6]+offset,arr[7],arr[8]);return new Date(millis)};exports.is=function(string,strict){if(strict&&false===/^\d{4}-\d{2}-\d{2}/.test(string))return false;return matcher.test(string)}},{}],5:[function(require,module,exports){var type=require("type");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn){switch(type(obj)){case"array":return array(obj,fn);case"object":if("number"==typeof obj.length)return array(obj,fn);return object(obj,fn);case"string":return string(obj,fn)}};function string(obj,fn){for(var i=0;i<obj.length;++i){fn(obj.charAt(i),i)}}function object(obj,fn){for(var key in obj){if(has.call(obj,key)){fn(key,obj[key])}}}function array(obj,fn){for(var i=0;i<obj.length;++i){fn(obj[i],i)}}},{type:35}],40:[function(require,module,exports){module.exports=function extend(object){var args=Array.prototype.slice.call(arguments,1);for(var i=0,source;source=args[i];i++){if(!source)continue;for(var property in source){object[property]=source[property]}}return object}},{}],38:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],9:[function(require,module,exports){var debug=require("debug")("analytics:user");var Entity=require("./entity");var inherit=require("inherit");var bind=require("bind");var cookie=require("./cookie");User.defaults={persist:true,cookie:{key:"ajs_user_id",oldKey:"ajs_user"},localStorage:{key:"ajs_user_traits"}}; function User(options){this.defaults=User.defaults;this.debug=debug;Entity.call(this,options)}inherit(User,Entity);User.prototype.load=function(){if(this._loadOldCookie())return;Entity.prototype.load.call(this)};User.prototype._loadOldCookie=function(){var user=cookie.get(this._options.cookie.oldKey);if(!user)return false;this.id(user.id);this.traits(user.traits);cookie.remove(this._options.cookie.oldKey);return true};module.exports=bind.all(new User);module.exports.User=User},{"./entity":37,"./cookie":6,debug:15,inherit:38,bind:11}],10:[function(require,module,exports){module.exports=function after(times,func){if(times<=0)return func();return function(){if(--times<1){return func.apply(this,arguments)}}}},{}],12:[function(require,module,exports){var next=require("next-tick");module.exports=callback;function callback(fn){if("function"===typeof fn)fn()}callback.async=function(fn,wait){if("function"!==typeof fn)return;if(!wait)return next(fn);setTimeout(fn,wait)};callback.sync=callback},{"next-tick":45}],45:[function(require,module,exports){"use strict";if(typeof setImmediate=="function"){module.exports=function(f){setImmediate(f)}}else if(typeof process!="undefined"&&typeof process.nextTick=="function"){module.exports=process.nextTick}else if(typeof window=="undefined"||window.ActiveXObject||!window.postMessage){module.exports=function(f){setTimeout(f)}}else{var q=[];window.addEventListener("message",function(){var i=0;while(i<q.length){try{q[i++]()}catch(e){q=q.slice(i);window.postMessage("tic!","*");throw e}}q.length=0},true);module.exports=function(fn){if(!q.length)window.postMessage("tic!","*");q.push(fn)}}},{}],13:[function(require,module,exports){module.exports=function canonical(){var tags=document.getElementsByTagName("link");for(var i=0,tag;tag=tags[i];i++){if("canonical"==tag.getAttribute("rel"))return tag.getAttribute("href")}}},{}],17:[function(require,module,exports){var index=require("indexof");module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};Emitter.prototype.once=function(event,fn){var self=this;this._callbacks=this._callbacks||{};function on(){self.off(event,on);fn.apply(this,arguments)}fn._off=on;this.on(event,on);return this};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}var i=index(callbacks,fn._off||fn);if(~i)callbacks.splice(i,1);return this};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};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{indexof:46}],46:[function(require,module,exports){module.exports=function(arr,obj){if(arr.indexOf)return arr.indexOf(obj);for(var i=0;i<arr.length;++i){if(arr[i]===obj)return i}return-1}},{}],18:[function(require,module,exports){var isEmpty=require("is-empty");try{var typeOf=require("type")}catch(e){var typeOf=require("component-type")}var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":44,type:35,"component-type":35}],19:[function(require,module,exports){module.exports=isEmail;var matcher=/.+\@.+\..+/;function isEmail(string){return matcher.test(string)}},{}],20:[function(require,module,exports){module.exports=function isMeta(e){if(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)return true;var which=e.which,button=e.button;if(!which&&button!==undefined){return!button&1&&!button&2&&button&4}else if(which===2){return true}return false}},{}],21:[function(require,module,exports){var is=require("is");var isodate=require("isodate");var milliseconds=require("./milliseconds");var seconds=require("./seconds");module.exports=function newDate(val){if(is.date(val))return val;if(is.number(val))return new Date(toMs(val));if(isodate.is(val))return isodate.parse(val);if(milliseconds.is(val))return milliseconds.parse(val);if(seconds.is(val))return seconds.parse(val);return new Date(val)};function toMs(num){if(num<315576e5)return num*1e3;return num}},{"./milliseconds":47,"./seconds":48,is:49,isodate:43}],47:[function(require,module,exports){var matcher=/\d{13}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(millis){millis=parseInt(millis,10);return new Date(millis)}},{}],48:[function(require,module,exports){var matcher=/\d{10}/;exports.is=function(string){return matcher.test(string)};exports.parse=function(seconds){var millis=parseInt(seconds,10)*1e3;return new Date(millis)}},{}],49:[function(require,module,exports){var isEmpty=require("is-empty"),typeOf=require("type");var types=["arguments","array","boolean","date","element","function","null","number","object","regexp","string","undefined"];for(var i=0,type;type=types[i];i++)exports[type]=generate(type);exports.fn=exports["function"];exports.empty=isEmpty;exports.nan=function(val){return exports.number(val)&&val!=val};function generate(type){return function(value){return type===typeOf(value)}}},{"is-empty":44,type:35}],22:[function(require,module,exports){exports.bind=function(el,type,fn,capture){if(el.addEventListener){el.addEventListener(type,fn,capture||false)}else{el.attachEvent("on"+type,fn)}return fn};exports.unbind=function(el,type,fn,capture){if(el.removeEventListener){el.removeEventListener(type,fn,capture||false)}else{el.detachEvent("on"+type,fn)}return fn}},{}],23:[function(require,module,exports){module.exports=function(e){e=e||window.event;return e.preventDefault?e.preventDefault():e.returnValue=false}},{}],24:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:50,type:35}],50:[function(require,module,exports){exports=module.exports=trim;function trim(str){if(str.trim)return str.trim();return str.replace(/^\s*|\s*$/g,"")}exports.left=function(str){if(str.trimLeft)return str.trimLeft();return str.replace(/^\s*/,"")};exports.right=function(str){if(str.trimRight)return str.trimRight();return str.replace(/\s*$/,"")}},{}],25:[function(require,module,exports){var has=Object.prototype.hasOwnProperty;exports.keys=Object.keys||function(obj){var keys=[];for(var key in obj){if(has.call(obj,key)){keys.push(key)}}return keys};exports.values=function(obj){var vals=[];for(var key in obj){if(has.call(obj,key)){vals.push(obj[key])}}return vals};exports.merge=function(a,b){for(var key in b){if(has.call(b,key)){a[key]=b[key]}}return a};exports.length=function(obj){return exports.keys(obj).length};exports.isEmpty=function(obj){return 0==exports.length(obj)}},{}],27:[function(require,module,exports){var Facade=require("./facade");module.exports=Facade;Facade.Alias=require("./alias");Facade.Group=require("./group");Facade.Identify=require("./identify");Facade.Track=require("./track");Facade.Page=require("./page");Facade.Screen=require("./screen")},{"./facade":51,"./alias":52,"./group":53,"./identify":54,"./track":55,"./page":56,"./screen":57}],51:[function(require,module,exports){var clone=require("./utils").clone;var isEnabled=require("./is-enabled");var objCase=require("obj-case");var traverse=require("isodate-traverse");var newDate=require("new-date");module.exports=Facade;function Facade(obj){if(!obj.hasOwnProperty("timestamp"))obj.timestamp=new Date;else obj.timestamp=newDate(obj.timestamp);traverse(obj);this.obj=obj}Facade.prototype.proxy=function(field){var fields=field.split(".");field=fields.shift();var obj=this[field]||this.field(field);if(!obj)return obj;if(typeof obj==="function")obj=obj.call(this)||{};if(fields.length===0)return transform(obj);obj=objCase(obj,fields.join("."));return transform(obj)};Facade.prototype.field=function(field){var obj=this.obj[field];return transform(obj)};Facade.proxy=function(field){return function(){return this.proxy(field)}};Facade.field=function(field){return function(){return this.field(field)}};Facade.prototype.json=function(){var ret=clone(this.obj);if(this.type)ret.type=this.type();return ret};Facade.prototype.context=Facade.prototype.options=function(integration){var options=clone(this.obj.options||this.obj.context)||{};if(!integration)return clone(options);if(!this.enabled(integration))return;var integrations=this.integrations();var value=integrations[integration]||objCase(integrations,integration);if("boolean"==typeof value)value={};return value||{}};Facade.prototype.enabled=function(integration){var allEnabled=this.proxy("options.providers.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("options.all");if(typeof allEnabled!=="boolean")allEnabled=this.proxy("integrations.all");if(typeof allEnabled!=="boolean")allEnabled=true;var enabled=allEnabled&&isEnabled(integration);var options=this.integrations();if(options.providers&&options.providers.hasOwnProperty(integration)){enabled=options.providers[integration]}if(options.hasOwnProperty(integration)){var settings=options[integration];if(typeof settings==="boolean"){enabled=settings}else{enabled=true}}return enabled?true:false};Facade.prototype.integrations=function(){return this.obj.integrations||this.proxy("options.providers")||this.options()};Facade.prototype.active=function(){var active=this.proxy("options.active");if(active===null||active===undefined)active=true;return active};Facade.prototype.sessionId=Facade.prototype.anonymousId=function(){return this.field("anonymousId")||this.field("sessionId")};Facade.prototype.groupId=Facade.proxy("options.groupId");Facade.prototype.traits=function(aliases){var ret=this.proxy("options.traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("options.traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Facade.prototype.library=function(){var library=this.proxy("options.library");if(!library)return{name:"unknown",version:null};if(typeof library==="string")return{name:library,version:null};return library};Facade.prototype.userId=Facade.field("userId");Facade.prototype.channel=Facade.field("channel");Facade.prototype.timestamp=Facade.field("timestamp");Facade.prototype.userAgent=Facade.proxy("options.userAgent");Facade.prototype.ip=Facade.proxy("options.ip");function transform(obj){var cloned=clone(obj);return cloned}},{"./utils":58,"./is-enabled":59,"obj-case":60,"isodate-traverse":39,"new-date":21}],58:[function(require,module,exports){try{exports.inherit=require("inherit");exports.clone=require("clone")}catch(e){exports.inherit=require("inherit-component");exports.clone=require("clone-component")}},{inherit:61,clone:62}],61:[function(require,module,exports){module.exports=function(a,b){var fn=function(){};fn.prototype=b.prototype;a.prototype=new fn;a.prototype.constructor=a}},{}],62:[function(require,module,exports){var type;try{type=require("component-type")}catch(_){type=require("type")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{"component-type":35,type:35}],59:[function(require,module,exports){var disabled={Salesforce:true,Marketo:true};module.exports=function(integration){return!disabled[integration]}},{}],60:[function(require,module,exports){var Case=require("case");var identity=function(_){return _};var cases=[identity,Case.upper,Case.lower,Case.snake,Case.pascal,Case.camel,Case.constant,Case.title,Case.capital,Case.sentence];module.exports=module.exports.find=multiple(find);module.exports.replace=function(obj,key,val){multiple(replace).apply(this,arguments);return obj};module.exports.del=function(obj,key){multiple(del).apply(this,arguments);return obj};function multiple(fn){return function(obj,key,val){var keys=key.split(".");if(keys.length===0)return;while(keys.length>1){key=keys.shift();obj=find(obj,key);if(obj===null||obj===undefined)return}key=keys.shift();return fn(obj,key,val)}}function find(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))return obj[cased]}}function del(obj,key){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))delete obj[cased]}return obj}function replace(obj,key,val){for(var i=0;i<cases.length;i++){var cased=cases[i](key);if(obj.hasOwnProperty(cased))obj[cased]=val}return obj}},{"case":63}],63:[function(require,module,exports){var cases=require("./cases");module.exports=exports=determineCase;function determineCase(string){for(var key in cases){if(key=="none")continue;var convert=cases[key];if(convert(string)==string)return key}return null}exports.add=function(name,convert){exports[name]=cases[name]=convert};for(var key in cases){exports.add(key,cases[key])}},{"./cases":64}],64:[function(require,module,exports){var camel=require("to-camel-case"),capital=require("to-capital-case"),constant=require("to-constant-case"),dot=require("to-dot-case"),none=require("to-no-case"),pascal=require("to-pascal-case"),sentence=require("to-sentence-case"),slug=require("to-slug-case"),snake=require("to-snake-case"),space=require("to-space-case"),title=require("to-title-case");exports.camel=camel;exports.pascal=pascal;exports.dot=dot;exports.slug=slug;exports.snake=snake;exports.space=space;exports.constant=constant;exports.capital=capital;exports.title=title;exports.sentence=sentence;exports.lower=function(string){return none(string).toLowerCase()};exports.upper=function(string){return none(string).toUpperCase()};exports.inverse=function(string){for(var i=0,char;char=string[i];i++){if(!/[a-z]/i.test(char))continue;var upper=char.toUpperCase();var lower=char.toLowerCase();string[i]=char==upper?lower:upper}return string};exports.none=none},{"to-camel-case":65,"to-capital-case":66,"to-constant-case":67,"to-dot-case":68,"to-no-case":69,"to-pascal-case":70,"to-sentence-case":71,"to-slug-case":72,"to-snake-case":73,"to-space-case":74,"to-title-case":75}],65:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toCamelCase;function toCamelCase(string){return toSpace(string).replace(/\s(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":74}],74:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":69}],69:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasCamel=/[a-z][A-Z]/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))string=unseparate(string);if(hasCamel.test(string))string=uncamelize(string);return string.toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],66:[function(require,module,exports){var clean=require("to-no-case");module.exports=toCapitalCase;function toCapitalCase(string){return clean(string).replace(/(^|\s)(\w)/g,function(matches,previous,letter){return previous+letter.toUpperCase()})}},{"to-no-case":69}],67:[function(require,module,exports){var snake=require("to-snake-case");module.exports=toConstantCase;function toConstantCase(string){return snake(string).toUpperCase()}},{"to-snake-case":73}],73:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":74}],68:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toDotCase;function toDotCase(string){return toSpace(string).replace(/\s/g,".")}},{"to-space-case":74}],70:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toPascalCase;function toPascalCase(string){return toSpace(string).replace(/(?:^|\s)(\w)/g,function(matches,letter){return letter.toUpperCase()})}},{"to-space-case":74}],71:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSentenceCase;function toSentenceCase(string){return clean(string).replace(/[a-z]/i,function(letter){return letter.toUpperCase()})}},{"to-no-case":69}],72:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSlugCase;function toSlugCase(string){return toSpace(string).replace(/\s/g,"-")}},{"to-space-case":74}],75:[function(require,module,exports){var capital=require("to-capital-case"),escape=require("escape-regexp"),map=require("map"),minors=require("title-case-minors");module.exports=toTitleCase;var escaped=map(minors,escape);var minorMatcher=new RegExp("[^^]\\b("+escaped.join("|")+")\\b","ig");var colonMatcher=/:\s*(\w)/g;function toTitleCase(string){return capital(string).replace(minorMatcher,function(minor){return minor.toLowerCase()}).replace(colonMatcher,function(letter){return letter.toUpperCase()})}},{"to-capital-case":66,"escape-regexp":76,map:77,"title-case-minors":78}],76:[function(require,module,exports){module.exports=function(str){return String(str).replace(/([.*+?=^!:${}()|[\]\/\\])/g,"\\$1")}},{}],77:[function(require,module,exports){var each=require("each");module.exports=function map(obj,iterator){var arr=[];each(obj,function(o){arr.push(iterator.apply(null,arguments))});return arr}},{each:79}],79:[function(require,module,exports){try{var type=require("type")}catch(err){var type=require("component-type")}var toFunction=require("to-function");var has=Object.prototype.hasOwnProperty;module.exports=function(obj,fn,ctx){fn=toFunction(fn);ctx=ctx||this;switch(type(obj)){case"array":return array(obj,fn,ctx);case"object":if("number"==typeof obj.length)return array(obj,fn,ctx);return object(obj,fn,ctx);case"string":return string(obj,fn,ctx)}};function string(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj.charAt(i),i)}}function object(obj,fn,ctx){for(var key in obj){if(has.call(obj,key)){fn.call(ctx,key,obj[key])}}}function array(obj,fn,ctx){for(var i=0;i<obj.length;++i){fn.call(ctx,obj[i],i)}}},{type:35,"component-type":35,"to-function":80}],80:[function(require,module,exports){var expr;try{expr=require("props")}catch(e){expr=require("component-props")}module.exports=toFunction;function toFunction(obj){switch({}.toString.call(obj)){case"[object Object]":return objectToFunction(obj);case"[object Function]":return obj;case"[object String]":return stringToFunction(obj);case"[object RegExp]":return regexpToFunction(obj);default:return defaultToFunction(obj)}}function defaultToFunction(val){return function(obj){return val===obj}}function regexpToFunction(re){return function(obj){return re.test(obj)}}function stringToFunction(str){if(/^ *\W+/.test(str))return new Function("_","return _ "+str);return new Function("_","return "+get(str))}function objectToFunction(obj){var match={};for(var key in obj){match[key]=typeof obj[key]==="string"?defaultToFunction(obj[key]):toFunction(obj[key])}return function(val){if(typeof val!=="object")return false;for(var key in match){if(!(key in val))return false;if(!match[key](val[key]))return false}return true}}function get(str){var props=expr(str);if(!props.length)return"_."+str;var val,i,prop;for(i=0;i<props.length;i++){prop=props[i];val="_."+prop;val="('function' == typeof "+val+" ? "+val+"() : "+val+")";str=stripNested(prop,str,val)}return str}function stripNested(prop,str,val){return str.replace(new RegExp("(\\.)?"+prop,"g"),function($0,$1){return $1?$0:val})}},{props:81,"component-props":81}],81:[function(require,module,exports){var globals=/\b(this|Array|Date|Object|Math|JSON)\b/g;module.exports=function(str,fn){var p=unique(props(str));if(fn&&"string"==typeof fn)fn=prefixed(fn);if(fn)return map(str,p,fn);return p};function props(str){return str.replace(/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\//g,"").replace(globals,"").match(/[$a-zA-Z_]\w*/g)||[]}function map(str,props,fn){var re=/\.\w+|\w+ *\(|"[^"]*"|'[^']*'|\/([^/]+)\/|[a-zA-Z_]\w*/g;return str.replace(re,function(_){if("("==_[_.length-1])return fn(_);if(!~props.indexOf(_))return _;return fn(_)})}function unique(arr){var ret=[];for(var i=0;i<arr.length;i++){if(~ret.indexOf(arr[i]))continue;ret.push(arr[i])}return ret}function prefixed(str){return function(_){return str+_}}},{}],78:[function(require,module,exports){module.exports=["a","an","and","as","at","but","by","en","for","from","how","if","in","neither","nor","of","on","only","onto","out","or","per","so","than","that","the","to","until","up","upon","v","v.","versus","vs","vs.","via","when","with","without","yet"]},{}],52:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");module.exports=Alias;function Alias(dictionary){Facade.call(this,dictionary)}inherit(Alias,Facade);Alias.prototype.type=Alias.prototype.action=function(){return"alias"};Alias.prototype.from=Alias.prototype.previousId=function(){return this.field("previousId")||this.field("from")};Alias.prototype.to=Alias.prototype.userId=function(){return this.field("userId")||this.field("to")}},{"./utils":58,"./facade":51}],53:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");var newDate=require("new-date");module.exports=Group;function Group(dictionary){Facade.call(this,dictionary)}inherit(Group,Facade);Group.prototype.type=Group.prototype.action=function(){return"group"};Group.prototype.groupId=Facade.field("groupId");Group.prototype.created=function(){var created=this.proxy("traits.createdAt")||this.proxy("traits.created")||this.proxy("properties.createdAt")||this.proxy("properties.created");if(created)return newDate(created)};Group.prototype.traits=function(aliases){var ret=this.properties();var id=this.groupId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Group.prototype.properties=function(){return this.field("traits")||this.field("properties")||{}}},{"./utils":58,"./facade":51,"new-date":21}],54:[function(require,module,exports){var Facade=require("./facade");var isEmail=require("is-email");var newDate=require("new-date");var utils=require("./utils");var trim=require("trim");var inherit=utils.inherit;var clone=utils.clone;module.exports=Identify;function Identify(dictionary){Facade.call(this,dictionary)}inherit(Identify,Facade);Identify.prototype.type=Identify.prototype.action=function(){return"identify"};Identify.prototype.traits=function(aliases){var ret=this.field("traits")||{};var id=this.userId();aliases=aliases||{};if(id)ret.id=id;for(var alias in aliases){var value=null==this[alias]?this.proxy("traits."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;if(alias!==aliases[alias])delete ret[alias]}return ret};Identify.prototype.email=function(){var email=this.proxy("traits.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Identify.prototype.created=function(){var created=this.proxy("traits.created")||this.proxy("traits.createdAt");if(created)return newDate(created)};Identify.prototype.companyCreated=function(){var created=this.proxy("traits.company.created")||this.proxy("traits.company.createdAt");if(created)return newDate(created)};Identify.prototype.name=function(){var name=this.proxy("traits.name");if(typeof name==="string")return trim(name);var firstName=this.firstName();var lastName=this.lastName();if(firstName&&lastName)return trim(firstName+" "+lastName)};Identify.prototype.firstName=function(){var firstName=this.proxy("traits.firstName");if(typeof firstName==="string")return trim(firstName);var name=this.proxy("traits.name");if(typeof name==="string")return trim(name).split(" ")[0]};Identify.prototype.lastName=function(){var lastName=this.proxy("traits.lastName");if(typeof lastName==="string")return trim(lastName);var name=this.proxy("traits.name");if(typeof name!=="string")return;var space=trim(name).indexOf(" ");if(space===-1)return;return trim(name.substr(space+1))};Identify.prototype.uid=function(){return this.userId()||this.username()||this.email()};Identify.prototype.description=function(){return this.proxy("traits.description")||this.proxy("traits.background")};Identify.prototype.username=Facade.proxy("traits.username");Identify.prototype.website=Facade.proxy("traits.website");Identify.prototype.phone=Facade.proxy("traits.phone");Identify.prototype.address=Facade.proxy("traits.address");Identify.prototype.avatar=Facade.proxy("traits.avatar")},{"./facade":51,"./utils":58,"is-email":19,"new-date":21,trim:50}],55:[function(require,module,exports){var inherit=require("./utils").inherit;var clone=require("./utils").clone;var Facade=require("./facade");var Identify=require("./identify");var isEmail=require("is-email");module.exports=Track;function Track(dictionary){Facade.call(this,dictionary)}inherit(Track,Facade);Track.prototype.type=Track.prototype.action=function(){return"track"};Track.prototype.event=Facade.field("event");Track.prototype.value=Facade.proxy("properties.value");Track.prototype.category=Facade.proxy("properties.category");Track.prototype.country=Facade.proxy("properties.country");Track.prototype.state=Facade.proxy("properties.state");Track.prototype.city=Facade.proxy("properties.city");Track.prototype.zip=Facade.proxy("properties.zip");Track.prototype.id=Facade.proxy("properties.id");Track.prototype.sku=Facade.proxy("properties.sku");Track.prototype.tax=Facade.proxy("properties.tax");Track.prototype.name=Facade.proxy("properties.name");Track.prototype.price=Facade.proxy("properties.price");Track.prototype.total=Facade.proxy("properties.total");Track.prototype.coupon=Facade.proxy("properties.coupon");Track.prototype.shipping=Facade.proxy("properties.shipping");Track.prototype.orderId=function(){return this.proxy("properties.id")||this.proxy("properties.orderId")};Track.prototype.subtotal=function(){var subtotal=this.obj.properties.subtotal;var total=this.total();var n;if(subtotal)return subtotal;if(!total)return 0;if(n=this.tax())total-=n;if(n=this.shipping())total-=n;return total};Track.prototype.products=function(){var props=this.obj.properties||{};return props.products||[]};Track.prototype.quantity=function(){var props=this.obj.properties||{};return props.quantity||1};Track.prototype.currency=function(){var props=this.obj.properties||{};return props.currency||"USD"};Track.prototype.referrer=Facade.proxy("properties.referrer");Track.prototype.query=Facade.proxy("options.query");Track.prototype.properties=function(aliases){var ret=this.field("properties")||{};aliases=aliases||{};for(var alias in aliases){var value=null==this[alias]?this.proxy("properties."+alias):this[alias]();if(null==value)continue;ret[aliases[alias]]=value;delete ret[alias]}return ret};Track.prototype.username=function(){return this.proxy("traits.username")||this.proxy("properties.username")||this.userId()||this.sessionId()};Track.prototype.email=function(){var email=this.proxy("traits.email");email=email||this.proxy("properties.email");if(email)return email;var userId=this.userId();if(isEmail(userId))return userId};Track.prototype.revenue=function(){var revenue=this.proxy("properties.revenue");var event=this.event();if(!revenue&&event&&event.match(/completed ?order/i)){revenue=this.proxy("properties.total")}return currency(revenue)};Track.prototype.cents=function(){var revenue=this.revenue();return"number"!=typeof revenue?this.value()||0:revenue*100};Track.prototype.identify=function(){var json=this.json();json.traits=this.traits();return new Identify(json)};function currency(val){if(!val)return;if(typeof val==="number")return val;if(typeof val!=="string")return;val=val.replace(/\$/g,"");val=parseFloat(val);if(!isNaN(val))return val}},{"./utils":58,"./facade":51,"./identify":54,"is-email":19}],56:[function(require,module,exports){var inherit=require("./utils").inherit;var Facade=require("./facade");var Track=require("./track");module.exports=Page;function Page(dictionary){Facade.call(this,dictionary)}inherit(Page,Facade);Page.prototype.type=Page.prototype.action=function(){return"page"};Page.prototype.category=Facade.field("category");Page.prototype.name=Facade.field("name");Page.prototype.properties=function(){var props=this.field("properties")||{};var category=this.category();var name=this.name();if(category)props.category=category;if(name)props.name=name;return props};Page.prototype.fullName=function(){var category=this.category();var name=this.name();return name&&category?category+" "+name:name};Page.prototype.event=function(name){return name?"Viewed "+name+" Page":"Loaded a Page"};Page.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),properties:props})}},{"./utils":58,"./facade":51,"./track":55}],57:[function(require,module,exports){var inherit=require("./utils").inherit;var Page=require("./page");var Track=require("./track");module.exports=Screen;function Screen(dictionary){Page.call(this,dictionary)}inherit(Screen,Page);Screen.prototype.type=Screen.prototype.action=function(){return"screen"};Screen.prototype.event=function(name){return name?"Viewed "+name+" Screen":"Loaded a Screen"};Screen.prototype.track=function(name){var props=this.properties();return new Track({event:this.event(name),properties:props})}},{"./utils":58,"./page":56,"./track":55}],3:[function(require,module,exports){module.exports="2.3.9"},{}],4:[function(require,module,exports){var each=require("each");var plugins=require("./integrations.js");each(plugins,function(plugin){var name=(plugin.Integration||plugin).prototype.name;exports[name]=plugin})},{"./integrations.js":82,each:5}],82:[function(require,module,exports){module.exports=[require("./lib/adroll"),require("./lib/adwords"),require("./lib/alexa"),require("./lib/amplitude"),require("./lib/appcues"),require("./lib/awesm"),require("./lib/awesomatic"),require("./lib/bing-ads"),require("./lib/bronto"),require("./lib/bugherd"),require("./lib/bugsnag"),require("./lib/chartbeat"),require("./lib/churnbee"),require("./lib/clicktale"),require("./lib/clicky"),require("./lib/comscore"),require("./lib/crazy-egg"),require("./lib/curebit"),require("./lib/customerio"),require("./lib/drip"),require("./lib/errorception"),require("./lib/evergage"),require("./lib/facebook-ads"),require("./lib/foxmetrics"),require("./lib/frontleaf"),require("./lib/gauges"),require("./lib/get-satisfaction"),require("./lib/google-analytics"),require("./lib/google-tag-manager"),require("./lib/gosquared"),require("./lib/heap"),require("./lib/hellobar"),require("./lib/hittail"),require("./lib/hublo"),require("./lib/hubspot"),require("./lib/improvely"),require("./lib/insidevault"),require("./lib/inspectlet"),require("./lib/intercom"),require("./lib/keen-io"),require("./lib/kenshoo"),require("./lib/kissmetrics"),require("./lib/klaviyo"),require("./lib/leadlander"),require("./lib/livechat"),require("./lib/lucky-orange"),require("./lib/lytics"),require("./lib/mixpanel"),require("./lib/mojn"),require("./lib/mouseflow"),require("./lib/mousestats"),require("./lib/navilytics"),require("./lib/olark"),require("./lib/optimizely"),require("./lib/perfect-audience"),require("./lib/pingdom"),require("./lib/piwik"),require("./lib/preact"),require("./lib/qualaroo"),require("./lib/quantcast"),require("./lib/rollbar"),require("./lib/saasquatch"),require("./lib/sentry"),require("./lib/snapengage"),require("./lib/spinnakr"),require("./lib/tapstream"),require("./lib/trakio"),require("./lib/twitter-ads"),require("./lib/usercycle"),require("./lib/userfox"),require("./lib/uservoice"),require("./lib/vero"),require("./lib/visual-website-optimizer"),require("./lib/webengage"),require("./lib/woopra"),require("./lib/yandex-metrica")] },{"./lib/adroll":83,"./lib/adwords":84,"./lib/alexa":85,"./lib/amplitude":86,"./lib/appcues":87,"./lib/awesm":88,"./lib/awesomatic":89,"./lib/bing-ads":90,"./lib/bronto":91,"./lib/bugherd":92,"./lib/bugsnag":93,"./lib/chartbeat":94,"./lib/churnbee":95,"./lib/clicktale":96,"./lib/clicky":97,"./lib/comscore":98,"./lib/crazy-egg":99,"./lib/curebit":100,"./lib/customerio":101,"./lib/drip":102,"./lib/errorception":103,"./lib/evergage":104,"./lib/facebook-ads":105,"./lib/foxmetrics":106,"./lib/frontleaf":107,"./lib/gauges":108,"./lib/get-satisfaction":109,"./lib/google-analytics":110,"./lib/google-tag-manager":111,"./lib/gosquared":112,"./lib/heap":113,"./lib/hellobar":114,"./lib/hittail":115,"./lib/hublo":116,"./lib/hubspot":117,"./lib/improvely":118,"./lib/insidevault":119,"./lib/inspectlet":120,"./lib/intercom":121,"./lib/keen-io":122,"./lib/kenshoo":123,"./lib/kissmetrics":124,"./lib/klaviyo":125,"./lib/leadlander":126,"./lib/livechat":127,"./lib/lucky-orange":128,"./lib/lytics":129,"./lib/mixpanel":130,"./lib/mojn":131,"./lib/mouseflow":132,"./lib/mousestats":133,"./lib/navilytics":134,"./lib/olark":135,"./lib/optimizely":136,"./lib/perfect-audience":137,"./lib/pingdom":138,"./lib/piwik":139,"./lib/preact":140,"./lib/qualaroo":141,"./lib/quantcast":142,"./lib/rollbar":143,"./lib/saasquatch":144,"./lib/sentry":145,"./lib/snapengage":146,"./lib/spinnakr":147,"./lib/tapstream":148,"./lib/trakio":149,"./lib/twitter-ads":150,"./lib/usercycle":151,"./lib/userfox":152,"./lib/uservoice":153,"./lib/vero":154,"./lib/visual-website-optimizer":155,"./lib/webengage":156,"./lib/woopra":157,"./lib/yandex-metrica":158}],83:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var useHttps=require("use-https");var each=require("each");var is=require("is");var has=Object.prototype.hasOwnProperty;var AdRoll=module.exports=integration("AdRoll").assumesPageview().global("__adroll_loaded").global("adroll_adv_id").global("adroll_pix_id").global("adroll_custom_data").option("advId","").option("pixId","").tag("http",'<script src="http://a.adroll.com/j/roundtrip.js">').tag("https",'<script src="https://s.adroll.com/j/roundtrip.js">').mapping("events");AdRoll.prototype.initialize=function(page){window.adroll_adv_id=this.options.advId;window.adroll_pix_id=this.options.pixId;window.__adroll_loaded=true;var name=useHttps()?"https":"http";this.load(name,this.ready)};AdRoll.prototype.loaded=function(){return window.__adroll};AdRoll.prototype.page=function(page){var name=page.fullName();this.track(page.track(name))};AdRoll.prototype.track=function(track){var event=track.event();var user=this.analytics.user();var events=this.events(event);var total=track.revenue()||track.total()||0;var orderId=track.orderId()||0;each(events,function(event){var data={};if(user.id())data.user_id=user.id();data.adroll_conversion_value_in_dollars=total;data.order_id=orderId;data.adroll_segments=snake(event);window.__adroll.record_user(data)});if(!events.length){var data={};if(user.id())data.user_id=user.id();data.adroll_segments=snake(event);window.__adroll.record_user(data)}}},{"analytics.js-integration":159,"to-snake-case":160,"use-https":161,each:5,is:18}],159:[function(require,module,exports){var bind=require("bind");var callback=require("callback");var clone=require("clone");var debug=require("debug");var defaults=require("defaults");var protos=require("./protos");var slug=require("slug");var statics=require("./statics");module.exports=createIntegration;function createIntegration(name){function Integration(options){if(options&&options.addIntegration){return options.addIntegration(Integration)}this.debug=debug("analytics:integration:"+slug(name));this.options=defaults(clone(options)||{},this.defaults);this._queue=[];this.once("ready",bind(this,this.flush));Integration.emit("construct",this);this.ready=bind(this,this.ready);this._wrapInitialize();this._wrapPage();this._wrapTrack()}Integration.prototype.defaults={};Integration.prototype.globals=[];Integration.prototype.templates={};Integration.prototype.name=name;for(var key in statics)Integration[key]=statics[key];for(var key in protos)Integration.prototype[key]=protos[key];return Integration}},{"./protos":162,"./statics":163,bind:164,callback:12,clone:14,debug:165,defaults:16,slug:166}],162:[function(require,module,exports){var loadScript=require("segmentio/load-script");var normalize=require("to-no-case");var callback=require("callback");var Emitter=require("emitter");var events=require("./events");var tick=require("next-tick");var assert=require("assert");var after=require("after");var each=require("component/each");var type=require("type");var fmt=require("yields/fmt");var setTimeout=window.setTimeout;var setInterval=window.setInterval;var onerror=null;var onload=null;Emitter(exports);exports.initialize=function(){var ready=this.ready;tick(ready)};exports.loaded=function(){return false};exports.load=function(cb){callback.async(cb)};exports.page=function(page){};exports.track=function(track){};exports.map=function(obj,str){var a=normalize(str);var ret=[];if(!obj)return ret;if("object"==type(obj)){for(var k in obj){var item=obj[k];var b=normalize(k);if(b==a)ret.push(item)}}if("array"==type(obj)){if(!obj.length)return ret;if(!obj[0].key)return ret;for(var i=0;i<obj.length;++i){var item=obj[i];var b=normalize(item.key);if(b==a)ret.push(item.value)}}return ret};exports.invoke=function(method){if(!this[method])return;var args=[].slice.call(arguments,1);if(!this._ready)return this.queue(method,args);var ret;try{this.debug("%s with %o",method,args);ret=this[method].apply(this,args)}catch(e){this.debug("error %o calling %s with %o",e,method,args)}return ret};exports.queue=function(method,args){if("page"==method&&this._assumesPageview&&!this._initialized){return this.page.apply(this,args)}this._queue.push({method:method,args:args})};exports.flush=function(){this._ready=true;var call;while(call=this._queue.shift())this[call.method].apply(this,call.args)};exports.reset=function(){for(var i=0,key;key=this.globals[i];i++)window[key]=undefined;window.setTimeout=setTimeout;window.setInterval=setInterval;window.onerror=onerror;window.onload=onload};exports.load=function(name,locals,fn){if("function"==typeof name)fn=name,locals=null,name=null;if(name&&"object"==typeof name)fn=locals,locals=name,name=null;if("function"==typeof locals)fn=locals,locals=null;name=name||"library";locals=locals||{};locals=this.locals(locals);var template=this.templates[name];assert(template,fmt('Template "%s" not defined.',name));var attrs=render(template,locals);var el;switch(template.type){case"img":attrs.width=1;attrs.height=1;el=loadImage(attrs,fn);break;case"script":el=loadScript(attrs,fn);delete attrs.src;each(attrs,function(key,val){el.setAttribute(key,val)});break;case"iframe":el=loadIframe(attrs,fn);break}return el};exports.locals=function(locals){locals=locals||{};var cache=Math.floor((new Date).getTime()/36e5);if(!locals.hasOwnProperty("cache"))locals.cache=cache;each(this.options,function(key,val){if(!locals.hasOwnProperty(key))locals[key]=val});return locals};exports.ready=function(){this.emit("ready")};exports._wrapInitialize=function(){var initialize=this.initialize;this.initialize=function(){this.debug("initialize");this._initialized=true;var ret=initialize.apply(this,arguments);this.emit("initialize");return ret};if(this._assumesPageview)this.initialize=after(2,this.initialize)};exports._wrapPage=function(){var page=this.page;this.page=function(){if(this._assumesPageview&&!this._initialized){return this.initialize.apply(this,arguments)}return page.apply(this,arguments)}};exports._wrapTrack=function(){var t=this.track;this.track=function(track){var event=track.event();var called;var ret;for(var method in events){var regexp=events[method];if(!this[method])continue;if(!regexp.test(event))continue;ret=this[method].apply(this,arguments);called=true;break}if(!called)ret=t.apply(this,arguments);return ret}};function loadImage(attrs,fn){fn=fn||function(){};var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};img.src=attrs.src;img.width=1;img.height=1;return img}function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}function render(template,locals){var attrs={};each(template.attrs,function(key,val){attrs[key]=val.replace(/\{\{\ *(\w+)\ *\}\}/g,function(_,$1){return locals[$1]})});return attrs}},{"./events":167,"segmentio/load-script":168,"to-no-case":169,callback:12,emitter:17,"next-tick":45,assert:170,after:10,"component/each":79,type:35,"yields/fmt":171}],167:[function(require,module,exports){module.exports={removedProduct:/removed[ _]?product/i,viewedProduct:/viewed[ _]?product/i,addedProduct:/added[ _]?product/i,completedOrder:/completed[ _]?order/i}},{}],168:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":172,"next-tick":45,type:35}],172:[function(require,module,exports){module.exports=function(el,fn){return el.addEventListener?add(el,fn):attach(el,fn)};function add(el,fn){el.addEventListener("load",function(_,e){fn(null,e)},false);el.addEventListener("error",function(e){var err=new Error('failed to load the script "'+el.src+'"');err.event=e;fn(err)},false)}function attach(el,fn){el.attachEvent("onreadystatechange",function(e){if(!/complete|loaded/.test(el.readyState))return;fn(null,e)})}},{}],169:[function(require,module,exports){module.exports=toNoCase;var hasSpace=/\s/;var hasSeparator=/[\W_]/;function toNoCase(string){if(hasSpace.test(string))return string.toLowerCase();if(hasSeparator.test(string))return unseparate(string).toLowerCase();return uncamelize(string).toLowerCase()}var separatorSplitter=/[\W_]+(.|$)/g;function unseparate(string){return string.replace(separatorSplitter,function(m,next){return next?" "+next:""})}var camelSplitter=/(.)([A-Z]+)/g;function uncamelize(string){return string.replace(camelSplitter,function(m,previous,uppers){return previous+" "+uppers.toLowerCase().split("").join(" ")})}},{}],170:[function(require,module,exports){var equals=require("equals");var fmt=require("fmt");var stack=require("stack");module.exports=exports=function(expr,msg){if(expr)return;throw new Error(msg||message())};exports.equal=function(actual,expected,msg){if(actual==expected)return;throw new Error(msg||fmt("Expected %o to equal %o.",actual,expected))};exports.notEqual=function(actual,expected,msg){if(actual!=expected)return;throw new Error(msg||fmt("Expected %o not to equal %o.",actual,expected))};exports.deepEqual=function(actual,expected,msg){if(equals(actual,expected))return;throw new Error(msg||fmt("Expected %o to deeply equal %o.",actual,expected))};exports.notDeepEqual=function(actual,expected,msg){if(!equals(actual,expected))return;throw new Error(msg||fmt("Expected %o not to deeply equal %o.",actual,expected))};exports.strictEqual=function(actual,expected,msg){if(actual===expected)return;throw new Error(msg||fmt("Expected %o to strictly equal %o.",actual,expected))};exports.notStrictEqual=function(actual,expected,msg){if(actual!==expected)return;throw new Error(msg||fmt("Expected %o not to strictly equal %o.",actual,expected))};exports.throws=function(block,error,msg){var err;try{block()}catch(e){err=e}if(!err)throw new Error(msg||fmt("Expected %s to throw an error.",block.toString()));if(error&&!(err instanceof error)){throw new Error(msg||fmt("Expected %s to throw an %o.",block.toString(),error))}};exports.doesNotThrow=function(block,error,msg){var err;try{block()}catch(e){err=e}if(err)throw new Error(msg||fmt("Expected %s not to throw an error.",block.toString()));if(error&&err instanceof error){throw new Error(msg||fmt("Expected %s not to throw an %o.",block.toString(),error))}};function message(){if(!Error.captureStackTrace)return"assertion failed";var callsite=stack()[2];var fn=callsite.getFunctionName();var file=callsite.getFileName();var line=callsite.getLineNumber()-1;var col=callsite.getColumnNumber()-1;var src=get(file);line=src.split("\n")[line].slice(col);var m=line.match(/assert\((.*)\)/);return m&&m[1].trim()}function get(script){var xhr=new XMLHttpRequest;xhr.open("GET",script,false);xhr.send(null);return xhr.responseText}},{equals:173,fmt:171,stack:174}],173:[function(require,module,exports){var type=require("type");module.exports=equals;equals.compare=compare;function equals(){var i=arguments.length-1;while(i>0){if(!compare(arguments[i],arguments[--i]))return false}return true}function compare(a,b,memos){if(a===b)return true;var fnA=types[type(a)];var fnB=types[type(b)];return fnA&&fnA===fnB?fnA(a,b,memos):false}var types={};types.number=function(a){return a!==a};types["function"]=function(a,b,memos){return a.toString()===b.toString()&&types.object(a,b,memos)&&compare(a.prototype,b.prototype)};types.date=function(a,b){return+a===+b};types.regexp=function(a,b){return a.toString()===b.toString()};types.element=function(a,b){return a.outerHTML===b.outerHTML};types.textnode=function(a,b){return a.textContent===b.textContent};function memoGaurd(fn){return function(a,b,memos){if(!memos)return fn(a,b,[]);var i=memos.length,memo;while(memo=memos[--i]){if(memo[0]===a&&memo[1]===b)return true}return fn(a,b,memos)}}types["arguments"]=types.array=memoGaurd(compareArrays);function compareArrays(a,b,memos){var i=a.length;if(i!==b.length)return false;memos.push([a,b]);while(i--){if(!compare(a[i],b[i],memos))return false}return true}types.object=memoGaurd(compareObjects);function compareObjects(a,b,memos){var ka=getEnumerableProperties(a);var kb=getEnumerableProperties(b);var i=ka.length;if(i!==kb.length)return false;ka.sort();kb.sort();while(i--)if(ka[i]!==kb[i])return false;memos.push([a,b]);i=ka.length;while(i--){var key=ka[i];if(!compare(a[key],b[key],memos))return false}return true}function getEnumerableProperties(object){var result=[];for(var k in object)if(k!=="constructor"){result.push(k)}return result}},{type:175}],175:[function(require,module,exports){var toString={}.toString;var DomNode=typeof window!="undefined"?window.Node:Function;module.exports=exports=function(x){var type=typeof x;if(type!="object")return type;type=types[toString.call(x)];if(type)return type;if(x instanceof DomNode)switch(x.nodeType){case 1:return"element";case 3:return"text-node";case 9:return"document";case 11:return"document-fragment";default:return"dom-node"}};var types=exports.types={"[object Function]":"function","[object Date]":"date","[object RegExp]":"regexp","[object Arguments]":"arguments","[object Array]":"array","[object String]":"string","[object Null]":"null","[object Undefined]":"undefined","[object Number]":"number","[object Boolean]":"boolean","[object Object]":"object","[object Text]":"text-node","[object Uint8Array]":"bit-array","[object Uint16Array]":"bit-array","[object Uint32Array]":"bit-array","[object Uint8ClampedArray]":"bit-array","[object Error]":"error","[object FormData]":"form-data","[object File]":"file","[object Blob]":"blob"}},{}],171:[function(require,module,exports){module.exports=fmt;fmt.o=JSON.stringify;fmt.s=String;fmt.d=parseInt;function fmt(str){var args=[].slice.call(arguments,1);var j=0;return str.replace(/%([a-z])/gi,function(_,f){return fmt[f]?fmt[f](args[j++]):_+f})}},{}],174:[function(require,module,exports){module.exports=stack;function stack(){var orig=Error.prepareStackTrace;Error.prepareStackTrace=function(_,stack){return stack};var err=new Error;Error.captureStackTrace(err,arguments.callee);var stack=err.stack;Error.prepareStackTrace=orig;return stack}},{}],163:[function(require,module,exports){var after=require("after");var domify=require("component/domify");var each=require("component/each");var Emitter=require("emitter");Emitter(exports);exports.option=function(key,value){this.prototype.defaults[key]=value;return this};exports.mapping=function(name){this.option(name,[]);this.prototype[name]=function(str){return this.map(this.options[name],str)};return this};exports.global=function(key){this.prototype.globals.push(key);return this};exports.assumesPageview=function(){this.prototype._assumesPageview=true;return this};exports.readyOnLoad=function(){this.prototype._readyOnLoad=true;return this};exports.readyOnInitialize=function(){this.prototype._readyOnInitialize=true;return this};exports.tag=function(name,str){if(null==str){str=name;name="library"}this.prototype.templates[name]=objectify(str);return this};function objectify(str){str=str.replace(' src="',' data-src="');var el=domify(str);var attrs={};each(el.attributes,function(attr){var name="data-src"==attr.name?"src":attr.name;attrs[name]=attr.value});return{type:el.tagName.toLowerCase(),attrs:attrs}}},{after:10,"component/domify":176,"component/each":79,emitter:17}],176:[function(require,module,exports){module.exports=parse;var div=document.createElement("div");div.innerHTML=' <link/><table></table><a href="/a">a</a><input type="checkbox"/>';var innerHTMLBug=!div.getElementsByTagName("link").length;div=undefined;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:innerHTMLBug?[1,"X<div>","</div>"]:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html,doc){if("string"!=typeof html)throw new TypeError("String expected");if(!doc)doc=document;var m=/<([\w:]+)/.exec(html);if(!m)return doc.createTextNode(html);html=html.replace(/^\s+|\s+$/g,"");var tag=m[1];if(tag=="body"){var el=doc.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=doc.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=doc.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],164:[function(require,module,exports){var bind=require("bind"),bindAll=require("bind-all");module.exports=exports=bind;exports.all=bindAll;exports.methods=bindMethods;function bindMethods(obj,methods){methods=[].slice.call(arguments,1);for(var i=0,method;method=methods[i];i++){obj[method]=bind(obj,obj[method])}return obj}},{bind:33,"bind-all":34}],165:[function(require,module,exports){if("undefined"==typeof window){module.exports=require("./lib/debug")}else{module.exports=require("./debug")}},{"./lib/debug":177,"./debug":178}],177:[function(require,module,exports){var tty=require("tty");module.exports=debug;var names=[],skips=[];(process.env.DEBUG||"").split(/[\s,]+/).forEach(function(name){name=name.replace("*",".*?");if(name[0]==="-"){skips.push(new RegExp("^"+name.substr(1)+"$"))}else{names.push(new RegExp("^"+name+"$"))}});var colors=[6,2,3,4,5,1];var prev={};var prevColor=0;var isatty=tty.isatty(2);function color(){return colors[prevColor++%colors.length]}function humanize(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"}function debug(name){function disabled(){}disabled.enabled=false;var match=skips.some(function(re){return re.test(name)});if(match)return disabled;match=names.some(function(re){return re.test(name)});if(!match)return disabled;var c=color();function colored(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(prev[name]||curr);prev[name]=curr;fmt=" [9"+c+"m"+name+" "+"[3"+c+"m"+fmt+"[3"+c+"m"+" +"+humanize(ms)+"";console.error.apply(this,arguments)}function plain(fmt){fmt=coerce(fmt);fmt=(new Date).toUTCString()+" "+name+" "+fmt;console.error.apply(this,arguments)}colored.enabled=plain.enabled=true;return isatty||process.env.DEBUG_COLORS?colored:plain}function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}},{}],178:[function(require,module,exports){module.exports=debug;function debug(name){if(!debug.enabled(name))return function(){};return function(fmt){fmt=coerce(fmt);var curr=new Date;var ms=curr-(debug[name]||curr);debug[name]=curr;fmt=name+" "+fmt+" +"+debug.humanize(ms);window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}}debug.names=[];debug.skips=[];debug.enable=function(name){try{localStorage.debug=name}catch(e){}var split=(name||"").split(/[\s,]+/),len=split.length;for(var i=0;i<len;i++){name=split[i].replace("*",".*?");if(name[0]==="-"){debug.skips.push(new RegExp("^"+name.substr(1)+"$"))}else{debug.names.push(new RegExp("^"+name+"$"))}}};debug.disable=function(){debug.enable("")};debug.humanize=function(ms){var sec=1e3,min=60*1e3,hour=60*min;if(ms>=hour)return(ms/hour).toFixed(1)+"h";if(ms>=min)return(ms/min).toFixed(1)+"m";if(ms>=sec)return(ms/sec|0)+"s";return ms+"ms"};debug.enabled=function(name){for(var i=0,len=debug.skips.length;i<len;i++){if(debug.skips[i].test(name)){return false}}for(var i=0,len=debug.names.length;i<len;i++){if(debug.names[i].test(name)){return true}}return false};function coerce(val){if(val instanceof Error)return val.stack||val.message;return val}try{if(window.localStorage)debug.enable(localStorage.debug)}catch(e){}},{}],166:[function(require,module,exports){module.exports=function(str,options){options||(options={});return str.toLowerCase().replace(options.replace||/[^a-z0-9]/g," ").replace(/^ +| +$/g,"").replace(/ +/g,options.separator||"-")}},{}],160:[function(require,module,exports){var toSpace=require("to-space-case");module.exports=toSnakeCase;function toSnakeCase(string){return toSpace(string).replace(/\s/g,"_")}},{"to-space-case":179}],179:[function(require,module,exports){var clean=require("to-no-case");module.exports=toSpaceCase;function toSpaceCase(string){return clean(string).replace(/[\W_]+(.|$)/g,function(matches,match){return match?" "+match:""})}},{"to-no-case":69}],161:[function(require,module,exports){module.exports=function(url){switch(arguments.length){case 0:return check();case 1:return transform(url)}};function transform(url){return check()?"https:"+url:"http:"+url}function check(){return location.protocol=="https:"||location.protocol=="chrome-extension:"}},{}],84:[function(require,module,exports){var integration=require("analytics.js-integration");var onbody=require("on-body");var domify=require("domify");var Queue=require("queue");var each=require("each");var has=Object.prototype.hasOwnProperty;var q=new Queue({concurrency:1,timeout:2e3});var AdWords=module.exports=integration("AdWords").option("conversionId","").option("remarketing",false).tag("conversion",'<script src="//www.googleadservices.com/pagead/conversion.js">').mapping("events");AdWords.prototype.initialize=function(){onbody(this.ready)};AdWords.prototype.loaded=function(){return!!document.body};AdWords.prototype.page=function(page){var remarketing=this.options.remarketing;var id=this.options.conversionId;if(remarketing)this.remarketing(id)};AdWords.prototype.track=function(track){var id=this.options.conversionId;var events=this.events(track.event());var revenue=track.revenue()||0;var self=this;each(events,function(label){self.conversion({conversionId:id,value:revenue,label:label})})};AdWords.prototype.conversion=function(obj,fn){this.enqueue({google_conversion_id:obj.conversionId,google_conversion_language:"en",google_conversion_format:"3",google_conversion_color:"ffffff",google_conversion_label:obj.label,google_conversion_value:obj.value,google_remarketing_only:false},fn)};AdWords.prototype.remarketing=function(id){this.enqueue({google_conversion_id:id,google_remarketing_only:true})};AdWords.prototype.enqueue=function(obj,fn){this.debug("sending %o",obj);var self=this;q.push(function(next){self.globalize(obj);self.shim();self.load("conversion",function(){if(fn)fn();next()})})};AdWords.prototype.globalize=function(obj){for(var name in obj){if(obj.hasOwnProperty(name)){window[name]=obj[name]}}};AdWords.prototype.shim=function(){var self=this;var write=document.write;document.write=append;function append(str){var el=domify(str);if(!el.src)return write(str);if(!/googleadservices/.test(el.src))return write(str);self.debug("append %o",el);document.body.appendChild(el);document.write=write}}},{"analytics.js-integration":159,"on-body":180,domify:181,queue:182,each:5}],180:[function(require,module,exports){var each=require("each");var body=false;var callbacks=[];module.exports=function onBody(callback){if(body){call(callback)}else{callbacks.push(callback)}};var interval=setInterval(function(){if(!document.body)return;body=true;each(callbacks,call);clearInterval(interval)},5);function call(callback){callback(document.body)}},{each:79}],181:[function(require,module,exports){module.exports=parse;var map={legend:[1,"<fieldset>","</fieldset>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],_default:[0,"",""]};map.td=map.th=[3,"<table><tbody><tr>","</tr></tbody></table>"];map.option=map.optgroup=[1,'<select multiple="multiple">',"</select>"];map.thead=map.tbody=map.colgroup=map.caption=map.tfoot=[1,"<table>","</table>"];map.text=map.circle=map.ellipse=map.line=map.path=map.polygon=map.polyline=map.rect=[1,'<svg xmlns="http://www.w3.org/2000/svg" version="1.1">',"</svg>"];function parse(html){if("string"!=typeof html)throw new TypeError("String expected");html=html.replace(/^\s+|\s+$/g,"");var m=/<([\w:]+)/.exec(html);if(!m)return document.createTextNode(html);var tag=m[1];if(tag=="body"){var el=document.createElement("html");el.innerHTML=html;return el.removeChild(el.lastChild)}var wrap=map[tag]||map._default;var depth=wrap[0];var prefix=wrap[1];var suffix=wrap[2];var el=document.createElement("div");el.innerHTML=prefix+html+suffix;while(depth--)el=el.lastChild;if(el.firstChild==el.lastChild){return el.removeChild(el.firstChild)}var fragment=document.createDocumentFragment();while(el.firstChild){fragment.appendChild(el.removeChild(el.firstChild))}return fragment}},{}],182:[function(require,module,exports){var Emitter;var bind;try{Emitter=require("emitter");bind=require("bind")}catch(err){Emitter=require("component-emitter");bind=require("component-bind")}module.exports=Queue;function Queue(options){options=options||{};this.timeout=options.timeout||0;this.concurrency=options.concurrency||1;this.pending=0;this.jobs=[]}Emitter(Queue.prototype);Queue.prototype.length=function(){return this.pending+this.jobs.length};Queue.prototype.push=function(fn,cb){this.jobs.push([fn,cb]);setTimeout(bind(this,this.run),0)};Queue.prototype.run=function(){while(this.pending<this.concurrency){var job=this.jobs.shift();if(!job)break;this.exec(job)}};Queue.prototype.exec=function(job){var self=this;var ms=this.timeout;var fn=job[0];var cb=job[1];if(ms)fn=timeout(fn,ms);this.pending++;fn(function(err,res){cb&&cb(err,res);self.pending--;self.run()})};function timeout(fn,ms){return function(cb){var done;var id=setTimeout(function(){done=true;var err=new Error("Timeout of "+ms+"ms exceeded");err.timeout=timeout;cb(err)},ms);fn(function(err,res){if(done)return;clearTimeout(id);cb(err,res)})}}},{emitter:183,bind:33,"component-emitter":183,"component-bind":33}],183:[function(require,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};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};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}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};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};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],85:[function(require,module,exports){var integration=require("analytics.js-integration");var Alexa=module.exports=integration("Alexa").assumesPageview().global("_atrk_opts").option("account",null).option("domain","").option("dynamic",true).tag('<script src="//d31qbv1cthcecs.cloudfront.net/atrk.js">');Alexa.prototype.initialize=function(page){var self=this;window._atrk_opts={atrk_acct:this.options.account,domain:this.options.domain,dynamic:this.options.dynamic};this.load(function(){window.atrk();self.ready()})};Alexa.prototype.loaded=function(){return!!window.atrk}},{"analytics.js-integration":159}],86:[function(require,module,exports){var integration=require("analytics.js-integration");var Amplitude=module.exports=integration("Amplitude").assumesPageview().global("amplitude").option("apiKey","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="https://d24n15hnbwhuhn.cloudfront.net/libs/amplitude-1.1-min.js">');Amplitude.prototype.initialize=function(page){(function(e,t){var r=e.amplitude||{};r._q=[];function i(e){r[e]=function(){r._q.push([e].concat(Array.prototype.slice.call(arguments,0)))}}var s=["init","logEvent","setUserId","setGlobalUserProperties","setVersionName","setDomain"];for(var c=0;c<s.length;c++){i(s[c])}e.amplitude=r})(window,document);window.amplitude.init(this.options.apiKey);this.load(this.ready)};Amplitude.prototype.loaded=function(){return!!(window.amplitude&&window.amplitude.options)};Amplitude.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Amplitude.prototype.identify=function(identify){var id=identify.userId();var traits=identify.traits();if(id)window.amplitude.setUserId(id);if(traits)window.amplitude.setGlobalUserProperties(traits)};Amplitude.prototype.track=function(track){var props=track.properties();var event=track.event(); window.amplitude.logEvent(event,props)}},{"analytics.js-integration":159}],87:[function(require,module,exports){var integration=require("analytics.js-integration");var load=require("load-script");var is=require("is");module.exports=exports=function(analytics){analytics.addIntegration(Appcues)};var Appcues=exports.Integration=integration("Appcues").assumesPageview().global("Appcues").global("AppcuesIdentity").option("appcuesId","").option("userId","").option("userEmail","");Appcues.prototype.initialize=function(){this.load(function(){window.Appcues.init()})};Appcues.prototype.loaded=function(){return is.object(window.Appcues)};Appcues.prototype.load=function(callback){var script=load("//d2dubfq97s02eu.cloudfront.net/appcues-bundle.min.js",callback);script.setAttribute("data-appcues-id",this.options.appcuesId);script.setAttribute("data-user-id",this.options.userId);script.setAttribute("data-user-email",this.options.userEmail)};Appcues.prototype.identify=function(identify){window.Appcues.identify(identify.traits())}},{"analytics.js-integration":159,"load-script":184,is:18}],184:[function(require,module,exports){var onload=require("script-onload");var tick=require("next-tick");var type=require("type");module.exports=function loadScript(options,fn){if(!options)throw new Error("Cant load nothing...");if("string"==type(options))options={src:options};var https=document.location.protocol==="https:"||document.location.protocol==="chrome-extension:";if(options.src&&options.src.indexOf("//")===0){options.src=https?"https:"+options.src:"http:"+options.src}if(https&&options.https)options.src=options.https;else if(!https&&options.http)options.src=options.http;var script=document.createElement("script");script.type="text/javascript";script.async=true;script.src=options.src;if("function"==type(fn)){onload(script,fn)}tick(function(){var firstScript=document.getElementsByTagName("script")[0];firstScript.parentNode.insertBefore(script,firstScript)});return script}},{"script-onload":172,"next-tick":45,type:35}],88:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var Awesm=module.exports=integration("awe.sm").assumesPageview().global("AWESM").option("apiKey","").tag('<script src="//widgets.awe.sm/v3/widgets.js?key={{ apiKey }}&async=true">').mapping("events");Awesm.prototype.initialize=function(page){window.AWESM={api_key:this.options.apiKey};this.load(this.ready)};Awesm.prototype.loaded=function(){return!!(window.AWESM&&window.AWESM._exists)};Awesm.prototype.track=function(track){var user=this.analytics.user();var goals=this.events(track.event());each(goals,function(goal){window.AWESM.convert(goal,track.cents(),null,user.id())})}},{"analytics.js-integration":159,each:5}],89:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var noop=function(){};var onBody=require("on-body");var Awesomatic=module.exports=integration("Awesomatic").assumesPageview().global("Awesomatic").global("AwesomaticSettings").global("AwsmSetup").global("AwsmTmp").option("appId","").tag('<script src="https://1c817b7a15b6941337c0-dff9b5f4adb7ba28259631e99c3f3691.ssl.cf2.rackcdn.com/gen/embed.js">');Awesomatic.prototype.initialize=function(page){var self=this;var user=this.analytics.user();var id=user.id();var options=user.traits();options.appId=this.options.appId;if(id)options.user_id=id;this.load(function(){window.Awesomatic.initialize(options,function(){self.ready()})})};Awesomatic.prototype.loaded=function(){return is.object(window.Awesomatic)}},{"analytics.js-integration":159,is:18,"on-body":180}],90:[function(require,module,exports){var integration=require("analytics.js-integration");var onbody=require("on-body");var domify=require("domify");var extend=require("extend");var bind=require("bind");var when=require("when");var each=require("each");var has=Object.prototype.hasOwnProperty;var noop=function(){};var Bing=module.exports=integration("Bing Ads").option("siteId","").option("domainId","").tag('<script id="mstag_tops" src="//flex.msn.com/mstag/site/{{ siteId }}/mstag.js">').mapping("events");Bing.prototype.initialize=function(page){if(!window.mstag){window.mstag={loadTag:noop,time:(new Date).getTime(),_write:writeToAppend}}var self=this;onbody(function(){self.load(function(){var loaded=bind(self,self.loaded);when(loaded,self.ready)})})};Bing.prototype.loaded=function(){return!!(window.mstag&&window.mstag.loadTag!==noop)};Bing.prototype.track=function(track){var events=this.events(track.event());var revenue=track.revenue()||0;var self=this;each(events,function(goal){window.mstag.loadTag("analytics",{domainId:self.options.domainId,revenue:revenue,dedup:"1",type:"1",actionid:goal})})};function writeToAppend(str){var first=document.getElementsByTagName("script")[0];var el=domify(str);if("script"==el.tagName.toLowerCase()&&el.getAttribute("src")){var tmp=document.createElement("script");tmp.src=el.getAttribute("src");tmp.async=true;el=tmp}document.body.appendChild(el)}},{"analytics.js-integration":159,"on-body":180,domify:181,extend:40,bind:33,when:185,each:5}],185:[function(require,module,exports){var callback=require("callback");module.exports=when;function when(condition,fn,interval){if(condition())return callback.async(fn);var ref=setInterval(function(){if(!condition())return;callback(fn);clearInterval(ref)},interval||10)}},{callback:12}],91:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var pixel=require("load-pixel")("http://app.bronto.com/public/");var qs=require("querystring");var each=require("each");var Bronto=module.exports=integration("Bronto").global("__bta").option("siteId","").option("host","").tag('<script src="//p.bm23.com/bta.js">');Bronto.prototype.initialize=function(page){var self=this;var params=qs.parse(window.location.search);if(!params._bta_tid&&!params._bta_c){this.debug("missing tracking URL parameters `_bta_tid` and `_bta_c`.")}this.load(function(){var opts=self.options;self.bta=new window.__bta(opts.siteId);if(opts.host)self.bta.setHost(opts.host);self.ready()})};Bronto.prototype.loaded=function(){return this.bta};Bronto.prototype.track=function(track){var revenue=track.revenue();var event=track.event();var type="number"==typeof revenue?"$":"t";this.bta.addConversionLegacy(type,event,revenue)};Bronto.prototype.completedOrder=function(track){var user=this.analytics.user();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({userId:user.id(),traits:user.traits()});var email=identify.email();each(products,function(product){var track=new Track({properties:product});items.push({item_id:track.id()||track.sku(),desc:product.description||track.name(),quantity:track.quantity(),amount:track.price()})});this.bta.addOrder({order_id:track.orderId(),email:email,items:items})}},{"analytics.js-integration":159,facade:27,"load-pixel":186,querystring:187,each:5}],186:[function(require,module,exports){var stringify=require("querystring").stringify;var sub=require("substitute");module.exports=function(path){return function(query,obj,fn){if("function"==typeof obj)fn=obj,obj={};obj=obj||{};fn=fn||function(){};var url=sub(path,obj);var img=new Image;img.onerror=error(fn,"failed to load pixel",img);img.onload=function(){fn()};query=stringify(query);if(query)query="?"+query;img.src=url+query;img.width=1;img.height=1;return img}};function error(fn,message,img){return function(e){e=e||window.event;var err=new Error(message);err.event=e;err.source=img;fn(err)}}},{querystring:187,substitute:188}],187:[function(require,module,exports){var encode=encodeURIComponent;var decode=decodeURIComponent;var trim=require("trim");var type=require("type");exports.parse=function(str){if("string"!=typeof str)return{};str=trim(str);if(""==str)return{};if("?"==str.charAt(0))str=str.slice(1);var obj={};var pairs=str.split("&");for(var i=0;i<pairs.length;i++){var parts=pairs[i].split("=");var key=decode(parts[0]);var m;if(m=/(\w+)\[(\d+)\]/.exec(key)){obj[m[1]]=obj[m[1]]||[];obj[m[1]][m[2]]=decode(parts[1]);continue}obj[parts[0]]=null==parts[1]?"":decode(parts[1])}return obj};exports.stringify=function(obj){if(!obj)return"";var pairs=[];for(var key in obj){var value=obj[key];if("array"==type(value)){for(var i=0;i<value.length;++i){pairs.push(encode(key+"["+i+"]")+"="+encode(value[i]))}continue}pairs.push(encode(key)+"="+encode(obj[key]))}return pairs.join("&")}},{trim:50,type:35}],188:[function(require,module,exports){module.exports=substitute;function substitute(str,obj,expr){if(!obj)throw new TypeError("expected an object");expr=expr||/:(\w+)/g;return str.replace(expr,function(_,prop){return null!=obj[prop]?obj[prop]:_})}},{}],92:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var BugHerd=module.exports=integration("BugHerd").assumesPageview().global("BugHerdConfig").global("_bugHerd").option("apiKey","").option("showFeedbackTab",true).tag('<script src="//www.bugherd.com/sidebarv2.js?apikey={{ apiKey }}">');BugHerd.prototype.initialize=function(page){window.BugHerdConfig={feedback:{hide:!this.options.showFeedbackTab}};var ready=this.ready;this.load(function(){tick(ready)})};BugHerd.prototype.loaded=function(){return!!window._bugHerd}},{"analytics.js-integration":159,"next-tick":45}],93:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var extend=require("extend");var onError=require("on-error");var Bugsnag=module.exports=integration("Bugsnag").global("Bugsnag").option("apiKey","").tag('<script src="//d2wy8f7a9ursnm.cloudfront.net/bugsnag-2.min.js">');Bugsnag.prototype.initialize=function(page){var self=this;this.load(function(){window.Bugsnag.apiKey=self.options.apiKey;self.ready()})};Bugsnag.prototype.loaded=function(){return is.object(window.Bugsnag)};Bugsnag.prototype.identify=function(identify){window.Bugsnag.metaData=window.Bugsnag.metaData||{};extend(window.Bugsnag.metaData,identify.traits())}},{"analytics.js-integration":159,is:18,extend:40,"on-error":189}],189:[function(require,module,exports){module.exports=onError;var callbacks=[];if("function"==typeof window.onerror)callbacks.push(window.onerror);window.onerror=handler;function handler(){for(var i=0,fn;fn=callbacks[i];i++)fn.apply(this,arguments)}function onError(fn){callbacks.push(fn);if(window.onerror!=handler){callbacks.push(window.onerror);window.onerror=handler}}},{}],94:[function(require,module,exports){var integration=require("analytics.js-integration");var defaults=require("defaults");var onBody=require("on-body");var Chartbeat=module.exports=integration("Chartbeat").assumesPageview().global("_sf_async_config").global("_sf_endpt").global("pSUPERFLY").option("domain","").option("uid",null).tag('<script src="//static.chartbeat.com/js/chartbeat.js">');Chartbeat.prototype.initialize=function(page){var self=this;window._sf_async_config=window._sf_async_config||{};window._sf_async_config.useCanonical=true;defaults(window._sf_async_config,this.options);onBody(function(){window._sf_endpt=(new Date).getTime();self.load(self.ready)})};Chartbeat.prototype.loaded=function(){return!!window.pSUPERFLY};Chartbeat.prototype.page=function(page){var props=page.properties();var name=page.fullName();window.pSUPERFLY.virtualPage(props.path,name||props.title)}},{"analytics.js-integration":159,defaults:190,"on-body":180}],190:[function(require,module,exports){module.exports=defaults;function defaults(dest,defaults){for(var prop in defaults){if(!(prop in dest)){dest[prop]=defaults[prop]}}return dest}},{}],95:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_cbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var supported={activation:true,changePlan:true,register:true,refund:true,charge:true,cancel:true,login:true};var ChurnBee=module.exports=integration("ChurnBee").global("_cbq").global("ChurnBee").option("apiKey","").tag('<script src="//api.churnbee.com/cb.js">').mapping("events");ChurnBee.prototype.initialize=function(page){push("_setApiKey",this.options.apiKey);this.load(this.ready)};ChurnBee.prototype.loaded=function(){return!!window.ChurnBee};ChurnBee.prototype.track=function(track){var event=track.event();var events=this.events(event);events.push(event);each(events,function(event){if(true!=supported[event])return;push(event,track.properties({revenue:"amount"}))})}},{"analytics.js-integration":159,"global-queue":191,each:5}],191:[function(require,module,exports){module.exports=generate;function generate(name,options){options=options||{};return function(args){args=[].slice.call(arguments);window[name]||(window[name]=[]);options.wrap===false?window[name].push.apply(window[name],args):window[name].push(args)}}},{}],96:[function(require,module,exports){var date=require("load-date");var domify=require("domify");var each=require("each");var integration=require("analytics.js-integration");var is=require("is");var useHttps=require("use-https");var onBody=require("on-body");var ClickTale=module.exports=integration("ClickTale").assumesPageview().global("WRInitTime").global("ClickTale").global("ClickTaleSetUID").global("ClickTaleField").global("ClickTaleEvent").option("httpCdnUrl","http://s.clicktale.net/WRe0.js").option("httpsCdnUrl","").option("projectId","").option("recordingRatio",.01).option("partitionId","").tag('<script src="{{src}}">');ClickTale.prototype.initialize=function(page){var self=this;window.WRInitTime=date.getTime();onBody(function(body){body.appendChild(domify('<div id="ClickTaleDiv" style="display: none;">'))});var http=this.options.httpCdnUrl;var https=this.options.httpsCdnUrl;if(useHttps()&&!https)return this.debug("https option required");var src=useHttps()?https:http;this.load({src:src},function(){window.ClickTale(self.options.projectId,self.options.recordingRatio,self.options.partitionId);self.ready()})};ClickTale.prototype.loaded=function(){return is.fn(window.ClickTale)};ClickTale.prototype.identify=function(identify){var id=identify.userId();window.ClickTaleSetUID(id);each(identify.traits(),function(key,value){window.ClickTaleField(key,value)})};ClickTale.prototype.track=function(track){window.ClickTaleEvent(track.event())}},{"load-date":192,domify:181,each:5,"analytics.js-integration":159,is:18,"use-https":161,"on-body":180}],192:[function(require,module,exports){var time=new Date,perf=window.performance;if(perf&&perf.timing&&perf.timing.responseEnd){time=new Date(perf.timing.responseEnd)}module.exports=time},{}],97:[function(require,module,exports){var Identify=require("facade").Identify;var extend=require("extend");var integration=require("analytics.js-integration");var is=require("is");var Clicky=module.exports=integration("Clicky").assumesPageview().global("clicky").global("clicky_site_ids").global("clicky_custom").option("siteId",null).tag('<script src="//static.getclicky.com/js"></script>');Clicky.prototype.initialize=function(page){var user=this.analytics.user();window.clicky_site_ids=window.clicky_site_ids||[this.options.siteId];this.identify(new Identify({userId:user.id(),traits:user.traits()}));this.load(this.ready)};Clicky.prototype.loaded=function(){return is.object(window.clicky)};Clicky.prototype.page=function(page){var properties=page.properties();var category=page.category();var name=page.fullName();window.clicky.log(properties.path,name||properties.title)};Clicky.prototype.identify=function(identify){window.clicky_custom=window.clicky_custom||{};window.clicky_custom.session=window.clicky_custom.session||{};extend(window.clicky_custom.session,identify.traits())};Clicky.prototype.track=function(track){window.clicky.goal(track.event(),track.revenue())}},{facade:27,extend:40,"analytics.js-integration":159,is:18}],98:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var Comscore=module.exports=integration("comScore").assumesPageview().global("_comscore").global("COMSCORE").option("c1","2").option("c2","").tag("http",'<script src="http://b.scorecardresearch.com/beacon.js">').tag("https",'<script src="https://sb.scorecardresearch.com/beacon.js">');Comscore.prototype.initialize=function(page){window._comscore=window._comscore||[this.options];var name=useHttps()?"https":"http";this.load(name,this.ready)};Comscore.prototype.loaded=function(){return!!window.COMSCORE}},{"analytics.js-integration":159,"use-https":161}],99:[function(require,module,exports){var integration=require("analytics.js-integration");var CrazyEgg=module.exports=integration("Crazy Egg").assumesPageview().global("CE2").option("accountNumber","").tag('<script src="//dnn506yrbagrg.cloudfront.net/pages/scripts/{{ path }}.js?{{ cache }}">');CrazyEgg.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,4)+"/"+number.slice(4);var cache=Math.floor((new Date).getTime()/36e5);this.load({path:path,cache:cache},this.ready)};CrazyEgg.prototype.loaded=function(){return!!window.CE2}},{"analytics.js-integration":159}],100:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_curebitq");var Identify=require("facade").Identify;var throttle=require("throttle");var Track=require("facade").Track;var iso=require("to-iso-string");var clone=require("clone");var each=require("each");var bind=require("bind");var Curebit=module.exports=integration("Curebit").global("_curebitq").global("curebit").option("siteId","").option("iframeWidth","100%").option("iframeHeight","480").option("iframeBorder",0).option("iframeId","curebit_integration").option("responsive",true).option("device","").option("insertIntoId","").option("campaigns",{}).option("server","https://www.curebit.com").tag('<script src="//d2jjzw81hqbuqv.cloudfront.net/integration/curebit-1.0.min.js">');Curebit.prototype.initialize=function(page){push("init",{site_id:this.options.siteId,server:this.options.server});this.load(this.ready);this.page=throttle(bind(this,this.page),250)};Curebit.prototype.loaded=function(){return!!window.curebit};Curebit.prototype.injectIntoId=function(url,id,fn){var server=this.options.server;when(function(){return document.getElementById(id)},function(){var script=document.createElement("script");script.src=url;var parent=document.getElementById(id);parent.appendChild(script);onload(script,fn)})};Curebit.prototype.page=function(page){var user=this.analytics.user();var campaigns=this.options.campaigns;var path=window.location.pathname;if(!campaigns[path])return;var tags=(campaigns[path]||"").split(",");if(!tags.length)return;var settings={responsive:this.options.responsive,device:this.options.device,campaign_tags:tags,iframe:{width:this.options.iframeWidth,height:this.options.iframeHeight,id:this.options.iframeId,frameborder:this.options.iframeBorder,container:this.options.insertIntoId}};var identify=new Identify({userId:user.id(),traits:user.traits()});if(identify.email()){settings.affiliate_member={email:identify.email(),first_name:identify.firstName(),last_name:identify.lastName(),customer_id:identify.userId()}}push("register_affiliate",settings)};Curebit.prototype.completedOrder=function(track){var user=this.analytics.user();var orderId=track.orderId();var products=track.products();var props=track.properties();var items=[];var identify=new Identify({traits:user.traits(),userId:user.id()});each(products,function(product){var track=new Track({properties:product});items.push({product_id:track.id()||track.sku(),quantity:track.quantity(),image_url:product.image,price:track.price(),title:track.name(),url:product.url})});push("register_purchase",{order_date:iso(props.date||new Date),order_number:orderId,coupon_code:track.coupon(),subtotal:track.total(),customer_id:identify.userId(),first_name:identify.firstName(),last_name:identify.lastName(),email:identify.email(),items:items})}},{"analytics.js-integration":159,"global-queue":191,facade:27,throttle:193,"to-iso-string":194,clone:195,each:5,bind:33}],193:[function(require,module,exports){module.exports=throttle;function throttle(func,wait){var rtn;var last=0;return function throttled(){var now=(new Date).getTime();var delta=now-last;if(delta>=wait){rtn=func.apply(this,arguments);last=now}return rtn}}},{}],194:[function(require,module,exports){module.exports=toIsoString;function toIsoString(date){return date.getUTCFullYear()+"-"+pad(date.getUTCMonth()+1)+"-"+pad(date.getUTCDate())+"T"+pad(date.getUTCHours())+":"+pad(date.getUTCMinutes())+":"+pad(date.getUTCSeconds())+"."+String((date.getUTCMilliseconds()/1e3).toFixed(3)).slice(2,5)+"Z"}function pad(number){var n=number.toString();return n.length===1?"0"+n:n}},{}],195:[function(require,module,exports){var type;try{type=require("type")}catch(e){type=require("type-component")}module.exports=clone;function clone(obj){switch(type(obj)){case"object":var copy={};for(var key in obj){if(obj.hasOwnProperty(key)){copy[key]=clone(obj[key])}}return copy;case"array":var copy=new Array(obj.length);for(var i=0,l=obj.length;i<l;i++){copy[i]=clone(obj[i])}return copy;case"regexp":var flags="";flags+=obj.multiline?"m":"";flags+=obj.global?"g":"";flags+=obj.ignoreCase?"i":"";return new RegExp(obj.source,flags);case"date":return new Date(obj.getTime());default:return obj}}},{type:35}],101:[function(require,module,exports){var alias=require("alias");var convertDates=require("convert-dates");var Identify=require("facade").Identify;var integration=require("analytics.js-integration");var Customerio=module.exports=integration("Customer.io").assumesPageview().global("_cio").option("siteId","").tag('<script id="cio-tracker" src="https://assets.customer.io/assets/track.js" data-site-id="{{ siteId }}">');Customerio.prototype.initialize=function(page){window._cio=window._cio||[];(function(){var a,b,c;a=function(f){return function(){window._cio.push([f].concat(Array.prototype.slice.call(arguments,0)))}};b=["identify","track"];for(c=0;c<b.length;c++){window._cio[b[c]]=a(b[c])}})();this.load(this.ready)};Customerio.prototype.loaded=function(){return!!(window._cio&&window._cio.pageHasLoaded)};Customerio.prototype.identify=function(identify){if(!identify.userId())return this.debug("user id required");var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);window._cio.identify(traits)};Customerio.prototype.group=function(group){var traits=group.traits();var user=this.analytics.user();traits=alias(traits,function(trait){return"Group "+trait});this.identify(new Identify({userId:user.id(),traits:traits}))};Customerio.prototype.track=function(track){var properties=track.properties();properties=convertDates(properties,convertDate);window._cio.track(track.event(),properties)};function convertDate(date){return Math.floor(date.getTime()/1e3)}},{alias:196,"convert-dates":197,facade:27,"analytics.js-integration":159}],196:[function(require,module,exports){var type=require("type");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=alias;function alias(obj,method){switch(type(method)){case"object":return aliasByDictionary(clone(obj),method);case"function":return aliasByFunction(clone(obj),method)}}function aliasByDictionary(obj,aliases){for(var key in aliases){if(undefined===obj[key])continue;obj[aliases[key]]=obj[key];delete obj[key]}return obj}function aliasByFunction(obj,convert){var output={};for(var key in obj)output[convert(key)]=obj[key];return output}},{type:35,clone:62}],197:[function(require,module,exports){var is=require("is");try{var clone=require("clone")}catch(e){var clone=require("clone-component")}module.exports=convertDates;function convertDates(obj,convert){obj=clone(obj);for(var key in obj){var val=obj[key];if(is.date(val))obj[key]=convert(val);if(is.object(val))obj[key]=convertDates(val,convert)}return obj}},{is:18,clone:14}],102:[function(require,module,exports){var alias=require("alias");var integration=require("analytics.js-integration");var is=require("is");var load=require("load-script");var push=require("global-queue")("_dcq");var Drip=module.exports=integration("Drip").assumesPageview().global("dc").global("_dcq").global("_dcs").option("account","").tag('<script src="//tag.getdrip.com/{{ account }}.js">');Drip.prototype.initialize=function(page){window._dcq=window._dcq||[];window._dcs=window._dcs||{};window._dcs.account=this.options.account;this.load(this.ready)};Drip.prototype.loaded=function(){return is.object(window.dc)};Drip.prototype.track=function(track){var props=track.properties();var cents=Math.round(track.cents());props.action=track.event();if(cents)props.value=cents;delete props.revenue;push("track",props)}},{alias:196,"analytics.js-integration":159,is:18,"load-script":184,"global-queue":191}],103:[function(require,module,exports){var extend=require("extend");var integration=require("analytics.js-integration");var onError=require("on-error");var push=require("global-queue")("_errs");var Errorception=module.exports=integration("Errorception").assumesPageview().global("_errs").option("projectId","").option("meta",true).tag('<script src="//beacon.errorception.com/{{ projectId }}.js">');Errorception.prototype.initialize=function(page){window._errs=window._errs||[this.options.projectId];onError(push);this.load(this.ready)};Errorception.prototype.loaded=function(){return!!(window._errs&&window._errs.push!==Array.prototype.push)};Errorception.prototype.identify=function(identify){if(!this.options.meta)return;var traits=identify.traits();window._errs=window._errs||[];window._errs.meta=window._errs.meta||{};extend(window._errs.meta,traits)}},{extend:40,"analytics.js-integration":159,"on-error":189,"global-queue":191}],104:[function(require,module,exports){var each=require("each");var integration=require("analytics.js-integration");var push=require("global-queue")("_aaq");var Evergage=module.exports=integration("Evergage").assumesPageview().global("_aaq").option("account","").option("dataset","").tag('<script src="//cdn.evergage.com/beacon/{{ account }}/{{ dataset }}/scripts/evergage.min.js">');Evergage.prototype.initialize=function(page){var account=this.options.account;var dataset=this.options.dataset;window._aaq=window._aaq||[];push("setEvergageAccount",account);push("setDataset",dataset);push("setUseSiteConfig",true);this.load(this.ready)};Evergage.prototype.loaded=function(){return!!(window._aaq&&window._aaq.push!==Array.prototype.push)};Evergage.prototype.page=function(page){var props=page.properties();var name=page.name();if(name)push("namePage",name);each(props,function(key,value){push("setCustomField",key,value,"page")});window.Evergage.init(true)};Evergage.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("setUser",id);var traits=identify.traits({email:"userEmail",name:"userName"});each(traits,function(key,value){push("setUserField",key,value,"page")})};Evergage.prototype.group=function(group){var props=group.traits();var id=group.groupId();if(!id)return;push("setCompany",id);each(props,function(key,value){push("setAccountField",key,value,"page")})};Evergage.prototype.track=function(track){push("trackAction",track.event(),track.properties())}},{each:5,"analytics.js-integration":159,"global-queue":191}],105:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_fbq");var each=require("each");var has=Object.prototype.hasOwnProperty;var Facebook=module.exports=integration("Facebook Ads").global("_fbq").option("currency","USD").tag('<script src="//connect.facebook.net/en_US/fbds.js">').mapping("events");Facebook.prototype.initialize=function(page){window._fbq=window._fbq||[];this.load(this.ready);window._fbq.loaded=true};Facebook.prototype.loaded=function(){return!!(window._fbq&&window._fbq.loaded)};Facebook.prototype.track=function(track){var event=track.event();var events=this.events(event);var revenue=track.revenue()||0;var self=this;each(events,function(event){push("track",event,{value:String(revenue.toFixed(2)),currency:self.options.currency})});if(!events.length){var data=track.properties();push("track",event,data)}}},{"analytics.js-integration":159,"global-queue":191,each:5}],106:[function(require,module,exports){var push=require("global-queue")("_fxm");var integration=require("analytics.js-integration");var Track=require("facade").Track;var each=require("each");var FoxMetrics=module.exports=integration("FoxMetrics").assumesPageview().global("_fxm").option("appId","").tag('<script src="//d35tca7vmefkrc.cloudfront.net/scripts/{{ appId }}.js">');FoxMetrics.prototype.initialize=function(page){window._fxm=window._fxm||[];this.load(this.ready)};FoxMetrics.prototype.loaded=function(){return!!(window._fxm&&window._fxm.appId)};FoxMetrics.prototype.page=function(page){var properties=page.proxy("properties");var category=page.category();var name=page.name();this._category=category;push("_fxm.pages.view",properties.title,name,category,properties.url,properties.referrer)};FoxMetrics.prototype.identify=function(identify){var id=identify.userId();if(!id)return;push("_fxm.visitor.profile",id,identify.firstName(),identify.lastName(),identify.email(),identify.address(),undefined,undefined,identify.traits())};FoxMetrics.prototype.track=function(track){var props=track.properties();var category=this._category||props.category;push(track.event(),category,props)};FoxMetrics.prototype.viewedProduct=function(track){ecommerce("productview",track)};FoxMetrics.prototype.removedProduct=function(track){ecommerce("removecartitem",track)};FoxMetrics.prototype.addedProduct=function(track){ecommerce("cartitem",track)};FoxMetrics.prototype.completedOrder=function(track){var orderId=track.orderId();push("_fxm.ecommerce.order",orderId,track.subtotal(),track.shipping(),track.tax(),track.city(),track.state(),track.zip(),track.quantity());each(track.products(),function(product){var track=new Track({properties:product});ecommerce("purchaseitem",track,[track.quantity(),track.price(),orderId])})};function ecommerce(event,track,arr){push.apply(null,["_fxm.ecommerce."+event,track.id()||track.sku(),track.name(),track.category()].concat(arr||[]))}},{"global-queue":191,"analytics.js-integration":159,facade:27,each:5}],107:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Frontleaf=module.exports=integration("Frontleaf").assumesPageview().global("_fl").global("_flBaseUrl").option("baseUrl","https://api.frontleaf.com").option("token","").option("stream","").option("trackNamedPages",false).option("trackCategorizedPages",false).tag('<script id="_fl" src="{{ baseUrl }}/lib/tracker.js">');Frontleaf.prototype.initialize=function(page){window._fl=window._fl||[];window._flBaseUrl=window._flBaseUrl||this.options.baseUrl;this._push("setApiToken",this.options.token);this._push("setStream",this.options.stream);var loaded=bind(this,this.loaded);var ready=this.ready;this.load({baseUrl:window._flBaseUrl},this.ready)};Frontleaf.prototype.loaded=function(){return is.array(window._fl)&&window._fl.ready===true};Frontleaf.prototype.identify=function(identify){var userId=identify.userId();if(userId){this._push("setUser",{id:userId,name:identify.name()||identify.username(),data:clean(identify.traits())})}};Frontleaf.prototype.group=function(group){var groupId=group.groupId();if(groupId){this._push("setAccount",{id:groupId,name:group.proxy("traits.name"),data:clean(group.traits())})}};Frontleaf.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Frontleaf.prototype.track=function(track){var event=track.event(); this._push("event",event,clean(track.properties()))};Frontleaf.prototype._push=function(command){var args=[].slice.call(arguments,1);window._fl.push(function(t){t[command].apply(command,args)})};function clean(obj){var ret={};var excludeKeys=["id","name","firstName","lastName"];var len=excludeKeys.length;for(var i=0;i<len;i++){clear(obj,excludeKeys[i])}obj=flatten(obj);for(var key in obj){var val=obj[key];if(null==val){continue}if(is.array(val)){ret[key]=val.toString();continue}ret[key]=val}return ret}function clear(obj,key){if(obj.hasOwnProperty(key)){delete obj[key]}}function flatten(source){var output={};function step(object,prev){for(var key in object){var value=object[key];var newKey=prev?prev+" "+key:key;if(!is.array(value)&&is.object(value)){return step(value,newKey)}output[newKey]=value}}step(source);return output}},{"analytics.js-integration":159,bind:33,when:185,is:18}],108:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gauges");var Gauges=module.exports=integration("Gauges").assumesPageview().global("_gauges").option("siteId","").tag('<script id="gauges-tracker" src="//secure.gaug.es/track.js" data-site-id="{{ siteId }}">');Gauges.prototype.initialize=function(page){window._gauges=window._gauges||[];this.load(this.ready)};Gauges.prototype.loaded=function(){return!!(window._gauges&&window._gauges.push!==Array.prototype.push)};Gauges.prototype.page=function(page){push("track")}},{"analytics.js-integration":159,"global-queue":191}],109:[function(require,module,exports){var integration=require("analytics.js-integration");var onBody=require("on-body");var GetSatisfaction=module.exports=integration("Get Satisfaction").assumesPageview().global("GSFN").option("widgetId","").tag('<script src="https://loader.engage.gsfn.us/loader.js">');GetSatisfaction.prototype.initialize=function(page){var self=this;var widget=this.options.widgetId;var div=document.createElement("div");var id=div.id="getsat-widget-"+widget;onBody(function(body){body.appendChild(div)});this.load(function(){window.GSFN.loadWidget(widget,{containerId:id});self.ready()})};GetSatisfaction.prototype.loaded=function(){return!!window.GSFN}},{"analytics.js-integration":159,"on-body":180}],110:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_gaq");var length=require("object").length;var canonical=require("canonical");var useHttps=require("use-https");var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var keys=require("object").keys;var dot=require("obj-case");var each=require("each");var type=require("type");var url=require("url");var is=require("is");var group;var user;module.exports=exports=function(analytics){analytics.addIntegration(GA);group=analytics.group();user=analytics.user()};var GA=exports.Integration=integration("Google Analytics").readyOnLoad().global("ga").global("gaplugins").global("_gaq").global("GoogleAnalyticsObject").option("anonymizeIp",false).option("classic",false).option("domain","none").option("doubleClick",false).option("enhancedLinkAttribution",false).option("ignoredReferrers",null).option("includeSearch",false).option("siteSpeedSampleRate",1).option("trackingId","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("sendUserId",false).option("metrics",{}).option("dimensions",{}).tag("library",'<script src="//www.google-analytics.com/analytics.js">').tag("double click",'<script src="//stats.g.doubleclick.net/dc.js">').tag("http",'<script src="http://www.google-analytics.com/ga.js">').tag("https",'<script src="https://ssl.google-analytics.com/ga.js">');GA.on("construct",function(integration){if(!integration.options.classic)return;integration.initialize=integration.initializeClassic;integration.loaded=integration.loadedClassic;integration.page=integration.pageClassic;integration.track=integration.trackClassic;integration.completedOrder=integration.completedOrderClassic});GA.prototype.initialize=function(){var opts=this.options;window.GoogleAnalyticsObject="ga";window.ga=window.ga||function(){window.ga.q=window.ga.q||[];window.ga.q.push(arguments)};window.ga.l=(new Date).getTime();window.ga("create",opts.trackingId,{cookieDomain:opts.domain||GA.prototype.defaults.domain,siteSpeedSampleRate:opts.siteSpeedSampleRate,allowLinker:true});if(opts.doubleClick){window.ga("require","displayfeatures")}if(opts.sendUserId&&user.id()){window.ga("set","&uid",user.id())}if(opts.anonymizeIp)window.ga("set","anonymizeIp",true);var custom=metrics(user.traits(),opts);if(length(custom))window.ga("set",custom);this.load("library",this.ready)};GA.prototype.loaded=function(){return!!window.gaplugins};GA.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var pageview={};var track;this._category=category;window.ga("send","pageview",{page:path(props,this.options),title:name||props.title,location:props.url});if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.track=function(track,options){var opts=options||track.options(this.name);var props=track.properties();window.ga("send","event",{eventAction:track.event(),eventCategory:props.category||this._category||"All",eventLabel:props.label,eventValue:formatValue(props.value||track.revenue()),nonInteraction:props.noninteraction||opts.noninteraction})};GA.prototype.completedOrder=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products();var props=track.properties();if(!orderId)return;if(!this.ecommerce){window.ga("require","ecommerce","ecommerce.js");this.ecommerce=true}window.ga("ecommerce:addTransaction",{affiliation:props.affiliation,shipping:track.shipping(),revenue:total,tax:track.tax(),id:orderId});each(products,function(product){var track=new Track({properties:product});window.ga("ecommerce:addItem",{category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name(),sku:track.sku(),id:orderId})});window.ga("ecommerce:send")};GA.prototype.initializeClassic=function(){var opts=this.options;var anonymize=opts.anonymizeIp;var db=opts.doubleClick;var domain=opts.domain;var enhanced=opts.enhancedLinkAttribution;var ignore=opts.ignoredReferrers;var sample=opts.siteSpeedSampleRate;window._gaq=window._gaq||[];push("_setAccount",opts.trackingId);push("_setAllowLinker",true);if(anonymize)push("_gat._anonymizeIp");if(domain)push("_setDomainName",domain);if(sample)push("_setSiteSpeedSampleRate",sample);if(enhanced){var protocol="https:"===document.location.protocol?"https:":"http:";var pluginUrl=protocol+"//www.google-analytics.com/plugins/ga/inpage_linkid.js";push("_require","inpage_linkid",pluginUrl)}if(ignore){if(!is.array(ignore))ignore=[ignore];each(ignore,function(domain){push("_addIgnoredRef",domain)})}if(this.options.doubleClick){this.load("double click",this.ready)}else{var name=useHttps()?"https":"http";this.load(name,this.ready)}};GA.prototype.loadedClassic=function(){return!!(window._gaq&&window._gaq.push!==Array.prototype.push)};GA.prototype.pageClassic=function(page){var opts=page.options(this.name);var category=page.category();var props=page.properties();var name=page.fullName();var track;push("_trackPageview",path(props,this.options));if(category&&this.options.trackCategorizedPages){track=page.track(category);this.track(track,{noninteraction:true})}if(name&&this.options.trackNamedPages){track=page.track(name);this.track(track,{noninteraction:true})}};GA.prototype.trackClassic=function(track,options){var opts=options||track.options(this.name);var props=track.properties();var revenue=track.revenue();var event=track.event();var category=this._category||props.category||"All";var label=props.label;var value=formatValue(revenue||props.value);var noninteraction=props.noninteraction||opts.noninteraction;push("_trackEvent",category,event,label,value,noninteraction)};GA.prototype.completedOrderClassic=function(track){var total=track.total()||track.revenue()||0;var orderId=track.orderId();var products=track.products()||[];var props=track.properties();if(!orderId)return;push("_addTrans",orderId,props.affiliation,total,track.tax(),track.shipping(),track.city(),track.state(),track.country());each(products,function(product){var track=new Track({properties:product});push("_addItem",orderId,track.sku(),track.name(),track.category(),track.price(),track.quantity())});push("_trackTrans")};function path(properties,options){if(!properties)return;var str=properties.path;if(options.includeSearch&&properties.search)str+=properties.search;return str}function formatValue(value){if(!value||value<0)return 0;return Math.round(value)}function metrics(obj,data){var dimensions=data.dimensions;var metrics=data.metrics;var names=keys(metrics).concat(keys(dimensions));var ret={};for(var i=0;i<names.length;++i){var name=names[i];var key=metrics[name]||dimensions[name];var value=dot(obj,name);if(null==value)continue;ret[key]=value}return ret}},{"analytics.js-integration":159,"global-queue":191,object:25,canonical:13,"use-https":161,facade:27,callback:12,"load-script":184,"obj-case":60,each:5,type:35,url:26,is:18}],111:[function(require,module,exports){var push=require("global-queue")("dataLayer",{wrap:false});var integration=require("analytics.js-integration");var GTM=module.exports=integration("Google Tag Manager").assumesPageview().global("dataLayer").global("google_tag_manager").option("containerId","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//www.googletagmanager.com/gtm.js?id={{ containerId }}&l=dataLayer">');GTM.prototype.initialize=function(){push({"gtm.start":+new Date,event:"gtm.js"});this.load(this.ready)};GTM.prototype.loaded=function(){return!!(window.dataLayer&&[].push!=window.dataLayer.push)};GTM.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;var track;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};GTM.prototype.track=function(track){var props=track.properties();props.event=track.event();push(props)}},{"global-queue":191,"analytics.js-integration":159}],112:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var Track=require("facade").Track;var callback=require("callback");var load=require("load-script");var onBody=require("on-body");var each=require("each");var GoSquared=module.exports=integration("GoSquared").assumesPageview().global("_gs").option("siteToken","").option("anonymizeIP",false).option("cookieDomain",null).option("useCookies",true).option("trackHash",false).option("trackLocal",false).option("trackParams",true).tag('<script src="//d1l6p2sc9645hc.cloudfront.net/tracker.js">');GoSquared.prototype.initialize=function(page){var self=this;var options=this.options;var user=this.analytics.user();push(options.siteToken);each(options,function(name,value){if("siteToken"==name)return;if(null==value)return;push("set",name,value)});self.identify(new Identify({traits:user.traits(),userId:user.id()}));self.load(this.ready)};GoSquared.prototype.loaded=function(){return!!(window._gs&&window._gs.v)};GoSquared.prototype.page=function(page){var props=page.properties();var name=page.fullName();push("track",props.path,name||props.title)};GoSquared.prototype.identify=function(identify){var traits=identify.traits({userId:"userID"});var username=identify.username();var email=identify.email();var id=identify.userId();if(id)push("set","visitorID",id);var name=email||username||id;if(name)push("set","visitorName",name);push("set","visitor",traits)};GoSquared.prototype.track=function(track){push("event",track.event(),track.properties())};GoSquared.prototype.completedOrder=function(track){var products=track.products();var items=[];each(products,function(product){var track=new Track({properties:product});items.push({category:track.category(),quantity:track.quantity(),price:track.price(),name:track.name()})});push("transaction",track.orderId(),{revenue:track.total(),track:true},items)};function push(){var _gs=window._gs=window._gs||function(){(_gs.q=_gs.q||[]).push(arguments)};_gs.apply(null,arguments)}},{"analytics.js-integration":159,facade:27,callback:12,"load-script":184,"on-body":180,each:5}],113:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Heap=module.exports=integration("Heap").assumesPageview().global("heap").global("_heapid").option("apiKey","").tag('<script src="//d36lvucg9kzous.cloudfront.net">');Heap.prototype.initialize=function(page){window.heap=window.heap||[];window.heap.load=function(a){window._heapid=a;var d=function(a){return function(){window.heap.push([a].concat(Array.prototype.slice.call(arguments,0)))}},e=["identify","track"];for(var f=0;f<e.length;f++)window.heap[e[f]]=d(e[f])};window.heap.load(this.options.apiKey);this.load(this.ready)};Heap.prototype.loaded=function(){return window.heap&&window.heap.appid};Heap.prototype.identify=function(identify){var traits=identify.traits();var username=identify.username();var id=identify.userId();var handle=username||id;if(handle)traits.handle=handle;delete traits.username;window.heap.identify(traits)};Heap.prototype.track=function(track){window.heap.track(track.event(),track.properties())}},{"analytics.js-integration":159,alias:196}],114:[function(require,module,exports){var integration=require("analytics.js-integration");var Hellobar=module.exports=integration("Hello Bar").assumesPageview().global("_hbq").option("apiKey","").tag('<script src="//s3.amazonaws.com/scripts.hellobar.com/{{ apiKey }}.js">');Hellobar.prototype.initialize=function(page){window._hbq=window._hbq||[];this.load(this.ready)};Hellobar.prototype.loaded=function(){return!!(window._hbq&&window._hbq.push!==Array.prototype.push)}},{"analytics.js-integration":159}],115:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var HitTail=module.exports=integration("HitTail").assumesPageview().global("htk").option("siteId","").tag('<script src="//{{ siteId }}.hittail.com/mlt.js">');HitTail.prototype.initialize=function(page){this.load(this.ready)};HitTail.prototype.loaded=function(){return is.fn(window.htk)}},{"analytics.js-integration":159,is:18}],116:[function(require,module,exports){var integration=require("analytics.js-integration");var Hublo=module.exports=integration("Hublo").assumesPageview().global("_hublo_").option("apiKey",null).tag('<script src="//cdn.hublo.co/{{ apiKey }}.js">');Hublo.prototype.initialize=function(page){this.load(this.ready)};Hublo.prototype.loaded=function(){return!!(window._hublo_&&typeof window._hublo_.setup==="function")}},{"analytics.js-integration":159}],117:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_hsq");var convert=require("convert-dates");var HubSpot=module.exports=integration("HubSpot").assumesPageview().global("_hsq").option("portalId",null).tag('<script id="hs-analytics" src="https://js.hs-analytics.net/analytics/{{ cache }}/{{ portalId }}.js">');HubSpot.prototype.initialize=function(page){window._hsq=[];var cache=Math.ceil(new Date/3e5)*3e5;this.load({cache:cache},this.ready)};HubSpot.prototype.loaded=function(){return!!(window._hsq&&window._hsq.push!==Array.prototype.push)};HubSpot.prototype.page=function(page){push("_trackPageview")};HubSpot.prototype.identify=function(identify){if(!identify.email())return;var traits=identify.traits();traits=convertDates(traits);push("identify",traits)};HubSpot.prototype.track=function(track){var props=track.properties();props=convertDates(props);push("trackEvent",track.event(),props)};function convertDates(properties){return convert(properties,function(date){return date.getTime()})}},{"analytics.js-integration":159,"global-queue":191,"convert-dates":197}],118:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Improvely=module.exports=integration("Improvely").assumesPageview().global("_improvely").global("improvely").option("domain","").option("projectId",null).tag('<script src="//{{ domain }}.iljmp.com/improvely.js">');Improvely.prototype.initialize=function(page){window._improvely=[];window.improvely={init:function(e,t){window._improvely.push(["init",e,t])},goal:function(e){window._improvely.push(["goal",e])},label:function(e){window._improvely.push(["label",e])}};var domain=this.options.domain;var id=this.options.projectId;window.improvely.init(domain,id);this.load(this.ready)};Improvely.prototype.loaded=function(){return!!(window.improvely&&window.improvely.identify)};Improvely.prototype.identify=function(identify){var id=identify.userId();if(id)window.improvely.label(id)};Improvely.prototype.track=function(track){var props=track.properties({revenue:"amount"});props.type=track.event();window.improvely.goal(props)}},{"analytics.js-integration":159,alias:196}],119:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_iva");var Track=require("facade").Track;var is=require("is");var has=Object.prototype.hasOwnProperty;var InsideVault=module.exports=integration("InsideVault").global("_iva").option("clientId","").option("domain","").tag('<script src="//analytics.staticiv.com/iva.js">').mapping("events");InsideVault.prototype.initialize=function(page){var domain=this.options.domain;window._iva=window._iva||[];push("setClientId",this.options.clientId);if(domain)push("setDomain",domain);this.load(this.ready)};InsideVault.prototype.loaded=function(){return!!(window._iva&&window._iva.push!==Array.prototype.push)};InsideVault.prototype.page=function(page){push("trackEvent","click")};InsideVault.prototype.track=function(track){var user=this.analytics.user();var events=this.options.events;var event=track.event();var value=track.revenue()||track.value()||0;var eventId=track.orderId()||user.id()||"";if(!has.call(events,event))return;event=events[event];if(event!="sale"){push("trackEvent",event,value,eventId)}}},{"analytics.js-integration":159,"global-queue":191,facade:27,is:18}],120:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__insp");var alias=require("alias");var clone=require("clone");var Inspectlet=module.exports=integration("Inspectlet").assumesPageview().global("__insp").global("__insp_").option("wid","").tag('<script src="//www.inspectlet.com/inspectlet.js">');Inspectlet.prototype.initialize=function(page){push("wid",this.options.wid);this.load(this.ready)};Inspectlet.prototype.loaded=function(){return!!window.__insp_};Inspectlet.prototype.identify=function(identify){var traits=identify.traits({id:"userid"});push("tagSession",traits)};Inspectlet.prototype.track=function(track){push("tagSession",track.event())}},{"analytics.js-integration":159,"global-queue":191,alias:196,clone:195}],121:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var defaults=require("defaults");var isEmail=require("is-email");var load=require("load-script");var empty=require("is-empty");var alias=require("alias");var each=require("each");var when=require("when");var is=require("is");var Intercom=module.exports=integration("Intercom").assumesPageview().global("Intercom").option("activator","#IntercomDefaultWidget").option("appId","").option("inbox",false).tag('<script src="https://static.intercomcdn.com/intercom.v1.js">');Intercom.prototype.initialize=function(page){var self=this;this.load(function(){when(function(){return self.loaded()},self.ready)})};Intercom.prototype.loaded=function(){return is.fn(window.Intercom)};Intercom.prototype.page=function(page){window.Intercom("update")};Intercom.prototype.identify=function(identify){var traits=identify.traits({userId:"user_id"});var activator=this.options.activator;var opts=identify.options(this.name);var companyCreated=identify.companyCreated();var created=identify.created();var email=identify.email();var name=identify.name();var id=identify.userId();var group=this.analytics.group();if(!id&&!traits.email)return;traits.app_id=this.options.appId;if(null!=traits.company&&!is.object(traits.company))delete traits.company;if(traits.company)defaults(traits.company,group.traits());if(name)traits.name=name;if(traits.company&&companyCreated)traits.company.created=companyCreated;if(created)traits.created=created;traits=convertDates(traits,formatDate);traits=alias(traits,{created:"created_at"});if(traits.company)traits.company=alias(traits.company,{created:"created_at"});if(opts.increments)traits.increments=opts.increments;if(opts.userHash)traits.user_hash=opts.userHash;if(opts.user_hash)traits.user_hash=opts.user_hash;if("#IntercomDefaultWidget"!=activator){traits.widget={activator:activator}}var method=this._id!==id?"boot":"update";this._id=id;window.Intercom(method,traits)};Intercom.prototype.group=function(group){var props=group.properties();var id=group.groupId();if(id)props.id=id;window.Intercom("update",{company:props})};Intercom.prototype.track=function(track){window.Intercom("trackEvent",track.event(),track.properties())};function formatDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":159,"convert-dates":197,defaults:190,"is-email":19,"load-script":184,"is-empty":44,alias:196,each:5,when:185,is:18}],122:[function(require,module,exports){var integration=require("analytics.js-integration");var Keen=module.exports=integration("Keen IO").global("Keen").option("projectId","").option("readKey","").option("writeKey","").option("trackNamedPages",true).option("trackAllPages",false).option("trackCategorizedPages",true).tag('<script src="//dc8na2hxrj29i.cloudfront.net/code/keen-2.1.0-min.js">');Keen.prototype.initialize=function(){var options=this.options;window.Keen=window.Keen||{configure:function(e){this._cf=e},addEvent:function(e,t,n,i){this._eq=this._eq||[],this._eq.push([e,t,n,i])},setGlobalProperties:function(e){this._gp=e},onChartsReady:function(e){this._ocrq=this._ocrq||[],this._ocrq.push(e)}};window.Keen.configure({projectId:options.projectId,writeKey:options.writeKey,readKey:options.readKey});this.load(this.ready)};Keen.prototype.loaded=function(){return!!(window.Keen&&window.Keen.Base64)};Keen.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Keen.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var user={};if(id)user.userId=id;if(traits)user.traits=traits;window.Keen.setGlobalProperties(function(){return{user:user}})};Keen.prototype.track=function(track){window.Keen.addEvent(track.event(),track.properties())}},{"analytics.js-integration":159}],123:[function(require,module,exports){var integration=require("analytics.js-integration");var indexof=require("indexof");var is=require("is");var Kenshoo=module.exports=integration("Kenshoo").global("k_trackevent").option("cid","").option("subdomain","").option("events",[]).tag('<script src="//{{ subdomain }}.xg4ken.com/media/getpx.php?cid={{ cid }}">');Kenshoo.prototype.initialize=function(page){this.load(this.ready)};Kenshoo.prototype.loaded=function(){return is.fn(window.k_trackevent)};Kenshoo.prototype.track=function(track){var events=this.options.events;var traits=track.traits();var event=track.event();var revenue=track.revenue()||0;if(!~indexof(events,event))return;var params=["id="+this.options.cid,"type=conv","val="+revenue,"orderId="+track.orderId(),"promoCode="+track.coupon(),"valueCurrency="+track.currency(),"GCID=","kw=","product="];window.k_trackevent(params,this.options.subdomain)}},{"analytics.js-integration":159,indexof:46,is:18}],124:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kmq");var Track=require("facade").Track;var alias=require("alias");var Batch=require("batch");var each=require("each");var is=require("is");var KISSmetrics=module.exports=integration("KISSmetrics").assumesPageview().global("_kmq").global("KM").global("_kmil").option("apiKey","").option("trackNamedPages",true).option("trackCategorizedPages",true).option("prefixProperties",true).tag("useless",'<script src="//i.kissmetrics.com/i.js">').tag("library",'<script src="//doug1izaerwt3.cloudfront.net/{{ apiKey }}.1.js">');exports.isMobile=navigator.userAgent.match(/Android/i)||navigator.userAgent.match(/BlackBerry/i)||navigator.userAgent.match(/iPhone|iPod/i)||navigator.userAgent.match(/iPad/i)||navigator.userAgent.match(/Opera Mini/i)||navigator.userAgent.match(/IEMobile/i);KISSmetrics.prototype.initialize=function(page){var self=this;window._kmq=[];if(exports.isMobile)push("set",{"Mobile Session":"Yes"});var batch=new Batch;batch.push(function(done){self.load("useless",done)});batch.push(function(done){self.load("library",done)});batch.end(function(){self.trackPage(page);self.ready()})};KISSmetrics.prototype.loaded=function(){return is.object(window.KM)};KISSmetrics.prototype.page=function(page){if(!window.KM_SKIP_PAGE_VIEW)window.KM.pageView();this.trackPage(page)};KISSmetrics.prototype.trackPage=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};KISSmetrics.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("identify",id);if(traits)push("set",traits)};KISSmetrics.prototype.track=function(track){var mapping={revenue:"Billing Amount"};var event=track.event();var properties=track.properties(mapping);if(this.options.prefixProperties)properties=prefix(event,properties);push("record",event,properties)};KISSmetrics.prototype.alias=function(alias){push("alias",alias.to(),alias.from())};KISSmetrics.prototype.completedOrder=function(track){var products=track.products();var event=track.event();push("record",event,prefix(event,track.properties()));window._kmq.push(function(){var km=window.KM;each(products,function(product,i){var temp=new Track({event:event,properties:product});var item=prefix(event,product);item._t=km.ts()+i;item._d=1;km.set(item)})})};function prefix(event,properties){var prefixed={};each(properties,function(key,val){if(key==="Billing Amount"){prefixed[key]=val}else{prefixed[event+" - "+key]=val}});return prefixed}},{"analytics.js-integration":159,"global-queue":191,facade:27,alias:196,batch:198,each:5,is:18}],198:[function(require,module,exports){try{var EventEmitter=require("events").EventEmitter}catch(err){var Emitter=require("emitter")}function noop(){}module.exports=Batch;function Batch(){if(!(this instanceof Batch))return new Batch;this.fns=[];this.concurrency(Infinity);this.throws(true);for(var i=0,len=arguments.length;i<len;++i){this.push(arguments[i])}}if(EventEmitter){Batch.prototype.__proto__=EventEmitter.prototype}else{Emitter(Batch.prototype)}Batch.prototype.concurrency=function(n){this.n=n;return this};Batch.prototype.push=function(fn){this.fns.push(fn);return this};Batch.prototype.throws=function(throws){this.e=!!throws;return this};Batch.prototype.end=function(cb){var self=this,total=this.fns.length,pending=total,results=[],errors=[],cb=cb||noop,fns=this.fns,max=this.n,throws=this.e,index=0,done;if(!fns.length)return cb(null,results);function next(){var i=index++;var fn=fns[i];if(!fn)return;var start=new Date;try{fn(callback)}catch(err){callback(err)}function callback(err,res){if(done)return;if(err&&throws)return done=true,cb(err);var complete=total-pending+1;var end=new Date;results[i]=res;errors[i]=err;self.emit("progress",{index:i,value:res,error:err,pending:pending,total:total,complete:complete,percent:complete/total*100|0,start:start,end:end,duration:end-start});if(--pending)next();else if(!throws)cb(errors,results);else cb(null,results)}}for(var i=0;i<fns.length;i++){if(i==max)break;next()}return this}},{emitter:199}],199:[function(require,module,exports){module.exports=Emitter;function Emitter(obj){if(obj)return mixin(obj)}function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key]}return obj}Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks[event]=this._callbacks[event]||[]).push(fn);return this};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};Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};if(0==arguments.length){this._callbacks={};return this}var callbacks=this._callbacks[event];if(!callbacks)return this;if(1==arguments.length){delete this._callbacks[event];return this}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};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};Emitter.prototype.listeners=function(event){this._callbacks=this._callbacks||{};return this._callbacks[event]||[]};Emitter.prototype.hasListeners=function(event){return!!this.listeners(event).length}},{}],125:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_learnq");var tick=require("next-tick");var alias=require("alias");var aliases={id:"$id",email:"$email",firstName:"$first_name",lastName:"$last_name",phone:"$phone_number",title:"$title"};var Klaviyo=module.exports=integration("Klaviyo").assumesPageview().global("_learnq").option("apiKey","").tag('<script src="//a.klaviyo.com/media/js/learnmarklet.js">');Klaviyo.prototype.initialize=function(page){var self=this;push("account",this.options.apiKey);this.load(function(){tick(self.ready)})};Klaviyo.prototype.loaded=function(){return!!(window._learnq&&window._learnq.push!==Array.prototype.push)};Klaviyo.prototype.identify=function(identify){var traits=identify.traits(aliases);if(!traits.$id&&!traits.$email)return;push("identify",traits)};Klaviyo.prototype.group=function(group){var props=group.properties();if(!props.name)return;push("identify",{$organization:props.name})};Klaviyo.prototype.track=function(track){push("track",track.event(),track.properties({revenue:"$value"}))}},{"analytics.js-integration":159,"global-queue":191,"next-tick":45,alias:196}],126:[function(require,module,exports){var integration=require("analytics.js-integration");var LeadLander=module.exports=integration("LeadLander").assumesPageview().global("llactid").global("trackalyzer").option("accountId",null).tag('<script src="http://t6.trackalyzer.com/trackalyze-nodoc.js">');LeadLander.prototype.initialize=function(page){window.llactid=this.options.accountId;this.load(this.ready)};LeadLander.prototype.loaded=function(){return!!window.trackalyzer}},{"analytics.js-integration":159}],127:[function(require,module,exports){var integration=require("analytics.js-integration"); var clone=require("clone");var each=require("each");var when=require("when");var LiveChat=module.exports=integration("LiveChat").assumesPageview().global("__lc").global("__lc_inited").global("LC_API").global("LC_Invite").option("group",0).option("license","").tag('<script src="//cdn.livechatinc.com/tracking.js">');LiveChat.prototype.initialize=function(page){var self=this;window.__lc=clone(this.options);this.load(function(){when(function(){return self.loaded()},self.ready)})};LiveChat.prototype.loaded=function(){return!!(window.LC_API&&window.LC_Invite)};LiveChat.prototype.identify=function(identify){var traits=identify.traits({userId:"User ID"});window.LC_API.set_custom_variables(convert(traits))};function convert(traits){var arr=[];each(traits,function(key,value){arr.push({name:key,value:value})});return arr}},{"analytics.js-integration":159,clone:195,each:5,when:185}],128:[function(require,module,exports){var integration=require("analytics.js-integration");var Identify=require("facade").Identify;var useHttps=require("use-https");var LuckyOrange=module.exports=integration("Lucky Orange").assumesPageview().global("_loq").global("__wtw_watcher_added").global("__wtw_lucky_site_id").global("__wtw_lucky_is_segment_io").global("__wtw_custom_user_data").option("siteId",null).tag("http",'<script src="http://www.luckyorange.com/w.js?{{ cache }}">').tag("https",'<script src="https://ssl.luckyorange.com/w.js?{{ cache }}">');LuckyOrange.prototype.initialize=function(page){var user=this.analytics.user();window._loq||(window._loq=[]);window.__wtw_lucky_site_id=this.options.siteId;this.identify(new Identify({traits:user.traits(),userId:user.id()}));var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{cache:cache},this.ready)};LuckyOrange.prototype.loaded=function(){return!!window.__wtw_watcher_added};LuckyOrange.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var name=identify.name();if(name)traits.name=name;if(email)traits.email=email;window.__wtw_custom_user_data=traits}},{"analytics.js-integration":159,facade:27,"use-https":161}],129:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var Lytics=module.exports=integration("Lytics").global("jstag").option("cid","").option("cookie","seerid").option("delay",2e3).option("sessionTimeout",1800).option("url","//c.lytics.io").tag('<script src="//c.lytics.io/static/io.min.js">');var aliases={sessionTimeout:"sessecs"};Lytics.prototype.initialize=function(page){var options=alias(this.options,aliases);window.jstag=function(){var t={_q:[],_c:options,ts:(new Date).getTime()};t.send=function(){this._q.push(["ready","send",Array.prototype.slice.call(arguments)]);return this};return t}();this.load(this.ready)};Lytics.prototype.loaded=function(){return!!(window.jstag&&window.jstag.bind)};Lytics.prototype.page=function(page){window.jstag.send(page.properties())};Lytics.prototype.identify=function(identify){var traits=identify.traits({userId:"_uid"});window.jstag.send(traits)};Lytics.prototype.track=function(track){var props=track.properties();props._e=track.event();window.jstag.send(props)}},{"analytics.js-integration":159,alias:196}],130:[function(require,module,exports){var alias=require("alias");var clone=require("clone");var dates=require("convert-dates");var integration=require("analytics.js-integration");var iso=require("to-iso-string");var indexof=require("indexof");var del=require("obj-case").del;var Mixpanel=module.exports=integration("Mixpanel").global("mixpanel").option("increments",[]).option("cookieName","").option("nameTag",true).option("pageview",false).option("people",false).option("token","").option("trackAllPages",false).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.mxpnl.com/libs/mixpanel-2.2.min.js">');var optionsAliases={cookieName:"cookie_name"};Mixpanel.prototype.initialize=function(){(function(c,a){window.mixpanel=a;var b,d,h,e;a._i=[];a.init=function(b,c,f){function d(a,b){var c=b.split(".");2==c.length&&(a=a[c[0]],b=c[1]);a[b]=function(){a.push([b].concat(Array.prototype.slice.call(arguments,0)))}}var g=a;"undefined"!==typeof f?g=a[f]=[]:f="mixpanel";g.people=g.people||[];h=["disable","track","track_pageview","track_links","track_forms","register","register_once","unregister","identify","alias","name_tag","set_config","people.set","people.increment","people.track_charge","people.append"];for(e=0;e<h.length;e++)d(g,h[e]);a._i.push([b,c,f])};a.__SV=1.2})(document,window.mixpanel||[]);this.options.increments=lowercase(this.options.increments);var options=alias(this.options,optionsAliases);window.mixpanel.init(options.token,options);this.load(this.ready)};Mixpanel.prototype.loaded=function(){return!!(window.mixpanel&&window.mixpanel.config)};Mixpanel.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(opts.trackAllPages){this.track(page.track())}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};var traitAliases={created:"$created",email:"$email",firstName:"$first_name",lastName:"$last_name",lastSeen:"$last_seen",name:"$name",username:"$username",phone:"$phone"};Mixpanel.prototype.identify=function(identify){var username=identify.username();var email=identify.email();var id=identify.userId();if(id)window.mixpanel.identify(id);var nametag=email||username||id;if(nametag)window.mixpanel.name_tag(nametag);var traits=identify.traits(traitAliases);if(traits.$created)del(traits,"createdAt");window.mixpanel.register(traits);if(this.options.people)window.mixpanel.people.set(traits)};Mixpanel.prototype.track=function(track){var increments=this.options.increments;var increment=track.event().toLowerCase();var people=this.options.people;var props=track.properties();var revenue=track.revenue();delete props.distinct_id;delete props.ip;delete props.mp_name_tag;delete props.mp_note;delete props.token;if(people&&~indexof(increments,increment)){window.mixpanel.people.increment(track.event());window.mixpanel.people.set("Last "+track.event(),new Date)}props=dates(props,iso);window.mixpanel.track(track.event(),props);if(revenue&&people){window.mixpanel.people.track_charge(revenue)}};Mixpanel.prototype.alias=function(alias){var mp=window.mixpanel;var to=alias.to();if(mp.get_distinct_id&&mp.get_distinct_id()===to)return;if(mp.get_property&&mp.get_property("$people_distinct_id")===to)return;mp.alias(to,alias.from())};function lowercase(arr){var ret=new Array(arr.length);for(var i=0;i<arr.length;++i){ret[i]=String(arr[i]).toLowerCase()}return ret}},{alias:196,clone:195,"convert-dates":197,"analytics.js-integration":159,"to-iso-string":194,indexof:46,"obj-case":60}],131:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var is=require("is");var Mojn=module.exports=integration("Mojn").option("customerCode","").global("_mojnTrack").tag('<script src="https://track.idtargeting.com/{{ customerCode }}/track.js">');Mojn.prototype.initialize=function(){window._mojnTrack=window._mojnTrack||[];window._mojnTrack.push({cid:this.options.customerCode});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Mojn.prototype.loaded=function(){return is.object(window._mojnTrack)};Mojn.prototype.identify=function(identify){var email=identify.email();if(!email)return;var img=new Image;img.src="//matcher.idtargeting.com/analytics.gif?cid="+this.options.customerCode+"&_mjnctid="+email;img.width=1;img.height=1;return img};Mojn.prototype.track=function(track){var properties=track.properties();var revenue=properties.revenue;var currency=properties.currency||"";var conv=currency+revenue;if(!revenue)return;window._mojnTrack.push({conv:conv});return conv}},{"analytics.js-integration":159,bind:33,when:185,is:18}],132:[function(require,module,exports){var push=require("global-queue")("_mfq");var integration=require("analytics.js-integration");var each=require("each");var Mouseflow=module.exports=integration("Mouseflow").assumesPageview().global("mouseflow").global("_mfq").option("apiKey","").option("mouseflowHtmlDelay",0).tag('<script src="//cdn.mouseflow.com/projects/{{ apiKey }}.js">');Mouseflow.prototype.initialize=function(page){window.mouseflowHtmlDelay=this.options.mouseflowHtmlDelay;this.load(this.ready)};Mouseflow.prototype.loaded=function(){return!!window.mouseflow};Mouseflow.prototype.page=function(page){if(!window.mouseflow)return;if("function"!=typeof mouseflow.newPageView)return;mouseflow.newPageView()};Mouseflow.prototype.identify=function(identify){set(identify.traits())};Mouseflow.prototype.track=function(track){var props=track.properties();props.event=track.event();set(props)};function set(obj){each(obj,function(key,value){push("setVariable",key,value)})}},{"global-queue":191,"analytics.js-integration":159,each:5}],133:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var each=require("each");var is=require("is");var MouseStats=module.exports=integration("MouseStats").assumesPageview().global("msaa").global("MouseStatsVisitorPlaybacks").option("accountNumber","").tag("http",'<script src="http://www2.mousestats.com/js/{{ path }}.js?{{ cache }}">').tag("https",'<script src="https://ssl.mousestats.com/js/{{ path }}.js?{{ cache }}">');MouseStats.prototype.initialize=function(page){var number=this.options.accountNumber;var path=number.slice(0,1)+"/"+number.slice(1,2)+"/"+number;var cache=Math.floor((new Date).getTime()/6e4);var name=useHttps()?"https":"http";this.load(name,{path:path,cache:cache},this.ready)};MouseStats.prototype.loaded=function(){return is.array(window.MouseStatsVisitorPlaybacks)};MouseStats.prototype.identify=function(identify){each(identify.traits(),function(key,value){window.MouseStatsVisitorPlaybacks.customVariable(key,value)})}},{"analytics.js-integration":159,"use-https":161,each:5,is:18}],134:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("__nls");var Navilytics=module.exports=integration("Navilytics").assumesPageview().global("__nls").option("memberId","").option("projectId","").tag('<script src="//www.navilytics.com/nls.js?mid={{ memberId }}&pid={{ projectId }}">');Navilytics.prototype.initialize=function(page){window.__nls=window.__nls||[];this.load(this.ready)};Navilytics.prototype.loaded=function(){return!!(window.__nls&&[].push!=window.__nls.push)};Navilytics.prototype.track=function(track){push("tagRecording",track.event())}},{"analytics.js-integration":159,"global-queue":191}],135:[function(require,module,exports){var integration=require("analytics.js-integration");var https=require("use-https");var tick=require("next-tick");var Olark=module.exports=integration("Olark").assumesPageview().global("olark").option("identify",true).option("page",true).option("siteId","").option("groupId","").option("track",false);Olark.prototype.initialize=function(page){var self=this;this.load(function(){tick(self.ready)});var groupId=this.options.groupId;if(groupId){chat("setOperatorGroup",{group:groupId})}var self=this;box("onExpand",function(){self._open=true});box("onShrink",function(){self._open=false})};Olark.prototype.loaded=function(){return!!window.olark};Olark.prototype.load=function(callback){var el=document.getElementById("olark");window.olark||function(c){var f=window,d=document,l=https()?"https:":"http:",z=c.name,r="load";var nt=function(){f[z]=function(){(a.s=a.s||[]).push(arguments)};var a=f[z]._={},q=c.methods.length;while(q--){(function(n){f[z][n]=function(){f[z]("call",n,arguments)}})(c.methods[q])}a.l=c.loader;a.i=nt;a.p={0:+new Date};a.P=function(u){a.p[u]=new Date-a.p[0]};function s(){a.P(r);f[z](r)}f.addEventListener?f.addEventListener(r,s,false):f.attachEvent("on"+r,s);var ld=function(){function p(hd){hd="head";return["<",hd,"></",hd,"><",i," onl"+'oad="var d=',g,";d.getElementsByTagName('head')[0].",j,"(d.",h,"('script')).",k,"='",l,"//",a.l,"'",'"',"></",i,">"].join("")}var i="body",m=d[i];if(!m){return setTimeout(ld,100)}a.P(1);var j="appendChild",h="createElement",k="src",n=d[h]("div"),v=n[j](d[h](z)),b=d[h]("iframe"),g="document",e="domain",o;n.style.display="none";m.insertBefore(n,m.firstChild).id=z;b.frameBorder="0";b.id=z+"-loader";if(/MSIE[ ]+6/.test(navigator.userAgent)){b.src="javascript:false"}b.allowTransparency="true";v[j](b);try{b.contentWindow[g].open()}catch(w){c[e]=d[e];o="javascript:var d="+g+".open();d.domain='"+d.domain+"';";b[k]=o+"void(0);"}try{var t=b.contentWindow[g];t.write(p());t.close()}catch(x){b[k]=o+'d.write("'+p().replace(/"/g,String.fromCharCode(92)+'"')+'");d.close();'}a.P(2)};ld()};nt()}({loader:"static.olark.com/jsclient/loader0.js",name:"olark",methods:["configure","extend","declare","identify"]});window.olark.identify(this.options.siteId);callback()};Olark.prototype.page=function(page){if(!this.options.page||!this._open)return;var props=page.properties();var name=page.fullName();if(!name&&!props.url)return;var msg=name?name.toLowerCase()+" page":props.url;chat("sendNotificationToOperator",{body:"looking at "+msg})};Olark.prototype.identify=function(identify){if(!this.options.identify)return;var username=identify.username();var traits=identify.traits();var id=identify.userId();var email=identify.email();var phone=identify.phone();var name=identify.name()||identify.firstName();visitor("updateCustomFields",traits);if(email)visitor("updateEmailAddress",{emailAddress:email});if(phone)visitor("updatePhoneNumber",{phoneNumber:phone});if(name)visitor("updateFullName",{fullName:name});var nickname=name||email||username||id;if(name&&email)nickname+=" ("+email+")";if(nickname)chat("updateVisitorNickname",{snippet:nickname})};Olark.prototype.track=function(track){if(!this.options.track||!this._open)return;chat("sendNotificationToOperator",{body:'visitor triggered "'+track.event()+'"'})};function box(action,value){window.olark("api.box."+action,value)}function visitor(action,value){window.olark("api.visitor."+action,value)}function chat(action,value){window.olark("api.chat."+action,value)}},{"analytics.js-integration":159,"use-https":161,"next-tick":45}],136:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("optimizely");var callback=require("callback");var tick=require("next-tick");var bind=require("bind");var each=require("each");var Optimizely=module.exports=integration("Optimizely").option("variations",true).option("trackNamedPages",true).option("trackCategorizedPages",true);Optimizely.prototype.initialize=function(){if(this.options.variations){var self=this;tick(function(){self.replay()})}this.ready()};Optimizely.prototype.track=function(track){var props=track.properties();if(props.revenue)props.revenue*=100;push("trackEvent",track.event(),props)};Optimizely.prototype.page=function(page){var category=page.category();var name=page.fullName();var opts=this.options;if(category&&opts.trackCategorizedPages){this.track(page.track(category))}if(name&&opts.trackNamedPages){this.track(page.track(name))}};Optimizely.prototype.replay=function(){if(!window.optimizely)return;var data=window.optimizely.data;if(!data)return;var experiments=data.experiments;var map=data.state.variationNamesMap;var traits={};each(map,function(experimentId,variation){var experiment=experiments[experimentId].name;traits["Experiment: "+experiment]=variation});this.analytics.identify(traits)}},{"analytics.js-integration":159,"global-queue":191,callback:12,"next-tick":45,bind:33,each:5}],137:[function(require,module,exports){var integration=require("analytics.js-integration");var PerfectAudience=module.exports=integration("Perfect Audience").assumesPageview().global("_pa").option("siteId","").tag('<script src="//tag.perfectaudience.com/serve/{{ siteId }}.js">');PerfectAudience.prototype.initialize=function(page){window._pa=window._pa||{};this.load(this.ready)};PerfectAudience.prototype.loaded=function(){return!!(window._pa&&window._pa.track)};PerfectAudience.prototype.track=function(track){window._pa.track(track.event(),track.properties())}},{"analytics.js-integration":159}],138:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_prum");var date=require("load-date");var Pingdom=module.exports=integration("Pingdom").assumesPageview().global("_prum").global("PRUM_EPISODES").option("id","").tag('<script src="//rum-static.pingdom.net/prum.min.js">');Pingdom.prototype.initialize=function(page){window._prum=window._prum||[];push("id",this.options.id);push("mark","firstbyte",date.getTime());var self=this;this.load(this.ready)};Pingdom.prototype.loaded=function(){return!!(window._prum&&window._prum.push!==Array.prototype.push)}},{"analytics.js-integration":159,"global-queue":191,"load-date":192}],139:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_paq");var each=require("each");var Piwik=module.exports=integration("Piwik").global("_paq").option("url",null).option("siteId","").mapping("goals").tag('<script src="{{ url }}/piwik.js">');Piwik.prototype.initialize=function(){window._paq=window._paq||[];push("setSiteId",this.options.siteId);push("setTrackerUrl",this.options.url+"/piwik.php");push("enableLinkTracking");this.load(this.ready)};Piwik.prototype.loaded=function(){return!!(window._paq&&window._paq.push!=[].push)};Piwik.prototype.page=function(page){push("trackPageView")};Piwik.prototype.track=function(track){var goals=this.goals(track.event());var revenue=track.revenue()||0;each(goals,function(goal){push("trackGoal",goal,revenue)})}},{"analytics.js-integration":159,"global-queue":191,each:5}],140:[function(require,module,exports){var integration=require("analytics.js-integration");var convertDates=require("convert-dates");var push=require("global-queue")("_lnq");var alias=require("alias");var Preact=module.exports=integration("Preact").assumesPageview().global("_lnq").option("projectCode","").tag('<script src="//d2bbvl6dq48fa6.cloudfront.net/js/ln-2.4.min.js">');Preact.prototype.initialize=function(page){window._lnq=window._lnq||[];push("_setCode",this.options.projectCode);this.load(this.ready)};Preact.prototype.loaded=function(){return!!(window._lnq&&window._lnq.push!==Array.prototype.push)};Preact.prototype.identify=function(identify){if(!identify.userId())return;var traits=identify.traits({created:"created_at"});traits=convertDates(traits,convertDate);push("_setPersonData",{name:identify.name(),email:identify.email(),uid:identify.userId(),properties:traits})};Preact.prototype.group=function(group){if(!group.groupId())return;push("_setAccount",group.traits())};Preact.prototype.track=function(track){var props=track.properties();var revenue=track.revenue();var event=track.event();var special={name:event};if(revenue){special.revenue=revenue*100;delete props.revenue}if(props.note){special.note=props.note;delete props.note}push("_logEvent",special,props)};function convertDate(date){return Math.floor(date/1e3)}},{"analytics.js-integration":159,"convert-dates":197,"global-queue":191,alias:196}],141:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_kiq");var Facade=require("facade");var Identify=Facade.Identify;var bind=require("bind");var when=require("when");var Qualaroo=module.exports=integration("Qualaroo").assumesPageview().global("_kiq").option("customerId","").option("siteToken","").option("track",false).tag('<script src="//s3.amazonaws.com/ki.js/{{ customerId }}/{{ siteToken }}.js">');Qualaroo.prototype.initialize=function(page){window._kiq=window._kiq||[];var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Qualaroo.prototype.loaded=function(){return!!(window._kiq&&window._kiq.push!==Array.prototype.push)};Qualaroo.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();var email=identify.email();if(email)id=email;if(id)push("identify",id);if(traits)push("set",traits)};Qualaroo.prototype.track=function(track){if(!this.options.track)return;var event=track.event();var traits={};traits["Triggered: "+event]=true;this.identify(new Identify({traits:traits}))}},{"analytics.js-integration":159,"global-queue":191,facade:27,bind:33,when:185}],142:[function(require,module,exports){var push=require("global-queue")("_qevents",{wrap:false});var integration=require("analytics.js-integration");var useHttps=require("use-https");var Quantcast=module.exports=integration("Quantcast").assumesPageview().global("_qevents").global("__qc").option("pCode",null).option("advertise",false).tag("http",'<script src="http://edge.quantserve.com/quant.js">').tag("https",'<script src="https://secure.quantserve.com/quant.js">');Quantcast.prototype.initialize=function(page){window._qevents=window._qevents||[];var opts=this.options;var settings={qacct:opts.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();if(page){settings.labels=this.labels("page",page.category(),page.name())}push(settings);var name=useHttps()?"https":"http";this.load(name,this.ready)};Quantcast.prototype.loaded=function(){return!!window.__qc};Quantcast.prototype.page=function(page){var category=page.category();var name=page.name();var settings={event:"refresh",labels:this.labels("page",category,name),qacct:this.options.pCode};var user=this.analytics.user();if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.identify=function(identify){var id=identify.userId();if(id){window._qevents[0]=window._qevents[0]||{};window._qevents[0].uid=id}};Quantcast.prototype.track=function(track){var name=track.event();var revenue=track.revenue();var settings={event:"click",labels:this.labels("event",name),qacct:this.options.pCode};var user=this.analytics.user();if(null!=revenue)settings.revenue=revenue+"";if(user.id())settings.uid=user.id();push(settings)};Quantcast.prototype.completedOrder=function(track){var name=track.event();var revenue=track.total();var labels=this.labels("event",name);var category=track.category();if(this.options.advertise&&category){labels+=","+this.labels("pcat",category)}var settings={event:"refresh",labels:labels,revenue:revenue+"",orderid:track.orderId(),qacct:this.options.pCode};push(settings)};Quantcast.prototype.labels=function(type){var args=[].slice.call(arguments,1);var advertise=this.options.advertise;var ret=[];if(advertise&&"page"==type)type="event";if(advertise)type="_fp."+type;for(var i=0;i<args.length;++i){if(null==args[i])continue;var value=String(args[i]);ret.push(value.replace(/,/g,";"))}ret=advertise?ret.join(" "):ret.join(".");return[type,ret].join(".")}},{"global-queue":191,"analytics.js-integration":159,"use-https":161}],143:[function(require,module,exports){var integration=require("analytics.js-integration");var extend=require("extend");var is=require("is");var RollbarIntegration=module.exports=integration("Rollbar").global("Rollbar").option("identify",true).option("accessToken","").option("environment","unknown").option("captureUncaught",true);RollbarIntegration.prototype.initialize=function(page){var _rollbarConfig=this.config={accessToken:this.options.accessToken,captureUncaught:this.options.captureUncaught,payload:{environment:this.options.environment}};(function(a){function b(b){this.shimId=++g,this.notifier=null,this.parentShim=b,this.logger=function(){},a.console&&void 0===a.console.shimId&&(this.logger=a.console.log)}function c(b,c,d){!d[4]&&a._rollbarWrappedError&&(d[4]=a._rollbarWrappedError,a._rollbarWrappedError=null),b.uncaughtError.apply(b,d),c&&c.apply(a,d)}function d(c){var d=b;return f(function(){if(this.notifier)return this.notifier[c].apply(this.notifier,arguments);var b=this,e="scope"===c;e&&(b=new d(this));var f=Array.prototype.slice.call(arguments,0),g={shim:b,method:c,args:f,ts:new Date};return a._rollbarShimQueue.push(g),e?b:void 0})}function e(a,b){if(b.hasOwnProperty&&b.hasOwnProperty("addEventListener")){var c=b.addEventListener;b.addEventListener=function(b,d,e){c.call(this,b,a.wrap(d),e)};var d=b.removeEventListener;b.removeEventListener=function(a,b,c){d.call(this,a,b._wrapped||b,c)}}}function f(a,b){return b=b||this.logger,function(){try{return a.apply(this,arguments)}catch(c){b("Rollbar internal error:",c)}}}var g=0;b.init=function(a,d){var g=d.globalAlias||"Rollbar";if("object"==typeof a[g])return a[g];a._rollbarShimQueue=[],a._rollbarWrappedError=null,d=d||{};var h=new b;return f(function(){if(h.configure(d),d.captureUncaught){var b=a.onerror;a.onerror=function(){var a=Array.prototype.slice.call(arguments,0);c(h,b,a)};var f,i,j=["EventTarget","Window","Node","ApplicationCache","AudioTrackList","ChannelMergerNode","CryptoOperation","EventSource","FileReader","HTMLUnknownElement","IDBDatabase","IDBRequest","IDBTransaction","KeyOperation","MediaController","MessagePort","ModalWindow","Notification","SVGElementInstance","Screen","TextTrack","TextTrackCue","TextTrackList","WebSocket","WebSocketWorker","Worker","XMLHttpRequest","XMLHttpRequestEventTarget","XMLHttpRequestUpload"];for(f=0;f<j.length;++f)i=j[f],a[i]&&a[i].prototype&&e(h,a[i].prototype)}return a[g]=h,h},h.logger)()},b.prototype.loadFull=function(a,b,c,d,e){var g=f(function(){var a=b.createElement("script"),e=b.getElementsByTagName("script")[0];a.src=d.rollbarJsUrl,a.async=!c,a.onload=h,e.parentNode.insertBefore(a,e)},this.logger),h=f(function(){var b;if(void 0===a._rollbarPayloadQueue){var c,d,f,g;for(b=new Error("rollbar.js did not load");c=a._rollbarShimQueue.shift();)for(f=c.args,g=0;g<f.length;++g)if(d=f[g],"function"==typeof d){d(b);break}}e&&e(b)},this.logger);f(function(){c?g():a.addEventListener?a.addEventListener("load",g,!1):a.attachEvent("onload",g)},this.logger)()},b.prototype.wrap=function(b){if("function"!=typeof b)return b;if(b._isWrap)return b;if(!b._wrapped){b._wrapped=function(){try{return b.apply(this,arguments)}catch(c){throw a._rollbarWrappedError=c,c}},b._wrapped._isWrap=!0;for(var c in b)b.hasOwnProperty(c)&&(b._wrapped[c]=b[c])}return b._wrapped};for(var h="log,debug,info,warn,warning,error,critical,global,configure,scope,uncaughtError".split(","),i=0;i<h.length;++i)b.prototype[h[i]]=d(h[i]);var j="//d37gvrvc0wt4s1.cloudfront.net/js/v1.0/rollbar.min.js";_rollbarConfig.rollbarJsUrl=_rollbarConfig.rollbarJsUrl||j,b.init(a,_rollbarConfig)})(window,document);this.load(this.ready)};RollbarIntegration.prototype.loaded=function(){return is.object(window.Rollbar)&&null==window.Rollbar.shimId};RollbarIntegration.prototype.load=function(callback){window.Rollbar.loadFull(window,document,true,this.config,callback)};RollbarIntegration.prototype.identify=function(identify){if(!this.options.identify)return;var uid=identify.userId();if(uid===null||uid===undefined)return;var rollbar=window.Rollbar;var person={id:uid};extend(person,identify.traits());rollbar.configure({payload:{person:person}})}},{"analytics.js-integration":159,extend:40,is:18}],144:[function(require,module,exports){var integration=require("analytics.js-integration");var SaaSquatch=module.exports=integration("SaaSquatch").option("tenantAlias","").global("_sqh").tag('<script src="//d2rcp9ak152ke1.cloudfront.net/assets/javascripts/squatch.min.js">');SaaSquatch.prototype.initialize=function(page){window._sqh=window._sqh||[];this.load(this.ready)};SaaSquatch.prototype.loaded=function(){return window._sqh&&window._sqh.push!=[].push};SaaSquatch.prototype.identify=function(identify){var sqh=window._sqh;var accountId=identify.proxy("traits.accountId");var image=identify.proxy("traits.referralImage");var opts=identify.options(this.name);var id=identify.userId();var email=identify.email();if(!(id||email))return;if(this.called)return;var init={tenant_alias:this.options.tenantAlias,first_name:identify.firstName(),last_name:identify.lastName(),user_image:identify.avatar(),email:email,user_id:id};if(accountId)init.account_id=accountId;if(opts.checksum)init.checksum=opts.checksum;if(image)init.fb_share_image=image;sqh.push(["init",init]);this.called=true;this.load()}},{"analytics.js-integration":159}],145:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var Sentry=module.exports=integration("Sentry").global("Raven").option("config","").tag('<script src="//cdn.ravenjs.com/1.1.10/native/raven.min.js">');Sentry.prototype.initialize=function(){var config=this.options.config;var self=this;this.load(function(){window.Raven.config(config).install();self.ready()})};Sentry.prototype.loaded=function(){return is.object(window.Raven)};Sentry.prototype.identify=function(identify){window.Raven.setUser(identify.traits())}},{"analytics.js-integration":159,is:18}],146:[function(require,module,exports){var integration=require("analytics.js-integration");var is=require("is");var SnapEngage=module.exports=integration("SnapEngage").assumesPageview().global("SnapABug").option("apiKey","").tag('<script src="//commondatastorage.googleapis.com/code.snapengage.com/js/{{ apiKey }}.js">');SnapEngage.prototype.initialize=function(page){this.load(this.ready)};SnapEngage.prototype.loaded=function(){return is.object(window.SnapABug)};SnapEngage.prototype.identify=function(identify){var email=identify.email();if(!email)return;window.SnapABug.setUserEmail(email)}},{"analytics.js-integration":159,is:18}],147:[function(require,module,exports){var integration=require("analytics.js-integration");var bind=require("bind");var when=require("when");var Spinnakr=module.exports=integration("Spinnakr").assumesPageview().global("_spinnakr_site_id").global("_spinnakr").option("siteId","").tag('<script src="//d3ojzyhbolvoi5.cloudfront.net/js/so.js">');Spinnakr.prototype.initialize=function(page){window._spinnakr_site_id=this.options.siteId;var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,ready)})};Spinnakr.prototype.loaded=function(){return!!window._spinnakr}},{"analytics.js-integration":159,bind:33,when:185}],148:[function(require,module,exports){var integration=require("analytics.js-integration");var slug=require("slug");var push=require("global-queue")("_tsq");var Tapstream=module.exports=integration("Tapstream").assumesPageview().global("_tsq").option("accountName","").option("trackAllPages",true).option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//cdn.tapstream.com/static/js/tapstream.js">');Tapstream.prototype.initialize=function(page){window._tsq=window._tsq||[];push("setAccountName",this.options.accountName);this.load(this.ready)};Tapstream.prototype.loaded=function(){return!!(window._tsq&&window._tsq.push!==Array.prototype.push)};Tapstream.prototype.page=function(page){var category=page.category();var opts=this.options;var name=page.fullName();if(opts.trackAllPages){this.track(page.track())}if(name&&opts.trackNamedPages){this.track(page.track(name))}if(category&&opts.trackCategorizedPages){this.track(page.track(category))}};Tapstream.prototype.track=function(track){var props=track.properties();push("fireHit",slug(track.event()),[props.url])}},{"analytics.js-integration":159,slug:166,"global-queue":191}],149:[function(require,module,exports){var integration=require("analytics.js-integration");var alias=require("alias");var clone=require("clone");var Trakio=module.exports=integration("trak.io").assumesPageview().global("trak").option("token","").option("trackNamedPages",true).option("trackCategorizedPages",true).tag('<script src="//d29p64779x43zo.cloudfront.net/v1/trak.io.min.js">');var optionsAliases={initialPageview:"auto_track_page_view"};Trakio.prototype.initialize=function(page){var options=this.options;window.trak=window.trak||[];window.trak.io=window.trak.io||{}; window.trak.push=window.trak.push||function(){};window.trak.io.load=window.trak.io.load||function(e){var r=function(e){return function(){window.trak.push([e].concat(Array.prototype.slice.call(arguments,0)))}},i=["initialize","identify","track","alias","channel","source","host","protocol","page_view"];for(var s=0;s<i.length;s++)window.trak.io[i[s]]=r(i[s]);window.trak.io.initialize.apply(window.trak.io,arguments)};window.trak.io.load(options.token,alias(options,optionsAliases));this.load(this.ready)};Trakio.prototype.loaded=function(){return!!(window.trak&&window.trak.loaded)};Trakio.prototype.page=function(page){var category=page.category();var props=page.properties();var name=page.fullName();window.trak.io.page_view(props.path,name||props.title);if(name&&this.options.trackNamedPages){this.track(page.track(name))}if(category&&this.options.trackCategorizedPages){this.track(page.track(category))}};var traitAliases={avatar:"avatar_url",firstName:"first_name",lastName:"last_name"};Trakio.prototype.identify=function(identify){var traits=identify.traits(traitAliases);var id=identify.userId();if(id){window.trak.io.identify(id,traits)}else{window.trak.io.identify(traits)}};Trakio.prototype.track=function(track){window.trak.io.track(track.event(),track.properties())};Trakio.prototype.alias=function(alias){if(!window.trak.io.distinct_id)return;var from=alias.from();var to=alias.to();if(to===window.trak.io.distinct_id())return;if(from){window.trak.io.alias(from,to)}else{window.trak.io.alias(to)}}},{"analytics.js-integration":159,alias:196,clone:195}],150:[function(require,module,exports){var integration=require("analytics.js-integration");var each=require("each");var has=Object.prototype.hasOwnProperty;var TwitterAds=module.exports=integration("Twitter Ads").tag("pixel",'<img src="//analytics.twitter.com/i/adsct?txn_id={{ event }}&p_id=Twitter"/>').mapping("events");TwitterAds.prototype.initialize=function(){this.ready()};TwitterAds.prototype.track=function(track){var events=this.events(track.event());var self=this;each(events,function(event){var el=self.load("pixel",{event:event})})}},{"analytics.js-integration":159,each:5}],151:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_uc");var Usercycle=module.exports=integration("USERcycle").assumesPageview().global("_uc").option("key","").tag('<script src="//api.usercycle.com/javascripts/track.js">');Usercycle.prototype.initialize=function(page){push("_key",this.options.key);this.load(this.ready)};Usercycle.prototype.loaded=function(){return!!(window._uc&&window._uc.push!==Array.prototype.push)};Usercycle.prototype.identify=function(identify){var traits=identify.traits();var id=identify.userId();if(id)push("uid",id);push("action","came_back",traits)};Usercycle.prototype.track=function(track){push("action",track.event(),track.properties({revenue:"revenue_amount"}))}},{"analytics.js-integration":159,"global-queue":191}],152:[function(require,module,exports){var alias=require("alias");var callback=require("callback");var convertDates=require("convert-dates");var integration=require("analytics.js-integration");var load=require("load-script");var push=require("global-queue")("_ufq");module.exports=exports=function(analytics){analytics.addIntegration(Userfox)};var Userfox=exports.Integration=integration("userfox").assumesPageview().readyOnLoad().global("_ufq").option("clientId","");Userfox.prototype.initialize=function(page){window._ufq=[];this.load()};Userfox.prototype.loaded=function(){return!!(window._ufq&&window._ufq.push!==Array.prototype.push)};Userfox.prototype.load=function(callback){load("//d2y71mjhnajxcg.cloudfront.net/js/userfox-stable.js",callback)};Userfox.prototype.identify=function(identify){var traits=identify.traits({created:"signup_date"});var email=identify.email();if(!email)return;push("init",{clientId:this.options.clientId,email:email});traits=convertDates(traits,formatDate);push("track",traits)};function formatDate(date){return Math.round(date.getTime()/1e3).toString()}},{alias:196,callback:12,"convert-dates":197,"analytics.js-integration":159,"load-script":184,"global-queue":191}],153:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("UserVoice");var convertDates=require("convert-dates");var unix=require("to-unix-timestamp");var alias=require("alias");var clone=require("clone");var UserVoice=module.exports=integration("UserVoice").assumesPageview().global("UserVoice").global("showClassicWidget").option("apiKey","").option("classic",false).option("forumId",null).option("showWidget",true).option("mode","contact").option("accentColor","#448dd6").option("smartvote",true).option("trigger",null).option("triggerPosition","bottom-right").option("triggerColor","#ffffff").option("triggerBackgroundColor","rgba(46, 49, 51, 0.6)").option("classicMode","full").option("primaryColor","#cc6d00").option("linkColor","#007dbf").option("defaultMode","support").option("tabLabel","Feedback & Support").option("tabColor","#cc6d00").option("tabPosition","middle-right").option("tabInverted",false).tag('<script src="//widget.uservoice.com/{{ apiKey }}.js">');UserVoice.on("construct",function(integration){if(!integration.options.classic)return;integration.group=undefined;integration.identify=integration.identifyClassic;integration.initialize=integration.initializeClassic});UserVoice.prototype.initialize=function(page){var options=this.options;var opts=formatOptions(options);push("set",opts);push("autoprompt",{});if(options.showWidget){options.trigger?push("addTrigger",options.trigger,opts):push("addTrigger",opts)}this.load(this.ready)};UserVoice.prototype.loaded=function(){return!!(window.UserVoice&&window.UserVoice.push!==Array.prototype.push)};UserVoice.prototype.identify=function(identify){var traits=identify.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",traits)};UserVoice.prototype.group=function(group){var traits=group.traits({created:"created_at"});traits=convertDates(traits,unix);push("identify",{account:traits})};UserVoice.prototype.initializeClassic=function(){var options=this.options;window.showClassicWidget=showClassicWidget;if(options.showWidget)showClassicWidget("showTab",formatClassicOptions(options));this.load(this.ready)};UserVoice.prototype.identifyClassic=function(identify){push("setCustomFields",identify.traits())};function formatOptions(options){return alias(options,{forumId:"forum_id",accentColor:"accent_color",smartvote:"smartvote_enabled",triggerColor:"trigger_color",triggerBackgroundColor:"trigger_background_color",triggerPosition:"trigger_position"})}function formatClassicOptions(options){return alias(options,{forumId:"forum_id",classicMode:"mode",primaryColor:"primary_color",tabPosition:"tab_position",tabColor:"tab_color",linkColor:"link_color",defaultMode:"default_mode",tabLabel:"tab_label",tabInverted:"tab_inverted"})}function showClassicWidget(type,options){type=type||"showLightbox";push(type,"classic_widget",options)}},{"analytics.js-integration":159,"global-queue":191,"convert-dates":197,"to-unix-timestamp":200,alias:196,clone:195}],200:[function(require,module,exports){module.exports=toUnixTimestamp;function toUnixTimestamp(date){return Math.floor(date.getTime()/1e3)}},{}],154:[function(require,module,exports){var integration=require("analytics.js-integration");var push=require("global-queue")("_veroq");var cookie=require("component/cookie");var Vero=module.exports=integration("Vero").global("_veroq").option("apiKey","").tag('<script src="//d3qxef4rp70elm.cloudfront.net/m.js">');Vero.prototype.initialize=function(page){if(!cookie("__veroc4"))cookie("__veroc4","[]");push("init",{api_key:this.options.apiKey});this.load(this.ready)};Vero.prototype.loaded=function(){return!!(window._veroq&&window._veroq.push!==Array.prototype.push)};Vero.prototype.page=function(page){push("trackPageview")};Vero.prototype.identify=function(identify){var traits=identify.traits();var email=identify.email();var id=identify.userId();if(!id||!email)return;push("user",traits)};Vero.prototype.track=function(track){push("track",track.event(),track.properties())}},{"analytics.js-integration":159,"global-queue":191,"component/cookie":28}],155:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var each=require("each");var VWO=module.exports=integration("Visual Website Optimizer").option("replay",true);VWO.prototype.initialize=function(){if(this.options.replay)this.replay();this.ready()};VWO.prototype.replay=function(){var analytics=this.analytics;tick(function(){experiments(function(err,traits){if(traits)analytics.identify(traits)})})};function experiments(fn){enqueue(function(){var data={};var ids=window._vwo_exp_ids;if(!ids)return fn();each(ids,function(id){var name=variation(id);if(name)data["Experiment: "+id]=name});fn(null,data)})}function enqueue(fn){window._vis_opt_queue=window._vis_opt_queue||[];window._vis_opt_queue.push(fn)}function variation(id){var experiments=window._vwo_exp;if(!experiments)return null;var experiment=experiments[id];var variationId=experiment.combination_chosen;return variationId?experiment.comb_n[variationId]:null}},{"analytics.js-integration":159,"next-tick":45,each:5}],156:[function(require,module,exports){var integration=require("analytics.js-integration");var useHttps=require("use-https");var WebEngage=module.exports=integration("WebEngage").assumesPageview().global("_weq").global("webengage").option("widgetVersion","4.0").option("licenseCode","").tag("http",'<script src="http://cdn.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">').tag("https",'<script src="https://ssl.widgets.webengage.com/js/widget/webengage-min-v-4.0.js">');WebEngage.prototype.initialize=function(page){var _weq=window._weq=window._weq||{};_weq["webengage.licenseCode"]=this.options.licenseCode;_weq["webengage.widgetVersion"]=this.options.widgetVersion;var name=useHttps()?"https":"http";this.load(name,this.ready)};WebEngage.prototype.loaded=function(){return!!window.webengage}},{"analytics.js-integration":159,"use-https":161}],157:[function(require,module,exports){var integration=require("analytics.js-integration");var snake=require("to-snake-case");var isEmail=require("is-email");var extend=require("extend");var each=require("each");var type=require("type");var Woopra=module.exports=integration("Woopra").global("woopra").option("domain","").option("cookieName","wooTracker").option("cookieDomain",null).option("cookiePath","/").option("ping",true).option("pingInterval",12e3).option("idleTimeout",3e5).option("downloadTracking",true).option("outgoingTracking",true).option("outgoingIgnoreSubdomain",true).option("downloadPause",200).option("outgoingPause",400).option("ignoreQueryUrl",true).option("hideCampaign",false).tag('<script src="//static.woopra.com/js/w.js">');Woopra.prototype.initialize=function(page){(function(){var i,s,z,w=window,d=document,a=arguments,q="script",f=["config","track","identify","visit","push","call"],c=function(){var i,self=this;self._e=[];for(i=0;i<f.length;i++){(function(f){self[f]=function(){self._e.push([f].concat(Array.prototype.slice.call(arguments,0)));return self}})(f[i])}};w._w=w._w||{};for(i=0;i<a.length;i++){w._w[a[i]]=w[a[i]]=w[a[i]]||new c}})("woopra");this.load(this.ready);each(this.options,function(key,value){key=snake(key);if(null==value)return;if(""===value)return;window.woopra.config(key,value)})};Woopra.prototype.loaded=function(){return!!(window.woopra&&window.woopra.loaded)};Woopra.prototype.page=function(page){var props=page.properties();var name=page.fullName();if(name)props.title=name;window.woopra.track("pv",props)};Woopra.prototype.identify=function(identify){var traits=identify.traits();if(identify.name())traits.name=identify.name();window.woopra.identify(traits).push()};Woopra.prototype.track=function(track){window.woopra.track(track.event(),track.properties())}},{"analytics.js-integration":159,"to-snake-case":160,"is-email":19,extend:40,each:5,type:35}],158:[function(require,module,exports){var integration=require("analytics.js-integration");var tick=require("next-tick");var bind=require("bind");var when=require("when");var Yandex=module.exports=integration("Yandex Metrica").assumesPageview().global("yandex_metrika_callbacks").global("Ya").option("counterId",null).tag('<script src="//mc.yandex.ru/metrika/watch.js">');Yandex.prototype.initialize=function(page){var id=this.options.counterId;push(function(){window["yaCounter"+id]=new window.Ya.Metrika({id:id})});var loaded=bind(this,this.loaded);var ready=this.ready;this.load(function(){when(loaded,function(){tick(ready)})})};Yandex.prototype.loaded=function(){return!!(window.Ya&&window.Ya.Metrika)};function push(callback){window.yandex_metrika_callbacks=window.yandex_metrika_callbacks||[];window.yandex_metrika_callbacks.push(callback)}},{"analytics.js-integration":159,"next-tick":45,bind:33,when:185}]},{},{1:"analytics"});
packages/material-ui-icons/src/RemoveRedEyeOutlined.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M12 6.5c3.79 0 7.17 2.13 8.82 5.5-1.65 3.37-5.02 5.5-8.82 5.5S4.83 15.37 3.18 12C4.83 8.63 8.21 6.5 12 6.5m0-2C7 4.5 2.73 7.61 1 12c1.73 4.39 6 7.5 11 7.5s9.27-3.11 11-7.5c-1.73-4.39-6-7.5-11-7.5z" /><path d="M12 9.5c1.38 0 2.5 1.12 2.5 2.5s-1.12 2.5-2.5 2.5-2.5-1.12-2.5-2.5 1.12-2.5 2.5-2.5m0-2c-2.48 0-4.5 2.02-4.5 4.5s2.02 4.5 4.5 4.5 4.5-2.02 4.5-4.5-2.02-4.5-4.5-4.5z" /></g></React.Fragment> , 'RemoveRedEyeOutlined');
ajax/libs/mini-meteor/1.0.1/mini-meteor.min.js
nareshs435/cdnjs
(function(){var a=this,b=a._,d=Array.prototype,f=Object.prototype,l=d.push,k=d.slice,n=d.concat,p=f.toString,C=f.hasOwnProperty,f=Array.isArray,D=Object.keys,w=Function.prototype.bind,c=function(e){return e instanceof c?e:this instanceof c?void(this._wrapped=e):new c(e)};"undefined"!=typeof exports?("undefined"!=typeof module&&module.exports&&(exports=module.exports=c),exports._=c):a._=c;c.VERSION="1.7.0";var t=function(e,a,c){if(void 0===a)return e;switch(null==c?3:c){case 1:return function(c){return e.call(a, c)};case 2:return function(c,g){return e.call(a,c,g)};case 3:return function(c,g,b){return e.call(a,c,g,b)};case 4:return function(c,g,b,d){return e.call(a,c,g,b,d)}}return function(){return e.apply(a,arguments)}};c.iteratee=function(e,a,g){return null==e?c.identity:c.isFunction(e)?t(e,a,g):c.isObject(e)?c.matches(e):c.property(e)};c.each=c.forEach=function(e,a,g){if(null==e)return e;a=t(a,g);var q=e.length;if(q===+q)for(g=0;q>g;g++)a(e[g],g,e);else{var b=c.keys(e);g=0;for(q=b.length;q>g;g++)a(e[b[g]], b[g],e)}return e};c.map=c.collect=function(e,a,g){if(null==e)return[];a=c.iteratee(a,g);for(var q=e.length!==+e.length&&c.keys(e),b=(q||e).length,d=Array(b),m=0;b>m;m++)g=q?q[m]:m,d[m]=a(e[g],g,e);return d};c.reduce=c.foldl=c.inject=function(e,a,g,q){null==e&&(e=[]);a=t(a,q,4);var b,d=e.length!==+e.length&&c.keys(e),m=(d||e).length,f=0;if(3>arguments.length){if(!m)throw new TypeError("Reduce of empty array with no initial value");g=e[d?d[f++]:f++]}for(;m>f;f++)b=d?d[f]:f,g=a(g,e[b],b,e);return g}; c.reduceRight=c.foldr=function(e,a,g,b){null==e&&(e=[]);a=t(a,b,4);var h,d=e.length!==+e.length&&c.keys(e),f=(d||e).length;if(3>arguments.length){if(!f)throw new TypeError("Reduce of empty array with no initial value");g=e[d?d[--f]:--f]}for(;f--;)h=d?d[f]:f,g=a(g,e[h],h,e);return g};c.find=c.detect=function(e,a,g){var b;return a=c.iteratee(a,g),c.some(e,function(e,c,g){return a(e,c,g)?(b=e,!0):void 0}),b};c.filter=c.select=function(e,a,g){var b=[];return null==e?b:(a=c.iteratee(a,g),c.each(e,function(e, c,g){a(e,c,g)&&b.push(e)}),b)};c.reject=function(e,a,g){return c.filter(e,c.negate(c.iteratee(a)),g)};c.every=c.all=function(e,a,g){if(null==e)return!0;a=c.iteratee(a,g);var b,h=e.length!==+e.length&&c.keys(e),d=(h||e).length;for(g=0;d>g;g++)if(b=h?h[g]:g,!a(e[b],b,e))return!1;return!0};c.some=c.any=function(e,a,g){if(null==e)return!1;a=c.iteratee(a,g);var b,h=e.length!==+e.length&&c.keys(e),d=(h||e).length;for(g=0;d>g;g++)if(b=h?h[g]:g,a(e[b],b,e))return!0;return!1};c.contains=c.include=function(e, a){return null==e?!1:(e.length!==+e.length&&(e=c.values(e)),0<=c.indexOf(e,a))};c.invoke=function(e,a){var g=k.call(arguments,2),b=c.isFunction(a);return c.map(e,function(e){return(b?a:e[a]).apply(e,g)})};c.pluck=function(e,a){return c.map(e,c.property(a))};c.where=function(e,a){return c.filter(e,c.matches(a))};c.findWhere=function(e,a){return c.find(e,c.matches(a))};c.max=function(e,a,g){var b,h=-1/0,d=-1/0;if(null==a&&null!=e){e=e.length===+e.length?e:c.values(e);for(var f=0,r=e.length;r>f;f++)g= e[f],g>h&&(h=g)}else a=c.iteratee(a,g),c.each(e,function(e,c,g){b=a(e,c,g);(b>d||b===-1/0&&h===-1/0)&&(h=e,d=b)});return h};c.min=function(e,a,g){var b,h=1/0,d=1/0;if(null==a&&null!=e){e=e.length===+e.length?e:c.values(e);for(var f=0,r=e.length;r>f;f++)g=e[f],h>g&&(h=g)}else a=c.iteratee(a,g),c.each(e,function(e,c,g){b=a(e,c,g);(d>b||1/0===b&&1/0===h)&&(h=e,d=b)});return h};c.shuffle=function(e){for(var a=e&&e.length===+e.length?e:c.values(e),g=a.length,b=Array(g),h=0;g>h;h++)e=c.random(0,h),e!== h&&(b[h]=b[e]),b[e]=a[h];return b};c.sample=function(e,a,g){return null==a||g?(e.length!==+e.length&&(e=c.values(e)),e[c.random(e.length-1)]):c.shuffle(e).slice(0,Math.max(0,a))};c.sortBy=function(e,a,g){return a=c.iteratee(a,g),c.pluck(c.map(e,function(e,c,g){return{value:e,index:c,criteria:a(e,c,g)}}).sort(function(e,a){var c=e.criteria,g=a.criteria;if(c!==g){if(c>g||void 0===c)return 1;if(g>c||void 0===g)return-1}return e.index-a.index}),"value")};var u=function(e){return function(a,g,b){var d= {};return g=c.iteratee(g,b),c.each(a,function(c,b){var q=g(c,b,a);e(d,c,q)}),d}};c.groupBy=u(function(e,a,g){c.has(e,g)?e[g].push(a):e[g]=[a]});c.indexBy=u(function(e,a,c){e[c]=a});c.countBy=u(function(e,a,g){c.has(e,g)?e[g]++:e[g]=1});c.sortedIndex=function(e,a,g,b){g=c.iteratee(g,b,1);a=g(a);b=0;for(var d=e.length;d>b;){var f=b+d>>>1;g(e[f])<a?b=f+1:d=f}return b};c.toArray=function(e){return e?c.isArray(e)?k.call(e):e.length===+e.length?c.map(e,c.identity):c.values(e):[]};c.size=function(e){return null== e?0:e.length===+e.length?e.length:c.keys(e).length};c.partition=function(e,a,g){a=c.iteratee(a,g);var b=[],d=[];return c.each(e,function(e,c,g){(a(e,c,g)?b:d).push(e)}),[b,d]};c.first=c.head=c.take=function(e,a,c){return null==e?void 0:null==a||c?e[0]:0>a?[]:k.call(e,0,a)};c.initial=function(e,a,c){return k.call(e,0,Math.max(0,e.length-(null==a||c?1:a)))};c.last=function(e,a,c){return null==e?void 0:null==a||c?e[e.length-1]:k.call(e,Math.max(e.length-a,0))};c.rest=c.tail=c.drop=function(e,a,c){return k.call(e, null==a||c?1:a)};c.compact=function(e){return c.filter(e,c.identity)};var v=function(e,a,g,b){if(a&&c.every(e,c.isArray))return n.apply(b,e);for(var d=0,f=e.length;f>d;d++){var m=e[d];c.isArray(m)||c.isArguments(m)?a?l.apply(b,m):v(m,a,g,b):g||b.push(m)}return b};c.flatten=function(e,a){return v(e,a,!1,[])};c.without=function(e){return c.difference(e,k.call(arguments,1))};c.uniq=c.unique=function(e,a,b,d){if(null==e)return[];c.isBoolean(a)||(d=b,b=a,a=!1);null!=b&&(b=c.iteratee(b,d));d=[];for(var h= [],f=0,m=e.length;m>f;f++){var r=e[f];if(a)f&&h===r||d.push(r),h=r;else if(b){var k=b(r,f,e);0>c.indexOf(h,k)&&(h.push(k),d.push(r))}else 0>c.indexOf(d,r)&&d.push(r)}return d};c.union=function(){return c.uniq(v(arguments,!0,!0,[]))};c.intersection=function(e){if(null==e)return[];for(var a=[],b=arguments.length,d=0,h=e.length;h>d;d++){var f=e[d];if(!c.contains(a,f)){for(var m=1;b>m&&c.contains(arguments[m],f);m++);m===b&&a.push(f)}}return a};c.difference=function(e){var a=v(k.call(arguments,1),!0, !0,[]);return c.filter(e,function(e){return!c.contains(a,e)})};c.zip=function(e){if(null==e)return[];for(var a=c.max(arguments,"length").length,b=Array(a),d=0;a>d;d++)b[d]=c.pluck(arguments,d);return b};c.object=function(a,c){if(null==a)return{};for(var b={},d=0,h=a.length;h>d;d++)c?b[a[d]]=c[d]:b[a[d][0]]=a[d][1];return b};c.indexOf=function(a,b,g){if(null==a)return-1;var d=0,h=a.length;if(g){if("number"!=typeof g)return d=c.sortedIndex(a,b),a[d]===b?d:-1;d=0>g?Math.max(0,h+g):g}for(;h>d;d++)if(a[d]=== b)return d;return-1};c.lastIndexOf=function(a,c,b){if(null==a)return-1;var d=a.length;for("number"==typeof b&&(d=0>b?d+b+1:Math.min(d,b+1));0<=--d;)if(a[d]===c)return d;return-1};c.range=function(a,c,b){1>=arguments.length&&(c=a||0,a=0);b=b||1;for(var d=Math.max(Math.ceil((c-a)/b),0),h=Array(d),f=0;d>f;f++,a+=b)h[f]=a;return h};var y=function(){};c.bind=function(a,b){var g,d;if(w&&a.bind===w)return w.apply(a,k.call(arguments,1));if(!c.isFunction(a))throw new TypeError("Bind must be called on a function"); return g=k.call(arguments,2),d=function(){if(!(this instanceof d))return a.apply(b,g.concat(k.call(arguments)));y.prototype=a.prototype;var h=new y;y.prototype=null;var f=a.apply(h,g.concat(k.call(arguments)));return c.isObject(f)?f:h}};c.partial=function(a){var b=k.call(arguments,1);return function(){for(var g=0,d=b.slice(),h=0,f=d.length;f>h;h++)d[h]===c&&(d[h]=arguments[g++]);for(;g<arguments.length;)d.push(arguments[g++]);return a.apply(this,d)}};c.bindAll=function(a){var b,g,d=arguments.length; if(1>=d)throw Error("bindAll must be passed function names");for(b=1;d>b;b++)g=arguments[b],a[g]=c.bind(a[g],a);return a};c.memoize=function(a,b){var g=function(d){var h=g.cache,f=b?b.apply(this,arguments):d;return c.has(h,f)||(h[f]=a.apply(this,arguments)),h[f]};return g.cache={},g};c.delay=function(a,c){var b=k.call(arguments,2);return setTimeout(function(){return a.apply(null,b)},c)};c.defer=function(a){return c.delay.apply(c,[a,1].concat(k.call(arguments,1)))};c.throttle=function(a,b,d){var f, h,x,m=null,k=0;d||(d={});var l=function(){k=!1===d.leading?0:c.now();m=null;x=a.apply(f,h);m||(f=h=null)};return function(){var p=c.now();k||!1!==d.leading||(k=p);var n=b-(p-k);return f=this,h=arguments,0>=n||n>b?(clearTimeout(m),m=null,k=p,x=a.apply(f,h),m||(f=h=null)):m||!1===d.trailing||(m=setTimeout(l,n)),x}};c.debounce=function(a,b,d){var f,h,k,m,l,p=function(){var n=c.now()-m;b>n&&0<n?f=setTimeout(p,b-n):(f=null,d||(l=a.apply(k,h),f||(k=h=null)))};return function(){k=this;h=arguments;m=c.now(); var n=d&&!f;return f||(f=setTimeout(p,b)),n&&(l=a.apply(k,h),k=h=null),l}};c.wrap=function(a,b){return c.partial(b,a)};c.negate=function(a){return function(){return!a.apply(this,arguments)}};c.compose=function(){var a=arguments,c=a.length-1;return function(){for(var b=c,d=a[c].apply(this,arguments);b--;)d=a[b].call(this,d);return d}};c.after=function(a,c){return function(){return 1>--a?c.apply(this,arguments):void 0}};c.before=function(a,c){var b;return function(){return 0<--a?b=c.apply(this,arguments): c=null,b}};c.once=c.partial(c.before,2);c.keys=function(a){if(!c.isObject(a))return[];if(D)return D(a);var b=[],d;for(d in a)c.has(a,d)&&b.push(d);return b};c.values=function(a){for(var b=c.keys(a),d=b.length,f=Array(d),h=0;d>h;h++)f[h]=a[b[h]];return f};c.pairs=function(a){for(var b=c.keys(a),d=b.length,f=Array(d),h=0;d>h;h++)f[h]=[b[h],a[b[h]]];return f};c.invert=function(a){for(var b={},d=c.keys(a),f=0,h=d.length;h>f;f++)b[a[d[f]]]=d[f];return b};c.functions=c.methods=function(a){var b=[],d;for(d in a)c.isFunction(a[d])&& b.push(d);return b.sort()};c.extend=function(a){if(!c.isObject(a))return a;for(var b,d,f=1,h=arguments.length;h>f;f++)for(d in b=arguments[f],b)C.call(b,d)&&(a[d]=b[d]);return a};c.pick=function(a,b,d){var f,h={};if(null==a)return h;if(c.isFunction(b))for(f in b=t(b,d),a){var l=a[f];b(l,f,a)&&(h[f]=l)}else{l=n.apply([],k.call(arguments,1));a=Object(a);for(var m=0,p=l.length;p>m;m++)f=l[m],f in a&&(h[f]=a[f])}return h};c.omit=function(a,b,d){if(c.isFunction(b))b=c.negate(b);else{var f=c.map(n.apply([], k.call(arguments,1)),String);b=function(a,e){return!c.contains(f,e)}}return c.pick(a,b,d)};c.defaults=function(a){if(!c.isObject(a))return a;for(var b=1,d=arguments.length;d>b;b++){var f=arguments[b],h;for(h in f)void 0===a[h]&&(a[h]=f[h])}return a};c.clone=function(a){return c.isObject(a)?c.isArray(a)?a.slice():c.extend({},a):a};c.tap=function(a,b){return b(a),a};var z=function(a,b,d,f){if(a===b)return 0!==a||1/a===1/b;if(null==a||null==b)return a===b;a instanceof c&&(a=a._wrapped);b instanceof c&& (b=b._wrapped);var h=p.call(a);if(h!==p.call(b))return!1;switch(h){case "[object RegExp]":case "[object String]":return""+a==""+b;case "[object Number]":return+a!==+a?+b!==+b:0===+a?1/+a===1/b:+a===+b;case "[object Date]":case "[object Boolean]":return+a===+b}if("object"!=typeof a||"object"!=typeof b)return!1;for(var k=d.length;k--;)if(d[k]===a)return f[k]===b;var k=a.constructor,m=b.constructor;if(k!==m&&"constructor"in a&&"constructor"in b&&!(c.isFunction(k)&&k instanceof k&&c.isFunction(m)&&m instanceof m))return!1;d.push(a);f.push(b);var l;if("[object Array]"===h){if(l=a.length,h=l===b.length)for(;l--&&(h=z(a[l],b[l],d,f)););}else{var n,k=c.keys(a);if(l=k.length,h=c.keys(b).length===l)for(;l--&&(n=k[l],h=c.has(b,n)&&z(a[n],b[n],d,f)););}return d.pop(),f.pop(),h};c.isEqual=function(a,b){return z(a,b,[],[])};c.isEmpty=function(a){if(null==a)return!0;if(c.isArray(a)||c.isString(a)||c.isArguments(a))return 0===a.length;for(var b in a)if(c.has(a,b))return!1;return!0};c.isElement=function(a){return!(!a|| 1!==a.nodeType)};c.isArray=f||function(a){return"[object Array]"===p.call(a)};c.isObject=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a};c.each("Arguments Function String Number Date RegExp".split(" "),function(a){c["is"+a]=function(b){return p.call(b)==="[object "+a+"]"}});c.isArguments(arguments)||(c.isArguments=function(a){return c.has(a,"callee")});"function"!=typeof/./&&(c.isFunction=function(a){return"function"==typeof a||!1});c.isFinite=function(a){return isFinite(a)&&!isNaN(parseFloat(a))}; c.isNaN=function(a){return c.isNumber(a)&&a!==+a};c.isBoolean=function(a){return!0===a||!1===a||"[object Boolean]"===p.call(a)};c.isNull=function(a){return null===a};c.isUndefined=function(a){return void 0===a};c.has=function(a,b){return null!=a&&C.call(a,b)};c.noConflict=function(){return a._=b,this};c.identity=function(a){return a};c.constant=function(a){return function(){return a}};c.noop=function(){};c.property=function(a){return function(b){return b[a]}};c.matches=function(a){var b=c.pairs(a), d=b.length;return function(a){if(null==a)return!d;a=Object(a);for(var c=0;d>c;c++){var e=b[c],f=e[0];if(e[1]!==a[f]||!(f in a))return!1}return!0}};c.times=function(a,b,c){var d=Array(Math.max(0,a));b=t(b,c,1);for(c=0;a>c;c++)d[c]=b(c);return d};c.random=function(a,b){return null==b&&(b=a,a=0),a+Math.floor(Math.random()*(b-a+1))};c.now=Date.now||function(){return(new Date).getTime()};var f={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;"},u=c.invert(f),E=function(a){var b= function(b){return a[b]},d="(?:"+c.keys(a).join("|")+")",f=RegExp(d),h=RegExp(d,"g");return function(a){return a=null==a?"":""+a,f.test(a)?a.replace(h,b):a}};c.escape=E(f);c.unescape=E(u);c.result=function(a,b){if(null!=a){var d=a[b];return c.isFunction(d)?a[b]():d}};var F=0;c.uniqueId=function(a){var b=++F+"";return a?a+b:b};c.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var A=/(.)^/,G={"'":"'","\\":"\\","\r":"r","\n":"n","\u2028":"u2028", "\u2029":"u2029"},H=/\\|'|\r|\n|\u2028|\u2029/g,I=function(a){return"\\"+G[a]};c.template=function(a,b,d){!b&&d&&(b=d);b=c.defaults({},b,c.templateSettings);d=RegExp([(b.escape||A).source,(b.interpolate||A).source,(b.evaluate||A).source].join("|")+"|$","g");var f=0,h="__p+='";a.replace(d,function(b,c,d,g,k){return h+=a.slice(f,k).replace(H,I),f=k+b.length,c?h+="'+\n((__t=("+c+"))==null?'':_.escape(__t))+\n'":d?h+="'+\n((__t=("+d+"))==null?'':__t)+\n'":g&&(h+="';\n"+g+"\n__p+='"),b});h+="';\n";b.variable|| (h="with(obj||{}){\n"+h+"}\n");h="var __t,__p='',__j=Array.prototype.join,print=function(){__p+=__j.call(arguments,'');};\n"+h+"return __p;\n";try{var k=new Function(b.variable||"obj","_",h)}catch(l){throw l.source=h,l;}d=function(a){return k.call(this,a,c)};return d.source="function("+(b.variable||"obj")+"){\n"+h+"}",d};c.chain=function(a){a=c(a);return a._chain=!0,a};var B=function(a){return this._chain?c(a).chain():a};c.mixin=function(a){c.each(c.functions(a),function(b){var d=c[b]=a[b];c.prototype[b]= function(){var a=[this._wrapped];return l.apply(a,arguments),B.call(this,d.apply(c,a))}})};c.mixin(c);c.each("pop push reverse shift sort splice unshift".split(" "),function(a){var b=d[a];c.prototype[a]=function(){var c=this._wrapped;return b.apply(c,arguments),"shift"!==a&&"splice"!==a||0!==c.length||delete c[0],B.call(this,c)}});c.each(["concat","join","slice"],function(a){var b=d[a];c.prototype[a]=function(){return B.call(this,b.apply(this._wrapped,arguments))}});c.prototype.value=function(){return this._wrapped}; "function"==typeof define&&define.amd&&define("underscore",[],function(){return c})}).call(this);for(var BASE_64_CHARS="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",BASE_64_VALS={},i=0;i<BASE_64_CHARS.length;i++)BASE_64_VALS[BASE_64_CHARS.charAt(i)]=i; Base64={encode:function(a){if("string"===typeof a){var b=a;a=Base64.newBinary(b.length);for(var d=0;d<b.length;d++){var f=b.charCodeAt(d);if(255<f)throw Error("Not ascii. Base64.encode can only take ascii strings.");a[d]=f}}for(var b=[],l=f=null,k=null,n=null,d=0;d<a.length;d++)switch(d%3){case 0:f=a[d]>>2&63;l=(a[d]&3)<<4;break;case 1:l|=a[d]>>4&15;k=(a[d]&15)<<2;break;case 2:k|=a[d]>>6&3,n=a[d]&63,b.push(getChar(f)),b.push(getChar(l)),b.push(getChar(k)),b.push(getChar(n)),n=k=l=f=null}null!=f&& (b.push(getChar(f)),b.push(getChar(l)),null==k?b.push("="):b.push(getChar(k)),null==n&&b.push("="));return b.join("")}};var getChar=function(a){return BASE_64_CHARS.charAt(a)},getVal=function(a){return"="===a?-1:BASE_64_VALS[a]};Base64.newBinary=function(a){if("undefined"===typeof Uint8Array||"undefined"===typeof ArrayBuffer){for(var b=[],d=0;d<a;d++)b.push(0);b.$Uint8ArrayPolyfill=!0;return b}return new Uint8Array(new ArrayBuffer(a))}; Base64.decode=function(a){var b=Math.floor(3*a.length/4);"="==a.charAt(a.length-1)&&(b--,"="==a.charAt(a.length-2)&&b--);for(var b=Base64.newBinary(b),d=null,f=null,l=null,k=0,n=0;n<a.length;n++){var p=a.charAt(n),p=getVal(p);switch(n%4){case 0:if(0>p)throw Error("invalid base64 string");d=p<<2;break;case 1:if(0>p)throw Error("invalid base64 string");d|=p>>4;b[k++]=d;f=(p&15)<<4;break;case 2:0<=p&&(f|=p>>2,b[k++]=f,l=(p&3)<<6);break;case 3:0<=p&&(b[k++]=l|p)}}return b};EJSON={};EJSONTest={}; var customTypes={};EJSON.addType=function(a,b){if(_.has(customTypes,a))throw Error("Type "+a+" already present");customTypes[a]=b}; var isInfOrNan=function(a){return _.isNaN(a)||Infinity===a||-Infinity===a},builtinConverters=[{matchJSONValue:function(a){return _.has(a,"$date")&&1===_.size(a)},matchObject:function(a){return a instanceof Date},toJSONValue:function(a){return{$date:a.getTime()}},fromJSONValue:function(a){return new Date(a.$date)}},{matchJSONValue:function(a){return _.has(a,"$InfNaN")&&1===_.size(a)},matchObject:isInfOrNan,toJSONValue:function(a){return{$InfNaN:_.isNaN(a)?0:Infinity===a?1:-1}},fromJSONValue:function(a){return a.$InfNaN/ 0}},{matchJSONValue:function(a){return _.has(a,"$binary")&&1===_.size(a)},matchObject:function(a){return"undefined"!==typeof Uint8Array&&a instanceof Uint8Array||a&&_.has(a,"$Uint8ArrayPolyfill")},toJSONValue:function(a){return{$binary:Base64.encode(a)}},fromJSONValue:function(a){return Base64.decode(a.$binary)}},{matchJSONValue:function(a){return _.has(a,"$escape")&&1===_.size(a)},matchObject:function(a){return _.isEmpty(a)||2<_.size(a)?!1:_.any(builtinConverters,function(b){return b.matchJSONValue(a)})}, toJSONValue:function(a){var b={};_.each(a,function(a,f){b[f]=EJSON.toJSONValue(a)});return{$escape:b}},fromJSONValue:function(a){var b={};_.each(a.$escape,function(a,f){b[f]=EJSON.fromJSONValue(a)});return b}},{matchJSONValue:function(a){return _.has(a,"$type")&&_.has(a,"$value")&&2===_.size(a)},matchObject:function(a){return EJSON._isCustomType(a)},toJSONValue:function(a){var b=Meteor._noYieldsAllowed(function(){return a.toJSONValue()});return{$type:a.typeName(),$value:b}},fromJSONValue:function(a){var b= a.$type;if(!_.has(customTypes,b))throw Error("Custom EJSON type "+b+" is not defined");var d=customTypes[b];return Meteor._noYieldsAllowed(function(){return d(a.$value)})}}];EJSON._isCustomType=function(a){return a&&"function"===typeof a.toJSONValue&&"function"===typeof a.typeName&&_.has(customTypes,a.typeName())}; var adjustTypesToJSONValue=EJSON._adjustTypesToJSONValue=function(a){if(null===a)return null;var b=toJSONValueHelper(a);if(void 0!==b)return b;if("object"!==typeof a)return a;_.each(a,function(b,f){if("object"===typeof b||void 0===b||isInfOrNan(b)){var l=toJSONValueHelper(b);l?a[f]=l:adjustTypesToJSONValue(b)}});return a},toJSONValueHelper=function(a){for(var b=0;b<builtinConverters.length;b++){var d=builtinConverters[b];if(d.matchObject(a))return d.toJSONValue(a)}}; EJSON.toJSONValue=function(a){var b=toJSONValueHelper(a);if(void 0!==b)return b;"object"===typeof a&&(a=EJSON.clone(a),adjustTypesToJSONValue(a));return a}; var adjustTypesFromJSONValue=EJSON._adjustTypesFromJSONValue=function(a){if(null===a)return null;var b=fromJSONValueHelper(a);if(b!==a)return b;if("object"!==typeof a)return a;_.each(a,function(b,f){if("object"===typeof b){var l=fromJSONValueHelper(b);b!==l?a[f]=l:adjustTypesFromJSONValue(b)}});return a},fromJSONValueHelper=function(a){if("object"===typeof a&&null!==a&&2>=_.size(a)&&_.all(a,function(a,b){return"string"===typeof b&&"$"===b.substr(0,1)}))for(var b=0;b<builtinConverters.length;b++){var d= builtinConverters[b];if(d.matchJSONValue(a))return d.fromJSONValue(a)}return a};EJSON.fromJSONValue=function(a){var b=fromJSONValueHelper(a);return b===a&&"object"===typeof a?(a=EJSON.clone(a),adjustTypesFromJSONValue(a),a):b};EJSON.stringify=function(a,b){var d=EJSON.toJSONValue(a);return b&&(b.canonical||b.indent)?EJSON._canonicalStringify(d,b):JSON.stringify(d)};EJSON.parse=function(a){if("string"!==typeof a)throw Error("EJSON.parse argument should be a string");return EJSON.fromJSONValue(JSON.parse(a))}; EJSON.isBinary=function(a){return!!("undefined"!==typeof Uint8Array&&a instanceof Uint8Array||a&&a.$Uint8ArrayPolyfill)}; EJSON.equals=function(a,b,d){var f,l=!(!d||!d.keyOrderSensitive);if(a===b||_.isNaN(a)&&_.isNaN(b))return!0;if(!a||!b||"object"!==typeof a||"object"!==typeof b)return!1;if(a instanceof Date&&b instanceof Date)return a.valueOf()===b.valueOf();if(EJSON.isBinary(a)&&EJSON.isBinary(b)){if(a.length!==b.length)return!1;for(f=0;f<a.length;f++)if(a[f]!==b[f])return!1;return!0}if("function"===typeof a.equals)return a.equals(b,d);if("function"===typeof b.equals)return b.equals(a,d);if(a instanceof Array){if(!(b instanceof Array)||a.length!==b.length)return!1;for(f=0;f<a.length;f++)if(!EJSON.equals(a[f],b[f],d))return!1;return!0}switch(EJSON._isCustomType(a)+EJSON._isCustomType(b)){case 1:return!1;case 2:return EJSON.equals(EJSON.toJSONValue(a),EJSON.toJSONValue(b))}if(l){var k=[];_.each(b,function(a,b){k.push(b)});f=0;return(a=_.all(a,function(a,l){if(f>=k.length||l!==k[f]||!EJSON.equals(a,b[k[f]],d))return!1;f++;return!0}))&&f===k.length}f=0;return(a=_.all(a,function(a,k){if(!_.has(b,k)||!EJSON.equals(a,b[k],d))return!1; f++;return!0}))&&_.size(b)===f}; EJSON.clone=function(a){var b;if("object"!==typeof a)return a;if(null===a)return null;if(a instanceof Date)return new Date(a.getTime());if(a instanceof RegExp)return a;if(EJSON.isBinary(a)){b=EJSON.newBinary(a.length);for(var d=0;d<a.length;d++)b[d]=a[d];return b}if(_.isArray(a)||_.isArguments(a)){b=[];for(d=0;d<a.length;d++)b[d]=EJSON.clone(a[d]);return b}if("function"===typeof a.clone)return a.clone();if(EJSON._isCustomType(a))return EJSON.fromJSONValue(EJSON.clone(EJSON.toJSONValue(a)),!0);b={}; _.each(a,function(a,d){b[d]=EJSON.clone(a)});return b};EJSON.newBinary=Base64.newBinary;Meteor={isClient:!0,active:!1,currentComputation:null}; var setCurrentComputation=function(a){Meteor.currentComputation=a;Meteor.active=!!a},_debugFunc=function(){return"undefined"!==typeof Meteor?Meteor._debug:"undefined"!==typeof console&&console.log?function(){console.log.apply(console,arguments)}:function(){}},_throwOrLog=function(a,b){if(throwFirstError)throw b;var d;b.stack&&b.message?(d=b.stack.indexOf(b.message),d=0<=d&&10>=d?b.stack:b.message+("\n"===b.stack.charAt(0)?"":"\n")+b.stack):d=b.stack||b.message;_debugFunc()("Exception from Meteor "+ a+" function:",d)},withNoYieldsAllowed=function(a){return"undefined"===typeof Meteor||Meteor.isClient?a:function(){var b=arguments;Meteor._noYieldsAllowed(function(){a.apply(null,b)})}},nextId=1,pendingComputations=[],willFlush=!1,inFlush=!1,inCompute=!1,throwFirstError=!1,afterFlushCallbacks=[],requireFlush=function(){willFlush||(setTimeout(Meteor.flush,0),willFlush=!0)},constructingComputation=!1; Meteor.Computation=function(a,b){if(!constructingComputation)throw Error("Meteor.Computation constructor is private; use Meteor.run");this.invalidated=this.stopped=constructingComputation=!1;this.firstRun=!0;this._id=nextId++;this._onInvalidateCallbacks=[];this._parent=b;this._func=a;this._recomputing=!1;var d=!0;try{this._compute(),d=!1}finally{this.firstRun=!1,d&&this.stop()}}; Meteor.Computation.prototype.onInvalidate=function(a){var b=this;if("function"!==typeof a)throw Error("onInvalidate requires a function");b.invalidated?Meteor.nonreactive(function(){withNoYieldsAllowed(a)(b)}):b._onInvalidateCallbacks.push(a)}; Meteor.Computation.prototype.invalidate=function(){var a=this;if(!a.invalidated){a._recomputing||a.stopped||(requireFlush(),pendingComputations.push(this));a.invalidated=!0;for(var b=0,d;d=a._onInvalidateCallbacks[b];b++)Meteor.nonreactive(function(){withNoYieldsAllowed(d)(a)});a._onInvalidateCallbacks=[]}};Meteor.Computation.prototype.stop=function(){this.stopped||(this.stopped=!0,this.invalidate())}; Meteor.Computation.prototype._compute=function(){this.invalidated=!1;var a=Meteor.currentComputation;setCurrentComputation(this);inCompute=!0;try{withNoYieldsAllowed(this._func)(this)}finally{setCurrentComputation(a),inCompute=!1}};Meteor.Computation.prototype._recompute=function(){this._recomputing=!0;try{for(;this.invalidated&&!this.stopped;)try{this._compute()}catch(a){_throwOrLog("recompute",a)}}finally{this._recomputing=!1}};Meteor.Dependency=function(){this._dependentsById={}}; Meteor.Dependency.prototype.depend=function(a){if(!a){if(!Meteor.active)return!1;a=Meteor.currentComputation}var b=this,d=a._id;return d in b._dependentsById?!1:(b._dependentsById[d]=a,a.onInvalidate(function(){delete b._dependentsById[d]}),!0)};Meteor.Dependency.prototype.changed=function(){for(var a in this._dependentsById)this._dependentsById[a].invalidate()};Meteor.Dependency.prototype.hasDependents=function(){for(var a in this._dependentsById)return!0;return!1}; Meteor.flush=function(a){if(inFlush)throw Error("Can't call Meteor.flush while flushing");if(inCompute)throw Error("Can't flush inside Meteor.run");willFlush=inFlush=!0;throwFirstError=!(!a||!a._throwFirstError);a=!1;try{for(;pendingComputations.length||afterFlushCallbacks.length;){for(;pendingComputations.length;)pendingComputations.shift()._recompute();if(afterFlushCallbacks.length){var b=afterFlushCallbacks.shift();try{b()}catch(d){_throwOrLog("afterFlush",d)}}}a=!0}finally{a||(inFlush=!1,Meteor.flush({_throwFirstError:!1})), inFlush=willFlush=!1}};Meteor.run=function(a){if("function"!==typeof a)throw Error("Meteor.run requires a function argument");constructingComputation=!0;var b=new Meteor.Computation(a,Meteor.currentComputation);if(Meteor.active)Meteor.onInvalidate(function(){b.stop()});return b};Meteor.nonreactive=function(a){var b=Meteor.currentComputation;setCurrentComputation(null);try{return a()}finally{setCurrentComputation(b)}}; Meteor.onInvalidate=function(a){if(!Meteor.active)throw Error("Meteor.onInvalidate requires a currentComputation");Meteor.currentComputation.onInvalidate(a)};Meteor.afterFlush=function(a){afterFlushCallbacks.push(a);requireFlush()};var stringify=function(a){return void 0===a?"undefined":EJSON.stringify(a)},parse=function(a){return void 0===a||"undefined"===a?void 0:EJSON.parse(a)};ReactiveMap=function(a){this.keys=a||{};this.keyDeps={};this.keyValueDeps={}}; _.extend(ReactiveMap.prototype,{set:function(a,b){b=stringify(b);var d="undefined";_.has(this.keys,a)&&(d=this.keys[a]);if(b!==d){this.keys[a]=b;var f=this.keyDeps[a];f&&f.changed();this.keyValueDeps[a]&&((d=this.keyValueDeps[a][d])&&d.changed(),(d=this.keyValueDeps[a][b])&&d.changed())}},setDefault:function(a,b){void 0===this.keys[a]&&this.set(a,b)},get:function(a){this._ensureKey(a);this.keyDeps[a].depend();return parse(this.keys[a])},equals:function(a,b){var d=this,f=Package["mongo-livedata"]&& Meteor.Collection.ObjectID;if(!("string"===typeof b||"number"===typeof b||"boolean"===typeof b||"undefined"===typeof b||b instanceof Date||f&&b instanceof f)&&null!==b)throw Error("ReactiveMap.equals: value must be scalar");var l=stringify(b);if(Meteor.active&&(d._ensureKey(a),_.has(d.keyValueDeps[a],l)||(d.keyValueDeps[a][l]=new Meteor.Dependency),d.keyValueDeps[a][l].depend()))Meteor.onInvalidate(function(){d.keyValueDeps[a][l].hasDependents()||delete d.keyValueDeps[a][l]});f=void 0;_.has(d.keys, a)&&(f=parse(d.keys[a]));return EJSON.equals(f,b)},_ensureKey:function(a){a in this.keyDeps||(this.keyDeps[a]=new Meteor.Dependency,this.keyValueDeps[a]={})},getMigrationData:function(){return this.keys}});ReactiveVar=function(a,b){if(!(this instanceof ReactiveVar))return new ReactiveVar(a,b);this.curValue=a;this.equalsFunc=b;this.dep=new Meteor.Dependency};ReactiveVar._isEqual=function(a,b){return a!==b?!1:!a||"number"===typeof a||"boolean"===typeof a||"string"===typeof a}; ReactiveVar.prototype.get=function(){Meteor.active&&this.dep.depend();return this.curValue};ReactiveVar.prototype.set=function(a){(this.equalsFunc||ReactiveVar._isEqual)(this.curValue,a)||(this.curValue=a,this.dep.changed())};ReactiveVar.prototype.toString=function(){return"ReactiveVar{"+this.get()+"}"};ReactiveVar.prototype._numListeners=function(){var a=0,b;for(b in this.dep._dependentsById)a++;return a}; ReactiveObject=function(a){var b;this._definePrivateProperty("_items",{});this._definePrivateProperty("_itemsMeteor",{});b=this;_.isArray(a)&&_.each(a,function(a){return b.defineProperty(a,void 0)});_.isObject(a)&&_.each(a,function(a,f){return b.defineProperty(f,a)})}; ReactiveObject.prototype.wrapArrayMethods=function(a,b){var d=this;_.each("pop push reverse shift sort slice unshift splice".split(" "),function(f){b[f]=function(){d._itemsMeteor[a].changed();return Array.prototype[f].apply(this,arguments)}});b.clean=function(){return _.filter(this,function(a){return!Match.test(a,Function)})};return b}; ReactiveObject.prototype.defineProperty=function(a,b){Object.defineProperty(this,a,{configurable:!0,enumerable:!0,get:_.bind(this._propertyGet,this,a),set:_.bind(this._propertySet,this,a)});this[a]=b;return this};ReactiveObject.prototype.undefineProperty=function(a){var b;b=this._itemsMeteor[a];delete this[a];delete this._items[a];delete this._itemsMeteor[a];b&&b.changed();return this};ReactiveObject.prototype.clone=function(){return new ReactiveObject(_.clone(this._items))}; ReactiveObject.prototype.equals=function(a){return null!=a&&a instanceof ReactiveObject&&_.isEqual(a._items,this._items)};ReactiveObject.prototype.typeName=function(){return"reactive-object"};ReactiveObject.prototype.toJSONValue=function(){return EJSON.toJSONValue(this._items)}; ReactiveObject.prototype._propertySet=function(a,b){var d,f;_.isArray(b)&&(b=this.wrapArrayMethods(a,b));this._items[a]=b;null==(d=this._itemsMeteor)[a]&&(d[a]=new Meteor.Dependency);null!=(f=this._itemsMeteor[a])&&f.changed();return this._items[a]};ReactiveObject.prototype._propertyGet=function(a){this._itemsMeteor[a].depend();return this._items[a]};ReactiveObject.prototype._definePrivateProperty=function(a,b){return Object.defineProperty(this,a,{configurable:!0,enumerable:!1,writable:!0,value:b})}; EJSON.addType("reactive-object",function(a){return new ReactiveObject(a)});
packages/material-ui-icons/src/Pool.js
callemall/material-ui
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path d="M22 21c-1.11 0-1.73-.37-2.18-.64-.37-.22-.6-.36-1.15-.36-.56 0-.78.13-1.15.36-.46.27-1.07.64-2.18.64s-1.73-.37-2.18-.64c-.37-.22-.6-.36-1.15-.36-.56 0-.78.13-1.15.36-.46.27-1.08.64-2.19.64-1.11 0-1.73-.37-2.18-.64-.37-.23-.6-.36-1.15-.36s-.78.13-1.15.36c-.46.27-1.08.64-2.19.64v-2c.56 0 .78-.13 1.15-.36.46-.27 1.08-.64 2.19-.64s1.73.37 2.18.64c.37.23.59.36 1.15.36.56 0 .78-.13 1.15-.36.46-.27 1.08-.64 2.19-.64 1.11 0 1.73.37 2.18.64.37.22.6.36 1.15.36s.78-.13 1.15-.36c.45-.27 1.07-.64 2.18-.64s1.73.37 2.18.64c.37.23.59.36 1.15.36v2zm0-4.5c-1.11 0-1.73-.37-2.18-.64-.37-.22-.6-.36-1.15-.36-.56 0-.78.13-1.15.36-.45.27-1.07.64-2.18.64s-1.73-.37-2.18-.64c-.37-.22-.6-.36-1.15-.36-.56 0-.78.13-1.15.36-.45.27-1.07.64-2.18.64s-1.73-.37-2.18-.64c-.37-.22-.6-.36-1.15-.36s-.78.13-1.15.36c-.47.27-1.09.64-2.2.64v-2c.56 0 .78-.13 1.15-.36.45-.27 1.07-.64 2.18-.64s1.73.37 2.18.64c.37.22.6.36 1.15.36.56 0 .78-.13 1.15-.36.45-.27 1.07-.64 2.18-.64s1.73.37 2.18.64c.37.22.6.36 1.15.36s.78-.13 1.15-.36c.45-.27 1.07-.64 2.18-.64s1.73.37 2.18.64c.37.22.6.36 1.15.36v2zM8.67 12c.56 0 .78-.13 1.15-.36.46-.27 1.08-.64 2.19-.64 1.11 0 1.73.37 2.18.64.37.22.6.36 1.15.36s.78-.13 1.15-.36c.12-.07.26-.15.41-.23L10.48 5C8.93 3.45 7.5 2.99 5 3v2.5c1.82-.01 2.89.39 4 1.5l1 1-3.25 3.25c.31.12.56.27.77.39.37.23.59.36 1.15.36z" /><circle cx="16.5" cy="5.5" r="2.5" /></React.Fragment> , 'Pool');
ajax/libs/material-ui/5.0.0-alpha.7/es/styles/useTheme.js
cdnjs/cdnjs
import { useTheme as useThemeWithoutDefault } from '@material-ui/styles'; import React from 'react'; import defaultTheme from './defaultTheme'; export default function useTheme() { const theme = useThemeWithoutDefault() || defaultTheme; if (process.env.NODE_ENV !== 'production') { // eslint-disable-next-line react-hooks/rules-of-hooks React.useDebugValue(theme); } return theme; }
src/components/box/box.js
growcss/docs
import React from 'react'; import PropTypes from 'prop-types'; import { Container } from './box.css'; const Box = ({ children }) => <Container>{children}</Container>; Box.propTypes = { children: PropTypes.node.isRequired, }; export default Box;
client/modules/App/components/DevTools.js
vladmokryi/Nation-Forecast
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-w" > <LogMonitor /> </DockMonitor> );
src/containers/InputBar/index.js
aisouard/sample-react-webrtc-chat
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import style from './style.less'; class InputBar extends Component { render() { return ( <div className={classnames(style.inputBar)}> <input className={classnames(style.inputBarInput)} /> </div> ); } } InputBar.defaultProps = { disabled: false }; InputBar.propTypes = { disabled: PropTypes.bool }; function mapStateToProps(state) { return { disabled: state.inputDisabled }; } function mapDispatchToProps(dispatch) { return bindActionCreators({ }, dispatch); } export default connect(mapStateToProps, mapDispatchToProps)(InputBar);
src/containers/Playground/TimeBar/index.js
mmazzarolo/tap-the-number
/* @flow */ /** * The time left bar at the top of the Playground screen. */ import React, { Component } from 'react'; import { View } from 'react-native-animatable'; import { Animated, Easing } from 'react-native'; import styles from './index.style'; import metrics from 'src/config/metrics'; import timings from 'src/config/timings'; type State = { animateValue: any, }; export default class TimeBar extends Component<void, {}, State> { state = { animateValue: new Animated.Value(timings.TIME_LIMIT_MS), }; componentDidMount() { Animated.timing(this.state.animateValue, { duration: timings.TIME_LIMIT_MS, easing: Easing.linear, // No easing toValue: 0, }).start(); } render() { // Animate the TimeBar color from grey to red, starting when there are left only 12 seconds const backgroundColor = this.state.animateValue.interpolate({ inputRange: [0, timings.TIME_LIMIT_MS * 0.4, timings.TIME_LIMIT_MS], outputRange: ['rgba(255,0,0, 1)', 'rgba(0,0,0, 0.3)', 'rgba(0,0,0, 0.3)'], }); // Animate the TimeBar width from DEVICE_WIDTH to 0 in TIME_LIMIT_MS (which currently is 30 seconds) const width = this.state.animateValue.interpolate({ inputRange: [0, timings.TIME_LIMIT_MS], outputRange: [0, metrics.DEVICE_WIDTH], }); return ( <View style={styles.container}> <View style={[styles.content, { width, backgroundColor }]} /> </View> ); } }
tic-tac-toe/src/index.js
rohitkrai03/react-tutorial
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import Game from './components/Game'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<Game />, document.getElementById('root')); registerServiceWorker();
src/components/video_list.js
daveprochazka/ReduxSimpleStarter
import React from 'react'; import VideoListItem from './video_list_item'; const VideoList = (props) =>{ const videoItems = props.videos.map((video) =>{ return ( <VideoListItem onVideoSelect={props.onVideoSelect} key={video.etag} video={video}> </VideoListItem> ); }); return( <ul className="col-md-4 list-group"> {videoItems} </ul> ); } export default VideoList;
bundle.js
nfelix/primeNameChecker
/******/ (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 React = __webpack_require__(1); var ReactDOM = __webpack_require__(33); // **** // Natural Language Form // **** var Intro = React.createClass({ displayName: 'Intro', getInitialState: function () { return {}; }, render: function () { return React.createElement( 'div', null, 'Hello, my name is Christopher John Francis Boone. I am fifteen-year-old. I am from Swindon, England.' ); } }); var Error = React.createClass({ displayName: 'Error', getInitialState: function () { return {}; }, render: function () { return React.createElement( 'div', { className: 'errorMessage' }, 'I cannot perform the calculation without your name.' ); } }); var Result = React.createClass({ displayName: 'Result', getInitialState: function () { return { prime: '' }; }, componentDidMount: function () { if (!this.props.isPrime) { this.setState({ prime: 'not ' }); } else { this.setState({ prime: '' }); } }, render: function () { return React.createElement( 'div', null, React.createElement( 'span', { className: 'highlight' }, this.props.name ), ' equals to ', this.props.number, '.', React.createElement('br', null), 'Your name ', React.createElement( 'span', { className: 'highlight' }, 'is ', this.state.prime ), 'a prime number!' ); } }); var FreeTextBox = React.createClass({ displayName: 'FreeTextBox', getInitialState: function () { return { value: '', toggleClass: 'nl-field nl-ti-text', displayText: this.props.displayText }; }, componentWillReceiveProps: function (nextProps) { console.log('componentWillReceiveProps'); if (!nextProps.open) { this.setState({ toggleClass: 'nl-field nl-ti-text' }); this.updateValue(); } }, handleChange: function (e) { this.setState({ value: e.target.value }); }, handleSubmit: function (e) { e.preventDefault();e.stopPropagation(); this.setState({ toggleClass: 'nl-field nl-ti-text' }); this.updateValue(); this.props.onUpdate(false); }, handleToggle: function (e) { e.preventDefault();e.stopPropagation(); this.setState({ toggleClass: 'nl-field nl-ti-text nl-field-open' }); this.props.onUpdate(true); }, updateValue: function (e) { if (this.state.value.trim() != '') { this.setState({ displayText: this.state.value }); } else { this.setState({ displayText: this.props.displayText }); } }, getInputValue: function () { return this.state.value; }, render: function () { return React.createElement( 'div', { className: 'nl-field nl-ti-text', className: this.state.toggleClass }, React.createElement( 'a', { className: 'nl-field-toggle ', onClick: this.handleToggle }, this.state.displayText ), React.createElement( 'ul', null, React.createElement( 'li', { className: 'nl-ti-input' }, React.createElement('input', { type: 'text', placeholder: this.props.displayText, value: this.state.value, onChange: this.handleChange }), React.createElement( 'button', { className: 'nl-field-go noselect', onClick: this.handleSubmit }, 'Go' ) ), React.createElement( 'li', { className: 'nl-ti-example' }, 'For example: ', React.createElement( 'em', null, this.props.exampleText ) ) ) ); } }); var NLForm = React.createClass({ displayName: 'NLForm', componentDidMount: function () { window.addEventListener('keyup', this.keyDown); setTimeout(this.nextStage, 1000); }, getInitialState: function () { return { open: false, stage: 0, isPrime: false, number: 0, name: '' }; }, nextStage: function () { this.setState({ error: false }); this.setState({ stage: this.state.stage + 1 }); }, lastStage: function () { this.setState({ stage: this.state.stage - 1 }); }, closeOverlay: function (e) { this.setState({ open: false }); }, keyDown: function (e) { if (this.state.open) { //Esc Key if (e.keyCode == 27) { this.setState({ open: false }); } // if(e.keyCode == 13) { // this.setState({open: false}); // } } else { // if(e.keyCode == 13){ // this.handleSubmit(e); // } } }, handleSubmit: function (e) { e.preventDefault();e.stopPropagation(); var name = this.refs['name'].getInputValue(); if (name != '') { var resultNumber = this.calcNumber(name.replace(' ', '')); this.setState({ name: name }); if (resultNumber != undefined && resultNumber % 2 !== 0) { this.setState({ isPrime: true, number: resultNumber }); } else { this.setState({ isPrime: false, number: resultNumber }); } this.nextStage(); } else { this.setState({ error: true }); } }, back: function (e) { e.preventDefault();e.stopPropagation(); if (this.state.stage > 0) { this.lastStage(); } }, handleChange: function (val) { this.setState({ open: val }); }, calcNumber: function (name) { if (name.length > 0) { var num = name.toLowerCase().split('').map(function (char) { return char.charCodeAt(0) - 96; }).reduce(function (current, previous) { return previous + current; }); return num; } }, render: function () { return React.createElement( 'div', { className: 'fs-form-wrap', id: 'fs-form-wrap' }, React.createElement( 'div', { className: 'fs-title' }, React.createElement( 'h1', null, React.createElement( 'a', { href: '/' }, 'Project Curious' ) ), React.createElement( 'div', { className: 'curious-top' }, this.state.stage != 0 ? React.createElement( 'a', { className: 'curious-icon curious-icon-prev', onClick: this.back }, React.createElement( 'span', null, 'Back' ) ) : null, this.state.stage == 0 ? React.createElement( 'a', { className: 'curious-icon curious-icon-next', onClick: this.nextStage }, React.createElement( 'span', null, 'Next' ) ) : null ) ), React.createElement( 'div', { className: 'main clearfix', id: 'main' }, React.createElement( 'form', { id: 'nl-form', className: 'nl-form' }, this.state.stage == 0 ? React.createElement(Intro, null) : null, this.state.error ? React.createElement(Error, null) : null, this.state.stage == 1 ? React.createElement( 'div', { id: 'details' }, 'My name is ', React.createElement(FreeTextBox, { ref: 'name', open: this.state.open, onUpdate: this.handleChange, displayText: 'Christopher', exampleText: 'Christopher Boone' }), '. I live in ', React.createElement(FreeTextBox, { open: this.state.open, onUpdate: this.handleChange, displayText: 'somewhere in UK', exampleText: 'London, or New York' }), '. And you can reach me at ', React.createElement(FreeTextBox, { open: this.state.open, onUpdate: this.handleChange, displayText: '[email protected]', exampleText: 'Christopher Boone' }), '.', React.createElement( 'div', { className: 'nl-submit-wrap' }, React.createElement( 'button', { className: 'nl-submit', type: 'submit', onClick: this.handleSubmit }, 'Is my name a Prime Number?' ) ), React.createElement('div', { className: 'nl-overlay', onClick: this.closeOverlay }) ) : null, this.state.stage == 2 ? React.createElement(Result, { name: this.state.name, isPrime: this.state.isPrime, number: this.state.number }) : null ) ) ); } }); ReactDOM.render(React.createElement(NLForm, null), document.getElementById('container')); // **** // Single Question // **** // var QuestionForm = React.createClass({ // getInitialState: function() { // return {name: '', error: ''}; // }, // handleSubmit: function(e) { // e.preventDefault(); // var name = this.state.name.trim(); // if (name.length > 0 ){ // this.clearError(); // var num = name.toLowerCase().split('') // .map(function (char) { // return char.charCodeAt(0) - 96; // }) // .reduce(function (current, previous) { // return previous + current; // }); // console.log(num); // } // else { // this.showError('NOVAL'); // } // }, // clearError: function(err){ // this.setState({errorMessage: ''}); // this.setState({errorClass: ''}); // }, // showError: function(err){ // var message = ''; // switch( err ) { // case 'NOVAL' : // message = 'Please fill the field before continuing'; // break; // case 'INVALIDEMAIL' : // message = 'Please fill a valid email address'; // break; // }; // this.setState({errorMessage: message}); // this.setState({errorClass: 'fs-show fs-message-error'}); // }, // handleTextChange: function(e) { // this.setState({name: e.target.value}); // }, // render: function() { // return ( // <form id="myform" className="" autoComplete="off" > // <ol className="fs-fields"> // <li className="fs-current"> // <label className="fs-field-label fs-anim-upper" htmlFor="q1"> // What is your name? // </label> // <input // className="fs-anim-lower" // id="q1" // name="q1" // type="text" // placeholder="Christopher Boone" // value={this.state.name} // onChange={this.handleTextChange} // required /> // </li> // </ol> // <button className="fs-continue fs-show" onClick={this.handleSubmit}>Continue</button> // <span className="fs-message-error" className={this.state.errorClass}>{this.state.errorMessage}</span> // </form> // ); // } // }); // ReactDOM.render( // <QuestionForm />, // document.getElementById('main') // ); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(2); /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule React */ 'use strict'; var _assign = __webpack_require__(4); var ReactChildren = __webpack_require__(5); var ReactComponent = __webpack_require__(16); var ReactClass = __webpack_require__(22); var ReactDOMFactories = __webpack_require__(27); var ReactElement = __webpack_require__(8); var ReactElementValidator = __webpack_require__(28); var ReactPropTypes = __webpack_require__(30); var ReactVersion = __webpack_require__(31); var onlyChild = __webpack_require__(32); var warning = __webpack_require__(10); var createElement = ReactElement.createElement; var createFactory = ReactElement.createFactory; var cloneElement = ReactElement.cloneElement; if (process.env.NODE_ENV !== 'production') { createElement = ReactElementValidator.createElement; createFactory = ReactElementValidator.createFactory; cloneElement = ReactElementValidator.cloneElement; } var __spread = _assign; if (process.env.NODE_ENV !== 'production') { var warned = false; __spread = function () { process.env.NODE_ENV !== 'production' ? warning(warned, 'React.__spread is deprecated and should not be used. Use ' + 'Object.assign directly or another helper function with similar ' + 'semantics. You may be seeing this warning due to your compiler. ' + 'See https://fb.me/react-spread-deprecation for more details.') : void 0; warned = true; return _assign.apply(null, arguments); }; } var React = { // Modern Children: { map: ReactChildren.map, forEach: ReactChildren.forEach, count: ReactChildren.count, toArray: ReactChildren.toArray, only: onlyChild }, Component: ReactComponent, createElement: createElement, cloneElement: cloneElement, isValidElement: ReactElement.isValidElement, // Classic PropTypes: ReactPropTypes, createClass: ReactClass.createClass, createFactory: createFactory, createMixin: function (mixin) { // Currently a noop. Will be used to validate and trace mixins. return mixin; }, // This looks DOM specific but these are actually isomorphic helpers // since they are just generating DOM strings. DOM: ReactDOMFactories, version: ReactVersion, // Deprecated hook for JSX spread, don't use this for anything. __spread: __spread }; module.exports = React; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 3 */ /***/ 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() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = 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; }; /***/ }, /* 4 */ /***/ function(module, exports) { 'use strict'; /* eslint-disable no-unused-vars */ var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } // Detect buggy property enumeration order in older V8 versions. // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { test2['_' + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function (n) { return test2[n]; }); if (order2.join('') !== '0123456789') { return false; } // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join('') !== 'abcdefghijklmnopqrst') { return false; } return true; } catch (e) { // We don't expect any of the above to throw, but better to be safe. return false; } } module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } if (Object.getOwnPropertySymbols) { symbols = Object.getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildren */ 'use strict'; var PooledClass = __webpack_require__(6); var ReactElement = __webpack_require__(8); var emptyFunction = __webpack_require__(11); var traverseAllChildren = __webpack_require__(13); var twoArgumentPooler = PooledClass.twoArgumentPooler; var fourArgumentPooler = PooledClass.fourArgumentPooler; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text) { return ('' + text).replace(userProvidedKeyEscapeRegex, '$&/'); } /** * PooledClass representing the bookkeeping associated with performing a child * traversal. Allows avoiding binding callbacks. * * @constructor ForEachBookKeeping * @param {!function} forEachFunction Function to perform traversal with. * @param {?*} forEachContext Context to perform context with. */ function ForEachBookKeeping(forEachFunction, forEachContext) { this.func = forEachFunction; this.context = forEachContext; this.count = 0; } ForEachBookKeeping.prototype.destructor = function () { this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler); function forEachSingleChild(bookKeeping, child, name) { var func = bookKeeping.func; var context = bookKeeping.context; func.call(context, child, bookKeeping.count++); } /** * Iterates through children that are typically specified as `props.children`. * * The provided forEachFunc(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} forEachFunc * @param {*} forEachContext Context for forEachContext. */ function forEachChildren(children, forEachFunc, forEachContext) { if (children == null) { return children; } var traverseContext = ForEachBookKeeping.getPooled(forEachFunc, forEachContext); traverseAllChildren(children, forEachSingleChild, traverseContext); ForEachBookKeeping.release(traverseContext); } /** * PooledClass representing the bookkeeping associated with performing a child * mapping. Allows avoiding binding callbacks. * * @constructor MapBookKeeping * @param {!*} mapResult Object containing the ordered map of results. * @param {!function} mapFunction Function to perform mapping with. * @param {?*} mapContext Context to perform mapping with. */ function MapBookKeeping(mapResult, keyPrefix, mapFunction, mapContext) { this.result = mapResult; this.keyPrefix = keyPrefix; this.func = mapFunction; this.context = mapContext; this.count = 0; } MapBookKeeping.prototype.destructor = function () { this.result = null; this.keyPrefix = null; this.func = null; this.context = null; this.count = 0; }; PooledClass.addPoolingTo(MapBookKeeping, fourArgumentPooler); function mapSingleChildIntoContext(bookKeeping, child, childKey) { var result = bookKeeping.result; var keyPrefix = bookKeeping.keyPrefix; var func = bookKeeping.func; var context = bookKeeping.context; var mappedChild = func.call(context, child, bookKeeping.count++); if (Array.isArray(mappedChild)) { mapIntoWithKeyPrefixInternal(mappedChild, result, childKey, emptyFunction.thatReturnsArgument); } else if (mappedChild != null) { if (ReactElement.isValidElement(mappedChild)) { mappedChild = ReactElement.cloneAndReplaceKey(mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children keyPrefix + (mappedChild.key && (!child || child.key !== mappedChild.key) ? escapeUserProvidedKey(mappedChild.key) + '/' : '') + childKey); } result.push(mappedChild); } } function mapIntoWithKeyPrefixInternal(children, array, prefix, func, context) { var escapedPrefix = ''; if (prefix != null) { escapedPrefix = escapeUserProvidedKey(prefix) + '/'; } var traverseContext = MapBookKeeping.getPooled(array, escapedPrefix, func, context); traverseAllChildren(children, mapSingleChildIntoContext, traverseContext); MapBookKeeping.release(traverseContext); } /** * Maps children that are typically specified as `props.children`. * * The provided mapFunction(child, index) will be called for each * leaf child. * * @param {?*} children Children tree container. * @param {function(*, int)} func The map function. * @param {*} context Context for mapFunction. * @return {object} Object containing the ordered map of results. */ function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; mapIntoWithKeyPrefixInternal(children, result, null, func, context); return result; } function forEachSingleChildDummy(traverseContext, child, name) { return null; } /** * Count the number of children that are typically specified as * `props.children`. * * @param {?*} children Children tree container. * @return {number} The number of children. */ function countChildren(children, context) { return traverseAllChildren(children, forEachSingleChildDummy, null); } /** * Flatten a children object (typically specified as `props.children`) and * return an array with appropriately re-keyed children. */ function toArray(children) { var result = []; mapIntoWithKeyPrefixInternal(children, result, null, emptyFunction.thatReturnsArgument); return result; } var ReactChildren = { forEach: forEachChildren, map: mapChildren, mapIntoWithKeyPrefixInternal: mapIntoWithKeyPrefixInternal, count: countChildren, toArray: toArray }; module.exports = ReactChildren; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule PooledClass */ 'use strict'; var invariant = __webpack_require__(7); /** * Static poolers. Several custom versions for each potential number of * arguments. A completely generic pooler is easy to implement, but would * require accessing the `arguments` object. In each of these, `this` refers to * the Class itself, not an instance. If any others are needed, simply add them * here, or in their own files. */ var oneArgumentPooler = function (copyFieldsFrom) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, copyFieldsFrom); return instance; } else { return new Klass(copyFieldsFrom); } }; var twoArgumentPooler = function (a1, a2) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2); return instance; } else { return new Klass(a1, a2); } }; var threeArgumentPooler = function (a1, a2, a3) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3); return instance; } else { return new Klass(a1, a2, a3); } }; var fourArgumentPooler = function (a1, a2, a3, a4) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4); return instance; } else { return new Klass(a1, a2, a3, a4); } }; var fiveArgumentPooler = function (a1, a2, a3, a4, a5) { var Klass = this; if (Klass.instancePool.length) { var instance = Klass.instancePool.pop(); Klass.call(instance, a1, a2, a3, a4, a5); return instance; } else { return new Klass(a1, a2, a3, a4, a5); } }; var standardReleaser = function (instance) { var Klass = this; !(instance instanceof Klass) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Trying to release an instance into a pool of a different type.') : invariant(false) : void 0; instance.destructor(); if (Klass.instancePool.length < Klass.poolSize) { Klass.instancePool.push(instance); } }; var DEFAULT_POOL_SIZE = 10; var DEFAULT_POOLER = oneArgumentPooler; /** * Augments `CopyConstructor` to be a poolable class, augmenting only the class * itself (statically) not adding any prototypical fields. Any CopyConstructor * you give this may have a `poolSize` property, and will look for a * prototypical `destructor` on instances (optional). * * @param {Function} CopyConstructor Constructor that can be used to reset. * @param {Function} pooler Customizable pooler. */ var addPoolingTo = function (CopyConstructor, pooler) { var NewKlass = CopyConstructor; NewKlass.instancePool = []; NewKlass.getPooled = pooler || DEFAULT_POOLER; if (!NewKlass.poolSize) { NewKlass.poolSize = DEFAULT_POOL_SIZE; } NewKlass.release = standardReleaser; return NewKlass; }; var PooledClass = { addPoolingTo: addPoolingTo, oneArgumentPooler: oneArgumentPooler, twoArgumentPooler: twoArgumentPooler, threeArgumentPooler: threeArgumentPooler, fourArgumentPooler: fourArgumentPooler, fiveArgumentPooler: fiveArgumentPooler }; module.exports = PooledClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * 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__(3))) /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElement */ 'use strict'; var _assign = __webpack_require__(4); var ReactCurrentOwner = __webpack_require__(9); var warning = __webpack_require__(10); var canDefineProperty = __webpack_require__(12); // The Symbol used to tag the ReactElement type. If there is no native Symbol // nor polyfill, then a plain number is used for performance. var REACT_ELEMENT_TYPE = typeof Symbol === 'function' && Symbol['for'] && Symbol['for']('react.element') || 0xeac7; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown; /** * Factory method to create a new React element. This no longer adheres to * the class pattern, so do not use new to call it. Also, no instanceof check * will work. Instead test $$typeof field against Symbol.for('react.element') to check * if something is a React Element. * * @param {*} type * @param {*} key * @param {string|object} ref * @param {*} self A *temporary* helper to detect places where `this` is * different from the `owner` when React.createElement is called, so that we * can warn. We want to get rid of owner and replace string `ref`s with arrow * functions, and as long as `this` and owner are the same, there will be no * change in behavior. * @param {*} source An annotation object (added by a transpiler or otherwise) * indicating filename, line number, and/or other information. * @param {*} owner * @param {*} props * @internal */ var ReactElement = function (type, key, ref, self, source, owner, props) { var element = { // This tag allow us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type, key: key, ref: ref, props: props, // Record the component responsible for creating this element. _owner: owner }; if (process.env.NODE_ENV !== 'production') { // The validation flag is currently mutative. We put it on // an external backing store so that we can freeze the whole object. // This can be replaced with a WeakMap once they are implemented in // commonly used development environments. element._store = {}; // To make comparing ReactElements easier for testing purposes, we make // the validation flag non-enumerable (where possible, which should // include every environment we run tests in), so the test framework // ignores it. if (canDefineProperty) { Object.defineProperty(element._store, 'validated', { configurable: false, enumerable: false, writable: true, value: false }); // self and source are DEV only properties. Object.defineProperty(element, '_self', { configurable: false, enumerable: false, writable: false, value: self }); // Two elements created in two different places should be considered // equal for testing purposes and therefore we hide it from enumeration. Object.defineProperty(element, '_source', { configurable: false, enumerable: false, writable: false, value: source }); } else { element._store.validated = false; element._self = self; element._source = source; } if (Object.freeze) { Object.freeze(element.props); Object.freeze(element); } } return element; }; ReactElement.createElement = function (type, config, children) { var propName; // Reserved names are extracted var props = {}; var key = null; var ref = null; var self = null; var source = null; if (config != null) { if (process.env.NODE_ENV !== 'production') { ref = !config.hasOwnProperty('ref') || Object.getOwnPropertyDescriptor(config, 'ref').get ? null : config.ref; key = !config.hasOwnProperty('key') || Object.getOwnPropertyDescriptor(config, 'key').get ? null : '' + config.key; } else { ref = config.ref === undefined ? null : config.ref; key = config.key === undefined ? null : '' + config.key; } self = config.__self === undefined ? null : config.__self; source = config.__source === undefined ? null : config.__source; // Remaining properties are added to a new props object for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } // Resolve default props if (type && type.defaultProps) { var defaultProps = type.defaultProps; for (propName in defaultProps) { if (props[propName] === undefined) { props[propName] = defaultProps[propName]; } } } if (process.env.NODE_ENV !== 'production') { // Create dummy `key` and `ref` property to `props` to warn users // against its use if (typeof props.$$typeof === 'undefined' || props.$$typeof !== REACT_ELEMENT_TYPE) { if (!props.hasOwnProperty('key')) { Object.defineProperty(props, 'key', { get: function () { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; process.env.NODE_ENV !== 'production' ? warning(false, '%s: `key` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', typeof type === 'function' && 'displayName' in type ? type.displayName : 'Element') : void 0; } return undefined; }, configurable: true }); } if (!props.hasOwnProperty('ref')) { Object.defineProperty(props, 'ref', { get: function () { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; process.env.NODE_ENV !== 'production' ? warning(false, '%s: `ref` is not a prop. Trying to access it will result ' + 'in `undefined` being returned. If you need to access the same ' + 'value within the child component, you should pass it as a different ' + 'prop. (https://fb.me/react-special-props)', typeof type === 'function' && 'displayName' in type ? type.displayName : 'Element') : void 0; } return undefined; }, configurable: true }); } } } return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); }; ReactElement.createFactory = function (type) { var factory = ReactElement.createElement.bind(null, type); // Expose the type on the factory and the prototype so that it can be // easily accessed on elements. E.g. `<Foo />.type === Foo`. // This should not be named `constructor` since this may not be the function // that created the element, and it may not even be a constructor. // Legacy hook TODO: Warn if this is accessed factory.type = type; return factory; }; ReactElement.cloneAndReplaceKey = function (oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; }; ReactElement.cloneElement = function (element, config, children) { var propName; // Original props are copied var props = _assign({}, element.props); // Reserved names are extracted var key = element.key; var ref = element.ref; // Self is preserved since the owner is preserved. var self = element._self; // Source is preserved since cloneElement is unlikely to be targeted by a // transpiler, and the original source is probably a better indicator of the // true owner. var source = element._source; // Owner will be preserved, unless ref is overridden var owner = element._owner; if (config != null) { if (config.ref !== undefined) { // Silently steal the ref from the parent. ref = config.ref; owner = ReactCurrentOwner.current; } if (config.key !== undefined) { key = '' + config.key; } // Remaining properties override existing props var defaultProps; if (element.type && element.type.defaultProps) { defaultProps = element.type.defaultProps; } for (propName in config) { if (config.hasOwnProperty(propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === undefined && defaultProps !== undefined) { // Resolve default props props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } // Children can be more than one argument, and those are transferred onto // the newly allocated props object. var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element.type, key, ref, self, source, owner, props); }; /** * @param {?object} object * @return {boolean} True if `object` is a valid component. * @final */ ReactElement.isValidElement = function (object) { return typeof object === 'object' && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; }; module.exports = ReactElement; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 9 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCurrentOwner */ 'use strict'; /** * Keeps track of the current owner. * * The current owner is the component who should own any components that are * currently being constructed. */ var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; module.exports = ReactCurrentOwner; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * 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. * */ 'use strict'; var emptyFunction = __webpack_require__(11); /** * Similar to invariant but only logs a warning if the condition is not met. * This can be used to log issues in development environments in critical * paths. Removing the logging code for production environments will keep the * same logic and follow the same code paths. */ var warning = emptyFunction; if (process.env.NODE_ENV !== 'production') { warning = function (condition, format) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } if (format === undefined) { throw new Error('`warning(condition, format, ...args)` requires a warning ' + 'message argument'); } if (format.indexOf('Failed Composite propType: ') === 0) { return; // Ignore CompositeComponent proptype check. } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function () { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // --- Welcome to debugging React --- // This error was thrown as a convenience so that you can use this stack // to find the callsite that caused this warning to fire. throw new Error(message); } catch (x) {} } }; } module.exports = warning; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 11 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ function makeEmptyFunction(arg) { return function () { return arg; }; } /** * This function accepts and discards inputs; it has no side effects. This is * primarily useful idiomatically for overridable function endpoints which * always need to be callable, since JS lacks a null-call idiom ala Cocoa. */ function emptyFunction() {} emptyFunction.thatReturns = makeEmptyFunction; emptyFunction.thatReturnsFalse = makeEmptyFunction(false); emptyFunction.thatReturnsTrue = makeEmptyFunction(true); emptyFunction.thatReturnsNull = makeEmptyFunction(null); emptyFunction.thatReturnsThis = function () { return this; }; emptyFunction.thatReturnsArgument = function (arg) { return arg; }; module.exports = emptyFunction; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule canDefineProperty */ 'use strict'; var canDefineProperty = false; if (process.env.NODE_ENV !== 'production') { try { Object.defineProperty({}, 'x', { get: function () {} }); canDefineProperty = true; } catch (x) { // IE will fail on defineProperty } } module.exports = canDefineProperty; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule traverseAllChildren */ 'use strict'; var ReactCurrentOwner = __webpack_require__(9); var ReactElement = __webpack_require__(8); var getIteratorFn = __webpack_require__(14); var invariant = __webpack_require__(7); var KeyEscapeUtils = __webpack_require__(15); var warning = __webpack_require__(10); var SEPARATOR = '.'; var SUBSEPARATOR = ':'; /** * TODO: Test that a single child and an array with one item have the same key * pattern. */ var didWarnAboutMaps = false; /** * Generate a key string that identifies a component within a set. * * @param {*} component A component that could contain a manual key. * @param {number} index Index that is used if a manual key is not provided. * @return {string} */ function getComponentKey(component, index) { // Do some typechecking here since we call this blindly. We want to ensure // that we don't block potential future ES APIs. if (component && typeof component === 'object' && component.key != null) { // Explicit key return KeyEscapeUtils.escape(component.key); } // Implicit key determined by the index in the set return index.toString(36); } /** * @param {?*} children Children tree container. * @param {!string} nameSoFar Name of the key path so far. * @param {!function} callback Callback to invoke with each child found. * @param {?*} traverseContext Used to pass information throughout the traversal * process. * @return {!number} The number of children in this subtree. */ function traverseAllChildrenImpl(children, nameSoFar, callback, traverseContext) { var type = typeof children; if (type === 'undefined' || type === 'boolean') { // All of the above are perceived as null. children = null; } if (children === null || type === 'string' || type === 'number' || ReactElement.isValidElement(children)) { callback(traverseContext, children, // If it's the only child, treat the name as if it was wrapped in an array // so that it's consistent if the number of children grows. nameSoFar === '' ? SEPARATOR + getComponentKey(children, 0) : nameSoFar); return 1; } var child; var nextName; var subtreeCount = 0; // Count of children found in the current subtree. var nextNamePrefix = nameSoFar === '' ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getComponentKey(child, i); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { var iteratorFn = getIteratorFn(children); if (iteratorFn) { var iterator = iteratorFn.call(children); var step; if (iteratorFn !== children.entries) { var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getComponentKey(child, ii++); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } else { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(didWarnAboutMaps, '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; didWarnAboutMaps = true; } // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { child = entry[1]; nextName = nextNamePrefix + KeyEscapeUtils.escape(entry[0]) + SUBSEPARATOR + getComponentKey(child, 0); subtreeCount += traverseAllChildrenImpl(child, nextName, callback, traverseContext); } } } } else if (type === 'object') { var addendum = ''; if (process.env.NODE_ENV !== 'production') { addendum = ' 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.'; if (children._isReactElement) { addendum = ' It looks like you\'re using an element created by a different ' + 'version of React. Make sure to use only one copy of React.'; } if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { addendum += ' Check the render method of `' + name + '`.'; } } } var childrenString = String(children); true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Objects are not valid as a React child (found: %s).%s', childrenString === '[object Object]' ? 'object with keys {' + Object.keys(children).join(', ') + '}' : childrenString, addendum) : invariant(false) : void 0; } } return subtreeCount; } /** * Traverses children that are typically specified as `props.children`, but * might also be specified through attributes: * * - `traverseAllChildren(this.props.children, ...)` * - `traverseAllChildren(this.props.leftPanelChildren, ...)` * * The `traverseContext` is an optional argument that is passed through the * entire traversal. It can be used to store accumulations or anything else that * the callback might find relevant. * * @param {?*} children Children tree object. * @param {!function} callback To invoke upon traversing each child. * @param {?*} traverseContext Context for traversal. * @return {!number} The number of children in this subtree. */ function traverseAllChildren(children, callback, traverseContext) { if (children == null) { return 0; } return traverseAllChildrenImpl(children, '', callback, traverseContext); } module.exports = traverseAllChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 14 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getIteratorFn */ 'use strict'; /* global Symbol */ var ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; // Before Symbol spec. /** * Returns the iterator method function contained on the iterable object. * * Be sure to invoke the function with the iterable as context: * * var iteratorFn = getIteratorFn(myIterable); * if (iteratorFn) { * var iterator = iteratorFn.call(myIterable); * ... * } * * @param {?object} maybeIterable * @return {?function} */ function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === 'function') { return iteratorFn; } } module.exports = getIteratorFn; /***/ }, /* 15 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule KeyEscapeUtils */ 'use strict'; /** * Escape and wrap key so it is safe to use as a reactid * * @param {*} key to be escaped. * @return {string} the escaped key. */ function escape(key) { var escapeRegex = /[=:]/g; var escaperLookup = { '=': '=0', ':': '=2' }; var escapedString = ('' + key).replace(escapeRegex, function (match) { return escaperLookup[match]; }); return '$' + escapedString; } /** * Unescape and unwrap key for human-readable display * * @param {string} key to unescape. * @return {string} the unescaped key. */ function unescape(key) { var unescapeRegex = /(=0|=2)/g; var unescaperLookup = { '=0': '=', '=2': ':' }; var keySubstring = key[0] === '.' && key[1] === '$' ? key.substring(2) : key.substring(1); return ('' + keySubstring).replace(unescapeRegex, function (match) { return unescaperLookup[match]; }); } var KeyEscapeUtils = { escape: escape, unescape: unescape }; module.exports = KeyEscapeUtils; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponent */ 'use strict'; var ReactNoopUpdateQueue = __webpack_require__(17); var ReactInstrumentation = __webpack_require__(18); var canDefineProperty = __webpack_require__(12); var emptyObject = __webpack_require__(21); var invariant = __webpack_require__(7); var warning = __webpack_require__(10); /** * Base class helpers for the updating state of a component. */ function ReactComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; // We initialize the default updater but the real one gets injected by the // renderer. this.updater = updater || ReactNoopUpdateQueue; } ReactComponent.prototype.isReactComponent = {}; /** * Sets a subset of the state. Always use this to mutate * state. You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * There is no guarantee that calls to `setState` will run synchronously, * as they may eventually be batched together. You can provide an optional * callback that will be executed when the call to setState is actually * completed. * * When a function is provided to setState, it will be called at some point in * the future (not synchronously). It will be called with the up to date * component arguments (state, props, context). These values can be different * from this.* because your function may be called after receiveProps but before * shouldComponentUpdate, and this new state, props, and context will not yet be * assigned to this. * * @param {object|function} partialState Next partial state or function to * produce next partial state to be merged with current state. * @param {?function} callback Called after state is updated. * @final * @protected */ ReactComponent.prototype.setState = function (partialState, callback) { !(typeof partialState === 'object' || typeof partialState === 'function' || partialState == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'setState(...): takes an object of state variables to update or a ' + 'function which returns an object of state variables.') : invariant(false) : void 0; if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onSetState(); process.env.NODE_ENV !== 'production' ? warning(partialState != null, 'setState(...): You passed an undefined or null state object; ' + 'instead, use forceUpdate().') : void 0; } this.updater.enqueueSetState(this, partialState); if (callback) { this.updater.enqueueCallback(this, callback, 'setState'); } }; /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {?function} callback Called after update is complete. * @final * @protected */ ReactComponent.prototype.forceUpdate = function (callback) { this.updater.enqueueForceUpdate(this); if (callback) { this.updater.enqueueCallback(this, callback, 'forceUpdate'); } }; /** * Deprecated APIs. These APIs used to exist on classic React classes but since * we would like to deprecate them, we're not going to move them over to this * modern base class. Instead, we define a getter that warns if it's accessed. */ if (process.env.NODE_ENV !== 'production') { var deprecatedAPIs = { isMounted: ['isMounted', 'Instead, make sure to clean up subscriptions and pending requests in ' + 'componentWillUnmount to prevent memory leaks.'], replaceState: ['replaceState', 'Refactor your code to use setState instead (see ' + 'https://github.com/facebook/react/issues/3236).'] }; var defineDeprecationWarning = function (methodName, info) { if (canDefineProperty) { Object.defineProperty(ReactComponent.prototype, methodName, { get: function () { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...) is deprecated in plain JavaScript React classes. %s', info[0], info[1]) : void 0; return undefined; } }); } }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } module.exports = ReactComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNoopUpdateQueue */ 'use strict'; var warning = __webpack_require__(10); function warnTDZ(publicInstance, callerName) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, '%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.', callerName, callerName, publicInstance.constructor && publicInstance.constructor.displayName || '') : void 0; } } /** * This is the abstract API for an update queue. */ var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { return false; }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @internal */ enqueueCallback: function (publicInstance, callback) {}, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { warnTDZ(publicInstance, 'forceUpdate'); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { warnTDZ(publicInstance, 'replaceState'); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { warnTDZ(publicInstance, 'setState'); } }; module.exports = ReactNoopUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstrumentation */ 'use strict'; var ReactDebugTool = __webpack_require__(19); module.exports = { debugTool: ReactDebugTool }; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDebugTool */ 'use strict'; var ReactInvalidSetStateWarningDevTool = __webpack_require__(20); var warning = __webpack_require__(10); var eventHandlers = []; var handlerDoesThrowForEvent = {}; function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) { if (process.env.NODE_ENV !== 'production') { eventHandlers.forEach(function (handler) { try { if (handler[handlerFunctionName]) { handler[handlerFunctionName](arg1, arg2, arg3, arg4, arg5); } } catch (e) { process.env.NODE_ENV !== 'production' ? warning(!handlerDoesThrowForEvent[handlerFunctionName], 'exception thrown by devtool while handling %s: %s', handlerFunctionName, e.message) : void 0; handlerDoesThrowForEvent[handlerFunctionName] = true; } }); } } var ReactDebugTool = { addDevtool: function (devtool) { eventHandlers.push(devtool); }, removeDevtool: function (devtool) { for (var i = 0; i < eventHandlers.length; i++) { if (eventHandlers[i] === devtool) { eventHandlers.splice(i, 1); i--; } } }, onBeginProcessingChildContext: function () { emitEvent('onBeginProcessingChildContext'); }, onEndProcessingChildContext: function () { emitEvent('onEndProcessingChildContext'); }, onSetState: function () { emitEvent('onSetState'); }, onMountRootComponent: function (internalInstance) { emitEvent('onMountRootComponent', internalInstance); }, onMountComponent: function (internalInstance) { emitEvent('onMountComponent', internalInstance); }, onUpdateComponent: function (internalInstance) { emitEvent('onUpdateComponent', internalInstance); }, onUnmountComponent: function (internalInstance) { emitEvent('onUnmountComponent', internalInstance); } }; ReactDebugTool.addDevtool(ReactInvalidSetStateWarningDevTool); module.exports = ReactDebugTool; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2016-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInvalidSetStateWarningDevTool */ 'use strict'; var warning = __webpack_require__(10); if (process.env.NODE_ENV !== 'production') { var processingChildContext = false; var warnInvalidSetState = function () { process.env.NODE_ENV !== 'production' ? warning(!processingChildContext, 'setState(...): Cannot call setState() inside getChildContext()') : void 0; }; } var ReactInvalidSetStateWarningDevTool = { onBeginProcessingChildContext: function () { processingChildContext = true; }, onEndProcessingChildContext: function () { processingChildContext = false; }, onSetState: function () { warnInvalidSetState(); } }; module.exports = ReactInvalidSetStateWarningDevTool; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var emptyObject = {}; if (process.env.NODE_ENV !== 'production') { Object.freeze(emptyObject); } module.exports = emptyObject; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactClass */ 'use strict'; var _assign = __webpack_require__(4); var ReactComponent = __webpack_require__(16); var ReactElement = __webpack_require__(8); var ReactPropTypeLocations = __webpack_require__(23); var ReactPropTypeLocationNames = __webpack_require__(25); var ReactNoopUpdateQueue = __webpack_require__(17); var emptyObject = __webpack_require__(21); var invariant = __webpack_require__(7); var keyMirror = __webpack_require__(24); var keyOf = __webpack_require__(26); var warning = __webpack_require__(10); var MIXINS_KEY = keyOf({ mixins: null }); /** * Policies that describe methods in `ReactClassInterface`. */ var SpecPolicy = keyMirror({ /** * These methods may be defined only once by the class specification or mixin. */ DEFINE_ONCE: null, /** * These methods may be defined by both the class specification and mixins. * Subsequent definitions will be chained. These methods must return void. */ DEFINE_MANY: null, /** * These methods are overriding the base class. */ OVERRIDE_BASE: null, /** * These methods are similar to DEFINE_MANY, except we assume they return * objects. We try to merge the keys of the return values of all the mixed in * functions. If there is a key conflict we throw. */ DEFINE_MANY_MERGED: null }); var injectedMixins = []; /** * Composite components are higher-level components that compose other composite * or native components. * * To create a new type of `ReactClass`, pass a specification of * your new class to `React.createClass`. The only requirement of your class * specification is that you implement a `render` method. * * var MyComponent = React.createClass({ * render: function() { * return <div>Hello World</div>; * } * }); * * The class specification supports a specific protocol of methods that have * special meaning (e.g. `render`). See `ReactClassInterface` for * more the comprehensive protocol. Any other properties and methods in the * class specification will be available on the prototype. * * @interface ReactClassInterface * @internal */ var ReactClassInterface = { /** * An array of Mixin objects to include when defining your component. * * @type {array} * @optional */ mixins: SpecPolicy.DEFINE_MANY, /** * An object containing properties and methods that should be defined on * the component's constructor instead of its prototype (static methods). * * @type {object} * @optional */ statics: SpecPolicy.DEFINE_MANY, /** * Definition of prop types for this component. * * @type {object} * @optional */ propTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types for this component. * * @type {object} * @optional */ contextTypes: SpecPolicy.DEFINE_MANY, /** * Definition of context types this component sets for its children. * * @type {object} * @optional */ childContextTypes: SpecPolicy.DEFINE_MANY, // ==== Definition methods ==== /** * Invoked when the component is mounted. Values in the mapping will be set on * `this.props` if that prop is not specified (i.e. using an `in` check). * * This method is invoked before `getInitialState` and therefore cannot rely * on `this.state` or use `this.setState`. * * @return {object} * @optional */ getDefaultProps: SpecPolicy.DEFINE_MANY_MERGED, /** * Invoked once before the component is mounted. The return value will be used * as the initial value of `this.state`. * * getInitialState: function() { * return { * isOn: false, * fooBaz: new BazFoo() * } * } * * @return {object} * @optional */ getInitialState: SpecPolicy.DEFINE_MANY_MERGED, /** * @return {object} * @optional */ getChildContext: SpecPolicy.DEFINE_MANY_MERGED, /** * Uses props from `this.props` and state from `this.state` to render the * structure of the component. * * No guarantees are made about when or how often this method is invoked, so * it must not have side effects. * * render: function() { * var name = this.props.name; * return <div>Hello, {name}!</div>; * } * * @return {ReactComponent} * @nosideeffects * @required */ render: SpecPolicy.DEFINE_ONCE, // ==== Delegate methods ==== /** * Invoked when the component is initially created and about to be mounted. * This may have side effects, but any external subscriptions or data created * by this method must be cleaned up in `componentWillUnmount`. * * @optional */ componentWillMount: SpecPolicy.DEFINE_MANY, /** * Invoked when the component has been mounted and has a DOM representation. * However, there is no guarantee that the DOM node is in the document. * * Use this as an opportunity to operate on the DOM when the component has * been mounted (initialized and rendered) for the first time. * * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidMount: SpecPolicy.DEFINE_MANY, /** * Invoked before the component receives new props. * * Use this as an opportunity to react to a prop transition by updating the * state using `this.setState`. Current props are accessed via `this.props`. * * componentWillReceiveProps: function(nextProps, nextContext) { * this.setState({ * likesIncreasing: nextProps.likeCount > this.props.likeCount * }); * } * * NOTE: There is no equivalent `componentWillReceiveState`. An incoming prop * transition may cause a state change, but the opposite is not true. If you * need it, you are probably looking for `componentWillUpdate`. * * @param {object} nextProps * @optional */ componentWillReceiveProps: SpecPolicy.DEFINE_MANY, /** * Invoked while deciding if the component should be updated as a result of * receiving new props, state and/or context. * * Use this as an opportunity to `return false` when you're certain that the * transition to the new props/state/context will not require a component * update. * * shouldComponentUpdate: function(nextProps, nextState, nextContext) { * return !equal(nextProps, this.props) || * !equal(nextState, this.state) || * !equal(nextContext, this.context); * } * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @return {boolean} True if the component should update. * @optional */ shouldComponentUpdate: SpecPolicy.DEFINE_ONCE, /** * Invoked when the component is about to update due to a transition from * `this.props`, `this.state` and `this.context` to `nextProps`, `nextState` * and `nextContext`. * * Use this as an opportunity to perform preparation before an update occurs. * * NOTE: You **cannot** use `this.setState()` in this method. * * @param {object} nextProps * @param {?object} nextState * @param {?object} nextContext * @param {ReactReconcileTransaction} transaction * @optional */ componentWillUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component's DOM representation has been updated. * * Use this as an opportunity to operate on the DOM when the component has * been updated. * * @param {object} prevProps * @param {?object} prevState * @param {?object} prevContext * @param {DOMElement} rootNode DOM element representing the component. * @optional */ componentDidUpdate: SpecPolicy.DEFINE_MANY, /** * Invoked when the component is about to be removed from its parent and have * its DOM representation destroyed. * * Use this as an opportunity to deallocate any external resources. * * NOTE: There is no `componentDidUnmount` since your component will have been * destroyed by that point. * * @optional */ componentWillUnmount: SpecPolicy.DEFINE_MANY, // ==== Advanced methods ==== /** * Updates the component's currently mounted DOM representation. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @internal * @overridable */ updateComponent: SpecPolicy.OVERRIDE_BASE }; /** * Mapping from class specification keys to special processing functions. * * Although these are declared like instance properties in the specification * when defining classes using `React.createClass`, they are actually static * and are accessible on the constructor instead of the prototype. Despite * being static, they must be defined outside of the "statics" key under * which all other static methods are defined. */ var RESERVED_SPEC_KEYS = { displayName: function (Constructor, displayName) { Constructor.displayName = displayName; }, mixins: function (Constructor, mixins) { if (mixins) { for (var i = 0; i < mixins.length; i++) { mixSpecIntoComponent(Constructor, mixins[i]); } } }, childContextTypes: function (Constructor, childContextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, childContextTypes, ReactPropTypeLocations.childContext); } Constructor.childContextTypes = _assign({}, Constructor.childContextTypes, childContextTypes); }, contextTypes: function (Constructor, contextTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, contextTypes, ReactPropTypeLocations.context); } Constructor.contextTypes = _assign({}, Constructor.contextTypes, contextTypes); }, /** * Special case getDefaultProps which should move into statics but requires * automatic merging. */ getDefaultProps: function (Constructor, getDefaultProps) { if (Constructor.getDefaultProps) { Constructor.getDefaultProps = createMergedResultFunction(Constructor.getDefaultProps, getDefaultProps); } else { Constructor.getDefaultProps = getDefaultProps; } }, propTypes: function (Constructor, propTypes) { if (process.env.NODE_ENV !== 'production') { validateTypeDef(Constructor, propTypes, ReactPropTypeLocations.prop); } Constructor.propTypes = _assign({}, Constructor.propTypes, propTypes); }, statics: function (Constructor, statics) { mixStaticSpecIntoComponent(Constructor, statics); }, autobind: function () {} }; // noop function validateTypeDef(Constructor, typeDef, location) { for (var propName in typeDef) { if (typeDef.hasOwnProperty(propName)) { // use a warning instead of an invariant so components // don't show up in prod but only in __DEV__ process.env.NODE_ENV !== 'production' ? warning(typeof typeDef[propName] === 'function', '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', Constructor.displayName || 'ReactClass', ReactPropTypeLocationNames[location], propName) : void 0; } } } function validateMethodOverride(isAlreadyDefined, name) { var specPolicy = ReactClassInterface.hasOwnProperty(name) ? ReactClassInterface[name] : null; // Disallow overriding of base class methods unless explicitly allowed. if (ReactClassMixin.hasOwnProperty(name)) { !(specPolicy === SpecPolicy.OVERRIDE_BASE) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to override ' + '`%s` from your class specification. Ensure that your method names ' + 'do not overlap with React methods.', name) : invariant(false) : void 0; } // Disallow defining methods more than once unless explicitly allowed. if (isAlreadyDefined) { !(specPolicy === SpecPolicy.DEFINE_MANY || specPolicy === SpecPolicy.DEFINE_MANY_MERGED) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClassInterface: You are attempting to define ' + '`%s` on your component more than once. This conflict may be due ' + 'to a mixin.', name) : invariant(false) : void 0; } } /** * Mixin helper which handles policy validation and reserved * specification keys when building React classes. */ function mixSpecIntoComponent(Constructor, spec) { if (!spec) { return; } !(typeof spec !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component class or function as a mixin. Instead, just use a ' + 'regular object.') : invariant(false) : void 0; !!ReactElement.isValidElement(spec) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You\'re attempting to ' + 'use a component as a mixin. Instead, just use a regular object.') : invariant(false) : void 0; var proto = Constructor.prototype; var autoBindPairs = proto.__reactAutoBindPairs; // By handling mixins before any other properties, we ensure the same // chaining order is applied to methods with DEFINE_MANY policy, whether // mixins are listed before or after these methods in the spec. if (spec.hasOwnProperty(MIXINS_KEY)) { RESERVED_SPEC_KEYS.mixins(Constructor, spec.mixins); } for (var name in spec) { if (!spec.hasOwnProperty(name)) { continue; } if (name === MIXINS_KEY) { // We have already handled mixins in a special case above. continue; } var property = spec[name]; var isAlreadyDefined = proto.hasOwnProperty(name); validateMethodOverride(isAlreadyDefined, name); if (RESERVED_SPEC_KEYS.hasOwnProperty(name)) { RESERVED_SPEC_KEYS[name](Constructor, property); } else { // Setup methods on prototype: // The following member methods should not be automatically bound: // 1. Expected ReactClass methods (in the "interface"). // 2. Overridden methods (that were mixed in). var isReactClassMethod = ReactClassInterface.hasOwnProperty(name); var isFunction = typeof property === 'function'; var shouldAutoBind = isFunction && !isReactClassMethod && !isAlreadyDefined && spec.autobind !== false; if (shouldAutoBind) { autoBindPairs.push(name, property); proto[name] = property; } else { if (isAlreadyDefined) { var specPolicy = ReactClassInterface[name]; // These cases should already be caught by validateMethodOverride. !(isReactClassMethod && (specPolicy === SpecPolicy.DEFINE_MANY_MERGED || specPolicy === SpecPolicy.DEFINE_MANY)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: Unexpected spec policy %s for key %s ' + 'when mixing in component specs.', specPolicy, name) : invariant(false) : void 0; // For methods which are defined more than once, call the existing // methods before calling the new property, merging if appropriate. if (specPolicy === SpecPolicy.DEFINE_MANY_MERGED) { proto[name] = createMergedResultFunction(proto[name], property); } else if (specPolicy === SpecPolicy.DEFINE_MANY) { proto[name] = createChainedFunction(proto[name], property); } } else { proto[name] = property; if (process.env.NODE_ENV !== 'production') { // Add verbose displayName to the function, which helps when looking // at profiling tools. if (typeof property === 'function' && spec.displayName) { proto[name].displayName = spec.displayName + '_' + name; } } } } } } } function mixStaticSpecIntoComponent(Constructor, statics) { if (!statics) { return; } for (var name in statics) { var property = statics[name]; if (!statics.hasOwnProperty(name)) { continue; } var isReserved = name in RESERVED_SPEC_KEYS; !!isReserved ? process.env.NODE_ENV !== 'production' ? invariant(false, '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.', name) : invariant(false) : void 0; var isInherited = name in Constructor; !!isInherited ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactClass: You are attempting to define ' + '`%s` on your component more than once. This conflict may be ' + 'due to a mixin.', name) : invariant(false) : void 0; Constructor[name] = property; } } /** * Merge two objects, but throw if both contain the same key. * * @param {object} one The first object, which is mutated. * @param {object} two The second object * @return {object} one after it has been mutated to contain everything in two. */ function mergeIntoWithNoDuplicateKeys(one, two) { !(one && two && typeof one === 'object' && typeof two === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mergeIntoWithNoDuplicateKeys(): Cannot merge non-objects.') : invariant(false) : void 0; for (var key in two) { if (two.hasOwnProperty(key)) { !(one[key] === undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, '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.', key) : invariant(false) : void 0; one[key] = two[key]; } } return one; } /** * Creates a function that invokes two functions and merges their return values. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createMergedResultFunction(one, two) { return function mergedResult() { var a = one.apply(this, arguments); var b = two.apply(this, arguments); if (a == null) { return b; } else if (b == null) { return a; } var c = {}; mergeIntoWithNoDuplicateKeys(c, a); mergeIntoWithNoDuplicateKeys(c, b); return c; }; } /** * Creates a function that invokes two functions and ignores their return vales. * * @param {function} one Function to invoke first. * @param {function} two Function to invoke second. * @return {function} Function that invokes the two argument functions. * @private */ function createChainedFunction(one, two) { return function chainedFunction() { one.apply(this, arguments); two.apply(this, arguments); }; } /** * Binds a method to the component. * * @param {object} component Component whose method is going to be bound. * @param {function} method Method to be bound. * @return {function} The bound method. */ function bindAutoBindMethod(component, method) { var boundMethod = method.bind(component); if (process.env.NODE_ENV !== 'production') { boundMethod.__reactBoundContext = component; boundMethod.__reactBoundMethod = method; boundMethod.__reactBoundArguments = null; var componentName = component.constructor.displayName; var _bind = boundMethod.bind; boundMethod.bind = function (newThis) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } // User is trying to bind() an autobound method; we effectively will // ignore the value of "this" that the user is trying to use, so // let's warn. if (newThis !== component && newThis !== null) { process.env.NODE_ENV !== 'production' ? warning(false, 'bind(): React component methods may only be bound to the ' + 'component instance. See %s', componentName) : void 0; } else if (!args.length) { process.env.NODE_ENV !== 'production' ? warning(false, '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', componentName) : void 0; return boundMethod; } var reboundMethod = _bind.apply(boundMethod, arguments); reboundMethod.__reactBoundContext = component; reboundMethod.__reactBoundMethod = method; reboundMethod.__reactBoundArguments = args; return reboundMethod; }; } return boundMethod; } /** * Binds all auto-bound methods in a component. * * @param {object} component Component whose method is going to be bound. */ function bindAutoBindMethods(component) { var pairs = component.__reactAutoBindPairs; for (var i = 0; i < pairs.length; i += 2) { var autoBindKey = pairs[i]; var method = pairs[i + 1]; component[autoBindKey] = bindAutoBindMethod(component, method); } } /** * Add more to the ReactClass base class. These are all legacy features and * therefore not already part of the modern ReactComponent. */ var ReactClassMixin = { /** * TODO: This will be deprecated because state should always keep a consistent * type signature and the only use case for this, is to avoid that. */ replaceState: function (newState, callback) { this.updater.enqueueReplaceState(this, newState); if (callback) { this.updater.enqueueCallback(this, callback, 'replaceState'); } }, /** * Checks whether or not this composite component is mounted. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function () { return this.updater.isMounted(this); } }; var ReactClassComponent = function () {}; _assign(ReactClassComponent.prototype, ReactComponent.prototype, ReactClassMixin); /** * Module for creating composite components. * * @class ReactClass */ var ReactClass = { /** * Creates a composite component class given a class specification. * * @param {object} spec Class specification (which must define `render`). * @return {function} Component constructor function. * @public */ createClass: function (spec) { var Constructor = function (props, context, updater) { // This constructor gets overridden by mocks. The argument is used // by mocks to assert on what gets mounted. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(this instanceof Constructor, 'Something is calling a React component directly. Use a factory or ' + 'JSX instead. See: https://fb.me/react-legacyfactory') : void 0; } // Wire up auto-binding if (this.__reactAutoBindPairs.length) { bindAutoBindMethods(this); } this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; this.state = null; // ReactClasses doesn't have constructors. Instead, they use the // getInitialState and componentWillMount methods for initialization. var initialState = this.getInitialState ? this.getInitialState() : null; if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (initialState === undefined && this.getInitialState._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. initialState = null; } } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getInitialState(): must return an object or null', Constructor.displayName || 'ReactCompositeComponent') : invariant(false) : void 0; this.state = initialState; }; Constructor.prototype = new ReactClassComponent(); Constructor.prototype.constructor = Constructor; Constructor.prototype.__reactAutoBindPairs = []; injectedMixins.forEach(mixSpecIntoComponent.bind(null, Constructor)); mixSpecIntoComponent(Constructor, spec); // Initialize the defaultProps property after all mixins have been merged. if (Constructor.getDefaultProps) { Constructor.defaultProps = Constructor.getDefaultProps(); } if (process.env.NODE_ENV !== 'production') { // This is a tag to indicate that the use of these method names is ok, // since it's used with createClass. If it's not, then it's likely a // mistake so we'll warn you to use the static property, property // initializer or constructor respectively. if (Constructor.getDefaultProps) { Constructor.getDefaultProps.isReactClassApproved = {}; } if (Constructor.prototype.getInitialState) { Constructor.prototype.getInitialState.isReactClassApproved = {}; } } !Constructor.prototype.render ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createClass(...): Class specification must implement a `render` method.') : invariant(false) : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!Constructor.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.', spec.displayName || 'A component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!Constructor.prototype.componentWillRecieveProps, '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', spec.displayName || 'A component') : void 0; } // Reduce time spent doing lookups by setting these on the prototype. for (var methodName in ReactClassInterface) { if (!Constructor.prototype[methodName]) { Constructor.prototype[methodName] = null; } } return Constructor; }, injection: { injectMixin: function (mixin) { injectedMixins.push(mixin); } } }; module.exports = ReactClass; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocations */ 'use strict'; var keyMirror = __webpack_require__(24); var ReactPropTypeLocations = keyMirror({ prop: null, context: null, childContext: null }); module.exports = ReactPropTypeLocations; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only */ 'use strict'; var invariant = __webpack_require__(7); /** * Constructs an enumeration with keys equal to their value. * * For example: * * var COLORS = keyMirror({blue: null, red: null}); * var myColor = COLORS.blue; * var isColorValid = !!COLORS[myColor]; * * The last line could not be performed if the values of the generated enum were * not equal to their keys. * * Input: {key1: val1, key2: val2} * Output: {key1: key1, key2: key2} * * @param {object} obj * @return {object} */ var keyMirror = function (obj) { var ret = {}; var key; !(obj instanceof Object && !Array.isArray(obj)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'keyMirror(...): Argument must be an object.') : invariant(false) : void 0; for (key in obj) { if (!obj.hasOwnProperty(key)) { continue; } ret[key] = key; } return ret; }; module.exports = keyMirror; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypeLocationNames */ 'use strict'; var ReactPropTypeLocationNames = {}; if (process.env.NODE_ENV !== 'production') { ReactPropTypeLocationNames = { prop: 'prop', context: 'context', childContext: 'child context' }; } module.exports = ReactPropTypeLocationNames; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 26 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /** * 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. */ var keyOf = function (oneKeyObj) { var key; for (key in oneKeyObj) { if (!oneKeyObj.hasOwnProperty(key)) { continue; } return key; } return null; }; module.exports = keyOf; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMFactories */ 'use strict'; var ReactElement = __webpack_require__(8); var ReactElementValidator = __webpack_require__(28); var mapObject = __webpack_require__(29); /** * Create a factory that creates HTML tag elements. * * @param {string} tag Tag name (e.g. `div`). * @private */ function createDOMFactory(tag) { if (process.env.NODE_ENV !== 'production') { return ReactElementValidator.createFactory(tag); } return ReactElement.createFactory(tag); } /** * Creates a mapping from supported HTML tags to `ReactDOMComponent` classes. * This is also accessible via `React.DOM`. * * @public */ var ReactDOMFactories = mapObject({ a: 'a', abbr: 'abbr', address: 'address', area: 'area', article: 'article', aside: 'aside', audio: 'audio', b: 'b', base: 'base', bdi: 'bdi', bdo: 'bdo', big: 'big', blockquote: 'blockquote', body: 'body', br: 'br', button: 'button', canvas: 'canvas', caption: 'caption', cite: 'cite', code: 'code', col: 'col', colgroup: 'colgroup', data: 'data', datalist: 'datalist', dd: 'dd', del: 'del', details: 'details', dfn: 'dfn', dialog: 'dialog', div: 'div', dl: 'dl', dt: 'dt', em: 'em', embed: 'embed', fieldset: 'fieldset', figcaption: 'figcaption', figure: 'figure', footer: 'footer', form: 'form', h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', head: 'head', header: 'header', 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', // SVG 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' }, createDOMFactory); module.exports = ReactDOMFactories; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactElementValidator */ /** * ReactElementValidator provides a wrapper around a element factory * which validates the props passed to the element. This is intended to be * used only in DEV and could be replaced by a static type checker for languages * that support it. */ 'use strict'; var ReactElement = __webpack_require__(8); var ReactPropTypeLocations = __webpack_require__(23); var ReactPropTypeLocationNames = __webpack_require__(25); var ReactCurrentOwner = __webpack_require__(9); var canDefineProperty = __webpack_require__(12); var getIteratorFn = __webpack_require__(14); var invariant = __webpack_require__(7); var warning = __webpack_require__(10); function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = ReactCurrentOwner.current.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Warn if there's no key explicitly set on dynamic arrays of children or * object keys are not valid. This allows us to keep track of children between * updates. */ var ownerHasKeyUseWarning = {}; var loggedTypeFailures = {}; /** * Warn if the element doesn't have an explicit key assigned to it. * This element is in an array. The array could grow and shrink or be * reordered. All children that haven't already been validated are required to * have a "key" property assigned to it. * * @internal * @param {ReactElement} element Element that requires a key. * @param {*} parentType element's parent's type. */ function validateExplicitKey(element, parentType) { if (!element._store || element._store.validated || element.key != null) { return; } element._store.validated = true; var addenda = getAddendaForKeyUse('uniqueKey', element, parentType); if (addenda === null) { // we already showed the warning return; } process.env.NODE_ENV !== 'production' ? warning(false, 'Each child in an array or iterator should have a unique "key" prop.' + '%s%s%s', addenda.parentOrOwner || '', addenda.childOwner || '', addenda.url || '') : void 0; } /** * Shared warning and monitoring code for the key warnings. * * @internal * @param {string} messageType A key used for de-duping warnings. * @param {ReactElement} element Component that requires a key. * @param {*} parentType element's parent's type. * @returns {?object} A set of addenda to use in the warning message, or null * if the warning has already been shown before (and shouldn't be shown again). */ function getAddendaForKeyUse(messageType, element, parentType) { var addendum = getDeclarationErrorAddendum(); if (!addendum) { var parentName = typeof parentType === 'string' ? parentType : parentType.displayName || parentType.name; if (parentName) { addendum = ' Check the top-level render call using <' + parentName + '>.'; } } var memoizer = ownerHasKeyUseWarning[messageType] || (ownerHasKeyUseWarning[messageType] = {}); if (memoizer[addendum]) { return null; } memoizer[addendum] = true; var addenda = { parentOrOwner: addendum, url: ' See https://fb.me/react-warning-keys for more information.', childOwner: null }; // Usually the current owner is the offender, but if it accepts children as a // property, it may be the creator of the child that's responsible for // assigning it a key. if (element && element._owner && element._owner !== ReactCurrentOwner.current) { // Give the component that originally created this child. addenda.childOwner = ' It was passed a child from ' + element._owner.getName() + '.'; } return addenda; } /** * Ensure that every element either is passed in a static location, in an * array with an explicit keys property defined, or in an object literal * with valid key property. * * @internal * @param {ReactNode} node Statically passed child of any type. * @param {*} parentType node's parent's type. */ function validateChildKeys(node, parentType) { if (typeof node !== 'object') { return; } if (Array.isArray(node)) { for (var i = 0; i < node.length; i++) { var child = node[i]; if (ReactElement.isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (ReactElement.isValidElement(node)) { // This element was passed in a valid location. if (node._store) { node._store.validated = true; } } else if (node) { var iteratorFn = getIteratorFn(node); // Entry iterators provide implicit keys. if (iteratorFn) { if (iteratorFn !== node.entries) { var iterator = iteratorFn.call(node); var step; while (!(step = iterator.next()).done) { if (ReactElement.isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } /** * Assert that the props are valid * * @param {string} componentName Name of the component for error messages. * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ function checkPropTypes(componentName, propTypes, props, location) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; // Prop type validation may throw. In case they do, we don't want to // fail the render phase where it didn't fail before. So we log it. // After these have been cleaned up, we'll let them throw. try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually from ' + 'React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : void 0; error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } process.env.NODE_ENV !== 'production' ? warning(!error || error 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).', componentName || 'React class', ReactPropTypeLocationNames[location], propName, typeof error) : void 0; if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(); process.env.NODE_ENV !== 'production' ? warning(false, 'Failed propType: %s%s', error.message, addendum) : void 0; } } } } /** * Given an element, validate that its props follow the propTypes definition, * provided by the type. * * @param {ReactElement} element */ function validatePropTypes(element) { var componentClass = element.type; if (typeof componentClass !== 'function') { return; } var name = componentClass.displayName || componentClass.name; if (componentClass.propTypes) { checkPropTypes(name, componentClass.propTypes, element.props, ReactPropTypeLocations.prop); } if (typeof componentClass.getDefaultProps === 'function') { process.env.NODE_ENV !== 'production' ? warning(componentClass.getDefaultProps.isReactClassApproved, 'getDefaultProps is only used on classic React.createClass ' + 'definitions. Use a static property named `defaultProps` instead.') : void 0; } } var ReactElementValidator = { createElement: function (type, props, children) { var validType = typeof type === 'string' || typeof type === 'function'; // We warn in this case but don't throw. We expect the element creation to // succeed and there will likely be errors in render. process.env.NODE_ENV !== 'production' ? warning(validType, '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', getDeclarationErrorAddendum()) : void 0; var element = ReactElement.createElement.apply(this, arguments); // The result can be nullish if a mock or a custom function is used. // TODO: Drop this when these are no longer allowed as the type argument. if (element == null) { return element; } // Skip key warning if the type isn't valid since our key validation logic // doesn't expect a non-string/function type and can throw confusing errors. // We don't want exception behavior to differ between dev and prod. // (Rendering will throw with a helpful message and as soon as the type is // fixed, the key warnings will appear.) if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type); } } validatePropTypes(element); return element; }, createFactory: function (type) { var validatedFactory = ReactElementValidator.createElement.bind(null, type); // Legacy hook TODO: Warn if this is accessed validatedFactory.type = type; if (process.env.NODE_ENV !== 'production') { if (canDefineProperty) { Object.defineProperty(validatedFactory, 'type', { enumerable: false, get: function () { process.env.NODE_ENV !== 'production' ? warning(false, 'Factory.type is deprecated. Access the class directly ' + 'before passing it to createFactory.') : void 0; Object.defineProperty(this, 'type', { value: type }); return type; } }); } } return validatedFactory; }, cloneElement: function (element, props, children) { var newElement = ReactElement.cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } }; module.exports = ReactElementValidator; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 29 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Executes the provided `callback` once for each enumerable own property in the * object and constructs a new object from the results. The `callback` is * invoked with three arguments: * * - the property value * - the property name * - the object being traversed * * Properties that are added after the call to `mapObject` will not be visited * by `callback`. If the values of existing properties are changed, the value * passed to `callback` will be the value at the time `mapObject` visits them. * Properties that are deleted before being visited are not visited. * * @grep function objectMap() * @grep function objMap() * * @param {?object} object * @param {function} callback * @param {*} context * @return {?object} */ function mapObject(object, callback, context) { if (!object) { return null; } var result = {}; for (var name in object) { if (hasOwnProperty.call(object, name)) { result[name] = callback.call(context, object[name], name, object); } } return result; } module.exports = mapObject; /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTypes */ 'use strict'; var ReactElement = __webpack_require__(8); var ReactPropTypeLocationNames = __webpack_require__(25); var emptyFunction = __webpack_require__(11); var getIteratorFn = __webpack_require__(14); /** * Collection of methods that allow declaration and validation of props that are * supplied to React components. Example usage: * * var Props = require('ReactPropTypes'); * var MyArticle = React.createClass({ * propTypes: { * // An optional string prop named "description". * description: Props.string, * * // A required enum prop named "category". * category: Props.oneOf(['News','Photos']).isRequired, * * // A prop named "dialog" that requires an instance of Dialog. * dialog: Props.instanceOf(Dialog).isRequired * }, * render: function() { ... } * }); * * A more formal specification of how these methods are used: * * type := array|bool|func|object|number|string|oneOf([...])|instanceOf(...) * decl := ReactPropTypes.{type}(.isRequired)? * * Each and every declaration produces a function with the same signature. This * allows the creation of custom validation functions. For example: * * var MyLink = React.createClass({ * propTypes: { * // An optional string or URI prop named "href". * href: function(props, propName, componentName) { * var propValue = props[propName]; * if (propValue != null && typeof propValue !== 'string' && * !(propValue instanceof URI)) { * return new Error( * 'Expected a string or an URI for ' + propName + ' in ' + * componentName * ); * } * } * }, * render: function() {...} * }); * * @internal */ var ANONYMOUS = '<<anonymous>>'; var ReactPropTypes = { array: createPrimitiveTypeChecker('array'), bool: createPrimitiveTypeChecker('boolean'), func: createPrimitiveTypeChecker('function'), number: createPrimitiveTypeChecker('number'), object: createPrimitiveTypeChecker('object'), string: createPrimitiveTypeChecker('string'), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker }; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ /*eslint-disable no-self-compare*/ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /*eslint-enable no-self-compare*/ function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location, propFullName) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (props[propName] == null) { var locationName = ReactPropTypeLocationNames[location]; if (isRequired) { return new Error('Required ' + locationName + ' `' + propFullName + '` was not specified in ' + ('`' + componentName + '`.')); } return null; } else { return validate(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var locationName = ReactPropTypeLocationNames[location]; // `propValue` being instance of, say, date/regexp, pass the 'object' // check, but we can offer a more precise error message here rather than // 'of type `object`'. var preciseType = getPreciseType(propValue); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + preciseType + '` supplied to `' + componentName + '`, expected ') + ('`' + expectedType + '`.')); } return null; } return createChainableTypeChecker(validate); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunction.thatReturns(null)); } function createArrayOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new Error('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside arrayOf.'); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var locationName = ReactPropTypeLocationNames[location]; var propType = getPropType(propValue); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an array.')); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + '[' + i + ']'); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate); } function createElementTypeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!ReactElement.isValidElement(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a single ReactElement.')); } return null; } return createChainableTypeChecker(validate); } function createInstanceTypeChecker(expectedClass) { function validate(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var locationName = ReactPropTypeLocationNames[location]; var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + actualClassName + '` supplied to `' + componentName + '`, expected ') + ('instance of `' + expectedClassName + '`.')); } return null; } return createChainableTypeChecker(validate); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { return createChainableTypeChecker(function () { return new Error('Invalid argument supplied to oneOf, expected an instance of array.'); }); } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is(propValue, expectedValues[i])) { return null; } } var locationName = ReactPropTypeLocationNames[location]; var valuesString = JSON.stringify(expectedValues); return new Error('Invalid ' + locationName + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected one of ' + valuesString + '.')); } return createChainableTypeChecker(validate); } function createObjectOfTypeChecker(typeChecker) { function validate(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== 'function') { return new Error('Property `' + propFullName + '` of component `' + componentName + '` has invalid PropType notation inside objectOf.'); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type ' + ('`' + propType + '` supplied to `' + componentName + '`, expected an object.')); } for (var key in propValue) { if (propValue.hasOwnProperty(key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + '.' + key); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { return createChainableTypeChecker(function () { return new Error('Invalid argument supplied to oneOfType, expected an instance of array.'); }); } function validate(props, propName, componentName, location, propFullName) { for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (checker(props, propName, componentName, location, propFullName) == null) { return null; } } var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`.')); } return createChainableTypeChecker(validate); } function createNodeChecker() { function validate(props, propName, componentName, location, propFullName) { if (!isNode(props[propName])) { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` supplied to ' + ('`' + componentName + '`, expected a ReactNode.')); } return null; } return createChainableTypeChecker(validate); } function createShapeTypeChecker(shapeTypes) { function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== 'object') { var locationName = ReactPropTypeLocationNames[location]; return new Error('Invalid ' + locationName + ' `' + propFullName + '` of type `' + propType + '` ' + ('supplied to `' + componentName + '`, expected `object`.')); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (!checker) { continue; } var error = checker(propValue, key, componentName, location, propFullName + '.' + key); if (error) { return error; } } return null; } return createChainableTypeChecker(validate); } function isNode(propValue) { switch (typeof propValue) { case 'number': case 'string': case 'undefined': return true; case 'boolean': return !propValue; case 'object': if (Array.isArray(propValue)) { return propValue.every(isNode); } if (propValue === null || ReactElement.isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode(step.value)) { return false; } } } else { // Iterator will provide entry [k,v] tuples rather than values. while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } // Equivalent of `typeof` but with special handling for array and regexp. function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return 'array'; } if (propValue instanceof RegExp) { // Old webkits (at least until Android 4.0) return 'function' rather than // 'object' for typeof a RegExp. We'll normalize this here so that /bla/ // passes PropTypes.object. return 'object'; } return propType; } // This handles more types than `getPropType`. Only used for error messages. // See `createPrimitiveTypeChecker`. function getPreciseType(propValue) { var propType = getPropType(propValue); if (propType === 'object') { if (propValue instanceof Date) { return 'date'; } else if (propValue instanceof RegExp) { return 'regexp'; } } return propType; } // Returns class name of the object, if any. function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } module.exports = ReactPropTypes; /***/ }, /* 31 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactVersion */ 'use strict'; module.exports = '15.0.2'; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule onlyChild */ 'use strict'; var ReactElement = __webpack_require__(8); var invariant = __webpack_require__(7); /** * Returns the first child in a collection of children and verifies that there * is only one child in the collection. The current implementation of this * function assumes that a single child gets passed without a wrapper, but the * purpose of this helper function is to abstract away the particular structure * of children. * * @param {?object} children Child collection structure. * @return {ReactElement} The first and only `ReactElement` contained in the * structure. */ function onlyChild(children) { !ReactElement.isValidElement(children) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'onlyChild must be passed a children with exactly one child.') : invariant(false) : void 0; return children; } module.exports = onlyChild; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = __webpack_require__(34); /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOM */ /* globals __REACT_DEVTOOLS_GLOBAL_HOOK__*/ 'use strict'; var ReactDOMComponentTree = __webpack_require__(35); var ReactDefaultInjection = __webpack_require__(38); var ReactMount = __webpack_require__(158); var ReactPerf = __webpack_require__(58); var ReactReconciler = __webpack_require__(59); var ReactUpdates = __webpack_require__(55); var ReactVersion = __webpack_require__(31); var findDOMNode = __webpack_require__(165); var getNativeComponentFromComposite = __webpack_require__(166); var renderSubtreeIntoContainer = __webpack_require__(167); var warning = __webpack_require__(10); ReactDefaultInjection.inject(); var render = ReactPerf.measure('React', 'render', ReactMount.render); var React = { findDOMNode: findDOMNode, render: render, unmountComponentAtNode: ReactMount.unmountComponentAtNode, version: ReactVersion, /* eslint-disable camelcase */ unstable_batchedUpdates: ReactUpdates.batchedUpdates, unstable_renderSubtreeIntoContainer: renderSubtreeIntoContainer }; // Inject the runtime into a devtools global hook regardless of browser. // Allows for debugging when the hook is injected on the page. /* eslint-enable camelcase */ if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') { __REACT_DEVTOOLS_GLOBAL_HOOK__.inject({ ComponentTree: { getClosestInstanceFromNode: ReactDOMComponentTree.getClosestInstanceFromNode, getNodeFromInstance: function (inst) { // inst is an internal instance (but could be a composite) if (inst._renderedComponent) { inst = getNativeComponentFromComposite(inst); } if (inst) { return ReactDOMComponentTree.getNodeFromInstance(inst); } else { return null; } } }, Mount: ReactMount, Reconciler: ReactReconciler }); } if (process.env.NODE_ENV !== 'production') { var ExecutionEnvironment = __webpack_require__(48); if (ExecutionEnvironment.canUseDOM && window.top === window.self) { // First check if devtools is not installed if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') { // If we're in Chrome or Firefox, provide a download link if not installed. if (navigator.userAgent.indexOf('Chrome') > -1 && navigator.userAgent.indexOf('Edge') === -1 || navigator.userAgent.indexOf('Firefox') > -1) { // Firefox does not have the issue with devtools loaded over file:// var showFileUrlMessage = window.location.protocol.indexOf('http') === -1 && navigator.userAgent.indexOf('Firefox') === -1; console.debug('Download the React DevTools ' + (showFileUrlMessage ? 'and use an HTTP server (instead of a file: URL) ' : '') + 'for a better development experience: ' + 'https://fb.me/react-devtools'); } } var testFunc = function testFn() {}; process.env.NODE_ENV !== 'production' ? warning((testFunc.name || testFunc.toString()).indexOf('testFn') !== -1, 'It looks like you\'re using a minified copy of the development build ' + 'of React. When deploying React apps to production, make sure to use ' + 'the production build which skips development warnings and is faster. ' + 'See https://fb.me/react-minification for more details.') : void 0; // If we're in IE8, check to see if we are in compatibility mode and provide // information on preventing compatibility mode var ieCompatibilityMode = document.documentMode && document.documentMode < 8; process.env.NODE_ENV !== 'production' ? warning(!ieCompatibilityMode, '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; var expectedFeatures = [ // shims Array.isArray, Array.prototype.every, Array.prototype.forEach, Array.prototype.indexOf, Array.prototype.map, Date.now, Function.prototype.bind, Object.keys, String.prototype.split, String.prototype.trim]; for (var i = 0; i < expectedFeatures.length; i++) { if (!expectedFeatures[i]) { process.env.NODE_ENV !== 'production' ? warning(false, 'One or more ES5 shims expected by React are not available: ' + 'https://fb.me/react-warning-polyfills') : void 0; break; } } } } module.exports = React; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 35 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponentTree */ 'use strict'; var DOMProperty = __webpack_require__(36); var ReactDOMComponentFlags = __webpack_require__(37); var invariant = __webpack_require__(7); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var Flags = ReactDOMComponentFlags; var internalInstanceKey = '__reactInternalInstance$' + Math.random().toString(36).slice(2); /** * Drill down (through composites and empty components) until we get a native or * native text component. * * This is pretty polymorphic but unavoidable with the current structure we have * for `_renderedChildren`. */ function getRenderedNativeOrTextFromComponent(component) { var rendered; while (rendered = component._renderedComponent) { component = rendered; } return component; } /** * Populate `_nativeNode` on the rendered native/text component with the given * DOM node. The passed `inst` can be a composite. */ function precacheNode(inst, node) { var nativeInst = getRenderedNativeOrTextFromComponent(inst); nativeInst._nativeNode = node; node[internalInstanceKey] = nativeInst; } function uncacheNode(inst) { var node = inst._nativeNode; if (node) { delete node[internalInstanceKey]; inst._nativeNode = null; } } /** * Populate `_nativeNode` on each child of `inst`, assuming that the children * match up with the DOM (element) children of `node`. * * We cache entire levels at once to avoid an n^2 problem where we access the * children of a node sequentially and have to walk from the start to our target * node every time. * * Since we update `_renderedChildren` and the actual DOM at (slightly) * different times, we could race here and see a newer `_renderedChildren` than * the DOM nodes we see. To avoid this, ReactMultiChild calls * `prepareToManageChildren` before we change `_renderedChildren`, at which * time the container's child nodes are always cached (until it unmounts). */ function precacheChildNodes(inst, node) { if (inst._flags & Flags.hasCachedChildNodes) { return; } var children = inst._renderedChildren; var childNode = node.firstChild; outer: for (var name in children) { if (!children.hasOwnProperty(name)) { continue; } var childInst = children[name]; var childID = getRenderedNativeOrTextFromComponent(childInst)._domID; if (childID == null) { // We're currently unmounting this child in ReactMultiChild; skip it. continue; } // We assume the child nodes are in the same order as the child instances. for (; childNode !== null; childNode = childNode.nextSibling) { if (childNode.nodeType === 1 && childNode.getAttribute(ATTR_NAME) === String(childID) || childNode.nodeType === 8 && childNode.nodeValue === ' react-text: ' + childID + ' ' || childNode.nodeType === 8 && childNode.nodeValue === ' react-empty: ' + childID + ' ') { precacheNode(childInst, childNode); continue outer; } } // We reached the end of the DOM children without finding an ID match. true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unable to find element with ID %s.', childID) : invariant(false) : void 0; } inst._flags |= Flags.hasCachedChildNodes; } /** * Given a DOM node, return the closest ReactDOMComponent or * ReactDOMTextComponent instance ancestor. */ function getClosestInstanceFromNode(node) { if (node[internalInstanceKey]) { return node[internalInstanceKey]; } // Walk up the tree until we find an ancestor whose instance we have cached. var parents = []; while (!node[internalInstanceKey]) { parents.push(node); if (node.parentNode) { node = node.parentNode; } else { // Top of the tree. This node must not be part of a React tree (or is // unmounted, potentially). return null; } } var closest; var inst; for (; node && (inst = node[internalInstanceKey]); node = parents.pop()) { closest = inst; if (parents.length) { precacheChildNodes(inst, node); } } return closest; } /** * Given a DOM node, return the ReactDOMComponent or ReactDOMTextComponent * instance, or null if the node was not rendered by this React. */ function getInstanceFromNode(node) { var inst = getClosestInstanceFromNode(node); if (inst != null && inst._nativeNode === node) { return inst; } else { return null; } } /** * Given a ReactDOMComponent or ReactDOMTextComponent, return the corresponding * DOM node. */ function getNodeFromInstance(inst) { // Without this first invariant, passing a non-DOM-component triggers the next // invariant for a missing parent, which is super confusing. !(inst._nativeNode !== undefined) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : invariant(false) : void 0; if (inst._nativeNode) { return inst._nativeNode; } // Walk up the tree until we find an ancestor whose DOM node we have cached. var parents = []; while (!inst._nativeNode) { parents.push(inst); !inst._nativeParent ? process.env.NODE_ENV !== 'production' ? invariant(false, 'React DOM tree root should always have a node reference.') : invariant(false) : void 0; inst = inst._nativeParent; } // Now parents contains each ancestor that does *not* have a cached native // node, and `inst` is the deepest ancestor that does. for (; parents.length; inst = parents.pop()) { precacheChildNodes(inst, inst._nativeNode); } return inst._nativeNode; } var ReactDOMComponentTree = { getClosestInstanceFromNode: getClosestInstanceFromNode, getInstanceFromNode: getInstanceFromNode, getNodeFromInstance: getNodeFromInstance, precacheChildNodes: precacheChildNodes, precacheNode: precacheNode, uncacheNode: uncacheNode }; module.exports = ReactDOMComponentTree; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMProperty */ 'use strict'; var invariant = __webpack_require__(7); 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_PROPERTY: 0x1, HAS_SIDE_EFFECTS: 0x2, HAS_BOOLEAN_VALUE: 0x4, HAS_NUMERIC_VALUE: 0x8, HAS_POSITIVE_NUMERIC_VALUE: 0x10 | 0x8, HAS_OVERLOADED_BOOLEAN_VALUE: 0x20, /** * 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. * * DOMAttributeNamespaces: object mapping React attribute name to the DOM * attribute namespace URL. (Attribute names not specified use no namespace.) * * 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 Injection = DOMPropertyInjection; var Properties = domPropertyConfig.Properties || {}; var DOMAttributeNamespaces = domPropertyConfig.DOMAttributeNamespaces || {}; 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) { !!DOMProperty.properties.hasOwnProperty(propName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'injectDOMPropertyConfig(...): You\'re trying to inject DOM property ' + '\'%s\' which has already been injected. You may be accidentally ' + 'injecting the same DOM property config twice, or you may be ' + 'injecting two configs that have conflicting property names.', propName) : invariant(false) : void 0; var lowerCased = propName.toLowerCase(); var propConfig = Properties[propName]; var propertyInfo = { attributeName: lowerCased, attributeNamespace: null, propertyName: propName, mutationMethod: null, mustUseProperty: checkMask(propConfig, Injection.MUST_USE_PROPERTY), hasSideEffects: checkMask(propConfig, Injection.HAS_SIDE_EFFECTS), hasBooleanValue: checkMask(propConfig, Injection.HAS_BOOLEAN_VALUE), hasNumericValue: checkMask(propConfig, Injection.HAS_NUMERIC_VALUE), hasPositiveNumericValue: checkMask(propConfig, Injection.HAS_POSITIVE_NUMERIC_VALUE), hasOverloadedBooleanValue: checkMask(propConfig, Injection.HAS_OVERLOADED_BOOLEAN_VALUE) }; !(propertyInfo.mustUseProperty || !propertyInfo.hasSideEffects) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Properties that have side effects must use property: %s', propName) : invariant(false) : void 0; !(propertyInfo.hasBooleanValue + propertyInfo.hasNumericValue + propertyInfo.hasOverloadedBooleanValue <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'DOMProperty: Value can be one of boolean, overloaded boolean, or ' + 'numeric value, but not a combination: %s', propName) : invariant(false) : void 0; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[lowerCased] = propName; } if (DOMAttributeNames.hasOwnProperty(propName)) { var attributeName = DOMAttributeNames[propName]; propertyInfo.attributeName = attributeName; if (process.env.NODE_ENV !== 'production') { DOMProperty.getPossibleStandardName[attributeName] = propName; } } if (DOMAttributeNamespaces.hasOwnProperty(propName)) { propertyInfo.attributeNamespace = DOMAttributeNamespaces[propName]; } if (DOMPropertyNames.hasOwnProperty(propName)) { propertyInfo.propertyName = DOMPropertyNames[propName]; } if (DOMMutationMethods.hasOwnProperty(propName)) { propertyInfo.mutationMethod = DOMMutationMethods[propName]; } DOMProperty.properties[propName] = propertyInfo; } } }; /* eslint-disable max-len */ var ATTRIBUTE_NAME_START_CHAR = ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD'; /* eslint-enable max-len */ /** * 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', ROOT_ATTRIBUTE_NAME: 'data-reactroot', ATTRIBUTE_NAME_START_CHAR: ATTRIBUTE_NAME_START_CHAR, ATTRIBUTE_NAME_CHAR: ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\uB7\\u0300-\\u036F\\u203F-\\u2040', /** * Map from property "standard name" to an object with info about how to set * the property in the DOM. Each object contains: * * attributeName: * Used when rendering markup or with `*Attribute()`. * attributeNamespace * propertyName: * Used on DOM node instances. (This includes properties that mutate due to * external factors.) * mutationMethod: * If non-null, used instead of the property or `setAttribute()` after * initial render. * mustUseProperty: * Whether the property must be accessed and mutated as an object property. * hasSideEffects: * Whether or not setting a value causes side effects such as triggering * resources to be loaded or text selection changes. If true, we read from * the DOM before updating to ensure that the value is only set if it has * changed. * hasBooleanValue: * Whether the property should be removed when set to a falsey value. * hasNumericValue: * Whether the property must be numeric or parse as a numeric and should be * removed when set to a falsey value. * hasPositiveNumericValue: * Whether the property must be positive numeric or parse as a positive * numeric and should be removed when set to a falsey value. * hasOverloadedBooleanValue: * 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. */ properties: {}, /** * Mapping from lowercase property names to the properly cased version, used * to warn in the case of missing properties. Available only in __DEV__. * @type {Object} */ getPossibleStandardName: process.env.NODE_ENV !== 'production' ? {} : null, /** * 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; }, injection: DOMPropertyInjection }; module.exports = DOMProperty; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 37 */ /***/ function(module, exports) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponentFlags */ 'use strict'; var ReactDOMComponentFlags = { hasCachedChildNodes: 1 << 0 }; module.exports = ReactDOMComponentFlags; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultInjection */ 'use strict'; var BeforeInputEventPlugin = __webpack_require__(39); var ChangeEventPlugin = __webpack_require__(54); var DefaultEventPluginOrder = __webpack_require__(66); var EnterLeaveEventPlugin = __webpack_require__(67); var ExecutionEnvironment = __webpack_require__(48); var HTMLDOMPropertyConfig = __webpack_require__(72); var ReactComponentBrowserEnvironment = __webpack_require__(73); var ReactDOMComponent = __webpack_require__(86); var ReactDOMComponentTree = __webpack_require__(35); var ReactDOMEmptyComponent = __webpack_require__(127); var ReactDOMTreeTraversal = __webpack_require__(128); var ReactDOMTextComponent = __webpack_require__(129); var ReactDefaultBatchingStrategy = __webpack_require__(130); var ReactEventListener = __webpack_require__(131); var ReactInjection = __webpack_require__(134); var ReactReconcileTransaction = __webpack_require__(135); var SVGDOMPropertyConfig = __webpack_require__(143); var SelectEventPlugin = __webpack_require__(144); var SimpleEventPlugin = __webpack_require__(145); var alreadyInjected = false; function inject() { if (alreadyInjected) { // TODO: This is currently true because these injections are shared between // the client and the server package. They should be built independently // and not share any injection state. Then this problem will be solved. return; } alreadyInjected = true; ReactInjection.EventEmitter.injectReactEventListener(ReactEventListener); /** * Inject modules for resolving DOM hierarchy and plugin ordering. */ ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder); ReactInjection.EventPluginUtils.injectComponentTree(ReactDOMComponentTree); ReactInjection.EventPluginUtils.injectTreeTraversal(ReactDOMTreeTraversal); /** * Some important event plugins included by default (without having to require * them). */ ReactInjection.EventPluginHub.injectEventPluginsByName({ SimpleEventPlugin: SimpleEventPlugin, EnterLeaveEventPlugin: EnterLeaveEventPlugin, ChangeEventPlugin: ChangeEventPlugin, SelectEventPlugin: SelectEventPlugin, BeforeInputEventPlugin: BeforeInputEventPlugin }); ReactInjection.NativeComponent.injectGenericComponentClass(ReactDOMComponent); ReactInjection.NativeComponent.injectTextComponentClass(ReactDOMTextComponent); ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig); ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig); ReactInjection.EmptyComponent.injectEmptyComponentFactory(function (instantiate) { return new ReactDOMEmptyComponent(instantiate); }); ReactInjection.Updates.injectReconcileTransaction(ReactReconcileTransaction); ReactInjection.Updates.injectBatchingStrategy(ReactDefaultBatchingStrategy); ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment); if (process.env.NODE_ENV !== 'production') { var url = ExecutionEnvironment.canUseDOM && window.location.href || ''; if (/[?&]react_perf\b/.test(url)) { var ReactDefaultPerf = __webpack_require__(156); ReactDefaultPerf.start(); } } } module.exports = { inject: inject }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule BeforeInputEventPlugin */ 'use strict'; var EventConstants = __webpack_require__(40); var EventPropagators = __webpack_require__(41); var ExecutionEnvironment = __webpack_require__(48); var FallbackCompositionState = __webpack_require__(49); var SyntheticCompositionEvent = __webpack_require__(51); var SyntheticInputEvent = __webpack_require__(53); var keyOf = __webpack_require__(26); var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space var START_KEYCODE = 229; var canUseCompositionEvent = ExecutionEnvironment.canUseDOM && 'CompositionEvent' in window; var documentMode = null; if (ExecutionEnvironment.canUseDOM && 'documentMode' in document) { documentMode = document.documentMode; } // Webkit offers a very useful `textInput` event that can be used to // directly represent `beforeInput`. The IE `textinput` event is not as // useful, so we don't use it. var canUseTextInputEvent = ExecutionEnvironment.canUseDOM && 'TextEvent' in window && !documentMode && !isPresto(); // In IE9+, we have access to composition events, but the data supplied // by the native compositionend event may be incorrect. Japanese ideographic // spaces, for instance (\u3000) are not recorded correctly. var useFallbackCompositionData = ExecutionEnvironment.canUseDOM && (!canUseCompositionEvent || documentMode && documentMode > 8 && documentMode <= 11); /** * Opera <= 12 includes TextEvent in window, but does not fire * text input events. Rely on keypress instead. */ function isPresto() { var opera = window.opera; return typeof opera === 'object' && typeof opera.version === 'function' && parseInt(opera.version(), 10) <= 12; } var SPACEBAR_CODE = 32; var SPACEBAR_CHAR = String.fromCharCode(SPACEBAR_CODE); var topLevelTypes = EventConstants.topLevelTypes; // Events and their corresponding property names. var eventTypes = { beforeInput: { phasedRegistrationNames: { bubbled: keyOf({ onBeforeInput: null }), captured: keyOf({ onBeforeInputCapture: null }) }, dependencies: [topLevelTypes.topCompositionEnd, topLevelTypes.topKeyPress, topLevelTypes.topTextInput, topLevelTypes.topPaste] }, compositionEnd: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionEnd: null }), captured: keyOf({ onCompositionEndCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionEnd, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] }, compositionStart: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionStart: null }), captured: keyOf({ onCompositionStartCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionStart, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] }, compositionUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onCompositionUpdate: null }), captured: keyOf({ onCompositionUpdateCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topCompositionUpdate, topLevelTypes.topKeyDown, topLevelTypes.topKeyPress, topLevelTypes.topKeyUp, topLevelTypes.topMouseDown] } }; // Track whether we've ever handled a keypress on the space key. var hasSpaceKeypress = false; /** * Return whether a native keypress event is assumed to be a command. * This is required because Firefox fires `keypress` events for key commands * (cut, copy, select-all, etc.) even though no character is inserted. */ function isKeypressCommand(nativeEvent) { return (nativeEvent.ctrlKey || nativeEvent.altKey || nativeEvent.metaKey) && // ctrlKey && altKey is equivalent to AltGr, and is not a command. !(nativeEvent.ctrlKey && nativeEvent.altKey); } /** * Translate native top level events into event types. * * @param {string} topLevelType * @return {object} */ function getCompositionEventType(topLevelType) { switch (topLevelType) { case topLevelTypes.topCompositionStart: return eventTypes.compositionStart; case topLevelTypes.topCompositionEnd: return eventTypes.compositionEnd; case topLevelTypes.topCompositionUpdate: return eventTypes.compositionUpdate; } } /** * Does our fallback best-guess model think this event signifies that * composition has begun? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionStart(topLevelType, nativeEvent) { return topLevelType === topLevelTypes.topKeyDown && nativeEvent.keyCode === START_KEYCODE; } /** * Does our fallback mode think that this event is the end of composition? * * @param {string} topLevelType * @param {object} nativeEvent * @return {boolean} */ function isFallbackCompositionEnd(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topKeyUp: // Command keys insert or clear IME input. return END_KEYCODES.indexOf(nativeEvent.keyCode) !== -1; case topLevelTypes.topKeyDown: // Expect IME keyCode on each keydown. If we get any other // code we must have exited earlier. return nativeEvent.keyCode !== START_KEYCODE; case topLevelTypes.topKeyPress: case topLevelTypes.topMouseDown: case topLevelTypes.topBlur: // Events are not possible without cancelling IME. return true; default: return false; } } /** * Google Input Tools provides composition data via a CustomEvent, * with the `data` property populated in the `detail` object. If this * is available on the event object, use it. If not, this is a plain * composition event and we have nothing special to extract. * * @param {object} nativeEvent * @return {?string} */ function getDataFromCustomEvent(nativeEvent) { var detail = nativeEvent.detail; if (typeof detail === 'object' && 'data' in detail) { return detail.data; } return null; } // Track the current IME composition fallback object, if any. var currentComposition = null; /** * @return {?object} A SyntheticCompositionEvent. */ function extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var eventType; var fallbackData; if (canUseCompositionEvent) { eventType = getCompositionEventType(topLevelType); } else if (!currentComposition) { if (isFallbackCompositionStart(topLevelType, nativeEvent)) { eventType = eventTypes.compositionStart; } } else if (isFallbackCompositionEnd(topLevelType, nativeEvent)) { eventType = eventTypes.compositionEnd; } if (!eventType) { return null; } if (useFallbackCompositionData) { // The current composition is stored statically and must not be // overwritten while composition continues. if (!currentComposition && eventType === eventTypes.compositionStart) { currentComposition = FallbackCompositionState.getPooled(nativeEventTarget); } else if (eventType === eventTypes.compositionEnd) { if (currentComposition) { fallbackData = currentComposition.getData(); } } } var event = SyntheticCompositionEvent.getPooled(eventType, targetInst, nativeEvent, nativeEventTarget); if (fallbackData) { // Inject data generated from fallback path into the synthetic event. // This matches the property of native CompositionEventInterface. event.data = fallbackData; } else { var customData = getDataFromCustomEvent(nativeEvent); if (customData !== null) { event.data = customData; } } EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The string corresponding to this `beforeInput` event. */ function getNativeBeforeInputChars(topLevelType, nativeEvent) { switch (topLevelType) { case topLevelTypes.topCompositionEnd: return getDataFromCustomEvent(nativeEvent); case topLevelTypes.topKeyPress: /** * If native `textInput` events are available, our goal is to make * use of them. However, there is a special case: the spacebar key. * In Webkit, preventing default on a spacebar `textInput` event * cancels character insertion, but it *also* causes the browser * to fall back to its default spacebar behavior of scrolling the * page. * * Tracking at: * https://code.google.com/p/chromium/issues/detail?id=355103 * * To avoid this issue, use the keypress event as if no `textInput` * event is available. */ var which = nativeEvent.which; if (which !== SPACEBAR_CODE) { return null; } hasSpaceKeypress = true; return SPACEBAR_CHAR; case topLevelTypes.topTextInput: // Record the characters to be added to the DOM. var chars = nativeEvent.data; // If it's a spacebar character, assume that we have already handled // it at the keypress level and bail immediately. Android Chrome // doesn't give us keycodes, so we need to blacklist it. if (chars === SPACEBAR_CHAR && hasSpaceKeypress) { return null; } return chars; default: // For other native event types, do nothing. return null; } } /** * For browsers that do not provide the `textInput` event, extract the * appropriate string to use for SyntheticInputEvent. * * @param {string} topLevelType Record from `EventConstants`. * @param {object} nativeEvent Native browser event. * @return {?string} The fallback string for this `beforeInput` event. */ function getFallbackBeforeInputChars(topLevelType, nativeEvent) { // If we are currently composing (IME) and using a fallback to do so, // try to extract the composed characters from the fallback object. if (currentComposition) { if (topLevelType === topLevelTypes.topCompositionEnd || isFallbackCompositionEnd(topLevelType, nativeEvent)) { var chars = currentComposition.getData(); FallbackCompositionState.release(currentComposition); currentComposition = null; return chars; } return null; } switch (topLevelType) { case topLevelTypes.topPaste: // If a paste event occurs after a keypress, throw out the input // chars. Paste events should not lead to BeforeInput events. return null; case topLevelTypes.topKeyPress: /** * As of v27, Firefox may fire keypress events even when no character * will be inserted. A few possibilities: * * - `which` is `0`. Arrow keys, Esc key, etc. * * - `which` is the pressed key code, but no char is available. * Ex: 'AltGr + d` in Polish. There is no modified character for * this key combination and no character is inserted into the * document, but FF fires the keypress for char code `100` anyway. * No `input` event will occur. * * - `which` is the pressed key code, but a command combination is * being used. Ex: `Cmd+C`. No character is inserted, and no * `input` event will occur. */ if (nativeEvent.which && !isKeypressCommand(nativeEvent)) { return String.fromCharCode(nativeEvent.which); } return null; case topLevelTypes.topCompositionEnd: return useFallbackCompositionData ? null : nativeEvent.data; default: return null; } } /** * Extract a SyntheticInputEvent for `beforeInput`, based on either native * `textInput` or fallback behavior. * * @return {?object} A SyntheticInputEvent. */ function extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget) { var chars; if (canUseTextInputEvent) { chars = getNativeBeforeInputChars(topLevelType, nativeEvent); } else { chars = getFallbackBeforeInputChars(topLevelType, nativeEvent); } // If no characters are being inserted, no BeforeInput event should // be fired. if (!chars) { return null; } var event = SyntheticInputEvent.getPooled(eventTypes.beforeInput, targetInst, nativeEvent, nativeEventTarget); event.data = chars; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } /** * Create an `onBeforeInput` event to match * http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105/#events-inputevents. * * This event plugin is based on the native `textInput` event * available in Chrome, Safari, Opera, and IE. This event fires after * `onKeyPress` and `onCompositionEnd`, but before `onInput`. * * `beforeInput` is spec'd but not implemented in any browsers, and * the `input` event does not provide any useful information about what has * actually been added, contrary to the spec. Thus, `textInput` is the best * available event to identify the characters that have actually been inserted * into the target node. * * This plugin is also responsible for emitting `composition` events, thus * allowing us to share composition fallback code for both `beforeInput` and * `composition` event types. */ var BeforeInputEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { return [extractCompositionEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget), extractBeforeInputEvent(topLevelType, targetInst, nativeEvent, nativeEventTarget)]; } }; module.exports = BeforeInputEventPlugin; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventConstants */ 'use strict'; var keyMirror = __webpack_require__(24); var PropagationPhases = keyMirror({ bubbled: null, captured: null }); /** * Types of raw signals from the browser caught at the top level. */ var topLevelTypes = keyMirror({ topAbort: null, topAnimationEnd: null, topAnimationIteration: null, topAnimationStart: null, topBlur: null, topCanPlay: null, topCanPlayThrough: null, topChange: null, topClick: null, topCompositionEnd: null, topCompositionStart: null, topCompositionUpdate: null, topContextMenu: null, topCopy: null, topCut: null, topDoubleClick: null, topDrag: null, topDragEnd: null, topDragEnter: null, topDragExit: null, topDragLeave: null, topDragOver: null, topDragStart: null, topDrop: null, topDurationChange: null, topEmptied: null, topEncrypted: null, topEnded: null, topError: null, topFocus: null, topInput: null, topInvalid: null, topKeyDown: null, topKeyPress: null, topKeyUp: null, topLoad: null, topLoadedData: null, topLoadedMetadata: null, topLoadStart: null, topMouseDown: null, topMouseMove: null, topMouseOut: null, topMouseOver: null, topMouseUp: null, topPaste: null, topPause: null, topPlay: null, topPlaying: null, topProgress: null, topRateChange: null, topReset: null, topScroll: null, topSeeked: null, topSeeking: null, topSelectionChange: null, topStalled: null, topSubmit: null, topSuspend: null, topTextInput: null, topTimeUpdate: null, topTouchCancel: null, topTouchEnd: null, topTouchMove: null, topTouchStart: null, topTransitionEnd: null, topVolumeChange: null, topWaiting: null, topWheel: null }); var EventConstants = { topLevelTypes: topLevelTypes, PropagationPhases: PropagationPhases }; module.exports = EventConstants; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPropagators */ 'use strict'; var EventConstants = __webpack_require__(40); var EventPluginHub = __webpack_require__(42); var EventPluginUtils = __webpack_require__(44); var accumulateInto = __webpack_require__(46); var forEachAccumulated = __webpack_require__(47); var warning = __webpack_require__(10); var PropagationPhases = EventConstants.PropagationPhases; var getListener = EventPluginHub.getListener; /** * Some event types have a notion of different registration names for different * "phases" of propagation. This finds listeners by a given phase. */ function listenerAtPhase(inst, event, propagationPhase) { var registrationName = event.dispatchConfig.phasedRegistrationNames[propagationPhase]; return getListener(inst, registrationName); } /** * Tags a `SyntheticEvent` with dispatched listeners. Creating this function * here, allows us to not have to bind or create functions for each event. * Mutating the event's members allows us to not have to create a wrapping * "dispatch" object that pairs the event with the listener. */ function accumulateDirectionalDispatches(inst, upwards, event) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(inst, 'Dispatching inst must not be null') : void 0; } var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured; var listener = listenerAtPhase(inst, event, phase); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } /** * Collect dispatches (must be entirely collected before dispatching - see unit * tests). Lazily allocate the array to conserve memory. We must loop through * each event and perform the traversal for each one. We cannot perform a * single traversal for the entire collection of events because each event may * have a different target. */ function accumulateTwoPhaseDispatchesSingle(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { EventPluginUtils.traverseTwoPhase(event._targetInst, accumulateDirectionalDispatches, event); } } /** * Same as `accumulateTwoPhaseDispatchesSingle`, but skips over the targetID. */ function accumulateTwoPhaseDispatchesSingleSkipTarget(event) { if (event && event.dispatchConfig.phasedRegistrationNames) { var targetInst = event._targetInst; var parentInst = targetInst ? EventPluginUtils.getParentInstance(targetInst) : null; EventPluginUtils.traverseTwoPhase(parentInst, accumulateDirectionalDispatches, event); } } /** * Accumulates without regard to direction, does not look for phased * registration names. Same as `accumulateDirectDispatchesSingle` but without * requiring that the `dispatchMarker` be the same as the dispatched ID. */ function accumulateDispatches(inst, ignoredDirection, event) { if (event && event.dispatchConfig.registrationName) { var registrationName = event.dispatchConfig.registrationName; var listener = getListener(inst, registrationName); if (listener) { event._dispatchListeners = accumulateInto(event._dispatchListeners, listener); event._dispatchInstances = accumulateInto(event._dispatchInstances, inst); } } } /** * Accumulates dispatches on an `SyntheticEvent`, but only for the * `dispatchMarker`. * @param {SyntheticEvent} event */ function accumulateDirectDispatchesSingle(event) { if (event && event.dispatchConfig.registrationName) { accumulateDispatches(event._targetInst, null, event); } } function accumulateTwoPhaseDispatches(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle); } function accumulateTwoPhaseDispatchesSkipTarget(events) { forEachAccumulated(events, accumulateTwoPhaseDispatchesSingleSkipTarget); } function accumulateEnterLeaveDispatches(leave, enter, from, to) { EventPluginUtils.traverseEnterLeave(from, to, accumulateDispatches, leave, enter); } function accumulateDirectDispatches(events) { forEachAccumulated(events, accumulateDirectDispatchesSingle); } /** * A small set of propagation patterns, each of which will accept a small amount * of information, and generate a set of "dispatch ready event objects" - which * are sets of events that have already been annotated with a set of dispatched * listener functions/ids. The API is designed this way to discourage these * propagation strategies from actually executing the dispatches, since we * always want to collect the entire set of dispatches before executing event a * single one. * * @constructor EventPropagators */ var EventPropagators = { accumulateTwoPhaseDispatches: accumulateTwoPhaseDispatches, accumulateTwoPhaseDispatchesSkipTarget: accumulateTwoPhaseDispatchesSkipTarget, accumulateDirectDispatches: accumulateDirectDispatches, accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches }; module.exports = EventPropagators; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginHub */ 'use strict'; var EventPluginRegistry = __webpack_require__(43); var EventPluginUtils = __webpack_require__(44); var ReactErrorUtils = __webpack_require__(45); var accumulateInto = __webpack_require__(46); var forEachAccumulated = __webpack_require__(47); var invariant = __webpack_require__(7); /** * Internal store for event listeners */ var listenerBank = {}; /** * Internal queue of events that have accumulated their dispatches and are * waiting to have their dispatches executed. */ var eventQueue = null; /** * Dispatches an event and releases it back into the pool, unless persistent. * * @param {?object} event Synthetic event to be dispatched. * @param {boolean} simulated If the event is simulated (changes exn behavior) * @private */ var executeDispatchesAndRelease = function (event, simulated) { if (event) { EventPluginUtils.executeDispatchesInOrder(event, simulated); if (!event.isPersistent()) { event.constructor.release(event); } } }; var executeDispatchesAndReleaseSimulated = function (e) { return executeDispatchesAndRelease(e, true); }; var executeDispatchesAndReleaseTopLevel = function (e) { return executeDispatchesAndRelease(e, false); }; /** * This is a unified interface for event plugins to be installed and configured. * * Event plugins can implement the following properties: * * `extractEvents` {function(string, DOMEventTarget, string, object): *} * Required. When a top-level event is fired, this method is expected to * extract synthetic events that will in turn be queued and dispatched. * * `eventTypes` {object} * Optional, plugins that fire events must publish a mapping of registration * names that are used to register listeners. Values of this mapping must * be objects that contain `registrationName` or `phasedRegistrationNames`. * * `executeDispatch` {function(object, function, string)} * Optional, allows plugins to override how an event gets dispatched. By * default, the listener is simply invoked. * * Each plugin that is injected into `EventsPluginHub` is immediately operable. * * @public */ var EventPluginHub = { /** * Methods for injecting dependencies. */ injection: { /** * @param {array} InjectedEventPluginOrder * @public */ injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder, /** * @param {object} injectedNamesToPlugins Map from names to plugin modules. */ injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName }, /** * Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {function} listener The callback to store. */ putListener: function (inst, registrationName, listener) { !(typeof listener === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected %s listener to be a function, instead got type %s', registrationName, typeof listener) : invariant(false) : void 0; var bankForRegistrationName = listenerBank[registrationName] || (listenerBank[registrationName] = {}); bankForRegistrationName[inst._rootNodeID] = listener; var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.didPutListener) { PluginModule.didPutListener(inst, registrationName, listener); } }, /** * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). * @return {?function} The stored callback. */ getListener: function (inst, registrationName) { var bankForRegistrationName = listenerBank[registrationName]; return bankForRegistrationName && bankForRegistrationName[inst._rootNodeID]; }, /** * Deletes a listener from the registration bank. * * @param {object} inst The instance, which is the source of events. * @param {string} registrationName Name of listener (e.g. `onClick`). */ deleteListener: function (inst, registrationName) { var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } var bankForRegistrationName = listenerBank[registrationName]; // TODO: This should never be null -- when is it? if (bankForRegistrationName) { delete bankForRegistrationName[inst._rootNodeID]; } }, /** * Deletes all listeners for the DOM element with the supplied ID. * * @param {object} inst The instance, which is the source of events. */ deleteAllListeners: function (inst) { for (var registrationName in listenerBank) { if (!listenerBank[registrationName][inst._rootNodeID]) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[registrationName]; if (PluginModule && PluginModule.willDeleteListener) { PluginModule.willDeleteListener(inst, registrationName); } delete listenerBank[registrationName][inst._rootNodeID]; } }, /** * Allows registered plugins an opportunity to extract events from top-level * native browser events. * * @return {*} An accumulation of synthetic events. * @internal */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events; var plugins = EventPluginRegistry.plugins; for (var i = 0; i < plugins.length; i++) { // Not every plugin in the ordering may be loaded at runtime. var possiblePlugin = plugins[i]; if (possiblePlugin) { var extractedEvents = possiblePlugin.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); if (extractedEvents) { events = accumulateInto(events, extractedEvents); } } } return events; }, /** * Enqueues a synthetic event that should be dispatched when * `processEventQueue` is invoked. * * @param {*} events An accumulation of synthetic events. * @internal */ enqueueEvents: function (events) { if (events) { eventQueue = accumulateInto(eventQueue, events); } }, /** * Dispatches all synthetic events on the event queue. * * @internal */ processEventQueue: function (simulated) { // Set `eventQueue` to null before processing it so that we can tell if more // events get enqueued while processing. var processingEventQueue = eventQueue; eventQueue = null; if (simulated) { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseSimulated); } else { forEachAccumulated(processingEventQueue, executeDispatchesAndReleaseTopLevel); } !!eventQueue ? process.env.NODE_ENV !== 'production' ? invariant(false, 'processEventQueue(): Additional events were enqueued while processing ' + 'an event queue. Support for this has not yet been implemented.') : invariant(false) : void 0; // This would be a good time to rethrow if any of the event handlers threw. ReactErrorUtils.rethrowCaughtError(); }, /** * These are needed for tests only. Do not use! */ __purge: function () { listenerBank = {}; }, __getListenerBank: function () { return listenerBank; } }; module.exports = EventPluginHub; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginRegistry */ 'use strict'; var invariant = __webpack_require__(7); /** * Injectable ordering of event plugins. */ var EventPluginOrder = null; /** * Injectable mapping from names to event plugin modules. */ var namesToPlugins = {}; /** * Recomputes the plugin list using the injected plugins and plugin ordering. * * @private */ function recomputePluginOrdering() { if (!EventPluginOrder) { // Wait until an `EventPluginOrder` is injected. return; } for (var pluginName in namesToPlugins) { var PluginModule = namesToPlugins[pluginName]; var pluginIndex = EventPluginOrder.indexOf(pluginName); !(pluginIndex > -1) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugins that do not exist in ' + 'the plugin ordering, `%s`.', pluginName) : invariant(false) : void 0; if (EventPluginRegistry.plugins[pluginIndex]) { continue; } !PluginModule.extractEvents ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Event plugins must implement an `extractEvents` ' + 'method, but `%s` does not.', pluginName) : invariant(false) : void 0; EventPluginRegistry.plugins[pluginIndex] = PluginModule; var publishedEvents = PluginModule.eventTypes; for (var eventName in publishedEvents) { !publishEventForPlugin(publishedEvents[eventName], PluginModule, eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.', eventName, pluginName) : invariant(false) : void 0; } } } /** * Publishes an event so that it can be dispatched by the supplied plugin. * * @param {object} dispatchConfig Dispatch configuration for the event. * @param {object} PluginModule Plugin publishing the event. * @return {boolean} True if the event was successfully published. * @private */ function publishEventForPlugin(dispatchConfig, PluginModule, eventName) { !!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'event name, `%s`.', eventName) : invariant(false) : void 0; EventPluginRegistry.eventNameDispatchConfigs[eventName] = dispatchConfig; var phasedRegistrationNames = dispatchConfig.phasedRegistrationNames; if (phasedRegistrationNames) { for (var phaseName in phasedRegistrationNames) { if (phasedRegistrationNames.hasOwnProperty(phaseName)) { var phasedRegistrationName = phasedRegistrationNames[phaseName]; publishRegistrationName(phasedRegistrationName, PluginModule, eventName); } } return true; } else if (dispatchConfig.registrationName) { publishRegistrationName(dispatchConfig.registrationName, PluginModule, eventName); return true; } return false; } /** * Publishes a registration name that is used to identify dispatched events and * can be used with `EventPluginHub.putListener` to register listeners. * * @param {string} registrationName Registration name to add. * @param {object} PluginModule Plugin publishing the event. * @private */ function publishRegistrationName(registrationName, PluginModule, eventName) { !!EventPluginRegistry.registrationNameModules[registrationName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginHub: More than one plugin attempted to publish the same ' + 'registration name, `%s`.', registrationName) : invariant(false) : void 0; EventPluginRegistry.registrationNameModules[registrationName] = PluginModule; EventPluginRegistry.registrationNameDependencies[registrationName] = PluginModule.eventTypes[eventName].dependencies; if (process.env.NODE_ENV !== 'production') { var lowerCasedName = registrationName.toLowerCase(); EventPluginRegistry.possibleRegistrationNames[lowerCasedName] = registrationName; } } /** * Registers plugins so that they can extract and dispatch events. * * @see {EventPluginHub} */ var EventPluginRegistry = { /** * Ordered list of injected plugins. */ plugins: [], /** * Mapping from event name to dispatch config */ eventNameDispatchConfigs: {}, /** * Mapping from registration name to plugin module */ registrationNameModules: {}, /** * Mapping from registration name to event name */ registrationNameDependencies: {}, /** * Mapping from lowercase registration names to the properly cased version, * used to warn in the case of missing event handlers. Available * only in __DEV__. * @type {Object} */ possibleRegistrationNames: process.env.NODE_ENV !== 'production' ? {} : null, /** * Injects an ordering of plugins (by plugin name). This allows the ordering * to be decoupled from injection of the actual plugins so that ordering is * always deterministic regardless of packaging, on-the-fly injection, etc. * * @param {array} InjectedEventPluginOrder * @internal * @see {EventPluginHub.injection.injectEventPluginOrder} */ injectEventPluginOrder: function (InjectedEventPluginOrder) { !!EventPluginOrder ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject event plugin ordering more than ' + 'once. You are likely trying to load more than one copy of React.') : invariant(false) : void 0; // Clone the ordering so it cannot be dynamically mutated. EventPluginOrder = Array.prototype.slice.call(InjectedEventPluginOrder); recomputePluginOrdering(); }, /** * Injects plugins to be used by `EventPluginHub`. The plugin names must be * in the ordering injected by `injectEventPluginOrder`. * * Plugins can be injected as part of page initialization or on-the-fly. * * @param {object} injectedNamesToPlugins Map from names to plugin modules. * @internal * @see {EventPluginHub.injection.injectEventPluginsByName} */ injectEventPluginsByName: function (injectedNamesToPlugins) { var isOrderingDirty = false; for (var pluginName in injectedNamesToPlugins) { if (!injectedNamesToPlugins.hasOwnProperty(pluginName)) { continue; } var PluginModule = injectedNamesToPlugins[pluginName]; if (!namesToPlugins.hasOwnProperty(pluginName) || namesToPlugins[pluginName] !== PluginModule) { !!namesToPlugins[pluginName] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'EventPluginRegistry: Cannot inject two different event plugins ' + 'using the same name, `%s`.', pluginName) : invariant(false) : void 0; namesToPlugins[pluginName] = PluginModule; isOrderingDirty = true; } } if (isOrderingDirty) { recomputePluginOrdering(); } }, /** * Looks up the plugin for the supplied event. * * @param {object} event A synthetic event. * @return {?object} The plugin that created the supplied event. * @internal */ getPluginModuleForEvent: function (event) { var dispatchConfig = event.dispatchConfig; if (dispatchConfig.registrationName) { return EventPluginRegistry.registrationNameModules[dispatchConfig.registrationName] || null; } for (var phase in dispatchConfig.phasedRegistrationNames) { if (!dispatchConfig.phasedRegistrationNames.hasOwnProperty(phase)) { continue; } var PluginModule = EventPluginRegistry.registrationNameModules[dispatchConfig.phasedRegistrationNames[phase]]; if (PluginModule) { return PluginModule; } } return null; }, /** * Exposed for unit testing. * @private */ _resetEventPlugins: function () { EventPluginOrder = null; for (var pluginName in namesToPlugins) { if (namesToPlugins.hasOwnProperty(pluginName)) { delete namesToPlugins[pluginName]; } } EventPluginRegistry.plugins.length = 0; var eventNameDispatchConfigs = EventPluginRegistry.eventNameDispatchConfigs; for (var eventName in eventNameDispatchConfigs) { if (eventNameDispatchConfigs.hasOwnProperty(eventName)) { delete eventNameDispatchConfigs[eventName]; } } var registrationNameModules = EventPluginRegistry.registrationNameModules; for (var registrationName in registrationNameModules) { if (registrationNameModules.hasOwnProperty(registrationName)) { delete registrationNameModules[registrationName]; } } if (process.env.NODE_ENV !== 'production') { var possibleRegistrationNames = EventPluginRegistry.possibleRegistrationNames; for (var lowerCasedName in possibleRegistrationNames) { if (possibleRegistrationNames.hasOwnProperty(lowerCasedName)) { delete possibleRegistrationNames[lowerCasedName]; } } } } }; module.exports = EventPluginRegistry; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EventPluginUtils */ 'use strict'; var EventConstants = __webpack_require__(40); var ReactErrorUtils = __webpack_require__(45); var invariant = __webpack_require__(7); var warning = __webpack_require__(10); /** * Injected dependencies: */ /** * - `ComponentTree`: [required] Module that can convert between React instances * and actual node references. */ var ComponentTree; var TreeTraversal; var injection = { injectComponentTree: function (Injected) { ComponentTree = Injected; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.getNodeFromInstance && Injected.getInstanceFromNode, 'EventPluginUtils.injection.injectComponentTree(...): Injected ' + 'module is missing getNodeFromInstance or getInstanceFromNode.') : void 0; } }, injectTreeTraversal: function (Injected) { TreeTraversal = Injected; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(Injected && Injected.isAncestor && Injected.getLowestCommonAncestor, 'EventPluginUtils.injection.injectTreeTraversal(...): Injected ' + 'module is missing isAncestor or getLowestCommonAncestor.') : void 0; } } }; var topLevelTypes = EventConstants.topLevelTypes; function isEndish(topLevelType) { return topLevelType === topLevelTypes.topMouseUp || topLevelType === topLevelTypes.topTouchEnd || topLevelType === topLevelTypes.topTouchCancel; } function isMoveish(topLevelType) { return topLevelType === topLevelTypes.topMouseMove || topLevelType === topLevelTypes.topTouchMove; } function isStartish(topLevelType) { return topLevelType === topLevelTypes.topMouseDown || topLevelType === topLevelTypes.topTouchStart; } var validateEventDispatches; if (process.env.NODE_ENV !== 'production') { validateEventDispatches = function (event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; var listenersIsArr = Array.isArray(dispatchListeners); var listenersLen = listenersIsArr ? dispatchListeners.length : dispatchListeners ? 1 : 0; var instancesIsArr = Array.isArray(dispatchInstances); var instancesLen = instancesIsArr ? dispatchInstances.length : dispatchInstances ? 1 : 0; process.env.NODE_ENV !== 'production' ? warning(instancesIsArr === listenersIsArr && instancesLen === listenersLen, 'EventPluginUtils: Invalid `event`.') : void 0; }; } /** * Dispatch the event to the listener. * @param {SyntheticEvent} event SyntheticEvent to handle * @param {boolean} simulated If the event is simulated (changes exn behavior) * @param {function} listener Application-level callback * @param {*} inst Internal component instance */ function executeDispatch(event, simulated, listener, inst) { var type = event.type || 'unknown-event'; event.currentTarget = EventPluginUtils.getNodeFromInstance(inst); if (simulated) { ReactErrorUtils.invokeGuardedCallbackWithCatch(type, listener, event); } else { ReactErrorUtils.invokeGuardedCallback(type, listener, event); } event.currentTarget = null; } /** * Standard/simple iteration through an event's collected dispatches. */ function executeDispatchesInOrder(event, simulated) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. executeDispatch(event, simulated, dispatchListeners[i], dispatchInstances[i]); } } else if (dispatchListeners) { executeDispatch(event, simulated, dispatchListeners, dispatchInstances); } event._dispatchListeners = null; event._dispatchInstances = null; } /** * Standard/simple iteration through an event's collected dispatches, but stops * at the first dispatch execution returning true, and returns that id. * * @return {?string} id of the first dispatch execution who's listener returns * true, or null if no listener returned true. */ function executeDispatchesInOrderStopAtTrueImpl(event) { var dispatchListeners = event._dispatchListeners; var dispatchInstances = event._dispatchInstances; if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } if (Array.isArray(dispatchListeners)) { for (var i = 0; i < dispatchListeners.length; i++) { if (event.isPropagationStopped()) { break; } // Listeners and Instances are two parallel arrays that are always in sync. if (dispatchListeners[i](event, dispatchInstances[i])) { return dispatchInstances[i]; } } } else if (dispatchListeners) { if (dispatchListeners(event, dispatchInstances)) { return dispatchInstances; } } return null; } /** * @see executeDispatchesInOrderStopAtTrueImpl */ function executeDispatchesInOrderStopAtTrue(event) { var ret = executeDispatchesInOrderStopAtTrueImpl(event); event._dispatchInstances = null; event._dispatchListeners = null; return ret; } /** * Execution of a "direct" dispatch - there must be at most one dispatch * accumulated on the event or it is considered an error. It doesn't really make * sense for an event with multiple dispatches (bubbled) to keep track of the * return values at each dispatch execution, but it does tend to make sense when * dealing with "direct" dispatches. * * @return {*} The return value of executing the single dispatch. */ function executeDirectDispatch(event) { if (process.env.NODE_ENV !== 'production') { validateEventDispatches(event); } var dispatchListener = event._dispatchListeners; var dispatchInstance = event._dispatchInstances; !!Array.isArray(dispatchListener) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'executeDirectDispatch(...): Invalid `event`.') : invariant(false) : void 0; event.currentTarget = dispatchListener ? EventPluginUtils.getNodeFromInstance(dispatchInstance) : null; var res = dispatchListener ? dispatchListener(event) : null; event.currentTarget = null; event._dispatchListeners = null; event._dispatchInstances = null; return res; } /** * @param {SyntheticEvent} event * @return {boolean} True iff number of dispatches accumulated is greater than 0. */ function hasDispatches(event) { return !!event._dispatchListeners; } /** * General utilities that are useful in creating custom Event Plugins. */ var EventPluginUtils = { isEndish: isEndish, isMoveish: isMoveish, isStartish: isStartish, executeDirectDispatch: executeDirectDispatch, executeDispatchesInOrder: executeDispatchesInOrder, executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue, hasDispatches: hasDispatches, getInstanceFromNode: function (node) { return ComponentTree.getInstanceFromNode(node); }, getNodeFromInstance: function (node) { return ComponentTree.getNodeFromInstance(node); }, isAncestor: function (a, b) { return TreeTraversal.isAncestor(a, b); }, getLowestCommonAncestor: function (a, b) { return TreeTraversal.getLowestCommonAncestor(a, b); }, getParentInstance: function (inst) { return TreeTraversal.getParentInstance(inst); }, traverseTwoPhase: function (target, fn, arg) { return TreeTraversal.traverseTwoPhase(target, fn, arg); }, traverseEnterLeave: function (from, to, fn, argFrom, argTo) { return TreeTraversal.traverseEnterLeave(from, to, fn, argFrom, argTo); }, injection: injection }; module.exports = EventPluginUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 45 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactErrorUtils */ 'use strict'; var caughtError = null; /** * Call a function while guarding against errors that happens within it. * * @param {?String} name of the guard to use for logging or debugging * @param {Function} func The function to invoke * @param {*} a First argument * @param {*} b Second argument */ function invokeGuardedCallback(name, func, a, b) { try { return func(a, b); } catch (x) { if (caughtError === null) { caughtError = x; } return undefined; } } var ReactErrorUtils = { invokeGuardedCallback: invokeGuardedCallback, /** * Invoked by ReactTestUtils.Simulate so that any errors thrown by the event * handler are sure to be rethrown by rethrowCaughtError. */ invokeGuardedCallbackWithCatch: invokeGuardedCallback, /** * During execution of guarded functions we will capture the first error which * we will rethrow to be handled by the top level error handler. */ rethrowCaughtError: function () { if (caughtError) { var error = caughtError; caughtError = null; throw error; } } }; if (process.env.NODE_ENV !== 'production') { /** * To help development we can get better devtools integration by simulating a * real browser event. */ if (typeof window !== 'undefined' && typeof window.dispatchEvent === 'function' && typeof document !== 'undefined' && typeof document.createEvent === 'function') { var fakeNode = document.createElement('react'); ReactErrorUtils.invokeGuardedCallback = function (name, func, a, b) { var boundFunc = func.bind(null, a, b); var evtType = 'react-' + name; fakeNode.addEventListener(evtType, boundFunc, false); var evt = document.createEvent('Event'); evt.initEvent(evtType, false, false); fakeNode.dispatchEvent(evt); fakeNode.removeEventListener(evtType, boundFunc, false); }; } } module.exports = ReactErrorUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule accumulateInto */ 'use strict'; var invariant = __webpack_require__(7); /** * * Accumulates items that must not be null or undefined into the first one. This * is used to conserve memory by avoiding array allocations, and thus sacrifices * API cleanness. Since `current` can be null before being passed in and not * null after this function, make sure to assign it back to `current`: * * `a = accumulateInto(a, b);` * * This API should be sparingly used. Try `accumulate` for something cleaner. * * @return {*|array<*>} An accumulation of items. */ function accumulateInto(current, next) { !(next != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'accumulateInto(...): Accumulated items must not be null or undefined.') : invariant(false) : void 0; if (current == null) { return next; } // Both are not empty. Warning: Never call x.concat(y) when you are not // certain that x is an Array (x could be a string with concat method). var currentIsArray = Array.isArray(current); var nextIsArray = Array.isArray(next); if (currentIsArray && nextIsArray) { current.push.apply(current, next); return current; } if (currentIsArray) { current.push(next); return current; } if (nextIsArray) { // A bit too dangerous to mutate `next`. return [current].concat(next); } return [current, next]; } module.exports = accumulateInto; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 47 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule forEachAccumulated */ 'use strict'; /** * @param {array} arr an "accumulation" of items which is either an Array or * a single item. Useful when paired with the `accumulate` module. This is a * simple utility that allows us to reason about a collection of items, but * handling the case when there is exactly one item (and we do not need to * allocate an array). */ var forEachAccumulated = function (arr, cb, scope) { if (Array.isArray(arr)) { arr.forEach(cb, scope); } else if (arr) { cb.call(scope, arr); } }; module.exports = forEachAccumulated; /***/ }, /* 48 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; var 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; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule FallbackCompositionState */ 'use strict'; var _assign = __webpack_require__(4); var PooledClass = __webpack_require__(6); var getTextContentAccessor = __webpack_require__(50); /** * This helper class stores information about text content of a target node, * allowing comparison of content before and after a given event. * * Identify the node where selection currently begins, then observe * both its text content and its current position in the DOM. Since the * browser may natively replace the target node during composition, we can * use its position to find its replacement. * * @param {DOMEventTarget} root */ function FallbackCompositionState(root) { this._root = root; this._startText = this.getText(); this._fallbackText = null; } _assign(FallbackCompositionState.prototype, { destructor: function () { this._root = null; this._startText = null; this._fallbackText = null; }, /** * Get current text of input. * * @return {string} */ getText: function () { if ('value' in this._root) { return this._root.value; } return this._root[getTextContentAccessor()]; }, /** * Determine the differing substring between the initially stored * text content and the current content. * * @return {string} */ getData: function () { if (this._fallbackText) { return this._fallbackText; } var start; var startValue = this._startText; var startLength = startValue.length; var end; var endValue = this.getText(); var endLength = endValue.length; for (start = 0; start < startLength; start++) { if (startValue[start] !== endValue[start]) { break; } } var minEnd = startLength - start; for (end = 1; end <= minEnd; end++) { if (startValue[startLength - end] !== endValue[endLength - end]) { break; } } var sliceTail = end > 1 ? 1 - end : undefined; this._fallbackText = endValue.slice(start, sliceTail); return this._fallbackText; } }); PooledClass.addPoolingTo(FallbackCompositionState); module.exports = FallbackCompositionState; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getTextContentAccessor */ 'use strict'; var ExecutionEnvironment = __webpack_require__(48); var contentKey = null; /** * Gets the key used to access text content on a DOM node. * * @return {?string} Key used to access text content. * @internal */ function getTextContentAccessor() { if (!contentKey && ExecutionEnvironment.canUseDOM) { // Prefer textContent to innerText because many browsers support both but // SVG <text> elements don't support innerText even when <div> does. contentKey = 'textContent' in document.documentElement ? 'textContent' : 'innerText'; } return contentKey; } module.exports = getTextContentAccessor; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticCompositionEvent */ 'use strict'; var SyntheticEvent = __webpack_require__(52); /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/#events-compositionevents */ var CompositionEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticCompositionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticCompositionEvent, CompositionEventInterface); module.exports = SyntheticCompositionEvent; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticEvent */ 'use strict'; var _assign = __webpack_require__(4); var PooledClass = __webpack_require__(6); var emptyFunction = __webpack_require__(11); var warning = __webpack_require__(10); var didWarnForAddedNewProperty = false; var isProxySupported = typeof Proxy === 'function'; var shouldBeReleasedProperties = ['dispatchConfig', '_targetInst', 'nativeEvent', 'isDefaultPrevented', 'isPropagationStopped', '_dispatchListeners', '_dispatchInstances']; /** * @interface Event * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var EventInterface = { type: null, target: null, // currentTarget is set when dispatching; no use in copying it here currentTarget: emptyFunction.thatReturnsNull, eventPhase: null, bubbles: null, cancelable: null, timeStamp: function (event) { return event.timeStamp || Date.now(); }, defaultPrevented: null, isTrusted: null }; /** * Synthetic events are dispatched by event plugins, typically in response to a * top-level event delegation handler. * * These systems should generally use pooling to reduce the frequency of garbage * collection. The system should check `isPersistent` to determine whether the * event should be released into the pool after being dispatched. Users that * need a persisted event should invoke `persist`. * * Synthetic events (and subclasses) implement the DOM Level 3 Events API by * normalizing browser quirks. Subclasses do not necessarily have to implement a * DOM interface; custom application-specific events can also subclass this. * * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {*} targetInst Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @param {DOMEventTarget} nativeEventTarget Target node. */ function SyntheticEvent(dispatchConfig, targetInst, nativeEvent, nativeEventTarget) { if (process.env.NODE_ENV !== 'production') { // these have a getter/setter for warnings delete this.nativeEvent; delete this.preventDefault; delete this.stopPropagation; } this.dispatchConfig = dispatchConfig; this._targetInst = targetInst; this.nativeEvent = nativeEvent; var Interface = this.constructor.Interface; for (var propName in Interface) { if (!Interface.hasOwnProperty(propName)) { continue; } if (process.env.NODE_ENV !== 'production') { delete this[propName]; // this has a getter/setter for warnings } var normalize = Interface[propName]; if (normalize) { this[propName] = normalize(nativeEvent); } else { if (propName === 'target') { this.target = nativeEventTarget; } else { this[propName] = nativeEvent[propName]; } } } var defaultPrevented = nativeEvent.defaultPrevented != null ? nativeEvent.defaultPrevented : nativeEvent.returnValue === false; if (defaultPrevented) { this.isDefaultPrevented = emptyFunction.thatReturnsTrue; } else { this.isDefaultPrevented = emptyFunction.thatReturnsFalse; } this.isPropagationStopped = emptyFunction.thatReturnsFalse; return this; } _assign(SyntheticEvent.prototype, { preventDefault: function () { this.defaultPrevented = true; var event = this.nativeEvent; if (!event) { return; } if (event.preventDefault) { event.preventDefault(); } else { event.returnValue = false; } this.isDefaultPrevented = emptyFunction.thatReturnsTrue; }, stopPropagation: function () { var event = this.nativeEvent; if (!event) { return; } if (event.stopPropagation) { event.stopPropagation(); } else { event.cancelBubble = true; } this.isPropagationStopped = emptyFunction.thatReturnsTrue; }, /** * We release all dispatched `SyntheticEvent`s after each event loop, adding * them back into the pool. This allows a way to hold onto a reference that * won't be added back into the pool. */ persist: function () { this.isPersistent = emptyFunction.thatReturnsTrue; }, /** * Checks if this event should be released back into the pool. * * @return {boolean} True if this should not be released, false otherwise. */ isPersistent: emptyFunction.thatReturnsFalse, /** * `PooledClass` looks for `destructor` on each instance it releases. */ destructor: function () { var Interface = this.constructor.Interface; for (var propName in Interface) { if (process.env.NODE_ENV !== 'production') { Object.defineProperty(this, propName, getPooledWarningPropertyDefinition(propName, Interface[propName])); } else { this[propName] = null; } } for (var i = 0; i < shouldBeReleasedProperties.length; i++) { this[shouldBeReleasedProperties[i]] = null; } if (process.env.NODE_ENV !== 'production') { var noop = __webpack_require__(11); Object.defineProperty(this, 'nativeEvent', getPooledWarningPropertyDefinition('nativeEvent', null)); Object.defineProperty(this, 'preventDefault', getPooledWarningPropertyDefinition('preventDefault', noop)); Object.defineProperty(this, 'stopPropagation', getPooledWarningPropertyDefinition('stopPropagation', noop)); } } }); SyntheticEvent.Interface = EventInterface; if (process.env.NODE_ENV !== 'production') { if (isProxySupported) { /*eslint-disable no-func-assign */ SyntheticEvent = new Proxy(SyntheticEvent, { construct: function (target, args) { return this.apply(target, Object.create(target.prototype), args); }, apply: function (constructor, that, args) { return new Proxy(constructor.apply(that, args), { set: function (target, prop, value) { if (prop !== 'isPersistent' && !target.constructor.Interface.hasOwnProperty(prop) && shouldBeReleasedProperties.indexOf(prop) === -1) { process.env.NODE_ENV !== 'production' ? warning(didWarnForAddedNewProperty || target.isPersistent(), 'This synthetic event is reused for performance reasons. If you\'re ' + 'seeing this, you\'re adding a new property in the synthetic event object. ' + 'The property is never released. See ' + 'https://fb.me/react-event-pooling for more information.') : void 0; didWarnForAddedNewProperty = true; } target[prop] = value; return true; } }); } }); /*eslint-enable no-func-assign */ } } /** * Helper to reduce boilerplate when creating subclasses. * * @param {function} Class * @param {?object} Interface */ SyntheticEvent.augmentClass = function (Class, Interface) { var Super = this; var E = function () {}; E.prototype = Super.prototype; var prototype = new E(); _assign(prototype, Class.prototype); Class.prototype = prototype; Class.prototype.constructor = Class; Class.Interface = _assign({}, Super.Interface, Interface); Class.augmentClass = Super.augmentClass; PooledClass.addPoolingTo(Class, PooledClass.fourArgumentPooler); }; PooledClass.addPoolingTo(SyntheticEvent, PooledClass.fourArgumentPooler); module.exports = SyntheticEvent; /** * Helper to nullify syntheticEvent instance properties when destructing * * @param {object} SyntheticEvent * @param {String} propName * @return {object} defineProperty object */ function getPooledWarningPropertyDefinition(propName, getVal) { var isFunction = typeof getVal === 'function'; return { configurable: true, set: set, get: get }; function set(val) { var action = isFunction ? 'setting the method' : 'setting the property'; warn(action, 'This is effectively a no-op'); return val; } function get() { var action = isFunction ? 'accessing the method' : 'accessing the property'; var result = isFunction ? 'This is a no-op function' : 'This is set to null'; warn(action, result); return getVal; } function warn(action, result) { var warningCondition = false; process.env.NODE_ENV !== 'production' ? warning(warningCondition, 'This synthetic event is reused for performance reasons. If you\'re seeing this, ' + 'you\'re %s `%s` on a released/nullified synthetic event. %s. ' + 'If you must keep the original synthetic event around, use event.persist(). ' + 'See https://fb.me/react-event-pooling for more information.', action, propName, result) : void 0; } } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 53 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticInputEvent */ 'use strict'; var SyntheticEvent = __webpack_require__(52); /** * @interface Event * @see http://www.w3.org/TR/2013/WD-DOM-Level-3-Events-20131105 * /#events-inputevents */ var InputEventInterface = { data: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticInputEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticInputEvent, InputEventInterface); module.exports = SyntheticInputEvent; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ChangeEventPlugin */ 'use strict'; var EventConstants = __webpack_require__(40); var EventPluginHub = __webpack_require__(42); var EventPropagators = __webpack_require__(41); var ExecutionEnvironment = __webpack_require__(48); var ReactDOMComponentTree = __webpack_require__(35); var ReactUpdates = __webpack_require__(55); var SyntheticEvent = __webpack_require__(52); var getEventTarget = __webpack_require__(63); var isEventSupported = __webpack_require__(64); var isTextInputElement = __webpack_require__(65); var keyOf = __webpack_require__(26); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { change: { phasedRegistrationNames: { bubbled: keyOf({ onChange: null }), captured: keyOf({ onChangeCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topChange, topLevelTypes.topClick, topLevelTypes.topFocus, topLevelTypes.topInput, topLevelTypes.topKeyDown, topLevelTypes.topKeyUp, topLevelTypes.topSelectionChange] } }; /** * For IE shims */ var activeElement = null; var activeElementInst = null; var activeElementValue = null; var activeElementValueProp = null; /** * SECTION: handle `change` event */ function shouldUseChangeEvent(elem) { var nodeName = elem.nodeName && elem.nodeName.toLowerCase(); return nodeName === 'select' || nodeName === 'input' && elem.type === 'file'; } var doesChangeEventBubble = false; if (ExecutionEnvironment.canUseDOM) { // See `handleChange` comment below doesChangeEventBubble = isEventSupported('change') && (!('documentMode' in document) || document.documentMode > 8); } function manualDispatchChangeEvent(nativeEvent) { var event = SyntheticEvent.getPooled(eventTypes.change, activeElementInst, nativeEvent, getEventTarget(nativeEvent)); EventPropagators.accumulateTwoPhaseDispatches(event); // If change and propertychange bubbled, we'd just bind to it like all the // other events and have it go through ReactBrowserEventEmitter. Since it // doesn't, we manually listen for the events and so we have to enqueue and // process the abstract event manually. // // Batching is necessary here in order to ensure that all event handlers run // before the next rerender (including event handlers attached to ancestor // elements instead of directly on the input). Without this, controlled // components don't work properly in conjunction with event bubbling because // the component is rerendered and the value reverted before all the event // handlers can run. See https://github.com/facebook/react/issues/708. ReactUpdates.batchedUpdates(runEventInBatch, event); } function runEventInBatch(event) { EventPluginHub.enqueueEvents(event); EventPluginHub.processEventQueue(false); } function startWatchingForChangeEventIE8(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElement.attachEvent('onchange', manualDispatchChangeEvent); } function stopWatchingForChangeEventIE8() { if (!activeElement) { return; } activeElement.detachEvent('onchange', manualDispatchChangeEvent); activeElement = null; activeElementInst = null; } function getTargetInstForChangeEvent(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topChange) { return targetInst; } } function handleEventsForChangeEventIE8(topLevelType, target, targetInst) { if (topLevelType === topLevelTypes.topFocus) { // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForChangeEventIE8(); startWatchingForChangeEventIE8(target, targetInst); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForChangeEventIE8(); } } /** * SECTION: handle `input` event */ var isInputEventSupported = false; if (ExecutionEnvironment.canUseDOM) { // IE9 claims to support the input event but fails to trigger it when // deleting text, so we ignore its input events. // IE10+ fire input events to often, such when a placeholder // changes or when an input with a placeholder is focused. isInputEventSupported = isEventSupported('input') && (!('documentMode' in document) || document.documentMode > 11); } /** * (For IE <=11) Replacement getter/setter for the `value` property that gets * set on the active element. */ var newValueProp = { get: function () { return activeElementValueProp.get.call(this); }, set: function (val) { // Cast to a string so we can do equality checks. activeElementValue = '' + val; activeElementValueProp.set.call(this, val); } }; /** * (For IE <=11) Starts tracking propertychange events on the passed-in element * and override the value property so that we can distinguish user events from * value changes in JS. */ function startWatchingForValueChange(target, targetInst) { activeElement = target; activeElementInst = targetInst; activeElementValue = target.value; activeElementValueProp = Object.getOwnPropertyDescriptor(target.constructor.prototype, 'value'); // Not guarded in a canDefineProperty check: IE8 supports defineProperty only // on DOM elements Object.defineProperty(activeElement, 'value', newValueProp); if (activeElement.attachEvent) { activeElement.attachEvent('onpropertychange', handlePropertyChange); } else { activeElement.addEventListener('propertychange', handlePropertyChange, false); } } /** * (For IE <=11) Removes the event listeners from the currently-tracked element, * if any exists. */ function stopWatchingForValueChange() { if (!activeElement) { return; } // delete restores the original property definition delete activeElement.value; if (activeElement.detachEvent) { activeElement.detachEvent('onpropertychange', handlePropertyChange); } else { activeElement.removeEventListener('propertychange', handlePropertyChange, false); } activeElement = null; activeElementInst = null; activeElementValue = null; activeElementValueProp = null; } /** * (For IE <=11) Handles a propertychange event, sending a `change` event if * the value of the active element has changed. */ function handlePropertyChange(nativeEvent) { if (nativeEvent.propertyName !== 'value') { return; } var value = nativeEvent.srcElement.value; if (value === activeElementValue) { return; } activeElementValue = value; manualDispatchChangeEvent(nativeEvent); } /** * If a `change` event should be fired, returns the target's ID. */ function getTargetInstForInputEvent(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topInput) { // In modern browsers (i.e., not IE8 or IE9), the input event is exactly // what we want so fall through here and trigger an abstract event return targetInst; } } function handleEventsForInputEventIE(topLevelType, target, targetInst) { if (topLevelType === topLevelTypes.topFocus) { // In IE8, we can capture almost all .value changes by adding a // propertychange handler and looking for events with propertyName // equal to 'value' // In IE9-11, propertychange fires for most input events but is buggy and // doesn't fire when text is deleted, but conveniently, selectionchange // appears to fire in all of the remaining cases so we catch those and // forward the event if the value has changed // In either case, we don't want to call the event handler if the value // is changed from JS so we redefine a setter for `.value` that updates // our activeElementValue variable, allowing us to ignore those changes // // stopWatching() should be a noop here but we call it just in case we // missed a blur event somehow. stopWatchingForValueChange(); startWatchingForValueChange(target, targetInst); } else if (topLevelType === topLevelTypes.topBlur) { stopWatchingForValueChange(); } } // For IE8 and IE9. function getTargetInstForInputEventIE(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topSelectionChange || topLevelType === topLevelTypes.topKeyUp || topLevelType === topLevelTypes.topKeyDown) { // On the selectionchange event, the target is just document which isn't // helpful for us so just check activeElement instead. // // 99% of the time, keydown and keyup aren't necessary. IE8 fails to fire // propertychange on the first input event after setting `value` from a // script and fires only keydown, keypress, keyup. Catching keyup usually // gets it and catching keydown lets us fire an event for the first // keystroke if user does a key repeat (it'll be a little delayed: right // before the second keystroke). Other input methods (e.g., paste) seem to // fire selectionchange normally. if (activeElement && activeElement.value !== activeElementValue) { activeElementValue = activeElement.value; return activeElementInst; } } } /** * SECTION: handle `click` event */ function shouldUseClickEvent(elem) { // Use the `click` event to detect changes to checkbox and radio inputs. // This approach works across all browsers, whereas `change` does not fire // until `blur` in IE8. return elem.nodeName && elem.nodeName.toLowerCase() === 'input' && (elem.type === 'checkbox' || elem.type === 'radio'); } function getTargetInstForClickEvent(topLevelType, targetInst) { if (topLevelType === topLevelTypes.topClick) { return targetInst; } } /** * This plugin creates an `onChange` event that normalizes change events * across form elements. This event fires at a time when it's possible to * change the element's value without seeing a flicker. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - select */ var ChangeEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; var getTargetInstFunc, handleEventFunc; if (shouldUseChangeEvent(targetNode)) { if (doesChangeEventBubble) { getTargetInstFunc = getTargetInstForChangeEvent; } else { handleEventFunc = handleEventsForChangeEventIE8; } } else if (isTextInputElement(targetNode)) { if (isInputEventSupported) { getTargetInstFunc = getTargetInstForInputEvent; } else { getTargetInstFunc = getTargetInstForInputEventIE; handleEventFunc = handleEventsForInputEventIE; } } else if (shouldUseClickEvent(targetNode)) { getTargetInstFunc = getTargetInstForClickEvent; } if (getTargetInstFunc) { var inst = getTargetInstFunc(topLevelType, targetInst); if (inst) { var event = SyntheticEvent.getPooled(eventTypes.change, inst, nativeEvent, nativeEventTarget); event.type = 'change'; EventPropagators.accumulateTwoPhaseDispatches(event); return event; } } if (handleEventFunc) { handleEventFunc(topLevelType, targetNode, targetInst); } } }; module.exports = ChangeEventPlugin; /***/ }, /* 55 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdates */ 'use strict'; var _assign = __webpack_require__(4); var CallbackQueue = __webpack_require__(56); var PooledClass = __webpack_require__(6); var ReactFeatureFlags = __webpack_require__(57); var ReactPerf = __webpack_require__(58); var ReactReconciler = __webpack_require__(59); var Transaction = __webpack_require__(62); var invariant = __webpack_require__(7); var dirtyComponents = []; var asapCallbackQueue = CallbackQueue.getPooled(); var asapEnqueued = false; var batchingStrategy = null; function ensureInjected() { !(ReactUpdates.ReactReconcileTransaction && batchingStrategy) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must inject a reconcile transaction class and batching ' + 'strategy') : invariant(false) : void 0; } var NESTED_UPDATES = { initialize: function () { this.dirtyComponentsLength = dirtyComponents.length; }, close: function () { if (this.dirtyComponentsLength !== dirtyComponents.length) { // Additional updates were enqueued by componentDidUpdate handlers or // similar; before our own UPDATE_QUEUEING wrapper closes, we want to run // these new updates so that if A's componentDidUpdate calls setState on // B, B will update before the callback A's updater provided when calling // setState. dirtyComponents.splice(0, this.dirtyComponentsLength); flushBatchedUpdates(); } else { dirtyComponents.length = 0; } } }; var UPDATE_QUEUEING = { initialize: function () { this.callbackQueue.reset(); }, close: function () { this.callbackQueue.notifyAll(); } }; var TRANSACTION_WRAPPERS = [NESTED_UPDATES, UPDATE_QUEUEING]; function ReactUpdatesFlushTransaction() { this.reinitializeTransaction(); this.dirtyComponentsLength = null; this.callbackQueue = CallbackQueue.getPooled(); this.reconcileTransaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */true); } _assign(ReactUpdatesFlushTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, destructor: function () { this.dirtyComponentsLength = null; CallbackQueue.release(this.callbackQueue); this.callbackQueue = null; ReactUpdates.ReactReconcileTransaction.release(this.reconcileTransaction); this.reconcileTransaction = null; }, perform: function (method, scope, a) { // Essentially calls `this.reconcileTransaction.perform(method, scope, a)` // with this transaction's wrappers around it. return Transaction.Mixin.perform.call(this, this.reconcileTransaction.perform, this.reconcileTransaction, method, scope, a); } }); PooledClass.addPoolingTo(ReactUpdatesFlushTransaction); function batchedUpdates(callback, a, b, c, d, e) { ensureInjected(); batchingStrategy.batchedUpdates(callback, a, b, c, d, e); } /** * Array comparator for ReactComponents by mount ordering. * * @param {ReactComponent} c1 first component you're comparing * @param {ReactComponent} c2 second component you're comparing * @return {number} Return value usable by Array.prototype.sort(). */ function mountOrderComparator(c1, c2) { return c1._mountOrder - c2._mountOrder; } function runBatchedUpdates(transaction) { var len = transaction.dirtyComponentsLength; !(len === dirtyComponents.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Expected flush transaction\'s stored dirty-components length (%s) to ' + 'match dirty-components array length (%s).', len, dirtyComponents.length) : invariant(false) : void 0; // Since reconciling a component higher in the owner hierarchy usually (not // always -- see shouldComponentUpdate()) will reconcile children, reconcile // them before their children by sorting the array. dirtyComponents.sort(mountOrderComparator); for (var i = 0; i < len; i++) { // If a component is unmounted before pending changes apply, it will still // be here, but we assume that it has cleared its _pendingCallbacks and // that performUpdateIfNecessary is a noop. var component = dirtyComponents[i]; // If performUpdateIfNecessary happens to enqueue any new updates, we // shouldn't execute the callbacks until the next render happens, so // stash the callbacks first var callbacks = component._pendingCallbacks; component._pendingCallbacks = null; var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var namedComponent = component; // Duck type TopLevelWrapper. This is probably always true. if (component._currentElement.props === component._renderedComponent._currentElement) { namedComponent = component._renderedComponent; } markerName = 'React update: ' + namedComponent.getName(); console.time(markerName); } ReactReconciler.performUpdateIfNecessary(component, transaction.reconcileTransaction); if (markerName) { console.timeEnd(markerName); } if (callbacks) { for (var j = 0; j < callbacks.length; j++) { transaction.callbackQueue.enqueue(callbacks[j], component.getPublicInstance()); } } } } var flushBatchedUpdates = function () { // ReactUpdatesFlushTransaction's wrappers will clear the dirtyComponents // array and perform any updates enqueued by mount-ready handlers (i.e., // componentDidUpdate) but we need to check here too in order to catch // updates enqueued by setState callbacks and asap calls. while (dirtyComponents.length || asapEnqueued) { if (dirtyComponents.length) { var transaction = ReactUpdatesFlushTransaction.getPooled(); transaction.perform(runBatchedUpdates, null, transaction); ReactUpdatesFlushTransaction.release(transaction); } if (asapEnqueued) { asapEnqueued = false; var queue = asapCallbackQueue; asapCallbackQueue = CallbackQueue.getPooled(); queue.notifyAll(); CallbackQueue.release(queue); } } }; flushBatchedUpdates = ReactPerf.measure('ReactUpdates', 'flushBatchedUpdates', flushBatchedUpdates); /** * Mark a component as needing a rerender, adding an optional callback to a * list of functions which will be executed once the rerender occurs. */ function enqueueUpdate(component) { ensureInjected(); // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (This is called by each top-level update // function, like setProps, setState, forceUpdate, etc.; creation and // destruction of top-level components is guarded in ReactMount.) if (!batchingStrategy.isBatchingUpdates) { batchingStrategy.batchedUpdates(enqueueUpdate, component); return; } dirtyComponents.push(component); } /** * Enqueue a callback to be run at the end of the current batching cycle. Throws * if no updates are currently being performed. */ function asap(callback, context) { !batchingStrategy.isBatchingUpdates ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' + 'updates are not being batched.') : invariant(false) : void 0; asapCallbackQueue.enqueue(callback, context); asapEnqueued = true; } var ReactUpdatesInjection = { injectReconcileTransaction: function (ReconcileTransaction) { !ReconcileTransaction ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a reconcile transaction class') : invariant(false) : void 0; ReactUpdates.ReactReconcileTransaction = ReconcileTransaction; }, injectBatchingStrategy: function (_batchingStrategy) { !_batchingStrategy ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batching strategy') : invariant(false) : void 0; !(typeof _batchingStrategy.batchedUpdates === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide a batchedUpdates() function') : invariant(false) : void 0; !(typeof _batchingStrategy.isBatchingUpdates === 'boolean') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactUpdates: must provide an isBatchingUpdates boolean attribute') : invariant(false) : void 0; batchingStrategy = _batchingStrategy; } }; var ReactUpdates = { /** * React references `ReactReconcileTransaction` using this property in order * to allow dependency injection. * * @internal */ ReactReconcileTransaction: null, batchedUpdates: batchedUpdates, enqueueUpdate: enqueueUpdate, flushBatchedUpdates: flushBatchedUpdates, injection: ReactUpdatesInjection, asap: asap }; module.exports = ReactUpdates; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CallbackQueue */ 'use strict'; var _assign = __webpack_require__(4); var PooledClass = __webpack_require__(6); var invariant = __webpack_require__(7); /** * A specialized pseudo-event module to help keep track of components waiting to * be notified when their DOM representations are available for use. * * This implements `PooledClass`, so you should never need to instantiate this. * Instead, use `CallbackQueue.getPooled()`. * * @class ReactMountReady * @implements PooledClass * @internal */ function CallbackQueue() { this._callbacks = null; this._contexts = null; } _assign(CallbackQueue.prototype, { /** * Enqueues a callback to be invoked when `notifyAll` is invoked. * * @param {function} callback Invoked when `notifyAll` is invoked. * @param {?object} context Context to call `callback` with. * @internal */ enqueue: function (callback, context) { this._callbacks = this._callbacks || []; this._contexts = this._contexts || []; this._callbacks.push(callback); this._contexts.push(context); }, /** * Invokes all enqueued callbacks and clears the queue. This is invoked after * the DOM representation of a component has been created or updated. * * @internal */ notifyAll: function () { var callbacks = this._callbacks; var contexts = this._contexts; if (callbacks) { !(callbacks.length === contexts.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Mismatched list of contexts in callback queue') : invariant(false) : void 0; this._callbacks = null; this._contexts = null; for (var i = 0; i < callbacks.length; i++) { callbacks[i].call(contexts[i]); } callbacks.length = 0; contexts.length = 0; } }, checkpoint: function () { return this._callbacks ? this._callbacks.length : 0; }, rollback: function (len) { if (this._callbacks) { this._callbacks.length = len; this._contexts.length = len; } }, /** * Resets the internal queue. * * @internal */ reset: function () { this._callbacks = null; this._contexts = null; }, /** * `PooledClass` looks for this. */ destructor: function () { this.reset(); } }); PooledClass.addPoolingTo(CallbackQueue); module.exports = CallbackQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 57 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactFeatureFlags */ 'use strict'; var ReactFeatureFlags = { // When true, call console.time() before and .timeEnd() after each top-level // render (both initial renders and updates). Useful when looking at prod-mode // timeline profiles in Chrome, for example. logTopLevelRenders: false }; module.exports = ReactFeatureFlags; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPerf */ 'use strict'; /** * ReactPerf is a general AOP system designed to measure performance. This * module only has the hooks: see ReactDefaultPerf for the analysis tool. */ var ReactPerf = { /** * Boolean to enable/disable measurement. Set to false by default to prevent * accidental logging and perf loss. */ enableMeasure: false, /** * Holds onto the measure function in use. By default, don't measure * anything, but we'll override this if we inject a measure function. */ storedMeasure: _noMeasure, /** * @param {object} object * @param {string} objectName * @param {object<string>} methodNames */ measureMethods: function (object, objectName, methodNames) { if (process.env.NODE_ENV !== 'production') { for (var key in methodNames) { if (!methodNames.hasOwnProperty(key)) { continue; } object[key] = ReactPerf.measure(objectName, methodNames[key], object[key]); } } }, /** * Use this to wrap methods you want to measure. Zero overhead in production. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ measure: function (objName, fnName, func) { if (process.env.NODE_ENV !== 'production') { var measuredFunc = null; var wrapper = function () { if (ReactPerf.enableMeasure) { if (!measuredFunc) { measuredFunc = ReactPerf.storedMeasure(objName, fnName, func); } return measuredFunc.apply(this, arguments); } return func.apply(this, arguments); }; wrapper.displayName = objName + '_' + fnName; return wrapper; } return func; }, injection: { /** * @param {function} measure */ injectMeasure: function (measure) { ReactPerf.storedMeasure = measure; } } }; /** * Simply passes through the measured function, without measuring it. * * @param {string} objName * @param {string} fnName * @param {function} func * @return {function} */ function _noMeasure(objName, fnName, func) { return func; } module.exports = ReactPerf; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconciler */ 'use strict'; var ReactRef = __webpack_require__(60); var ReactInstrumentation = __webpack_require__(18); /** * Helper to call ReactRef.attachRefs with this composite component, split out * to avoid allocations in the transaction mount-ready queue. */ function attachRefs() { ReactRef.attachRefs(this, this._currentElement); } var ReactReconciler = { /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} the containing native component instance * @param {?object} info about the native container * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (internalInstance, transaction, nativeParent, nativeContainerInfo, context) { var markup = internalInstance.mountComponent(transaction, nativeParent, nativeContainerInfo, context); if (internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onMountComponent(internalInstance); } return markup; }, /** * Returns a value that can be passed to * ReactComponentEnvironment.replaceNodeWithMarkup. */ getNativeNode: function (internalInstance) { return internalInstance.getNativeNode(); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (internalInstance, safely) { ReactRef.detachRefs(internalInstance, internalInstance._currentElement); internalInstance.unmountComponent(safely); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onUnmountComponent(internalInstance); } }, /** * Update a component using a new element. * * @param {ReactComponent} internalInstance * @param {ReactElement} nextElement * @param {ReactReconcileTransaction} transaction * @param {object} context * @internal */ receiveComponent: function (internalInstance, nextElement, transaction, context) { var prevElement = internalInstance._currentElement; if (nextElement === prevElement && context === internalInstance._context) { // Since elements are immutable after the owner is rendered, // we can do a cheap identity compare here to determine if this is a // superfluous reconcile. It's possible for state to be mutable but such // change should trigger an update of the owner which would recreate // the element. We explicitly check for the existence of an owner since // it's possible for an element created outside a composite to be // deeply mutated and reused. // TODO: Bailing out early is just a perf optimization right? // TODO: Removing the return statement should affect correctness? return; } var refsChanged = ReactRef.shouldUpdateRefs(prevElement, nextElement); if (refsChanged) { ReactRef.detachRefs(internalInstance, prevElement); } internalInstance.receiveComponent(nextElement, transaction, context); if (refsChanged && internalInstance._currentElement && internalInstance._currentElement.ref != null) { transaction.getReactMountReady().enqueue(attachRefs, internalInstance); } if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance); } }, /** * Flush any dirty changes in a component. * * @param {ReactComponent} internalInstance * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (internalInstance, transaction) { internalInstance.performUpdateIfNecessary(transaction); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onUpdateComponent(internalInstance); } } }; module.exports = ReactReconciler; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactRef */ 'use strict'; var ReactOwner = __webpack_require__(61); var ReactRef = {}; function attachRef(ref, component, owner) { if (typeof ref === 'function') { ref(component.getPublicInstance()); } else { // Legacy ref ReactOwner.addComponentAsRefTo(component, ref, owner); } } function detachRef(ref, component, owner) { if (typeof ref === 'function') { ref(null); } else { // Legacy ref ReactOwner.removeComponentAsRefFrom(component, ref, owner); } } ReactRef.attachRefs = function (instance, element) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { attachRef(ref, instance, element._owner); } }; ReactRef.shouldUpdateRefs = function (prevElement, nextElement) { // If either the owner or a `ref` has changed, make sure the newest owner // has stored a reference to `this`, and the previous owner (if different) // has forgotten the reference to `this`. We use the element instead // of the public this.props because the post processing cannot determine // a ref. The ref conceptually lives on the element. // TODO: Should this even be possible? The owner cannot change because // it's forbidden by shouldUpdateReactComponent. The ref can change // if you swap the keys of but not the refs. Reconsider where this check // is made. It probably belongs where the key checking and // instantiateReactComponent is done. var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; return( // This has a few false positives w/r/t empty components. prevEmpty || nextEmpty || nextElement._owner !== prevElement._owner || nextElement.ref !== prevElement.ref ); }; ReactRef.detachRefs = function (instance, element) { if (element === null || element === false) { return; } var ref = element.ref; if (ref != null) { detachRef(ref, instance, element._owner); } }; module.exports = ReactRef; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactOwner */ 'use strict'; var invariant = __webpack_require__(7); /** * ReactOwners are capable of storing references to owned components. * * All components are capable of //being// referenced by owner components, but * only ReactOwner components are capable of //referencing// owned components. * The named reference is known as a "ref". * * Refs are available when mounted and updated during reconciliation. * * var MyComponent = React.createClass({ * render: function() { * return ( * <div onClick={this.handleClick}> * <CustomComponent ref="custom" /> * </div> * ); * }, * handleClick: function() { * this.refs.custom.handleClick(); * }, * componentDidMount: function() { * this.refs.custom.initialize(); * } * }); * * Refs should rarely be used. When refs are used, they should only be done to * control data that is not handled by React's data flow. * * @class ReactOwner */ var ReactOwner = { /** * @param {?object} object * @return {boolean} True if `object` is a valid owner. * @final */ isValidOwner: function (object) { return !!(object && typeof object.attachRef === 'function' && typeof object.detachRef === 'function'); }, /** * Adds a component by ref to an owner component. * * @param {ReactComponent} component Component to reference. * @param {string} ref Name by which to refer to the component. * @param {ReactOwner} owner Component on which to record the ref. * @final * @internal */ addComponentAsRefTo: function (component, ref, owner) { !ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, '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).') : invariant(false) : void 0; owner.attachRef(ref, component); }, /** * Removes a component by ref from an owner component. * * @param {ReactComponent} component Component to dereference. * @param {string} ref Name of the ref to remove. * @param {ReactOwner} owner Component on which the ref is recorded. * @final * @internal */ removeComponentAsRefFrom: function (component, ref, owner) { !ReactOwner.isValidOwner(owner) ? process.env.NODE_ENV !== 'production' ? invariant(false, '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).') : invariant(false) : void 0; var ownerPublicInstance = owner.getPublicInstance(); // Check that `component`'s owner is still alive and that `component` is still the current ref // because we do not want to detach the ref if another component stole it. if (ownerPublicInstance && ownerPublicInstance.refs[ref] === component.getPublicInstance()) { owner.detachRef(ref); } } }; module.exports = ReactOwner; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Transaction */ 'use strict'; var invariant = __webpack_require__(7); /** * `Transaction` creates a black box that is able to wrap any method such that * certain invariants are maintained before and after the method is invoked * (Even if an exception is thrown while invoking the wrapped method). Whoever * instantiates a transaction can provide enforcers of the invariants at * creation time. The `Transaction` class itself will supply one additional * automatic invariant for you - the invariant that any transaction instance * should not be run while it is already being run. You would typically create a * single instance of a `Transaction` for reuse multiple times, that potentially * is used to wrap several different methods. Wrappers are extremely simple - * they only require implementing two methods. * * <pre> * wrappers (injected at creation time) * + + * | | * +-----------------|--------|--------------+ * | v | | * | +---------------+ | | * | +--| wrapper1 |---|----+ | * | | +---------------+ v | | * | | +-------------+ | | * | | +----| wrapper2 |--------+ | * | | | +-------------+ | | | * | | | | | | * | v v v v | wrapper * | +---+ +---+ +---------+ +---+ +---+ | invariants * perform(anyMethod) | | | | | | | | | | | | maintained * +----------------->|-|---|-|---|-->|anyMethod|---|---|-|---|-|--------> * | | | | | | | | | | | | * | | | | | | | | | | | | * | | | | | | | | | | | | * | +---+ +---+ +---------+ +---+ +---+ | * | initialize close | * +-----------------------------------------+ * </pre> * * Use cases: * - Preserving the input selection ranges before/after reconciliation. * Restoring selection even in the event of an unexpected error. * - Deactivating events while rearranging the DOM, preventing blurs/focuses, * while guaranteeing that afterwards, the event system is reactivated. * - Flushing a queue of collected DOM mutations to the main UI thread after a * reconciliation takes place in a worker thread. * - Invoking any collected `componentDidUpdate` callbacks after rendering new * content. * - (Future use case): Wrapping particular flushes of the `ReactWorker` queue * to preserve the `scrollTop` (an automatic scroll aware DOM). * - (Future use case): Layout calculations before and after DOM updates. * * Transactional plugin API: * - A module that has an `initialize` method that returns any precomputation. * - and a `close` method that accepts the precomputation. `close` is invoked * when the wrapped process is completed, or has failed. * * @param {Array<TransactionalWrapper>} transactionWrapper Wrapper modules * that implement `initialize` and `close`. * @return {Transaction} Single transaction for reuse in thread. * * @class Transaction */ var Mixin = { /** * Sets up this instance so that it is prepared for collecting metrics. Does * so such that this setup method may be used on an instance that is already * initialized, in a way that does not consume additional memory upon reuse. * That can be useful if you decide to make your subclass of this mixin a * "PooledClass". */ reinitializeTransaction: function () { this.transactionWrappers = this.getTransactionWrappers(); if (this.wrapperInitData) { this.wrapperInitData.length = 0; } else { this.wrapperInitData = []; } this._isInTransaction = false; }, _isInTransaction: false, /** * @abstract * @return {Array<TransactionWrapper>} Array of transaction wrappers. */ getTransactionWrappers: null, isInTransaction: function () { return !!this._isInTransaction; }, /** * Executes the function within a safety window. Use this for the top level * methods that result in large amounts of computation/mutations that would * need to be safety checked. The optional arguments helps prevent the need * to bind in many cases. * * @param {function} method Member of scope to call. * @param {Object} scope Scope to invoke from. * @param {Object?=} a Argument to pass to the method. * @param {Object?=} b Argument to pass to the method. * @param {Object?=} c Argument to pass to the method. * @param {Object?=} d Argument to pass to the method. * @param {Object?=} e Argument to pass to the method. * @param {Object?=} f Argument to pass to the method. * * @return {*} Return value from `method`. */ perform: function (method, scope, a, b, c, d, e, f) { !!this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.perform(...): Cannot initialize a transaction when there ' + 'is already an outstanding transaction.') : invariant(false) : void 0; var errorThrown; var ret; try { this._isInTransaction = true; // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // one of these calls threw. errorThrown = true; this.initializeAll(0); ret = method.call(scope, a, b, c, d, e, f); errorThrown = false; } finally { try { if (errorThrown) { // If `method` throws, prefer to show that stack trace over any thrown // by invoking `closeAll`. try { this.closeAll(0); } catch (err) {} } else { // Since `method` didn't throw, we don't want to silence the exception // here. this.closeAll(0); } } finally { this._isInTransaction = false; } } return ret; }, initializeAll: function (startIndex) { var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; try { // Catching errors makes debugging more difficult, so we start with the // OBSERVED_ERROR state before overwriting it with the real return value // of initialize -- if it's still set to OBSERVED_ERROR in the finally // block, it means wrapper.initialize threw. this.wrapperInitData[i] = Transaction.OBSERVED_ERROR; this.wrapperInitData[i] = wrapper.initialize ? wrapper.initialize.call(this) : null; } finally { if (this.wrapperInitData[i] === Transaction.OBSERVED_ERROR) { // The initializer for wrapper i threw an error; initialize the // remaining wrappers but silence any exceptions from them to ensure // that the first error is the one to bubble up. try { this.initializeAll(i + 1); } catch (err) {} } } } }, /** * Invokes each of `this.transactionWrappers.close[i]` functions, passing into * them the respective return values of `this.transactionWrappers.init[i]` * (`close`rs that correspond to initializers that failed will not be * invoked). */ closeAll: function (startIndex) { !this.isInTransaction() ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Transaction.closeAll(): Cannot close transaction when none are open.') : invariant(false) : void 0; var transactionWrappers = this.transactionWrappers; for (var i = startIndex; i < transactionWrappers.length; i++) { var wrapper = transactionWrappers[i]; var initData = this.wrapperInitData[i]; var errorThrown; try { // Catching errors makes debugging more difficult, so we start with // errorThrown set to true before setting it to false after calling // close -- if it's still set to true in the finally block, it means // wrapper.close threw. errorThrown = true; if (initData !== Transaction.OBSERVED_ERROR && wrapper.close) { wrapper.close.call(this, initData); } errorThrown = false; } finally { if (errorThrown) { // The closer for wrapper i threw an error; close the remaining // wrappers but silence any exceptions from them to ensure that the // first error is the one to bubble up. try { this.closeAll(i + 1); } catch (e) {} } } } this.wrapperInitData.length = 0; } }; var Transaction = { Mixin: Mixin, /** * Token to look for to determine if an error occurred. */ OBSERVED_ERROR: {} }; module.exports = Transaction; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 63 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventTarget */ 'use strict'; /** * Gets the target node from a native browser event by accounting for * inconsistencies in browser DOM APIs. * * @param {object} nativeEvent Native browser event. * @return {DOMEventTarget} Target node. */ function getEventTarget(nativeEvent) { var target = nativeEvent.target || nativeEvent.srcElement || window; // Normalize SVG <use> element events #4963 if (target.correspondingUseElement) { target = target.correspondingUseElement; } // Safari may fire events on text nodes (Node.TEXT_NODE is 3). // @see http://www.quirksmode.org/js/events_properties.html return target.nodeType === 3 ? target.parentNode : target; } module.exports = getEventTarget; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isEventSupported */ 'use strict'; var ExecutionEnvironment = __webpack_require__(48); var useHasFeature; if (ExecutionEnvironment.canUseDOM) { useHasFeature = document.implementation && document.implementation.hasFeature && // always returns true in newer browsers as per the standard. // @see http://dom.spec.whatwg.org/#dom-domimplementation-hasfeature document.implementation.hasFeature('', '') !== true; } /** * Checks if an event is supported in the current execution environment. * * NOTE: This will not work correctly for non-generic events such as `change`, * `reset`, `load`, `error`, and `select`. * * Borrows from Modernizr. * * @param {string} eventNameSuffix Event name, e.g. "click". * @param {?boolean} capture Check if the capture phase is supported. * @return {boolean} True if the event is supported. * @internal * @license Modernizr 3.0.0pre (Custom Build) | MIT */ function isEventSupported(eventNameSuffix, capture) { if (!ExecutionEnvironment.canUseDOM || capture && !('addEventListener' in document)) { return false; } var eventName = 'on' + eventNameSuffix; var isSupported = eventName in document; if (!isSupported) { var element = document.createElement('div'); element.setAttribute(eventName, 'return;'); isSupported = typeof element[eventName] === 'function'; } if (!isSupported && useHasFeature && eventNameSuffix === 'wheel') { // This is the only way to test support for the `wheel` event in IE9+. isSupported = document.implementation.hasFeature('Events.wheel', '3.0'); } return isSupported; } module.exports = isEventSupported; /***/ }, /* 65 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule isTextInputElement */ 'use strict'; /** * @see http://www.whatwg.org/specs/web-apps/current-work/multipage/the-input-element.html#input-type-attr-summary */ var supportedInputTypes = { 'color': true, 'date': true, 'datetime': true, 'datetime-local': true, 'email': true, 'month': true, 'number': true, 'password': true, 'range': true, 'search': true, 'tel': true, 'text': true, 'time': true, 'url': true, 'week': true }; function isTextInputElement(elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && supportedInputTypes[elem.type] || nodeName === 'textarea'); } module.exports = isTextInputElement; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DefaultEventPluginOrder */ 'use strict'; var keyOf = __webpack_require__(26); /** * Module that is injectable into `EventPluginHub`, that specifies a * deterministic ordering of `EventPlugin`s. A convenient way to reason about * plugins, without having to package every one of them. This is better than * having plugins be ordered in the same order that they are injected because * that ordering would be influenced by the packaging order. * `ResponderEventPlugin` must occur before `SimpleEventPlugin` so that * preventing default on events is convenient in `SimpleEventPlugin` handlers. */ var DefaultEventPluginOrder = [keyOf({ ResponderEventPlugin: null }), keyOf({ SimpleEventPlugin: null }), keyOf({ TapEventPlugin: null }), keyOf({ EnterLeaveEventPlugin: null }), keyOf({ ChangeEventPlugin: null }), keyOf({ SelectEventPlugin: null }), keyOf({ BeforeInputEventPlugin: null })]; module.exports = DefaultEventPluginOrder; /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule EnterLeaveEventPlugin */ 'use strict'; var EventConstants = __webpack_require__(40); var EventPropagators = __webpack_require__(41); var ReactDOMComponentTree = __webpack_require__(35); var SyntheticMouseEvent = __webpack_require__(68); var keyOf = __webpack_require__(26); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { mouseEnter: { registrationName: keyOf({ onMouseEnter: null }), dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] }, mouseLeave: { registrationName: keyOf({ onMouseLeave: null }), dependencies: [topLevelTypes.topMouseOut, topLevelTypes.topMouseOver] } }; var EnterLeaveEventPlugin = { eventTypes: eventTypes, /** * For almost every interaction we care about, there will be both a top-level * `mouseover` and `mouseout` event that occurs. Only use `mouseout` so that * we do not extract duplicate events. However, moving the mouse into the * browser from outside will not fire a `mouseout` event. In this case, we use * the `mouseover` top-level event. */ extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (topLevelType === topLevelTypes.topMouseOver && (nativeEvent.relatedTarget || nativeEvent.fromElement)) { return null; } if (topLevelType !== topLevelTypes.topMouseOut && topLevelType !== topLevelTypes.topMouseOver) { // Must not be a mouse in or mouse out - ignoring. return null; } var win; if (nativeEventTarget.window === nativeEventTarget) { // `nativeEventTarget` is probably a window object. win = nativeEventTarget; } else { // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. var doc = nativeEventTarget.ownerDocument; if (doc) { win = doc.defaultView || doc.parentWindow; } else { win = window; } } var from; var to; if (topLevelType === topLevelTypes.topMouseOut) { from = targetInst; var related = nativeEvent.relatedTarget || nativeEvent.toElement; to = related ? ReactDOMComponentTree.getClosestInstanceFromNode(related) : null; } else { // Moving to a node from outside the window. from = null; to = targetInst; } if (from === to) { // Nothing pertains to our managed components. return null; } var fromNode = from == null ? win : ReactDOMComponentTree.getNodeFromInstance(from); var toNode = to == null ? win : ReactDOMComponentTree.getNodeFromInstance(to); var leave = SyntheticMouseEvent.getPooled(eventTypes.mouseLeave, from, nativeEvent, nativeEventTarget); leave.type = 'mouseleave'; leave.target = fromNode; leave.relatedTarget = toNode; var enter = SyntheticMouseEvent.getPooled(eventTypes.mouseEnter, to, nativeEvent, nativeEventTarget); enter.type = 'mouseenter'; enter.target = toNode; enter.relatedTarget = fromNode; EventPropagators.accumulateEnterLeaveDispatches(leave, enter, from, to); return [leave, enter]; } }; module.exports = EnterLeaveEventPlugin; /***/ }, /* 68 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticMouseEvent */ 'use strict'; var SyntheticUIEvent = __webpack_require__(69); var ViewportMetrics = __webpack_require__(70); var getEventModifierState = __webpack_require__(71); /** * @interface MouseEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var MouseEventInterface = { screenX: null, screenY: null, clientX: null, clientY: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, getModifierState: getEventModifierState, button: function (event) { // Webkit, Firefox, IE9+ // which: 1 2 3 // button: 0 1 2 (standard) var button = event.button; if ('which' in event) { return button; } // IE<9 // which: undefined // button: 0 0 0 // button: 1 4 2 (onmouseup) return button === 2 ? 2 : button === 4 ? 1 : 0; }, buttons: null, relatedTarget: function (event) { return event.relatedTarget || (event.fromElement === event.srcElement ? event.toElement : event.fromElement); }, // "Proprietary" Interface. pageX: function (event) { return 'pageX' in event ? event.pageX : event.clientX + ViewportMetrics.currentScrollLeft; }, pageY: function (event) { return 'pageY' in event ? event.pageY : event.clientY + ViewportMetrics.currentScrollTop; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticMouseEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface); module.exports = SyntheticMouseEvent; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticUIEvent */ 'use strict'; var SyntheticEvent = __webpack_require__(52); var getEventTarget = __webpack_require__(63); /** * @interface UIEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var UIEventInterface = { view: function (event) { if (event.view) { return event.view; } var target = getEventTarget(event); if (target != null && target.window === target) { // target is a window object return target; } var doc = target.ownerDocument; // TODO: Figure out why `ownerDocument` is sometimes undefined in IE8. if (doc) { return doc.defaultView || doc.parentWindow; } else { return window; } }, detail: function (event) { return event.detail || 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticUIEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface); module.exports = SyntheticUIEvent; /***/ }, /* 70 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ViewportMetrics */ 'use strict'; var ViewportMetrics = { currentScrollLeft: 0, currentScrollTop: 0, refreshScrollValues: function (scrollPosition) { ViewportMetrics.currentScrollLeft = scrollPosition.x; ViewportMetrics.currentScrollTop = scrollPosition.y; } }; module.exports = ViewportMetrics; /***/ }, /* 71 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventModifierState */ 'use strict'; /** * Translation from modifier key to the associated property in the event. * @see http://www.w3.org/TR/DOM-Level-3-Events/#keys-Modifiers */ var modifierKeyToProp = { 'Alt': 'altKey', 'Control': 'ctrlKey', 'Meta': 'metaKey', 'Shift': 'shiftKey' }; // IE8 does not implement getModifierState so we simply map it to the only // modifier keys exposed by the event itself, does not support Lock-keys. // Currently, all major browsers except Chrome seems to support Lock-keys. function modifierStateGetter(keyArg) { var syntheticEvent = this; var nativeEvent = syntheticEvent.nativeEvent; if (nativeEvent.getModifierState) { return nativeEvent.getModifierState(keyArg); } var keyProp = modifierKeyToProp[keyArg]; return keyProp ? !!nativeEvent[keyProp] : false; } function getEventModifierState(nativeEvent) { return modifierStateGetter; } module.exports = getEventModifierState; /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule HTMLDOMPropertyConfig */ 'use strict'; var DOMProperty = __webpack_require__(36); var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY; var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE; var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS; var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE; var HAS_POSITIVE_NUMERIC_VALUE = DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE; var HAS_OVERLOADED_BOOLEAN_VALUE = DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE; var HTMLDOMPropertyConfig = { isCustomAttribute: RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$')), Properties: { /** * Standard Properties */ accept: 0, acceptCharset: 0, accessKey: 0, action: 0, allowFullScreen: HAS_BOOLEAN_VALUE, allowTransparency: 0, alt: 0, async: HAS_BOOLEAN_VALUE, autoComplete: 0, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: HAS_BOOLEAN_VALUE, autoPlay: HAS_BOOLEAN_VALUE, capture: HAS_BOOLEAN_VALUE, cellPadding: 0, cellSpacing: 0, charSet: 0, challenge: 0, checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, cite: 0, classID: 0, className: 0, cols: HAS_POSITIVE_NUMERIC_VALUE, colSpan: 0, content: 0, contentEditable: 0, contextMenu: 0, controls: HAS_BOOLEAN_VALUE, coords: 0, crossOrigin: 0, data: 0, // For `<object />` acts as `src`. dateTime: 0, 'default': HAS_BOOLEAN_VALUE, defer: HAS_BOOLEAN_VALUE, dir: 0, disabled: HAS_BOOLEAN_VALUE, download: HAS_OVERLOADED_BOOLEAN_VALUE, draggable: 0, encType: 0, form: 0, formAction: 0, formEncType: 0, formMethod: 0, formNoValidate: HAS_BOOLEAN_VALUE, formTarget: 0, frameBorder: 0, headers: 0, height: 0, hidden: HAS_BOOLEAN_VALUE, high: 0, href: 0, hrefLang: 0, htmlFor: 0, httpEquiv: 0, icon: 0, id: 0, inputMode: 0, integrity: 0, is: 0, keyParams: 0, keyType: 0, kind: 0, label: 0, lang: 0, list: 0, loop: HAS_BOOLEAN_VALUE, low: 0, manifest: 0, marginHeight: 0, marginWidth: 0, max: 0, maxLength: 0, media: 0, mediaGroup: 0, method: 0, min: 0, minLength: 0, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, name: 0, nonce: 0, noValidate: HAS_BOOLEAN_VALUE, open: HAS_BOOLEAN_VALUE, optimum: 0, pattern: 0, placeholder: 0, poster: 0, preload: 0, profile: 0, radioGroup: 0, readOnly: HAS_BOOLEAN_VALUE, rel: 0, required: HAS_BOOLEAN_VALUE, reversed: HAS_BOOLEAN_VALUE, role: 0, rows: HAS_POSITIVE_NUMERIC_VALUE, rowSpan: HAS_NUMERIC_VALUE, sandbox: 0, scope: 0, scoped: HAS_BOOLEAN_VALUE, scrolling: 0, seamless: HAS_BOOLEAN_VALUE, selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE, shape: 0, size: HAS_POSITIVE_NUMERIC_VALUE, sizes: 0, span: HAS_POSITIVE_NUMERIC_VALUE, spellCheck: 0, src: 0, srcDoc: 0, srcLang: 0, srcSet: 0, start: HAS_NUMERIC_VALUE, step: 0, style: 0, summary: 0, tabIndex: 0, target: 0, title: 0, // Setting .type throws on non-<input> tags type: 0, useMap: 0, value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS, width: 0, wmode: 0, wrap: 0, /** * RDFa Properties */ about: 0, datatype: 0, inlist: 0, prefix: 0, // property is also supported for OpenGraph in meta tags. property: 0, resource: 0, 'typeof': 0, vocab: 0, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: 0, autoCorrect: 0, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: 0, // color is for Safari mask-icon link color: 0, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: 0, itemScope: HAS_BOOLEAN_VALUE, itemType: 0, // itemID and itemRef are for Microdata support as well but // only specified in the WHATWG spec document. See // https://html.spec.whatwg.org/multipage/microdata.html#microdata-dom-api itemID: 0, itemRef: 0, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: 0, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: 0, // IE-only attribute that controls focus behavior unselectable: 0 }, DOMAttributeNames: { acceptCharset: 'accept-charset', className: 'class', htmlFor: 'for', httpEquiv: 'http-equiv' }, DOMPropertyNames: {} }; module.exports = HTMLDOMPropertyConfig; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentBrowserEnvironment */ 'use strict'; var DOMChildrenOperations = __webpack_require__(74); var ReactDOMIDOperations = __webpack_require__(85); var ReactPerf = __webpack_require__(58); /** * Abstracts away all functionality of the reconciler that requires knowledge of * the browser context. TODO: These callers should be refactored to avoid the * need for this injection. */ var ReactComponentBrowserEnvironment = { processChildrenUpdates: ReactDOMIDOperations.dangerouslyProcessChildrenUpdates, replaceNodeWithMarkup: DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup, /** * If a particular environment requires that some resources be cleaned up, * specify this in the injected Mixin. In the DOM, we would likely want to * purge any cached node ID lookups. * * @private */ unmountIDFromEnvironment: function (rootNodeID) {} }; ReactPerf.measureMethods(ReactComponentBrowserEnvironment, 'ReactComponentBrowserEnvironment', { replaceNodeWithMarkup: 'replaceNodeWithMarkup' }); module.exports = ReactComponentBrowserEnvironment; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMChildrenOperations */ 'use strict'; var DOMLazyTree = __webpack_require__(75); var Danger = __webpack_require__(80); var ReactMultiChildUpdateTypes = __webpack_require__(84); var ReactPerf = __webpack_require__(58); var createMicrosoftUnsafeLocalFunction = __webpack_require__(76); var setInnerHTML = __webpack_require__(79); var setTextContent = __webpack_require__(77); function getNodeAfter(parentNode, node) { // Special case for text components, which return [open, close] comments // from getNativeNode. if (Array.isArray(node)) { node = node[1]; } return node ? node.nextSibling : parentNode.firstChild; } /** * Inserts `childNode` as a child of `parentNode` at the `index`. * * @param {DOMElement} parentNode Parent node in which to insert. * @param {DOMElement} childNode Child node to insert. * @param {number} index Index at which to insert the child. * @internal */ var insertChildAt = createMicrosoftUnsafeLocalFunction(function (parentNode, childNode, referenceNode) { // We rely exclusively on `insertBefore(node, null)` instead of also using // `appendChild(node)`. (Using `undefined` is not allowed by all browsers so // we are careful to use `null`.) parentNode.insertBefore(childNode, referenceNode); }); function insertLazyTreeChildAt(parentNode, childTree, referenceNode) { DOMLazyTree.insertTreeBefore(parentNode, childTree, referenceNode); } function moveChild(parentNode, childNode, referenceNode) { if (Array.isArray(childNode)) { moveDelimitedText(parentNode, childNode[0], childNode[1], referenceNode); } else { insertChildAt(parentNode, childNode, referenceNode); } } function removeChild(parentNode, childNode) { if (Array.isArray(childNode)) { var closingComment = childNode[1]; childNode = childNode[0]; removeDelimitedText(parentNode, childNode, closingComment); parentNode.removeChild(closingComment); } parentNode.removeChild(childNode); } function moveDelimitedText(parentNode, openingComment, closingComment, referenceNode) { var node = openingComment; while (true) { var nextNode = node.nextSibling; insertChildAt(parentNode, node, referenceNode); if (node === closingComment) { break; } node = nextNode; } } function removeDelimitedText(parentNode, startNode, closingComment) { while (true) { var node = startNode.nextSibling; if (node === closingComment) { // The closing comment is removed by ReactMultiChild. break; } else { parentNode.removeChild(node); } } } function replaceDelimitedText(openingComment, closingComment, stringText) { var parentNode = openingComment.parentNode; var nodeAfterComment = openingComment.nextSibling; if (nodeAfterComment === closingComment) { // There are no text nodes between the opening and closing comments; insert // a new one if stringText isn't empty. if (stringText) { insertChildAt(parentNode, document.createTextNode(stringText), nodeAfterComment); } } else { if (stringText) { // Set the text content of the first node after the opening comment, and // remove all following nodes up until the closing comment. setTextContent(nodeAfterComment, stringText); removeDelimitedText(parentNode, nodeAfterComment, closingComment); } else { removeDelimitedText(parentNode, openingComment, closingComment); } } } /** * Operations for updating with DOM children. */ var DOMChildrenOperations = { dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup, replaceDelimitedText: replaceDelimitedText, /** * Updates a component's children by processing a series of updates. The * update configurations are each expected to have a `parentNode` property. * * @param {array<object>} updates List of update configurations. * @internal */ processUpdates: function (parentNode, updates) { for (var k = 0; k < updates.length; k++) { var update = updates[k]; switch (update.type) { case ReactMultiChildUpdateTypes.INSERT_MARKUP: insertLazyTreeChildAt(parentNode, update.content, getNodeAfter(parentNode, update.afterNode)); break; case ReactMultiChildUpdateTypes.MOVE_EXISTING: moveChild(parentNode, update.fromNode, getNodeAfter(parentNode, update.afterNode)); break; case ReactMultiChildUpdateTypes.SET_MARKUP: setInnerHTML(parentNode, update.content); break; case ReactMultiChildUpdateTypes.TEXT_CONTENT: setTextContent(parentNode, update.content); break; case ReactMultiChildUpdateTypes.REMOVE_NODE: removeChild(parentNode, update.fromNode); break; } } } }; ReactPerf.measureMethods(DOMChildrenOperations, 'DOMChildrenOperations', { replaceDelimitedText: 'replaceDelimitedText' }); module.exports = DOMChildrenOperations; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMLazyTree */ 'use strict'; var createMicrosoftUnsafeLocalFunction = __webpack_require__(76); var setTextContent = __webpack_require__(77); /** * In IE (8-11) and Edge, appending nodes with no children is dramatically * faster than appending a full subtree, so we essentially queue up the * .appendChild calls here and apply them so each node is added to its parent * before any children are added. * * In other browsers, doing so is slower or neutral compared to the other order * (in Firefox, twice as slow) so we only do this inversion in IE. * * See https://github.com/spicyj/innerhtml-vs-createelement-vs-clonenode. */ var enableLazy = typeof document !== 'undefined' && typeof document.documentMode === 'number' || typeof navigator !== 'undefined' && typeof navigator.userAgent === 'string' && /\bEdge\/\d/.test(navigator.userAgent); function insertTreeChildren(tree) { if (!enableLazy) { return; } var node = tree.node; var children = tree.children; if (children.length) { for (var i = 0; i < children.length; i++) { insertTreeBefore(node, children[i], null); } } else if (tree.html != null) { node.innerHTML = tree.html; } else if (tree.text != null) { setTextContent(node, tree.text); } } var insertTreeBefore = createMicrosoftUnsafeLocalFunction(function (parentNode, tree, referenceNode) { // DocumentFragments aren't actually part of the DOM after insertion so // appending children won't update the DOM. We need to ensure the fragment // is properly populated first, breaking out of our lazy approach for just // this level. if (tree.node.nodeType === 11) { insertTreeChildren(tree); parentNode.insertBefore(tree.node, referenceNode); } else { parentNode.insertBefore(tree.node, referenceNode); insertTreeChildren(tree); } }); function replaceChildWithTree(oldNode, newTree) { oldNode.parentNode.replaceChild(newTree.node, oldNode); insertTreeChildren(newTree); } function queueChild(parentTree, childTree) { if (enableLazy) { parentTree.children.push(childTree); } else { parentTree.node.appendChild(childTree.node); } } function queueHTML(tree, html) { if (enableLazy) { tree.html = html; } else { tree.node.innerHTML = html; } } function queueText(tree, text) { if (enableLazy) { tree.text = text; } else { setTextContent(tree.node, text); } } function DOMLazyTree(node) { return { node: node, children: [], html: null, text: null }; } DOMLazyTree.insertTreeBefore = insertTreeBefore; DOMLazyTree.replaceChildWithTree = replaceChildWithTree; DOMLazyTree.queueChild = queueChild; DOMLazyTree.queueHTML = queueHTML; DOMLazyTree.queueText = queueText; module.exports = DOMLazyTree; /***/ }, /* 76 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule createMicrosoftUnsafeLocalFunction */ /* globals MSApp */ 'use strict'; /** * Create a function which has 'unsafe' privileges (required by windows8 apps) */ var createMicrosoftUnsafeLocalFunction = function (func) { if (typeof MSApp !== 'undefined' && MSApp.execUnsafeLocalFunction) { return function (arg0, arg1, arg2, arg3) { MSApp.execUnsafeLocalFunction(function () { return func(arg0, arg1, arg2, arg3); }); }; } else { return func; } }; module.exports = createMicrosoftUnsafeLocalFunction; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setTextContent */ 'use strict'; var ExecutionEnvironment = __webpack_require__(48); var escapeTextContentForBrowser = __webpack_require__(78); var setInnerHTML = __webpack_require__(79); /** * Set the textContent property of a node, ensuring that whitespace is preserved * even in IE8. innerText is a poor substitute for textContent and, among many * issues, inserts <br> instead of the literal newline chars. innerHTML behaves * as it should. * * @param {DOMElement} node * @param {string} text * @internal */ var setTextContent = function (node, text) { node.textContent = text; }; if (ExecutionEnvironment.canUseDOM) { if (!('textContent' in document.documentElement)) { setTextContent = function (node, text) { setInnerHTML(node, escapeTextContentForBrowser(text)); }; } } module.exports = setTextContent; /***/ }, /* 78 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule escapeTextContentForBrowser */ 'use strict'; var ESCAPE_LOOKUP = { '&': '&amp;', '>': '&gt;', '<': '&lt;', '"': '&quot;', '\'': '&#x27;' }; var ESCAPE_REGEX = /[&><"']/g; function escaper(match) { return ESCAPE_LOOKUP[match]; } /** * Escapes text to prevent scripting attacks. * * @param {*} text Text value to escape. * @return {string} An escaped string. */ function escapeTextContentForBrowser(text) { return ('' + text).replace(ESCAPE_REGEX, escaper); } module.exports = escapeTextContentForBrowser; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule setInnerHTML */ 'use strict'; var ExecutionEnvironment = __webpack_require__(48); var WHITESPACE_TEST = /^[ \r\n\t\f]/; var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/; var createMicrosoftUnsafeLocalFunction = __webpack_require__(76); /** * Set the innerHTML property of a node, ensuring that whitespace is preserved * even in IE8. * * @param {DOMElement} node * @param {string} html * @internal */ var setInnerHTML = createMicrosoftUnsafeLocalFunction(function (node, html) { node.innerHTML = html; }); if (ExecutionEnvironment.canUseDOM) { // IE8: When updating a just created node with innerHTML only leading // whitespace is removed. When updating an existing node with innerHTML // whitespace in root TextNodes is also collapsed. // @see quirksmode.org/bugreports/archives/2004/11/innerhtml_and_t.html // Feature detection; only IE8 is known to behave improperly like this. var testElement = document.createElement('div'); testElement.innerHTML = ' '; if (testElement.innerHTML === '') { setInnerHTML = function (node, html) { // Magic theory: IE8 supposedly differentiates between added and updated // nodes when processing innerHTML, innerHTML on updated nodes suffers // from worse whitespace behavior. Re-adding a node like this triggers // the initial and more favorable whitespace behavior. // TODO: What to do on a detached node? if (node.parentNode) { node.parentNode.replaceChild(node, node); } // We also implement a workaround for non-visible tags disappearing into // thin air on IE8, this only happens if there is no visible text // in-front of the non-visible tags. Piggyback on the whitespace fix // and simply check if any non-visible tags appear in the source. if (WHITESPACE_TEST.test(html) || html[0] === '<' && NONVISIBLE_TEST.test(html)) { // Recover leading whitespace by temporarily prepending any character. // \uFEFF has the potential advantage of being zero-width/invisible. // UglifyJS drops U+FEFF chars when parsing, so use String.fromCharCode // in hopes that this is preserved even if "\uFEFF" is transformed to // the actual Unicode character (by Babel, for example). // https://github.com/mishoo/UglifyJS2/blob/v2.4.20/lib/parse.js#L216 node.innerHTML = String.fromCharCode(0xFEFF) + html; // deleteData leaves an empty `TextNode` which offsets the index of all // children. Definitely want to avoid this. var textNode = node.firstChild; if (textNode.data.length === 1) { node.removeChild(textNode); } else { textNode.deleteData(0, 1); } } else { node.innerHTML = html; } }; } testElement = null; } module.exports = setInnerHTML; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule Danger */ 'use strict'; var DOMLazyTree = __webpack_require__(75); var ExecutionEnvironment = __webpack_require__(48); var createNodesFromMarkup = __webpack_require__(81); var emptyFunction = __webpack_require__(11); var getMarkupWrap = __webpack_require__(83); var invariant = __webpack_require__(7); var OPEN_TAG_NAME_EXP = /^(<[^ \/>]+)/; var RESULT_INDEX_ATTR = 'data-danger-index'; /** * Extracts the `nodeName` from a string of markup. * * NOTE: Extracting the `nodeName` does not require a regular expression match * because we make assumptions about React-generated markup (i.e. there are no * spaces surrounding the opening tag and there is at least one attribute). * * @param {string} markup String of markup. * @return {string} Node name of the supplied markup. * @see http://jsperf.com/extract-nodename */ function getNodeName(markup) { return markup.substring(1, markup.indexOf(' ')); } var Danger = { /** * Renders markup into an array of nodes. The markup is expected to render * into a list of root nodes. Also, the length of `resultList` and * `markupList` should be the same. * * @param {array<string>} markupList List of markup strings to render. * @return {array<DOMElement>} List of rendered nodes. * @internal */ dangerouslyRenderMarkup: function (markupList) { !ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, '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.') : invariant(false) : void 0; var nodeName; var markupByNodeName = {}; // Group markup by `nodeName` if a wrap is necessary, else by '*'. for (var i = 0; i < markupList.length; i++) { !markupList[i] ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyRenderMarkup(...): Missing markup.') : invariant(false) : void 0; nodeName = getNodeName(markupList[i]); nodeName = getMarkupWrap(nodeName) ? nodeName : '*'; markupByNodeName[nodeName] = markupByNodeName[nodeName] || []; markupByNodeName[nodeName][i] = markupList[i]; } var resultList = []; var resultListAssignmentCount = 0; for (nodeName in markupByNodeName) { if (!markupByNodeName.hasOwnProperty(nodeName)) { continue; } var markupListByNodeName = markupByNodeName[nodeName]; // This for-in loop skips the holes of the sparse array. The order of // iteration should follow the order of assignment, which happens to match // numerical index order, but we don't rely on that. var resultIndex; for (resultIndex in markupListByNodeName) { if (markupListByNodeName.hasOwnProperty(resultIndex)) { var markup = markupListByNodeName[resultIndex]; // Push the requested markup with an additional RESULT_INDEX_ATTR // attribute. If the markup does not start with a < character, it // will be discarded below (with an appropriate console.error). markupListByNodeName[resultIndex] = markup.replace(OPEN_TAG_NAME_EXP, // This index will be parsed back out below. '$1 ' + RESULT_INDEX_ATTR + '="' + resultIndex + '" '); } } // Render each group of markup with similar wrapping `nodeName`. var renderNodes = createNodesFromMarkup(markupListByNodeName.join(''), emptyFunction // Do nothing special with <script> tags. ); for (var j = 0; j < renderNodes.length; ++j) { var renderNode = renderNodes[j]; if (renderNode.hasAttribute && renderNode.hasAttribute(RESULT_INDEX_ATTR)) { resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR); renderNode.removeAttribute(RESULT_INDEX_ATTR); !!resultList.hasOwnProperty(resultIndex) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Assigning to an already-occupied result index.') : invariant(false) : void 0; resultList[resultIndex] = renderNode; // This should match resultList.length and markupList.length when // we're done. resultListAssignmentCount += 1; } else if (process.env.NODE_ENV !== 'production') { console.error('Danger: Discarding unexpected node:', renderNode); } } } // Although resultList was populated out of order, it should now be a dense // array. !(resultListAssignmentCount === resultList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Did not assign to every index of resultList.') : invariant(false) : void 0; !(resultList.length === markupList.length) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Danger: Expected markup to render %s nodes, but rendered %s.', markupList.length, resultList.length) : invariant(false) : void 0; return resultList; }, /** * Replaces a node with a string of markup at its current position within its * parent. The markup must render into a single root node. * * @param {DOMElement} oldChild Child node to replace. * @param {string} markup Markup to render in place of the child node. * @internal */ dangerouslyReplaceNodeWithMarkup: function (oldChild, markup) { !ExecutionEnvironment.canUseDOM ? process.env.NODE_ENV !== 'production' ? invariant(false, '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.') : invariant(false) : void 0; !markup ? process.env.NODE_ENV !== 'production' ? invariant(false, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(false) : void 0; !(oldChild.nodeName !== 'HTML') ? process.env.NODE_ENV !== 'production' ? invariant(false, '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().') : invariant(false) : void 0; if (typeof markup === 'string') { var newChild = createNodesFromMarkup(markup, emptyFunction)[0]; oldChild.parentNode.replaceChild(newChild, oldChild); } else { DOMLazyTree.replaceChildWithTree(oldChild, markup); } } }; module.exports = Danger; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /*eslint-disable fb-www/unsafe-html*/ var ExecutionEnvironment = __webpack_require__(48); var createArrayFromMixed = __webpack_require__(82); var getMarkupWrap = __webpack_require__(83); var invariant = __webpack_require__(7); /** * Dummy container used to render all markup. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Pattern used by `getNodeName`. */ var nodeNamePattern = /^\s*<(\w+)/; /** * Extracts the `nodeName` of the first element in a string of markup. * * @param {string} markup String of markup. * @return {?string} Node name of the supplied markup. */ function getNodeName(markup) { var nodeNameMatch = markup.match(nodeNamePattern); return nodeNameMatch && nodeNameMatch[1].toLowerCase(); } /** * Creates an array containing the nodes rendered from the supplied markup. The * optionally supplied `handleScript` function will be invoked once for each * <script> element that is rendered. If no `handleScript` function is supplied, * an exception is thrown if any <script> elements are rendered. * * @param {string} markup A string of valid HTML markup. * @param {?function} handleScript Invoked once for each rendered <script>. * @return {array<DOMElement|DOMTextNode>} An array of rendered nodes. */ function createNodesFromMarkup(markup, handleScript) { var node = dummyNode; !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup dummy not initialized') : invariant(false) : void 0; var nodeName = getNodeName(markup); var wrap = nodeName && getMarkupWrap(nodeName); if (wrap) { node.innerHTML = wrap[1] + markup + wrap[2]; var wrapDepth = wrap[0]; while (wrapDepth--) { node = node.lastChild; } } else { node.innerHTML = markup; } var scripts = node.getElementsByTagName('script'); if (scripts.length) { !handleScript ? process.env.NODE_ENV !== 'production' ? invariant(false, 'createNodesFromMarkup(...): Unexpected <script> element rendered.') : invariant(false) : void 0; createArrayFromMixed(scripts).forEach(handleScript); } var nodes = Array.from(node.childNodes); while (node.lastChild) { node.removeChild(node.lastChild); } return nodes; } module.exports = createNodesFromMarkup; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var invariant = __webpack_require__(7); /** * Convert array-like objects to arrays. * * This API assumes the caller knows the contents of the data type. For less * well defined inputs use createArrayFromMixed. * * @param {object|function|filelist} obj * @return {array} */ function toArray(obj) { var length = obj.length; // Some browsers builtin objects can report typeof 'function' (e.g. NodeList // in old versions of Safari). !(!Array.isArray(obj) && (typeof obj === 'object' || typeof obj === 'function')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Array-like object expected') : invariant(false) : void 0; !(typeof length === 'number') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object needs a length property') : invariant(false) : void 0; !(length === 0 || length - 1 in obj) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object should have keys for indices') : invariant(false) : void 0; !(typeof obj.callee !== 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'toArray: Object can\'t be `arguments`. Use rest params ' + '(function(...args) {}) or Array.from() instead.') : invariant(false) : void 0; // Old IE doesn't give collections access to hasOwnProperty. Assume inputs // without method will throw during the slice call and skip straight to the // fallback. if (obj.hasOwnProperty) { try { return Array.prototype.slice.call(obj); } catch (e) { // IE < 9 does not support Array#slice on collections objects } } // Fall back to copying key by key. This assumes all keys have a value, // so will not preserve sparsely populated inputs. var ret = Array(length); for (var ii = 0; ii < length; ii++) { ret[ii] = obj[ii]; } return ret; } /** * Perform a heuristic test to determine if an object is "array-like". * * A monk asked Joshu, a Zen master, "Has a dog Buddha nature?" * Joshu replied: "Mu." * * This function determines if its argument has "array nature": it returns * true if the argument is an actual array, an `arguments' object, or an * HTMLCollection (e.g. node.childNodes or node.getElementsByTagName()). * * It will return false for other array-like objects like Filelist. * * @param {*} obj * @return {boolean} */ function hasArrayNature(obj) { return( // not null/false !!obj && ( // arrays are objects, NodeLists are functions in Safari typeof obj == 'object' || typeof obj == 'function') && // quacks like an array 'length' in obj && // not window !('setInterval' in obj) && // no DOM node should be considered an array-like // a 'select' element has 'length' and 'item' properties on IE8 typeof obj.nodeType != 'number' && ( // a real array Array.isArray(obj) || // arguments 'callee' in obj || // HTMLCollection/NodeList 'item' in obj) ); } /** * Ensure that the argument is an array by wrapping it in an array if it is not. * Creates a copy of the argument if it is already an array. * * This is mostly useful idiomatically: * * var createArrayFromMixed = require('createArrayFromMixed'); * * function takesOneOrMoreThings(things) { * things = createArrayFromMixed(things); * ... * } * * This allows you to treat `things' as an array, but accept scalars in the API. * * If you need to convert an array-like object, like `arguments`, into an array * use toArray instead. * * @param {*} obj * @return {array} */ function createArrayFromMixed(obj) { if (!hasArrayNature(obj)) { return [obj]; } else if (Array.isArray(obj)) { return obj.slice(); } else { return toArray(obj); } } module.exports = createArrayFromMixed; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ /*eslint-disable fb-www/unsafe-html */ var ExecutionEnvironment = __webpack_require__(48); var invariant = __webpack_require__(7); /** * Dummy container used to detect which wraps are necessary. */ var dummyNode = ExecutionEnvironment.canUseDOM ? document.createElement('div') : null; /** * Some browsers cannot use `innerHTML` to render certain elements standalone, * so we wrap them, render the wrapped nodes, then extract the desired node. * * In IE8, certain elements cannot render alone, so wrap all elements ('*'). */ var shouldWrap = {}; var selectWrap = [1, '<select multiple="true">', '</select>']; var tableWrap = [1, '<table>', '</table>']; var trWrap = [3, '<table><tbody><tr>', '</tr></tbody></table>']; var svgWrap = [1, '<svg xmlns="http://www.w3.org/2000/svg">', '</svg>']; var markupWrap = { '*': [1, '?<div>', '</div>'], 'area': [1, '<map>', '</map>'], 'col': [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], 'legend': [1, '<fieldset>', '</fieldset>'], 'param': [1, '<object>', '</object>'], 'tr': [2, '<table><tbody>', '</tbody></table>'], 'optgroup': selectWrap, 'option': selectWrap, 'caption': tableWrap, 'colgroup': tableWrap, 'tbody': tableWrap, 'tfoot': tableWrap, 'thead': tableWrap, 'td': trWrap, 'th': trWrap }; // Initialize the SVG elements since we know they'll always need to be wrapped // consistently. If they are created inside a <div> they will be initialized in // the wrong namespace (and will not display). var svgElements = ['circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'text', 'tspan']; svgElements.forEach(function (nodeName) { markupWrap[nodeName] = svgWrap; shouldWrap[nodeName] = true; }); /** * Gets the markup wrap configuration for the supplied `nodeName`. * * NOTE: This lazily detects which wraps are necessary for the current browser. * * @param {string} nodeName Lowercase `nodeName`. * @return {?array} Markup wrap configuration, if applicable. */ function getMarkupWrap(nodeName) { !!!dummyNode ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Markup wrapping node not initialized') : invariant(false) : void 0; if (!markupWrap.hasOwnProperty(nodeName)) { nodeName = '*'; } if (!shouldWrap.hasOwnProperty(nodeName)) { if (nodeName === '*') { dummyNode.innerHTML = '<link />'; } else { dummyNode.innerHTML = '<' + nodeName + '></' + nodeName + '>'; } shouldWrap[nodeName] = !dummyNode.firstChild; } return shouldWrap[nodeName] ? markupWrap[nodeName] : null; } module.exports = getMarkupWrap; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChildUpdateTypes */ 'use strict'; var keyMirror = __webpack_require__(24); /** * When a component's children are updated, a series of update configuration * objects are created in order to batch and serialize the required changes. * * Enumerates all the possible types of update configurations. * * @internal */ var ReactMultiChildUpdateTypes = keyMirror({ INSERT_MARKUP: null, MOVE_EXISTING: null, REMOVE_NODE: null, SET_MARKUP: null, TEXT_CONTENT: null }); module.exports = ReactMultiChildUpdateTypes; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMIDOperations */ 'use strict'; var DOMChildrenOperations = __webpack_require__(74); var ReactDOMComponentTree = __webpack_require__(35); var ReactPerf = __webpack_require__(58); /** * Operations used to process updates to DOM nodes. */ var ReactDOMIDOperations = { /** * Updates a component's children by processing a series of updates. * * @param {array<object>} updates List of update configurations. * @internal */ dangerouslyProcessChildrenUpdates: function (parentInst, updates) { var node = ReactDOMComponentTree.getNodeFromInstance(parentInst); DOMChildrenOperations.processUpdates(node, updates); } }; ReactPerf.measureMethods(ReactDOMIDOperations, 'ReactDOMIDOperations', { dangerouslyProcessChildrenUpdates: 'dangerouslyProcessChildrenUpdates' }); module.exports = ReactDOMIDOperations; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMComponent */ /* global hasOwnProperty:true */ 'use strict'; var _assign = __webpack_require__(4); var AutoFocusUtils = __webpack_require__(87); var CSSPropertyOperations = __webpack_require__(89); var DOMLazyTree = __webpack_require__(75); var DOMNamespaces = __webpack_require__(97); var DOMProperty = __webpack_require__(36); var DOMPropertyOperations = __webpack_require__(98); var EventConstants = __webpack_require__(40); var EventPluginHub = __webpack_require__(42); var EventPluginRegistry = __webpack_require__(43); var ReactBrowserEventEmitter = __webpack_require__(103); var ReactComponentBrowserEnvironment = __webpack_require__(73); var ReactDOMButton = __webpack_require__(106); var ReactDOMComponentFlags = __webpack_require__(37); var ReactDOMComponentTree = __webpack_require__(35); var ReactDOMInput = __webpack_require__(108); var ReactDOMOption = __webpack_require__(110); var ReactDOMSelect = __webpack_require__(111); var ReactDOMTextarea = __webpack_require__(112); var ReactMultiChild = __webpack_require__(113); var ReactPerf = __webpack_require__(58); var escapeTextContentForBrowser = __webpack_require__(78); var invariant = __webpack_require__(7); var isEventSupported = __webpack_require__(64); var keyOf = __webpack_require__(26); var shallowEqual = __webpack_require__(125); var validateDOMNesting = __webpack_require__(126); var warning = __webpack_require__(10); var Flags = ReactDOMComponentFlags; var deleteListener = EventPluginHub.deleteListener; var getNode = ReactDOMComponentTree.getNodeFromInstance; var listenTo = ReactBrowserEventEmitter.listenTo; var registrationNameModules = EventPluginRegistry.registrationNameModules; // For quickly matching children type, to test if can be treated as content. var CONTENT_TYPES = { 'string': true, 'number': true }; var STYLE = keyOf({ style: null }); var HTML = keyOf({ __html: null }); var RESERVED_PROPS = { children: null, dangerouslySetInnerHTML: null, suppressContentEditableWarning: null }; // Node type for document fragments (Node.DOCUMENT_FRAGMENT_NODE). var DOC_FRAGMENT_TYPE = 11; function getDeclarationErrorAddendum(internalInstance) { if (internalInstance) { var owner = internalInstance._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' This DOM node was rendered by `' + name + '`.'; } } } return ''; } function friendlyStringify(obj) { if (typeof obj === 'object') { if (Array.isArray(obj)) { return '[' + obj.map(friendlyStringify).join(', ') + ']'; } else { var pairs = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var keyEscaped = /^[a-z$_][\w$_]*$/i.test(key) ? key : JSON.stringify(key); pairs.push(keyEscaped + ': ' + friendlyStringify(obj[key])); } } return '{' + pairs.join(', ') + '}'; } } else if (typeof obj === 'string') { return JSON.stringify(obj); } else if (typeof obj === 'function') { return '[function object]'; } // Differs from JSON.stringify in that undefined because undefined and that // inf and nan don't become null return String(obj); } var styleMutationWarning = {}; function checkAndWarnForMutatedStyle(style1, style2, component) { if (style1 == null || style2 == null) { return; } if (shallowEqual(style1, style2)) { return; } var componentName = component._tag; var owner = component._currentElement._owner; var ownerName; if (owner) { ownerName = owner.getName(); } var hash = ownerName + '|' + componentName; if (styleMutationWarning.hasOwnProperty(hash)) { return; } styleMutationWarning[hash] = true; process.env.NODE_ENV !== 'production' ? warning(false, '`%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.', componentName, owner ? 'of `' + ownerName + '`' : 'using <' + componentName + '>', friendlyStringify(style1), friendlyStringify(style2)) : void 0; } /** * @param {object} component * @param {?object} props */ function assertValidProps(component, props) { if (!props) { return; } // Note the use of `==` which checks for null or undefined. if (voidElementTags[component._tag]) { !(props.children == null && props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s is a void element tag and must not have `children` or ' + 'use `props.dangerouslySetInnerHTML`.%s', component._tag, component._currentElement._owner ? ' Check the render method of ' + component._currentElement._owner.getName() + '.' : '') : invariant(false) : void 0; } if (props.dangerouslySetInnerHTML != null) { !(props.children == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.') : invariant(false) : void 0; !(typeof props.dangerouslySetInnerHTML === 'object' && HTML in props.dangerouslySetInnerHTML) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`props.dangerouslySetInnerHTML` must be in the form `{__html: ...}`. ' + 'Please visit https://fb.me/react-invariant-dangerously-set-inner-html ' + 'for more information.') : invariant(false) : void 0; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.innerHTML == null, 'Directly setting property `innerHTML` is not permitted. ' + 'For more information, lookup documentation on `dangerouslySetInnerHTML`.') : void 0; process.env.NODE_ENV !== 'production' ? warning(props.suppressContentEditableWarning || !props.contentEditable || props.children == null, '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; process.env.NODE_ENV !== 'production' ? warning(props.onFocusIn == null && props.onFocusOut == null, 'React uses onFocus and onBlur instead of onFocusIn and onFocusOut. ' + 'All React events are normalized to bubble, so onFocusIn and onFocusOut ' + 'are not needed/supported by React.') : void 0; } !(props.style == null || typeof props.style === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The `style` prop expects a mapping from style properties to values, ' + 'not a string. For example, style={{marginRight: spacing + \'em\'}} when ' + 'using JSX.%s', getDeclarationErrorAddendum(component)) : invariant(false) : void 0; } function enqueuePutListener(inst, registrationName, listener, transaction) { if (process.env.NODE_ENV !== 'production') { // IE8 has no API for event capturing and the `onScroll` event doesn't // bubble. process.env.NODE_ENV !== 'production' ? warning(registrationName !== 'onScroll' || isEventSupported('scroll', true), 'This browser doesn\'t support the `onScroll` event') : void 0; } var containerInfo = inst._nativeContainerInfo; var isDocumentFragment = containerInfo._node && containerInfo._node.nodeType === DOC_FRAGMENT_TYPE; var doc = isDocumentFragment ? containerInfo._node : containerInfo._ownerDocument; if (!doc) { // Server rendering. return; } listenTo(registrationName, doc); transaction.getReactMountReady().enqueue(putListener, { inst: inst, registrationName: registrationName, listener: listener }); } function putListener() { var listenerToPut = this; EventPluginHub.putListener(listenerToPut.inst, listenerToPut.registrationName, listenerToPut.listener); } function optionPostMount() { var inst = this; ReactDOMOption.postMountWrapper(inst); } // There are so many media events, it makes sense to just // maintain a list rather than create a `trapBubbledEvent` for each var mediaEvents = { 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' }; function trapBubbledEventsLocal() { var inst = this; // If a component renders to null or if another component fatals and causes // the state of the tree to be corrupted, `node` here can be null. !inst._rootNodeID ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Must be mounted to trap events') : invariant(false) : void 0; var node = getNode(inst); !node ? process.env.NODE_ENV !== 'production' ? invariant(false, 'trapBubbledEvent(...): Requires node to be rendered.') : invariant(false) : void 0; switch (inst._tag) { case 'iframe': case 'object': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'video': case 'audio': inst._wrapperState.listeners = []; // Create listener for each media event for (var event in mediaEvents) { if (mediaEvents.hasOwnProperty(event)) { inst._wrapperState.listeners.push(ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes[event], mediaEvents[event], node)); } } break; case 'img': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load', node)]; break; case 'form': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset', node), ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit', node)]; break; case 'input': case 'select': case 'textarea': inst._wrapperState.listeners = [ReactBrowserEventEmitter.trapBubbledEvent(EventConstants.topLevelTypes.topInvalid, 'invalid', node)]; break; } } function postUpdateSelectWrapper() { ReactDOMSelect.postUpdateWrapper(this); } // For HTML, certain tags should omit their close tag. We keep a whitelist for // those special-case tags. var omittedCloseTags = { 'area': true, 'base': true, 'br': true, 'col': true, 'embed': true, 'hr': true, 'img': true, 'input': true, 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true, 'track': true, 'wbr': true }; // NOTE: menuitem's close tag should be omitted, but that causes problems. var newlineEatingTags = { 'listing': true, 'pre': true, 'textarea': true }; // For HTML, certain tags cannot have children. This has the same purpose as // `omittedCloseTags` except that `menuitem` should still have its closing tag. var voidElementTags = _assign({ 'menuitem': true }, omittedCloseTags); // We accept any tag to be rendered but since this gets injected into arbitrary // HTML, we want to make sure that it's a safe tag. // http://www.w3.org/TR/REC-xml/#NT-Name var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset var validatedTagCache = {}; var hasOwnProperty = {}.hasOwnProperty; function validateDangerousTag(tag) { if (!hasOwnProperty.call(validatedTagCache, tag)) { !VALID_TAG_REGEX.test(tag) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Invalid tag: %s', tag) : invariant(false) : void 0; validatedTagCache[tag] = true; } } function isCustomComponent(tagName, props) { return tagName.indexOf('-') >= 0 || props.is != null; } var globalIdCounter = 1; /** * Creates a new React class that is idempotent and capable of containing other * React components. It accepts event listeners and DOM properties that are * valid according to `DOMProperty`. * * - Event listeners: `onClick`, `onMouseDown`, etc. * - DOM properties: `className`, `name`, `title`, etc. * * The `style` property functions differently from the DOM API. It accepts an * object mapping of style properties to values. * * @constructor ReactDOMComponent * @extends ReactMultiChild */ function ReactDOMComponent(element) { var tag = element.type; validateDangerousTag(tag); this._currentElement = element; this._tag = tag.toLowerCase(); this._namespaceURI = null; this._renderedChildren = null; this._previousStyle = null; this._previousStyleCopy = null; this._nativeNode = null; this._nativeParent = null; this._rootNodeID = null; this._domID = null; this._nativeContainerInfo = null; this._wrapperState = null; this._topLevelWrapper = null; this._flags = 0; if (process.env.NODE_ENV !== 'production') { this._ancestorInfo = null; } } ReactDOMComponent.displayName = 'ReactDOMComponent'; ReactDOMComponent.Mixin = { /** * Generates root tag markup then recurses. This method has side effects and * is not idempotent. * * @internal * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?ReactDOMComponent} the containing DOM component instance * @param {?object} info about the native container * @param {object} context * @return {string} The computed markup. */ mountComponent: function (transaction, nativeParent, nativeContainerInfo, context) { this._rootNodeID = globalIdCounter++; this._domID = nativeContainerInfo._idCounter++; this._nativeParent = nativeParent; this._nativeContainerInfo = nativeContainerInfo; var props = this._currentElement.props; switch (this._tag) { case 'iframe': case 'object': case 'img': case 'form': case 'video': case 'audio': this._wrapperState = { listeners: null }; transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'button': props = ReactDOMButton.getNativeProps(this, props, nativeParent); break; case 'input': ReactDOMInput.mountWrapper(this, props, nativeParent); props = ReactDOMInput.getNativeProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'option': ReactDOMOption.mountWrapper(this, props, nativeParent); props = ReactDOMOption.getNativeProps(this, props); break; case 'select': ReactDOMSelect.mountWrapper(this, props, nativeParent); props = ReactDOMSelect.getNativeProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; case 'textarea': ReactDOMTextarea.mountWrapper(this, props, nativeParent); props = ReactDOMTextarea.getNativeProps(this, props); transaction.getReactMountReady().enqueue(trapBubbledEventsLocal, this); break; } assertValidProps(this, props); // We create tags in the namespace of their parent container, except HTML // tags get no namespace. var namespaceURI; var parentTag; if (nativeParent != null) { namespaceURI = nativeParent._namespaceURI; parentTag = nativeParent._tag; } else if (nativeContainerInfo._tag) { namespaceURI = nativeContainerInfo._namespaceURI; parentTag = nativeContainerInfo._tag; } if (namespaceURI == null || namespaceURI === DOMNamespaces.svg && parentTag === 'foreignobject') { namespaceURI = DOMNamespaces.html; } if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'svg') { namespaceURI = DOMNamespaces.svg; } else if (this._tag === 'math') { namespaceURI = DOMNamespaces.mathml; } } this._namespaceURI = namespaceURI; if (process.env.NODE_ENV !== 'production') { var parentInfo; if (nativeParent != null) { parentInfo = nativeParent._ancestorInfo; } else if (nativeContainerInfo._tag) { parentInfo = nativeContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting(this._tag, this, parentInfo); } this._ancestorInfo = validateDOMNesting.updatedAncestorInfo(parentInfo, this._tag, this); } var mountImage; if (transaction.useCreateElement) { var ownerDocument = nativeContainerInfo._ownerDocument; var el; if (namespaceURI === DOMNamespaces.html) { if (this._tag === 'script') { // Create the script via .innerHTML so its "parser-inserted" flag is // set to true and it does not execute var div = ownerDocument.createElement('div'); var type = this._currentElement.type; div.innerHTML = '<' + type + '></' + type + '>'; el = div.removeChild(div.firstChild); } else { el = ownerDocument.createElement(this._currentElement.type); } } else { el = ownerDocument.createElementNS(namespaceURI, this._currentElement.type); } ReactDOMComponentTree.precacheNode(this, el); this._flags |= Flags.hasCachedChildNodes; if (!this._nativeParent) { DOMPropertyOperations.setAttributeForRoot(el); } this._updateDOMProperties(null, props, transaction); var lazyTree = DOMLazyTree(el); this._createInitialChildren(transaction, props, context, lazyTree); mountImage = lazyTree; } else { var tagOpen = this._createOpenTagMarkupAndPutListeners(transaction, props); var tagContent = this._createContentMarkup(transaction, props, context); if (!tagContent && omittedCloseTags[this._tag]) { mountImage = tagOpen + '/>'; } else { mountImage = tagOpen + '>' + tagContent + '</' + this._currentElement.type + '>'; } } switch (this._tag) { case 'button': case 'input': case 'select': case 'textarea': if (props.autoFocus) { transaction.getReactMountReady().enqueue(AutoFocusUtils.focusDOMComponent, this); } break; case 'option': transaction.getReactMountReady().enqueue(optionPostMount, this); } return mountImage; }, /** * Creates markup for the open tag and all attributes. * * This method has side effects because events get registered. * * Iterating over object properties is faster than iterating over arrays. * @see http://jsperf.com/obj-vs-arr-iteration * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @return {string} Markup of opening tag. */ _createOpenTagMarkupAndPutListeners: function (transaction, props) { var ret = '<' + this._currentElement.type; for (var propKey in props) { if (!props.hasOwnProperty(propKey)) { continue; } var propValue = props[propKey]; if (propValue == null) { continue; } if (registrationNameModules.hasOwnProperty(propKey)) { if (propValue) { enqueuePutListener(this, propKey, propValue, transaction); } } else { if (propKey === STYLE) { if (propValue) { if (process.env.NODE_ENV !== 'production') { // See `_updateDOMProperties`. style block this._previousStyle = propValue; } propValue = this._previousStyleCopy = _assign({}, props.style); } propValue = CSSPropertyOperations.createMarkupForStyles(propValue, this); } var markup = null; if (this._tag != null && isCustomComponent(this._tag, props)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { markup = DOMPropertyOperations.createMarkupForCustomAttribute(propKey, propValue); } } else { markup = DOMPropertyOperations.createMarkupForProperty(propKey, propValue); } if (markup) { ret += ' ' + markup; } } } // For static pages, no need to put React ID and checksum. Saves lots of // bytes. if (transaction.renderToStaticMarkup) { return ret; } if (!this._nativeParent) { ret += ' ' + DOMPropertyOperations.createMarkupForRoot(); } ret += ' ' + DOMPropertyOperations.createMarkupForID(this._domID); return ret; }, /** * Creates markup for the content between the tags. * * @private * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} props * @param {object} context * @return {string} Content markup. */ _createContentMarkup: function (transaction, props, context) { var ret = ''; // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { ret = innerHTML.__html; } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node ret = escapeTextContentForBrowser(contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); ret = mountImages.join(''); } } if (newlineEatingTags[this._tag] && ret.charAt(0) === '\n') { // text/html ignores the first character in these tags if it's a newline // Prefer to break application/xml over text/html (for now) by adding // a newline specifically to get eaten by the parser. (Alternately for // textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first // \r is normalized out by HTMLTextAreaElement#value.) // See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre> // See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions> // See: <http://www.w3.org/TR/html5/syntax.html#newlines> // See: Parsing of "textarea" "listing" and "pre" elements // from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody> return '\n' + ret; } else { return ret; } }, _createInitialChildren: function (transaction, props, context, lazyTree) { // Intentional use of != to avoid catching zero/false. var innerHTML = props.dangerouslySetInnerHTML; if (innerHTML != null) { if (innerHTML.__html != null) { DOMLazyTree.queueHTML(lazyTree, innerHTML.__html); } } else { var contentToUse = CONTENT_TYPES[typeof props.children] ? props.children : null; var childrenToUse = contentToUse != null ? null : props.children; if (contentToUse != null) { // TODO: Validate that text is allowed as a child of this node DOMLazyTree.queueText(lazyTree, contentToUse); } else if (childrenToUse != null) { var mountImages = this.mountChildren(childrenToUse, transaction, context); for (var i = 0; i < mountImages.length; i++) { DOMLazyTree.queueChild(lazyTree, mountImages[i]); } } } }, /** * Receives a next element and updates the component. * * @internal * @param {ReactElement} nextElement * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {object} context */ receiveComponent: function (nextElement, transaction, context) { var prevElement = this._currentElement; this._currentElement = nextElement; this.updateComponent(transaction, prevElement, nextElement, context); }, /** * Updates a native DOM component after it has already been allocated and * attached to the DOM. Reconciles the root DOM node, then recurses. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevElement * @param {ReactElement} nextElement * @internal * @overridable */ updateComponent: function (transaction, prevElement, nextElement, context) { var lastProps = prevElement.props; var nextProps = this._currentElement.props; switch (this._tag) { case 'button': lastProps = ReactDOMButton.getNativeProps(this, lastProps); nextProps = ReactDOMButton.getNativeProps(this, nextProps); break; case 'input': ReactDOMInput.updateWrapper(this); lastProps = ReactDOMInput.getNativeProps(this, lastProps); nextProps = ReactDOMInput.getNativeProps(this, nextProps); break; case 'option': lastProps = ReactDOMOption.getNativeProps(this, lastProps); nextProps = ReactDOMOption.getNativeProps(this, nextProps); break; case 'select': lastProps = ReactDOMSelect.getNativeProps(this, lastProps); nextProps = ReactDOMSelect.getNativeProps(this, nextProps); break; case 'textarea': ReactDOMTextarea.updateWrapper(this); lastProps = ReactDOMTextarea.getNativeProps(this, lastProps); nextProps = ReactDOMTextarea.getNativeProps(this, nextProps); break; } assertValidProps(this, nextProps); this._updateDOMProperties(lastProps, nextProps, transaction); this._updateDOMChildren(lastProps, nextProps, transaction, context); if (this._tag === 'select') { // <select> value update needs to occur after <option> children // reconciliation transaction.getReactMountReady().enqueue(postUpdateSelectWrapper, this); } }, /** * Reconciles the properties by detecting differences in property values and * updating the DOM as necessary. This function is probably the single most * critical path for performance optimization. * * TODO: Benchmark whether checking for changed values in memory actually * improves performance (especially statically positioned elements). * TODO: Benchmark the effects of putting this at the top since 99% of props * do not change for a given reconciliation. * TODO: Benchmark areas that can be improved with caching. * * @private * @param {object} lastProps * @param {object} nextProps * @param {?DOMElement} node */ _updateDOMProperties: function (lastProps, nextProps, transaction) { var propKey; var styleName; var styleUpdates; for (propKey in lastProps) { if (nextProps.hasOwnProperty(propKey) || !lastProps.hasOwnProperty(propKey) || lastProps[propKey] == null) { continue; } if (propKey === STYLE) { var lastStyle = this._previousStyleCopy; for (styleName in lastStyle) { if (lastStyle.hasOwnProperty(styleName)) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } this._previousStyleCopy = null; } else if (registrationNameModules.hasOwnProperty(propKey)) { if (lastProps[propKey]) { // Only call deleteListener if there was a listener previously or // else willDeleteListener gets called when there wasn't actually a // listener (e.g., onClick={null}) deleteListener(this, propKey); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { DOMPropertyOperations.deleteValueForProperty(getNode(this), propKey); } } for (propKey in nextProps) { var nextProp = nextProps[propKey]; var lastProp = propKey === STYLE ? this._previousStyleCopy : lastProps != null ? lastProps[propKey] : undefined; if (!nextProps.hasOwnProperty(propKey) || nextProp === lastProp || nextProp == null && lastProp == null) { continue; } if (propKey === STYLE) { if (nextProp) { if (process.env.NODE_ENV !== 'production') { checkAndWarnForMutatedStyle(this._previousStyleCopy, this._previousStyle, this); this._previousStyle = nextProp; } nextProp = this._previousStyleCopy = _assign({}, nextProp); } else { this._previousStyleCopy = null; } if (lastProp) { // Unset styles on `lastProp` but not on `nextProp`. for (styleName in lastProp) { if (lastProp.hasOwnProperty(styleName) && (!nextProp || !nextProp.hasOwnProperty(styleName))) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = ''; } } // Update styles that changed since `lastProp`. for (styleName in nextProp) { if (nextProp.hasOwnProperty(styleName) && lastProp[styleName] !== nextProp[styleName]) { styleUpdates = styleUpdates || {}; styleUpdates[styleName] = nextProp[styleName]; } } } else { // Relies on `updateStylesByID` not mutating `styleUpdates`. styleUpdates = nextProp; } } else if (registrationNameModules.hasOwnProperty(propKey)) { if (nextProp) { enqueuePutListener(this, propKey, nextProp, transaction); } else if (lastProp) { deleteListener(this, propKey); } } else if (isCustomComponent(this._tag, nextProps)) { if (!RESERVED_PROPS.hasOwnProperty(propKey)) { DOMPropertyOperations.setValueForAttribute(getNode(this), propKey, nextProp); } } else if (DOMProperty.properties[propKey] || DOMProperty.isCustomAttribute(propKey)) { var node = getNode(this); // If we're updating to null or undefined, we should remove the property // from the DOM node instead of inadvertently setting to a string. This // brings us in line with the same behavior we have on initial render. if (nextProp != null) { DOMPropertyOperations.setValueForProperty(node, propKey, nextProp); } else { DOMPropertyOperations.deleteValueForProperty(node, propKey); } } } if (styleUpdates) { CSSPropertyOperations.setValueForStyles(getNode(this), styleUpdates, this); } }, /** * Reconciles the children with the various properties that affect the * children content. * * @param {object} lastProps * @param {object} nextProps * @param {ReactReconcileTransaction} transaction * @param {object} context */ _updateDOMChildren: function (lastProps, nextProps, transaction, context) { var lastContent = CONTENT_TYPES[typeof lastProps.children] ? lastProps.children : null; var nextContent = CONTENT_TYPES[typeof nextProps.children] ? nextProps.children : null; var lastHtml = lastProps.dangerouslySetInnerHTML && lastProps.dangerouslySetInnerHTML.__html; var nextHtml = nextProps.dangerouslySetInnerHTML && nextProps.dangerouslySetInnerHTML.__html; // Note the use of `!=` which checks for null or undefined. var lastChildren = lastContent != null ? null : lastProps.children; var nextChildren = nextContent != null ? null : nextProps.children; // If we're switching from children to content/html or vice versa, remove // the old content var lastHasContentOrHtml = lastContent != null || lastHtml != null; var nextHasContentOrHtml = nextContent != null || nextHtml != null; if (lastChildren != null && nextChildren == null) { this.updateChildren(null, transaction, context); } else if (lastHasContentOrHtml && !nextHasContentOrHtml) { this.updateTextContent(''); } if (nextContent != null) { if (lastContent !== nextContent) { this.updateTextContent('' + nextContent); } } else if (nextHtml != null) { if (lastHtml !== nextHtml) { this.updateMarkup('' + nextHtml); } } else if (nextChildren != null) { this.updateChildren(nextChildren, transaction, context); } }, getNativeNode: function () { return getNode(this); }, /** * Destroys all event registrations for this instance. Does not remove from * the DOM. That must be done by the parent. * * @internal */ unmountComponent: function (safely) { switch (this._tag) { case 'iframe': case 'object': case 'img': case 'form': case 'video': case 'audio': var listeners = this._wrapperState.listeners; if (listeners) { for (var i = 0; i < listeners.length; i++) { listeners[i].remove(); } } break; case 'html': case 'head': case 'body': /** * Components like <html> <head> and <body> can't be removed or added * easily in a cross-browser way, however it's valuable to be able to * take advantage of React's reconciliation for styling and <title> * management. So we just document it and throw in dangerous cases. */ true ? process.env.NODE_ENV !== 'production' ? invariant(false, '<%s> tried to unmount. Because of cross-browser quirks it is ' + 'impossible to unmount some top-level components (eg <html>, ' + '<head>, and <body>) reliably and efficiently. To fix this, have a ' + 'single top-level component that never unmounts render these ' + 'elements.', this._tag) : invariant(false) : void 0; break; } this.unmountChildren(safely); ReactDOMComponentTree.uncacheNode(this); EventPluginHub.deleteAllListeners(this); ReactComponentBrowserEnvironment.unmountIDFromEnvironment(this._rootNodeID); this._rootNodeID = null; this._domID = null; this._wrapperState = null; }, getPublicInstance: function () { return getNode(this); } }; ReactPerf.measureMethods(ReactDOMComponent.Mixin, 'ReactDOMComponent', { mountComponent: 'mountComponent', receiveComponent: 'receiveComponent' }); _assign(ReactDOMComponent.prototype, ReactDOMComponent.Mixin, ReactMultiChild.Mixin); module.exports = ReactDOMComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 87 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule AutoFocusUtils */ 'use strict'; var ReactDOMComponentTree = __webpack_require__(35); var focusNode = __webpack_require__(88); var AutoFocusUtils = { focusDOMComponent: function () { focusNode(ReactDOMComponentTree.getNodeFromInstance(this)); } }; module.exports = AutoFocusUtils; /***/ }, /* 88 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ 'use strict'; /** * @param {DOMElement} node input/textarea to focus */ function focusNode(node) { // IE8 can throw "Can't move focus to the control because it is invisible, // not enabled, or of a type that does not accept the focus." for all kinds of // reasons that are too expensive and fragile to test. try { node.focus(); } catch (e) {} } module.exports = focusNode; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSPropertyOperations */ 'use strict'; var CSSProperty = __webpack_require__(90); var ExecutionEnvironment = __webpack_require__(48); var ReactPerf = __webpack_require__(58); var camelizeStyleName = __webpack_require__(91); var dangerousStyleValue = __webpack_require__(93); var hyphenateStyleName = __webpack_require__(94); var memoizeStringOnly = __webpack_require__(96); var warning = __webpack_require__(10); var processStyleName = memoizeStringOnly(function (styleName) { return hyphenateStyleName(styleName); }); var hasShorthandPropertyBug = false; var styleFloatAccessor = 'cssFloat'; if (ExecutionEnvironment.canUseDOM) { var tempStyle = document.createElement('div').style; try { // IE8 throws "Invalid argument." if resetting shorthand style properties. tempStyle.font = ''; } catch (e) { hasShorthandPropertyBug = true; } // IE8 only supports accessing cssFloat (standard) as styleFloat if (document.documentElement.style.cssFloat === undefined) { styleFloatAccessor = 'styleFloat'; } } if (process.env.NODE_ENV !== 'production') { // 'msTransform' is correct, but the other prefixes should be capitalized var badVendoredStyleNamePattern = /^(?:webkit|moz|o)[A-Z]/; // style values shouldn't contain a semicolon var badStyleValueWithSemicolonPattern = /;\s*$/; var warnedStyleNames = {}; var warnedStyleValues = {}; var warnedForNaNValue = false; var warnHyphenatedStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported style property %s. Did you mean %s?%s', name, camelizeStyleName(name), checkRenderMessage(owner)) : void 0; }; var warnBadVendoredStyleName = function (name, owner) { if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) { return; } warnedStyleNames[name] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Unsupported vendor-prefixed style property %s. Did you mean %s?%s', name, name.charAt(0).toUpperCase() + name.slice(1), checkRenderMessage(owner)) : void 0; }; var warnStyleValueWithSemicolon = function (name, value, owner) { if (warnedStyleValues.hasOwnProperty(value) && warnedStyleValues[value]) { return; } warnedStyleValues[value] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Style property values shouldn\'t contain a semicolon.%s ' + 'Try "%s: %s" instead.', checkRenderMessage(owner), name, value.replace(badStyleValueWithSemicolonPattern, '')) : void 0; }; var warnStyleValueIsNaN = function (name, value, owner) { if (warnedForNaNValue) { return; } warnedForNaNValue = true; process.env.NODE_ENV !== 'production' ? warning(false, '`NaN` is an invalid value for the `%s` css style property.%s', name, checkRenderMessage(owner)) : void 0; }; var checkRenderMessage = function (owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; }; /** * @param {string} name * @param {*} value * @param {ReactDOMComponent} component */ var warnValidStyle = function (name, value, component) { var owner; if (component) { owner = component._currentElement._owner; } if (name.indexOf('-') > -1) { warnHyphenatedStyleName(name, owner); } else if (badVendoredStyleNamePattern.test(name)) { warnBadVendoredStyleName(name, owner); } else if (badStyleValueWithSemicolonPattern.test(value)) { warnStyleValueWithSemicolon(name, value, owner); } if (typeof value === 'number' && isNaN(value)) { warnStyleValueIsNaN(name, value, owner); } }; } /** * Operations for dealing with CSS properties. */ var CSSPropertyOperations = { /** * Serializes a mapping of style properties for use as inline styles: * * > createMarkupForStyles({width: '200px', height: 0}) * "width:200px;height:0;" * * Undefined values are ignored so that declarative programming is easier. * The result should be HTML-escaped before insertion into the DOM. * * @param {object} styles * @param {ReactDOMComponent} component * @return {?string} */ createMarkupForStyles: function (styles, component) { var serialized = ''; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } var styleValue = styles[styleName]; if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styleValue, component); } if (styleValue != null) { serialized += processStyleName(styleName) + ':'; serialized += dangerousStyleValue(styleName, styleValue, component) + ';'; } } return serialized || null; }, /** * Sets the value for multiple styles on a node. If a value is specified as * '' (empty string), the corresponding style property will be unset. * * @param {DOMElement} node * @param {object} styles * @param {ReactDOMComponent} component */ setValueForStyles: function (node, styles, component) { var style = node.style; for (var styleName in styles) { if (!styles.hasOwnProperty(styleName)) { continue; } if (process.env.NODE_ENV !== 'production') { warnValidStyle(styleName, styles[styleName], component); } var styleValue = dangerousStyleValue(styleName, styles[styleName], component); if (styleName === 'float' || styleName === 'cssFloat') { styleName = styleFloatAccessor; } if (styleValue) { style[styleName] = styleValue; } else { var expansion = hasShorthandPropertyBug && CSSProperty.shorthandPropertyExpansions[styleName]; if (expansion) { // Shorthand property that IE8 won't like unsetting, so unset each // component to placate it for (var individualStyleName in expansion) { style[individualStyleName] = ''; } } else { style[styleName] = ''; } } } } }; ReactPerf.measureMethods(CSSPropertyOperations, 'CSSPropertyOperations', { setValueForStyles: 'setValueForStyles' }); module.exports = CSSPropertyOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 90 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule CSSProperty */ 'use strict'; /** * CSS properties which accept numbers but are not in units of "px". */ var isUnitlessNumber = { animationIterationCount: true, borderImageOutset: true, borderImageSlice: true, borderImageWidth: true, boxFlex: true, boxFlexGroup: true, boxOrdinalGroup: true, columnCount: true, flex: true, flexGrow: true, flexPositive: true, flexShrink: true, flexNegative: true, flexOrder: true, gridRow: true, gridColumn: true, fontWeight: true, lineClamp: true, lineHeight: true, opacity: true, order: true, orphans: true, tabSize: true, widows: true, zIndex: true, zoom: true, // SVG-related properties fillOpacity: true, floodOpacity: true, stopOpacity: true, strokeDasharray: true, strokeDashoffset: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true }; /** * @param {string} prefix vendor-specific prefix, eg: Webkit * @param {string} key style name, eg: transitionDuration * @return {string} style name prefixed with `prefix`, properly camelCased, eg: * WebkitTransitionDuration */ function prefixKey(prefix, key) { return prefix + key.charAt(0).toUpperCase() + key.substring(1); } /** * Support style names that may come passed in prefixed by adding permutations * of vendor prefixes. */ var prefixes = ['Webkit', 'ms', 'Moz', 'O']; // Using Object.keys here, or else the vanilla for-in loop makes IE8 go into an // infinite loop, because it iterates over the newly added props too. Object.keys(isUnitlessNumber).forEach(function (prop) { prefixes.forEach(function (prefix) { isUnitlessNumber[prefixKey(prefix, prop)] = isUnitlessNumber[prop]; }); }); /** * Most style properties can be unset by doing .style[prop] = '' but IE8 * doesn't like doing that with shorthand properties so for the properties that * IE8 breaks on, which are listed here, we instead unset each of the * individual properties. See http://bugs.jquery.com/ticket/12385. * The 4-value 'clock' properties like margin, padding, border-width seem to * behave without any problems. Curiously, list-style works too without any * special prodding. */ var shorthandPropertyExpansions = { background: { backgroundAttachment: true, backgroundColor: true, backgroundImage: true, backgroundPositionX: true, backgroundPositionY: true, backgroundRepeat: true }, backgroundPosition: { backgroundPositionX: true, backgroundPositionY: true }, border: { borderWidth: true, borderStyle: true, borderColor: true }, borderBottom: { borderBottomWidth: true, borderBottomStyle: true, borderBottomColor: true }, borderLeft: { borderLeftWidth: true, borderLeftStyle: true, borderLeftColor: true }, borderRight: { borderRightWidth: true, borderRightStyle: true, borderRightColor: true }, borderTop: { borderTopWidth: true, borderTopStyle: true, borderTopColor: true }, font: { fontStyle: true, fontVariant: true, fontWeight: true, fontSize: true, lineHeight: true, fontFamily: true }, outline: { outlineWidth: true, outlineStyle: true, outlineColor: true } }; var CSSProperty = { isUnitlessNumber: isUnitlessNumber, shorthandPropertyExpansions: shorthandPropertyExpansions }; module.exports = CSSProperty; /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var camelize = __webpack_require__(92); var msPattern = /^-ms-/; /** * Camelcases a hyphenated CSS property name, for example: * * > camelizeStyleName('background-color') * < "backgroundColor" * > camelizeStyleName('-moz-transition') * < "MozTransition" * > camelizeStyleName('-ms-transition') * < "msTransition" * * As Andi Smith suggests * (http://www.andismith.com/blog/2012/02/modernizr-prefixed/), an `-ms` prefix * is converted to lowercase `ms`. * * @param {string} string * @return {string} */ function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); } module.exports = camelizeStyleName; /***/ }, /* 92 */ /***/ function(module, exports) { "use strict"; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _hyphenPattern = /-(.)/g; /** * Camelcases a hyphenated string, for example: * * > camelize('background-color') * < "backgroundColor" * * @param {string} string * @return {string} */ function camelize(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } module.exports = camelize; /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule dangerousStyleValue */ 'use strict'; var CSSProperty = __webpack_require__(90); var warning = __webpack_require__(10); var isUnitlessNumber = CSSProperty.isUnitlessNumber; var styleWarnings = {}; /** * Convert a value into the proper css writable value. The style name `name` * should be logical (no hyphens), as specified * in `CSSProperty.isUnitlessNumber`. * * @param {string} name CSS property name such as `topMargin`. * @param {*} value CSS property value such as `10px`. * @param {ReactDOMComponent} component * @return {string} Normalized style value with dimensions applied. */ function dangerousStyleValue(name, value, component) { // Note that we've removed escapeTextForBrowser() calls here since the // whole string will be escaped when the attribute is injected into // the markup. If you provide unsafe user data here they can inject // arbitrary CSS which may be problematic (I couldn't repro this): // https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet // http://www.thespanner.co.uk/2007/11/26/ultimate-xss-css-injection/ // This is not an XSS hole but instead a potential CSS injection issue // which has lead to a greater discussion about how we're going to // trust URLs moving forward. See #2115901 var isEmpty = value == null || typeof value === 'boolean' || value === ''; if (isEmpty) { return ''; } var isNonNumeric = isNaN(value); if (isNonNumeric || value === 0 || isUnitlessNumber.hasOwnProperty(name) && isUnitlessNumber[name]) { return '' + value; // cast to string } if (typeof value === 'string') { if (process.env.NODE_ENV !== 'production') { if (component) { var owner = component._currentElement._owner; var ownerName = owner ? owner.getName() : null; if (ownerName && !styleWarnings[ownerName]) { styleWarnings[ownerName] = {}; } var warned = false; if (ownerName) { var warnings = styleWarnings[ownerName]; warned = warnings[name]; if (!warned) { warnings[name] = true; } } if (!warned) { process.env.NODE_ENV !== 'production' ? warning(false, 'a `%s` tag (owner: `%s`) was passed a numeric string value ' + 'for CSS property `%s` (value: `%s`) which will be treated ' + 'as a unitless number in a future version of React.', component._currentElement.type, ownerName || 'unknown', name, value) : void 0; } } } value = value.trim(); } return value + 'px'; } module.exports = dangerousStyleValue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var hyphenate = __webpack_require__(95); var msPattern = /^ms-/; /** * Hyphenates a camelcased CSS property name, for example: * * > hyphenateStyleName('backgroundColor') * < "background-color" * > hyphenateStyleName('MozTransition') * < "-moz-transition" * > hyphenateStyleName('msTransition') * < "-ms-transition" * * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix * is converted to `-ms-`. * * @param {string} string * @return {string} */ function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, '-ms-'); } module.exports = hyphenateStyleName; /***/ }, /* 95 */ /***/ function(module, exports) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var _uppercasePattern = /([A-Z])/g; /** * Hyphenates a camelcased string, for example: * * > hyphenate('backgroundColor') * < "background-color" * * For CSS style names, use `hyphenateStyleName` instead which works properly * with all vendor prefixes, including `ms`. * * @param {string} string * @return {string} */ function hyphenate(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } module.exports = hyphenate; /***/ }, /* 96 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks static-only */ 'use strict'; /** * Memoizes the return value of a function that accepts one string argument. * * @param {function} callback * @return {function} */ function memoizeStringOnly(callback) { var cache = {}; return function (string) { if (!cache.hasOwnProperty(string)) { cache[string] = callback.call(this, string); } return cache[string]; }; } module.exports = memoizeStringOnly; /***/ }, /* 97 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMNamespaces */ 'use strict'; var DOMNamespaces = { html: 'http://www.w3.org/1999/xhtml', mathml: 'http://www.w3.org/1998/Math/MathML', svg: 'http://www.w3.org/2000/svg' }; module.exports = DOMNamespaces; /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DOMPropertyOperations */ 'use strict'; var DOMProperty = __webpack_require__(36); var ReactDOMInstrumentation = __webpack_require__(99); var ReactPerf = __webpack_require__(58); var quoteAttributeValueForBrowser = __webpack_require__(102); var warning = __webpack_require__(10); var VALID_ATTRIBUTE_NAME_REGEX = new RegExp('^[' + DOMProperty.ATTRIBUTE_NAME_START_CHAR + '][' + DOMProperty.ATTRIBUTE_NAME_CHAR + ']*$'); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (validatedAttributeNameCache.hasOwnProperty(attributeName)) { return true; } if (illegalAttributeNameCache.hasOwnProperty(attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; process.env.NODE_ENV !== 'production' ? warning(false, 'Invalid attribute name: `%s`', attributeName) : void 0; return false; } function shouldIgnoreValue(propertyInfo, value) { return value == null || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && isNaN(value) || propertyInfo.hasPositiveNumericValue && value < 1 || propertyInfo.hasOverloadedBooleanValue && value === false; } /** * Operations for dealing with DOM properties. */ var DOMPropertyOperations = { /** * Creates markup for the ID property. * * @param {string} id Unescaped ID. * @return {string} Markup string. */ createMarkupForID: function (id) { return DOMProperty.ID_ATTRIBUTE_NAME + '=' + quoteAttributeValueForBrowser(id); }, setAttributeForID: function (node, id) { node.setAttribute(DOMProperty.ID_ATTRIBUTE_NAME, id); }, createMarkupForRoot: function () { return DOMProperty.ROOT_ATTRIBUTE_NAME + '=""'; }, setAttributeForRoot: function (node) { node.setAttribute(DOMProperty.ROOT_ATTRIBUTE_NAME, ''); }, /** * Creates markup for a property. * * @param {string} name * @param {*} value * @return {?string} Markup string, or null if the property was invalid. */ createMarkupForProperty: function (name, value) { if (process.env.NODE_ENV !== 'production') { ReactDOMInstrumentation.debugTool.onCreateMarkupForProperty(name, value); } var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { if (shouldIgnoreValue(propertyInfo, value)) { return ''; } var attributeName = propertyInfo.attributeName; if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { return attributeName + '=""'; } return attributeName + '=' + quoteAttributeValueForBrowser(value); } else if (DOMProperty.isCustomAttribute(name)) { if (value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); } return null; }, /** * Creates markup for a custom property. * * @param {string} name * @param {*} value * @return {string} Markup string, or empty string if the property was invalid. */ createMarkupForCustomAttribute: function (name, value) { if (!isAttributeNameSafe(name) || value == null) { return ''; } return name + '=' + quoteAttributeValueForBrowser(value); }, /** * Sets the value for a property on a node. * * @param {DOMElement} node * @param {string} name * @param {*} value */ setValueForProperty: function (node, name, value) { if (process.env.NODE_ENV !== 'production') { ReactDOMInstrumentation.debugTool.onSetValueForProperty(node, name, value); } var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, value); } else if (shouldIgnoreValue(propertyInfo, value)) { this.deleteValueForProperty(node, name); } else if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; // Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the // property type before comparing; only `value` does and is string. if (!propertyInfo.hasSideEffects || '' + node[propName] !== '' + value) { // Contrary to `setAttribute`, object properties are properly // `toString`ed by IE8/9. node[propName] = value; } } else { var attributeName = propertyInfo.attributeName; var namespace = propertyInfo.attributeNamespace; // `setAttribute` with objects becomes only `[object]` in IE8/9, // ('' + value) makes it output the correct toString()-value. if (namespace) { node.setAttributeNS(namespace, attributeName, '' + value); } else if (propertyInfo.hasBooleanValue || propertyInfo.hasOverloadedBooleanValue && value === true) { node.setAttribute(attributeName, ''); } else { node.setAttribute(attributeName, '' + value); } } } else if (DOMProperty.isCustomAttribute(name)) { DOMPropertyOperations.setValueForAttribute(node, name, value); } }, setValueForAttribute: function (node, name, value) { if (!isAttributeNameSafe(name)) { return; } if (value == null) { node.removeAttribute(name); } else { node.setAttribute(name, '' + value); } }, /** * Deletes the value for a property on a node. * * @param {DOMElement} node * @param {string} name */ deleteValueForProperty: function (node, name) { if (process.env.NODE_ENV !== 'production') { ReactDOMInstrumentation.debugTool.onDeleteValueForProperty(node, name); } var propertyInfo = DOMProperty.properties.hasOwnProperty(name) ? DOMProperty.properties[name] : null; if (propertyInfo) { var mutationMethod = propertyInfo.mutationMethod; if (mutationMethod) { mutationMethod(node, undefined); } else if (propertyInfo.mustUseProperty) { var propName = propertyInfo.propertyName; if (propertyInfo.hasBooleanValue) { // No HAS_SIDE_EFFECTS logic here, only `value` has it and is string. node[propName] = false; } else { if (!propertyInfo.hasSideEffects || '' + node[propName] !== '') { node[propName] = ''; } } } else { node.removeAttribute(propertyInfo.attributeName); } } else if (DOMProperty.isCustomAttribute(name)) { node.removeAttribute(name); } } }; ReactPerf.measureMethods(DOMPropertyOperations, 'DOMPropertyOperations', { setValueForProperty: 'setValueForProperty', setValueForAttribute: 'setValueForAttribute', deleteValueForProperty: 'deleteValueForProperty' }); module.exports = DOMPropertyOperations; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMInstrumentation */ 'use strict'; var ReactDOMDebugTool = __webpack_require__(100); module.exports = { debugTool: ReactDOMDebugTool }; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMDebugTool */ 'use strict'; var ReactDOMUnknownPropertyDevtool = __webpack_require__(101); var warning = __webpack_require__(10); var eventHandlers = []; var handlerDoesThrowForEvent = {}; function emitEvent(handlerFunctionName, arg1, arg2, arg3, arg4, arg5) { if (process.env.NODE_ENV !== 'production') { eventHandlers.forEach(function (handler) { try { if (handler[handlerFunctionName]) { handler[handlerFunctionName](arg1, arg2, arg3, arg4, arg5); } } catch (e) { process.env.NODE_ENV !== 'production' ? warning(!handlerDoesThrowForEvent[handlerFunctionName], 'exception thrown by devtool while handling %s: %s', handlerFunctionName, e.message) : void 0; handlerDoesThrowForEvent[handlerFunctionName] = true; } }); } } var ReactDOMDebugTool = { addDevtool: function (devtool) { eventHandlers.push(devtool); }, removeDevtool: function (devtool) { for (var i = 0; i < eventHandlers.length; i++) { if (eventHandlers[i] === devtool) { eventHandlers.splice(i, 1); i--; } } }, onCreateMarkupForProperty: function (name, value) { emitEvent('onCreateMarkupForProperty', name, value); }, onSetValueForProperty: function (node, name, value) { emitEvent('onSetValueForProperty', node, name, value); }, onDeleteValueForProperty: function (node, name) { emitEvent('onDeleteValueForProperty', node, name); } }; ReactDOMDebugTool.addDevtool(ReactDOMUnknownPropertyDevtool); module.exports = ReactDOMDebugTool; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMUnknownPropertyDevtool */ 'use strict'; var DOMProperty = __webpack_require__(36); var EventPluginRegistry = __webpack_require__(43); var warning = __webpack_require__(10); if (process.env.NODE_ENV !== 'production') { var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true }; var warnedProperties = {}; var warnUnknownProperty = function (name) { if (DOMProperty.properties.hasOwnProperty(name) || DOMProperty.isCustomAttribute(name)) { return; } if (reactProps.hasOwnProperty(name) && reactProps[name] || warnedProperties.hasOwnProperty(name) && warnedProperties[name]) { return; } warnedProperties[name] = true; var lowerCasedName = name.toLowerCase(); // data-* attributes should be lowercase; suggest the lowercase version var standardName = DOMProperty.isCustomAttribute(lowerCasedName) ? lowerCasedName : DOMProperty.getPossibleStandardName.hasOwnProperty(lowerCasedName) ? DOMProperty.getPossibleStandardName[lowerCasedName] : null; // For now, only warn when we have a suggested correction. This prevents // logging too much when using transferPropsTo. process.env.NODE_ENV !== 'production' ? warning(standardName == null, 'Unknown DOM property %s. Did you mean %s?', name, standardName) : void 0; var registrationName = EventPluginRegistry.possibleRegistrationNames.hasOwnProperty(lowerCasedName) ? EventPluginRegistry.possibleRegistrationNames[lowerCasedName] : null; process.env.NODE_ENV !== 'production' ? warning(registrationName == null, 'Unknown event handler property %s. Did you mean `%s`?', name, registrationName) : void 0; }; } var ReactDOMUnknownPropertyDevtool = { onCreateMarkupForProperty: function (name, value) { warnUnknownProperty(name); }, onSetValueForProperty: function (node, name, value) { warnUnknownProperty(name); }, onDeleteValueForProperty: function (node, name) { warnUnknownProperty(name); } }; module.exports = ReactDOMUnknownPropertyDevtool; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule quoteAttributeValueForBrowser */ 'use strict'; var escapeTextContentForBrowser = __webpack_require__(78); /** * Escapes attribute value to prevent scripting attacks. * * @param {*} value Value to escape. * @return {string} An escaped string. */ function quoteAttributeValueForBrowser(value) { return '"' + escapeTextContentForBrowser(value) + '"'; } module.exports = quoteAttributeValueForBrowser; /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactBrowserEventEmitter */ 'use strict'; var _assign = __webpack_require__(4); var EventConstants = __webpack_require__(40); var EventPluginRegistry = __webpack_require__(43); var ReactEventEmitterMixin = __webpack_require__(104); var ViewportMetrics = __webpack_require__(70); var getVendorPrefixedEventName = __webpack_require__(105); var isEventSupported = __webpack_require__(64); /** * Summary of `ReactBrowserEventEmitter` event handling: * * - Top-level delegation is used to trap most native browser events. This * may only occur in the main thread and is the responsibility of * ReactEventListener, which is injected and can therefore support pluggable * event sources. This is the only work that occurs in the main thread. * * - We normalize and de-duplicate events to account for browser quirks. This * may be done in the worker thread. * * - Forward these native events (with the associated top-level type used to * trap it) to `EventPluginHub`, which in turn will ask plugins if they want * to extract any synthetic events. * * - The `EventPluginHub` will then process each event by annotating them with * "dispatches", a sequence of listeners and IDs that care about that event. * * - The `EventPluginHub` then dispatches the events. * * Overview of React and the event system: * * +------------+ . * | DOM | . * +------------+ . * | . * v . * +------------+ . * | ReactEvent | . * | Listener | . * +------------+ . +-----------+ * | . +--------+|SimpleEvent| * | . | |Plugin | * +-----|------+ . v +-----------+ * | | | . +--------------+ +------------+ * | +-----------.--->|EventPluginHub| | Event | * | | . | | +-----------+ | Propagators| * | ReactEvent | . | | |TapEvent | |------------| * | Emitter | . | |<---+|Plugin | |other plugin| * | | . | | +-----------+ | utilities | * | +-----------.--->| | +------------+ * | | | . +--------------+ * +-----|------+ . ^ +-----------+ * | . | |Enter/Leave| * + . +-------+|Plugin | * +-------------+ . +-----------+ * | application | . * |-------------| . * | | . * | | . * +-------------+ . * . * React Core . General Purpose Event Plugin System */ var hasEventPageXY; var alreadyListeningTo = {}; var isMonitoringScrollValue = false; var reactTopListenersCounter = 0; // For events like 'submit' which don't consistently bubble (which we trap at a // lower node than `document`), binding at `document` would cause duplicate // events so we don't include them here var topEventMapping = { topAbort: 'abort', topAnimationEnd: getVendorPrefixedEventName('animationend') || 'animationend', topAnimationIteration: getVendorPrefixedEventName('animationiteration') || 'animationiteration', topAnimationStart: getVendorPrefixedEventName('animationstart') || 'animationstart', topBlur: 'blur', topCanPlay: 'canplay', topCanPlayThrough: 'canplaythrough', topChange: 'change', topClick: 'click', topCompositionEnd: 'compositionend', topCompositionStart: 'compositionstart', topCompositionUpdate: 'compositionupdate', topContextMenu: 'contextmenu', topCopy: 'copy', topCut: 'cut', topDoubleClick: 'dblclick', topDrag: 'drag', topDragEnd: 'dragend', topDragEnter: 'dragenter', topDragExit: 'dragexit', topDragLeave: 'dragleave', topDragOver: 'dragover', topDragStart: 'dragstart', topDrop: 'drop', topDurationChange: 'durationchange', topEmptied: 'emptied', topEncrypted: 'encrypted', topEnded: 'ended', topError: 'error', topFocus: 'focus', topInput: 'input', topKeyDown: 'keydown', topKeyPress: 'keypress', topKeyUp: 'keyup', topLoadedData: 'loadeddata', topLoadedMetadata: 'loadedmetadata', topLoadStart: 'loadstart', topMouseDown: 'mousedown', topMouseMove: 'mousemove', topMouseOut: 'mouseout', topMouseOver: 'mouseover', topMouseUp: 'mouseup', topPaste: 'paste', topPause: 'pause', topPlay: 'play', topPlaying: 'playing', topProgress: 'progress', topRateChange: 'ratechange', topScroll: 'scroll', topSeeked: 'seeked', topSeeking: 'seeking', topSelectionChange: 'selectionchange', topStalled: 'stalled', topSuspend: 'suspend', topTextInput: 'textInput', topTimeUpdate: 'timeupdate', topTouchCancel: 'touchcancel', topTouchEnd: 'touchend', topTouchMove: 'touchmove', topTouchStart: 'touchstart', topTransitionEnd: getVendorPrefixedEventName('transitionend') || 'transitionend', topVolumeChange: 'volumechange', topWaiting: 'waiting', topWheel: 'wheel' }; /** * To ensure no conflicts with other potential React instances on the page */ var topListenersIDKey = '_reactListenersID' + String(Math.random()).slice(2); function getListeningForDocument(mountAt) { // In IE8, `mountAt` is a host object and doesn't have `hasOwnProperty` // directly. if (!Object.prototype.hasOwnProperty.call(mountAt, topListenersIDKey)) { mountAt[topListenersIDKey] = reactTopListenersCounter++; alreadyListeningTo[mountAt[topListenersIDKey]] = {}; } return alreadyListeningTo[mountAt[topListenersIDKey]]; } /** * `ReactBrowserEventEmitter` is used to attach top-level event listeners. For * example: * * EventPluginHub.putListener('myID', 'onClick', myFunction); * * This would allocate a "registration" of `('onClick', myFunction)` on 'myID'. * * @internal */ var ReactBrowserEventEmitter = _assign({}, ReactEventEmitterMixin, { /** * Injectable event backend */ ReactEventListener: null, injection: { /** * @param {object} ReactEventListener */ injectReactEventListener: function (ReactEventListener) { ReactEventListener.setHandleTopLevel(ReactBrowserEventEmitter.handleTopLevel); ReactBrowserEventEmitter.ReactEventListener = ReactEventListener; } }, /** * Sets whether or not any created callbacks should be enabled. * * @param {boolean} enabled True if callbacks should be enabled. */ setEnabled: function (enabled) { if (ReactBrowserEventEmitter.ReactEventListener) { ReactBrowserEventEmitter.ReactEventListener.setEnabled(enabled); } }, /** * @return {boolean} True if callbacks are enabled. */ isEnabled: function () { return !!(ReactBrowserEventEmitter.ReactEventListener && ReactBrowserEventEmitter.ReactEventListener.isEnabled()); }, /** * We listen for bubbled touch events on the document object. * * Firefox v8.01 (and possibly others) exhibited strange behavior when * mounting `onmousemove` events at some node that was not the document * element. The symptoms were that if your mouse is not moving over something * contained within that mount point (for example on the background) the * top-level listeners for `onmousemove` won't be called. However, if you * register the `mousemove` on the document object, then it will of course * catch all `mousemove`s. This along with iOS quirks, justifies restricting * top-level listeners to the document object only, at least for these * movement types of events and possibly all events. * * @see http://www.quirksmode.org/blog/archives/2010/09/click_event_del.html * * Also, `keyup`/`keypress`/`keydown` do not bubble to the window on IE, but * they bubble to document. * * @param {string} registrationName Name of listener (e.g. `onClick`). * @param {object} contentDocumentHandle Document which owns the container */ listenTo: function (registrationName, contentDocumentHandle) { var mountAt = contentDocumentHandle; var isListening = getListeningForDocument(mountAt); var dependencies = EventPluginRegistry.registrationNameDependencies[registrationName]; var topLevelTypes = EventConstants.topLevelTypes; for (var i = 0; i < dependencies.length; i++) { var dependency = dependencies[i]; if (!(isListening.hasOwnProperty(dependency) && isListening[dependency])) { if (dependency === topLevelTypes.topWheel) { if (isEventSupported('wheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'wheel', mountAt); } else if (isEventSupported('mousewheel')) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'mousewheel', mountAt); } else { // Firefox needs to capture a different mouse scroll event. // @see http://www.quirksmode.org/dom/events/tests/scroll.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topWheel, 'DOMMouseScroll', mountAt); } } else if (dependency === topLevelTypes.topScroll) { if (isEventSupported('scroll', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topScroll, 'scroll', mountAt); } else { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topScroll, 'scroll', ReactBrowserEventEmitter.ReactEventListener.WINDOW_HANDLE); } } else if (dependency === topLevelTypes.topFocus || dependency === topLevelTypes.topBlur) { if (isEventSupported('focus', true)) { ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topFocus, 'focus', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelTypes.topBlur, 'blur', mountAt); } else if (isEventSupported('focusin')) { // IE has `focusin` and `focusout` events which bubble. // @see http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topFocus, 'focusin', mountAt); ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelTypes.topBlur, 'focusout', mountAt); } // to make sure blur and focus event listeners are only attached once isListening[topLevelTypes.topBlur] = true; isListening[topLevelTypes.topFocus] = true; } else if (topEventMapping.hasOwnProperty(dependency)) { ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(dependency, topEventMapping[dependency], mountAt); } isListening[dependency] = true; } } }, trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapBubbledEvent(topLevelType, handlerBaseName, handle); }, trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { return ReactBrowserEventEmitter.ReactEventListener.trapCapturedEvent(topLevelType, handlerBaseName, handle); }, /** * Listens to window scroll and resize events. We cache scroll values so that * application code can access them without triggering reflows. * * ViewportMetrics is only used by SyntheticMouse/TouchEvent and only when * pageX/pageY isn't supported (legacy browsers). * * NOTE: Scroll events do not bubble. * * @see http://www.quirksmode.org/dom/events/scroll.html */ ensureScrollValueMonitoring: function () { if (hasEventPageXY === undefined) { hasEventPageXY = document.createEvent && 'pageX' in document.createEvent('MouseEvent'); } if (!hasEventPageXY && !isMonitoringScrollValue) { var refresh = ViewportMetrics.refreshScrollValues; ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh); isMonitoringScrollValue = true; } } }); module.exports = ReactBrowserEventEmitter; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventEmitterMixin */ 'use strict'; var EventPluginHub = __webpack_require__(42); function runEventQueueInBatch(events) { EventPluginHub.enqueueEvents(events); EventPluginHub.processEventQueue(false); } var ReactEventEmitterMixin = { /** * Streams a fired top-level event to `EventPluginHub` where plugins have the * opportunity to create `ReactEvent`s to be dispatched. */ handleTopLevel: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var events = EventPluginHub.extractEvents(topLevelType, targetInst, nativeEvent, nativeEventTarget); runEventQueueInBatch(events); } }; module.exports = ReactEventEmitterMixin; /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getVendorPrefixedEventName */ 'use strict'; var ExecutionEnvironment = __webpack_require__(48); /** * Generate a mapping of standard vendor prefixes using the defined style property and event name. * * @param {string} styleProp * @param {string} eventName * @returns {object} */ function makePrefixMap(styleProp, eventName) { var prefixes = {}; prefixes[styleProp.toLowerCase()] = eventName.toLowerCase(); prefixes['Webkit' + styleProp] = 'webkit' + eventName; prefixes['Moz' + styleProp] = 'moz' + eventName; prefixes['ms' + styleProp] = 'MS' + eventName; prefixes['O' + styleProp] = 'o' + eventName.toLowerCase(); return prefixes; } /** * A list of event names to a configurable list of vendor prefixes. */ var vendorPrefixes = { animationend: makePrefixMap('Animation', 'AnimationEnd'), animationiteration: makePrefixMap('Animation', 'AnimationIteration'), animationstart: makePrefixMap('Animation', 'AnimationStart'), transitionend: makePrefixMap('Transition', 'TransitionEnd') }; /** * Event names that have already been detected and prefixed (if applicable). */ var prefixedEventNames = {}; /** * Element to check for prefixes on. */ var style = {}; /** * Bootstrap if a DOM exists. */ if (ExecutionEnvironment.canUseDOM) { style = document.createElement('div').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 usable, and if not remove them from the map. if (!('AnimationEvent' in window)) { delete vendorPrefixes.animationend.animation; delete vendorPrefixes.animationiteration.animation; delete vendorPrefixes.animationstart.animation; } // Same as above if (!('TransitionEvent' in window)) { delete vendorPrefixes.transitionend.transition; } } /** * Attempts to determine the correct vendor prefixed event name. * * @param {string} eventName * @returns {string} */ function getVendorPrefixedEventName(eventName) { if (prefixedEventNames[eventName]) { return prefixedEventNames[eventName]; } else if (!vendorPrefixes[eventName]) { return eventName; } var prefixMap = vendorPrefixes[eventName]; for (var styleProp in prefixMap) { if (prefixMap.hasOwnProperty(styleProp) && styleProp in style) { return prefixedEventNames[eventName] = prefixMap[styleProp]; } } return ''; } module.exports = getVendorPrefixedEventName; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMButton */ 'use strict'; var DisabledInputUtils = __webpack_require__(107); /** * Implements a <button> native component that does not receive mouse events * when `disabled` is set. */ var ReactDOMButton = { getNativeProps: DisabledInputUtils.getNativeProps }; module.exports = ReactDOMButton; /***/ }, /* 107 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule DisabledInputUtils */ 'use strict'; var disableableMouseListenerNames = { onClick: true, onDoubleClick: true, onMouseDown: true, onMouseMove: true, onMouseUp: true, onClickCapture: true, onDoubleClickCapture: true, onMouseDownCapture: true, onMouseMoveCapture: true, onMouseUpCapture: true }; /** * Implements a native component that does not receive mouse events * when `disabled` is set. */ var DisabledInputUtils = { getNativeProps: function (inst, props) { if (!props.disabled) { return props; } // Copy the props, except the mouse listeners var nativeProps = {}; for (var key in props) { if (!disableableMouseListenerNames[key] && props.hasOwnProperty(key)) { nativeProps[key] = props[key]; } } return nativeProps; } }; module.exports = DisabledInputUtils; /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMInput */ 'use strict'; var _assign = __webpack_require__(4); var DisabledInputUtils = __webpack_require__(107); var DOMPropertyOperations = __webpack_require__(98); var LinkedValueUtils = __webpack_require__(109); var ReactDOMComponentTree = __webpack_require__(35); var ReactUpdates = __webpack_require__(55); var invariant = __webpack_require__(7); var warning = __webpack_require__(10); var didWarnValueLink = false; var didWarnCheckedLink = false; var didWarnValueNull = false; var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMInput.updateWrapper(this); } } function warnIfValueIsNull(props) { if (props != null && props.value === null && !didWarnValueNull) { process.env.NODE_ENV !== 'production' ? warning(false, '`value` prop on `input` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.') : void 0; didWarnValueNull = true; } } /** * Implements an <input> native component that allows setting these optional * props: `checked`, `value`, `defaultChecked`, and `defaultValue`. * * If `checked` or `value` are not supplied (or null/undefined), user actions * that affect the checked state or value will trigger updates to the element. * * If they are supplied (and not null/undefined), the rendered element will not * trigger updates to the element. Instead, the props must change in order for * the rendered element to be updated. * * The rendered element will be initialized as unchecked (or `defaultChecked`) * with an empty value (or `defaultValue`). * * @see http://www.w3.org/TR/2012/WD-html5-20121025/the-input-element.html */ var ReactDOMInput = { getNativeProps: function (inst, props) { var value = LinkedValueUtils.getValue(props); var checked = LinkedValueUtils.getChecked(props); var nativeProps = _assign({ // Make sure we set .type before any other properties (setting .value // before .type means .value is lost in IE11 and below) type: undefined }, DisabledInputUtils.getNativeProps(inst, props), { defaultChecked: undefined, defaultValue: undefined, value: value != null ? value : inst._wrapperState.initialValue, checked: checked != null ? checked : inst._wrapperState.initialChecked, onChange: inst._wrapperState.onChange }); return nativeProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('input', props, inst._currentElement._owner); if (props.valueLink !== undefined && !didWarnValueLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.checkedLink !== undefined && !didWarnCheckedLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`checkedLink` prop on `input` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnCheckedLink = true; } if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { process.env.NODE_ENV !== 'production' ? warning(false, 'Input elements must be either controlled or uncontrolled ' + '(specify either the checked prop, or the defaultChecked prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnCheckedDefaultChecked = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { process.env.NODE_ENV !== 'production' ? warning(false, 'Input elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled input ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValueDefaultValue = true; } warnIfValueIsNull(props); } var defaultValue = props.defaultValue; inst._wrapperState = { initialChecked: props.defaultChecked || false, initialValue: defaultValue != null ? defaultValue : null, listeners: null, onChange: _handleChange.bind(inst) }; if (process.env.NODE_ENV !== 'production') { inst._wrapperState.controlled = props.checked !== undefined || props.value !== undefined; } }, updateWrapper: function (inst) { var props = inst._currentElement.props; if (process.env.NODE_ENV !== 'production') { warnIfValueIsNull(props); var initialValue = inst._wrapperState.initialChecked || inst._wrapperState.initialValue; var defaultValue = props.defaultChecked || props.defaultValue; var controlled = props.checked !== undefined || props.value !== undefined; var owner = inst._currentElement._owner; if ((initialValue || !inst._wrapperState.controlled) && controlled && !didWarnUncontrolledToControlled) { process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing a uncontrolled input of type %s to be controlled. ' + 'Input elements should not switch from uncontrolled to controlled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnUncontrolledToControlled = true; } if (inst._wrapperState.controlled && (defaultValue || !controlled) && !didWarnControlledToUncontrolled) { process.env.NODE_ENV !== 'production' ? warning(false, '%s is changing a controlled input of type %s to be uncontrolled. ' + 'Input elements should not switch from controlled to uncontrolled (or vice versa). ' + 'Decide between using a controlled or uncontrolled input ' + 'element for the lifetime of the component. More info: https://fb.me/react-controlled-components', owner && owner.getName() || 'A component', props.type) : void 0; didWarnControlledToUncontrolled = true; } } // TODO: Shouldn't this be getChecked(props)? var checked = props.checked; if (checked != null) { DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'checked', checked || false); } var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'value', '' + value); } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); // Here we use asap to wait until all updates have propagated, which // is important when using controlled components within layers: // https://github.com/facebook/react/issues/1698 ReactUpdates.asap(forceUpdateIfMounted, this); var name = props.name; if (props.type === 'radio' && name != null) { var rootNode = ReactDOMComponentTree.getNodeFromInstance(this); var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } // If `rootNode.form` was non-null, then we could try `form.elements`, // but that sometimes behaves strangely in IE8. We could also try using // `form.getElementsByName`, but that will only return direct children // and won't include inputs that use the HTML5 `form=` attribute. Since // the input might not even be in a form, let's just use the global // `querySelectorAll` to ensure we don't miss anything. var group = queryRoot.querySelectorAll('input[name=' + JSON.stringify('' + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } // This will throw if radio buttons rendered by different copies of React // and the same name are rendered into the same form (same as #1939). // That's probably okay; we don't support it just as we don't support // mixing React radio buttons with non-React ones. var otherInstance = ReactDOMComponentTree.getInstanceFromNode(otherNode); !otherInstance ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOMInput: Mixing React and non-React radio inputs with the ' + 'same `name` is not supported.') : invariant(false) : void 0; // If this is a controlled radio button group, forcing the input that // was previously checked to update will cause it to be come re-checked // as appropriate. ReactUpdates.asap(forceUpdateIfMounted, otherInstance); } } return returnValue; } module.exports = ReactDOMInput; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule LinkedValueUtils */ 'use strict'; var ReactPropTypes = __webpack_require__(30); var ReactPropTypeLocations = __webpack_require__(23); var invariant = __webpack_require__(7); var warning = __webpack_require__(10); var hasReadOnlyValue = { 'button': true, 'checkbox': true, 'image': true, 'hidden': true, 'radio': true, 'reset': true, 'submit': true }; function _assertSingleLink(inputProps) { !(inputProps.checkedLink == null || inputProps.valueLink == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a valueLink. If you want to use ' + 'checkedLink, you probably don\'t want to use valueLink and vice versa.') : invariant(false) : void 0; } function _assertValueLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.value == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a valueLink and a value or onChange event. If you want ' + 'to use value or onChange, you probably don\'t want to use valueLink.') : invariant(false) : void 0; } function _assertCheckedLink(inputProps) { _assertSingleLink(inputProps); !(inputProps.checked == null && inputProps.onChange == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Cannot provide a checkedLink and a checked property or onChange event. ' + 'If you want to use checked or onChange, you probably don\'t want to ' + 'use checkedLink') : invariant(false) : void 0; } var propTypes = { value: function (props, propName, componentName) { if (!props[propName] || hasReadOnlyValue[props.type] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `value` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultValue`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, checked: function (props, propName, componentName) { if (!props[propName] || props.onChange || props.readOnly || props.disabled) { return null; } return new Error('You provided a `checked` prop to a form field without an ' + '`onChange` handler. This will render a read-only field. If ' + 'the field should be mutable use `defaultChecked`. Otherwise, ' + 'set either `onChange` or `readOnly`.'); }, onChange: ReactPropTypes.func }; var loggedTypeFailures = {}; function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Provide a linked `value` attribute for controlled forms. You should not use * this outside of the ReactDOM controlled form components. */ var LinkedValueUtils = { checkPropTypes: function (tagName, props, owner) { for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, tagName, ReactPropTypeLocations.prop); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { // Only monitor this failure once because there tends to be a lot of the // same error. loggedTypeFailures[error.message] = true; var addendum = getDeclarationErrorAddendum(owner); process.env.NODE_ENV !== 'production' ? warning(false, 'Failed form propType: %s%s', error.message, addendum) : void 0; } } }, /** * @param {object} inputProps Props for form component * @return {*} current value of the input either from value prop or link. */ getValue: function (inputProps) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.value; } return inputProps.value; }, /** * @param {object} inputProps Props for form component * @return {*} current checked status of the input either from checked prop * or link. */ getChecked: function (inputProps) { if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.value; } return inputProps.checked; }, /** * @param {object} inputProps Props for form component * @param {SyntheticEvent} event change event to handle */ executeOnChange: function (inputProps, event) { if (inputProps.valueLink) { _assertValueLink(inputProps); return inputProps.valueLink.requestChange(event.target.value); } else if (inputProps.checkedLink) { _assertCheckedLink(inputProps); return inputProps.checkedLink.requestChange(event.target.checked); } else if (inputProps.onChange) { return inputProps.onChange.call(undefined, event); } } }; module.exports = LinkedValueUtils; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMOption */ 'use strict'; var _assign = __webpack_require__(4); var ReactChildren = __webpack_require__(5); var ReactDOMComponentTree = __webpack_require__(35); var ReactDOMSelect = __webpack_require__(111); var warning = __webpack_require__(10); /** * Implements an <option> native component that warns when `selected` is set. */ var ReactDOMOption = { mountWrapper: function (inst, props, nativeParent) { // TODO (yungsters): Remove support for `selected` in <option>. if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(props.selected == null, 'Use the `defaultValue` or `value` props on <select> instead of ' + 'setting `selected` on <option>.') : void 0; } // Look up whether this option is 'selected' var selectValue = null; if (nativeParent != null) { var selectParent = nativeParent; if (selectParent._tag === 'optgroup') { selectParent = selectParent._nativeParent; } if (selectParent != null && selectParent._tag === 'select') { selectValue = ReactDOMSelect.getSelectValueContext(selectParent); } } // If the value is null (e.g., no specified value or after initial mount) // or missing (e.g., for <datalist>), we don't change props.selected var selected = null; if (selectValue != null) { selected = false; if (Array.isArray(selectValue)) { // multiple for (var i = 0; i < selectValue.length; i++) { if ('' + selectValue[i] === '' + props.value) { selected = true; break; } } } else { selected = '' + selectValue === '' + props.value; } } inst._wrapperState = { selected: selected }; }, postMountWrapper: function (inst) { // value="" should make a value attribute (#6219) var props = inst._currentElement.props; if (props.value != null) { var node = ReactDOMComponentTree.getNodeFromInstance(inst); node.setAttribute('value', props.value); } }, getNativeProps: function (inst, props) { var nativeProps = _assign({ selected: undefined, children: undefined }, props); // Read state only from initial mount because <select> updates value // manually; we need the initial state only for server rendering if (inst._wrapperState.selected != null) { nativeProps.selected = inst._wrapperState.selected; } var content = ''; // Flatten children and warn if they aren't strings or numbers; // invalid types are ignored. ReactChildren.forEach(props.children, function (child) { if (child == null) { return; } if (typeof child === 'string' || typeof child === 'number') { content += child; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'Only strings and numbers are supported as <option> children.') : void 0; } }); if (content) { nativeProps.children = content; } return nativeProps; } }; module.exports = ReactDOMOption; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelect */ 'use strict'; var _assign = __webpack_require__(4); var DisabledInputUtils = __webpack_require__(107); var LinkedValueUtils = __webpack_require__(109); var ReactDOMComponentTree = __webpack_require__(35); var ReactUpdates = __webpack_require__(55); var warning = __webpack_require__(10); var didWarnValueLink = false; var didWarnValueNull = false; var didWarnValueDefaultValue = false; function updateOptionsIfPendingUpdateAndMounted() { if (this._rootNodeID && this._wrapperState.pendingUpdate) { this._wrapperState.pendingUpdate = false; var props = this._currentElement.props; var value = LinkedValueUtils.getValue(props); if (value != null) { updateOptions(this, Boolean(props.multiple), value); } } } function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } function warnIfValueIsNull(props) { if (props != null && props.value === null && !didWarnValueNull) { process.env.NODE_ENV !== 'production' ? warning(false, '`value` prop on `select` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.') : void 0; didWarnValueNull = true; } } var valuePropNames = ['value', 'defaultValue']; /** * Validation function for `value` and `defaultValue`. * @private */ function checkSelectPropTypes(inst, props) { var owner = inst._currentElement._owner; LinkedValueUtils.checkPropTypes('select', props, owner); if (props.valueLink !== undefined && !didWarnValueLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `select` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } for (var i = 0; i < valuePropNames.length; i++) { var propName = valuePropNames[i]; if (props[propName] == null) { continue; } if (props.multiple) { process.env.NODE_ENV !== 'production' ? warning(Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be an array if ' + '`multiple` is true.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } else { process.env.NODE_ENV !== 'production' ? warning(!Array.isArray(props[propName]), 'The `%s` prop supplied to <select> must be a scalar ' + 'value if `multiple` is false.%s', propName, getDeclarationErrorAddendum(owner)) : void 0; } } } /** * @param {ReactDOMComponent} inst * @param {boolean} multiple * @param {*} propValue A stringable (with `multiple`, a list of stringables). * @private */ function updateOptions(inst, multiple, propValue) { var selectedValue, i; var options = ReactDOMComponentTree.getNodeFromInstance(inst).options; if (multiple) { selectedValue = {}; for (i = 0; i < propValue.length; i++) { selectedValue['' + propValue[i]] = true; } for (i = 0; i < options.length; i++) { var selected = selectedValue.hasOwnProperty(options[i].value); if (options[i].selected !== selected) { options[i].selected = selected; } } } else { // Do not set `select.value` as exact behavior isn't consistent across all // browsers for all cases. selectedValue = '' + propValue; for (i = 0; i < options.length; i++) { if (options[i].value === selectedValue) { options[i].selected = true; return; } } if (options.length) { options[0].selected = true; } } } /** * Implements a <select> native component that allows optionally setting the * props `value` and `defaultValue`. If `multiple` is false, the prop must be a * stringable. If `multiple` is true, the prop must be an array of stringables. * * If `value` is not supplied (or null/undefined), user actions that change the * selected option will trigger updates to the rendered options. * * If it is supplied (and not null/undefined), the rendered options will not * update in response to user actions. Instead, the `value` prop must change in * order for the rendered options to update. * * If `defaultValue` is provided, any options with the supplied values will be * selected. */ var ReactDOMSelect = { getNativeProps: function (inst, props) { return _assign({}, DisabledInputUtils.getNativeProps(inst, props), { onChange: inst._wrapperState.onChange, value: undefined }); }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { checkSelectPropTypes(inst, props); warnIfValueIsNull(props); } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { pendingUpdate: false, initialValue: value != null ? value : props.defaultValue, listeners: null, onChange: _handleChange.bind(inst), wasMultiple: Boolean(props.multiple) }; if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { process.env.NODE_ENV !== 'production' ? warning(false, 'Select elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled select ' + 'element and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValueDefaultValue = true; } }, getSelectValueContext: function (inst) { // ReactDOMOption looks at this initial value so the initial generated // markup has correct `selected` attributes return inst._wrapperState.initialValue; }, postUpdateWrapper: function (inst) { var props = inst._currentElement.props; if (process.env.NODE_ENV !== 'production') { warnIfValueIsNull(props); } // After the initial mount, we control selected-ness manually so don't pass // this value down inst._wrapperState.initialValue = undefined; var wasMultiple = inst._wrapperState.wasMultiple; inst._wrapperState.wasMultiple = Boolean(props.multiple); var value = LinkedValueUtils.getValue(props); if (value != null) { inst._wrapperState.pendingUpdate = false; updateOptions(inst, Boolean(props.multiple), value); } else if (wasMultiple !== Boolean(props.multiple)) { // For simplicity, reapply `defaultValue` if `multiple` is toggled. if (props.defaultValue != null) { updateOptions(inst, Boolean(props.multiple), props.defaultValue); } else { // Revert the select back to its default unselected state. updateOptions(inst, Boolean(props.multiple), props.multiple ? [] : ''); } } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); if (this._rootNodeID) { this._wrapperState.pendingUpdate = true; } ReactUpdates.asap(updateOptionsIfPendingUpdateAndMounted, this); return returnValue; } module.exports = ReactDOMSelect; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextarea */ 'use strict'; var _assign = __webpack_require__(4); var DisabledInputUtils = __webpack_require__(107); var DOMPropertyOperations = __webpack_require__(98); var LinkedValueUtils = __webpack_require__(109); var ReactDOMComponentTree = __webpack_require__(35); var ReactUpdates = __webpack_require__(55); var invariant = __webpack_require__(7); var warning = __webpack_require__(10); var didWarnValueLink = false; var didWarnValueNull = false; var didWarnValDefaultVal = false; function forceUpdateIfMounted() { if (this._rootNodeID) { // DOM component is still mounted; update ReactDOMTextarea.updateWrapper(this); } } function warnIfValueIsNull(props) { if (props != null && props.value === null && !didWarnValueNull) { process.env.NODE_ENV !== 'production' ? warning(false, '`value` prop on `textarea` should not be null. ' + 'Consider using the empty string to clear the component or `undefined` ' + 'for uncontrolled components.') : void 0; didWarnValueNull = true; } } /** * Implements a <textarea> native component that allows setting `value`, and * `defaultValue`. This differs from the traditional DOM API because value is * usually set as PCDATA children. * * If `value` is not supplied (or null/undefined), user actions that affect the * value will trigger updates to the element. * * If `value` is supplied (and not null/undefined), the rendered element will * not trigger updates to the element. Instead, the `value` prop must change in * order for the rendered element to be updated. * * The rendered element will be initialized with an empty value, the prop * `defaultValue` if specified, or the children content (deprecated). */ var ReactDOMTextarea = { getNativeProps: function (inst, props) { !(props.dangerouslySetInnerHTML == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, '`dangerouslySetInnerHTML` does not make sense on <textarea>.') : invariant(false) : void 0; // Always set children to the same thing. In IE9, the selection range will // get reset if `textContent` is mutated. var nativeProps = _assign({}, DisabledInputUtils.getNativeProps(inst, props), { defaultValue: undefined, value: undefined, children: inst._wrapperState.initialValue, onChange: inst._wrapperState.onChange }); return nativeProps; }, mountWrapper: function (inst, props) { if (process.env.NODE_ENV !== 'production') { LinkedValueUtils.checkPropTypes('textarea', props, inst._currentElement._owner); if (props.valueLink !== undefined && !didWarnValueLink) { process.env.NODE_ENV !== 'production' ? warning(false, '`valueLink` prop on `textarea` is deprecated; set `value` and `onChange` instead.') : void 0; didWarnValueLink = true; } if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValDefaultVal) { process.env.NODE_ENV !== 'production' ? warning(false, 'Textarea elements must be either controlled or uncontrolled ' + '(specify either the value prop, or the defaultValue prop, but not ' + 'both). Decide between using a controlled or uncontrolled textarea ' + 'and remove one of these props. More info: ' + 'https://fb.me/react-controlled-components') : void 0; didWarnValDefaultVal = true; } warnIfValueIsNull(props); } var defaultValue = props.defaultValue; // TODO (yungsters): Remove support for children content in <textarea>. var children = props.children; if (children != null) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, 'Use the `defaultValue` or `value` props instead of setting ' + 'children on <textarea>.') : void 0; } !(defaultValue == null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'If you supply `defaultValue` on a <textarea>, do not pass children.') : invariant(false) : void 0; if (Array.isArray(children)) { !(children.length <= 1) ? process.env.NODE_ENV !== 'production' ? invariant(false, '<textarea> can only have at most one child.') : invariant(false) : void 0; children = children[0]; } defaultValue = '' + children; } if (defaultValue == null) { defaultValue = ''; } var value = LinkedValueUtils.getValue(props); inst._wrapperState = { // We save the initial value so that `ReactDOMComponent` doesn't update // `textContent` (unnecessary since we update value). // The initial value can be a boolean or object so that's why it's // forced to be a string. initialValue: '' + (value != null ? value : defaultValue), listeners: null, onChange: _handleChange.bind(inst) }; }, updateWrapper: function (inst) { var props = inst._currentElement.props; if (process.env.NODE_ENV !== 'production') { warnIfValueIsNull(props); } var value = LinkedValueUtils.getValue(props); if (value != null) { // Cast `value` to a string to ensure the value is set correctly. While // browsers typically do this as necessary, jsdom doesn't. DOMPropertyOperations.setValueForProperty(ReactDOMComponentTree.getNodeFromInstance(inst), 'value', '' + value); } } }; function _handleChange(event) { var props = this._currentElement.props; var returnValue = LinkedValueUtils.executeOnChange(props, event); ReactUpdates.asap(forceUpdateIfMounted, this); return returnValue; } module.exports = ReactDOMTextarea; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMultiChild */ 'use strict'; var ReactComponentEnvironment = __webpack_require__(114); var ReactMultiChildUpdateTypes = __webpack_require__(84); var ReactCurrentOwner = __webpack_require__(9); var ReactReconciler = __webpack_require__(59); var ReactChildReconciler = __webpack_require__(115); var flattenChildren = __webpack_require__(124); var invariant = __webpack_require__(7); /** * Make an update for markup to be rendered and inserted at a supplied index. * * @param {string} markup Markup that renders into an element. * @param {number} toIndex Destination index. * @private */ function makeInsertMarkup(markup, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.INSERT_MARKUP, content: markup, fromIndex: null, fromNode: null, toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for moving an existing element to another index. * * @param {number} fromIndex Source index of the existing element. * @param {number} toIndex Destination index of the element. * @private */ function makeMove(child, afterNode, toIndex) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.MOVE_EXISTING, content: null, fromIndex: child._mountIndex, fromNode: ReactReconciler.getNativeNode(child), toIndex: toIndex, afterNode: afterNode }; } /** * Make an update for removing an element at an index. * * @param {number} fromIndex Index of the element to remove. * @private */ function makeRemove(child, node) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.REMOVE_NODE, content: null, fromIndex: child._mountIndex, fromNode: node, toIndex: null, afterNode: null }; } /** * Make an update for setting the markup of a node. * * @param {string} markup Markup that renders into an element. * @private */ function makeSetMarkup(markup) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.SET_MARKUP, content: markup, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Make an update for setting the text content. * * @param {string} textContent Text content to set. * @private */ function makeTextContent(textContent) { // NOTE: Null values reduce hidden classes. return { type: ReactMultiChildUpdateTypes.TEXT_CONTENT, content: textContent, fromIndex: null, fromNode: null, toIndex: null, afterNode: null }; } /** * Push an update, if any, onto the queue. Creates a new queue if none is * passed and always returns the queue. Mutative. */ function enqueue(queue, update) { if (update) { queue = queue || []; queue.push(update); } return queue; } /** * Processes any enqueued updates. * * @private */ function processQueue(inst, updateQueue) { ReactComponentEnvironment.processChildrenUpdates(inst, updateQueue); } /** * ReactMultiChild are capable of reconciling multiple children. * * @class ReactMultiChild * @internal */ var ReactMultiChild = { /** * Provides common functionality for components that must reconcile multiple * children. This is used by `ReactDOMComponent` to mount, update, and * unmount child components. * * @lends {ReactMultiChild.prototype} */ Mixin: { _reconcilerInstantiateChildren: function (nestedChildren, transaction, context) { if (process.env.NODE_ENV !== 'production') { if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); } finally { ReactCurrentOwner.current = null; } } } return ReactChildReconciler.instantiateChildren(nestedChildren, transaction, context); }, _reconcilerUpdateChildren: function (prevChildren, nextNestedChildrenElements, removedNodes, transaction, context) { var nextChildren; if (process.env.NODE_ENV !== 'production') { if (this._currentElement) { try { ReactCurrentOwner.current = this._currentElement._owner; nextChildren = flattenChildren(nextNestedChildrenElements); } finally { ReactCurrentOwner.current = null; } ReactChildReconciler.updateChildren(prevChildren, nextChildren, removedNodes, transaction, context); return nextChildren; } } nextChildren = flattenChildren(nextNestedChildrenElements); ReactChildReconciler.updateChildren(prevChildren, nextChildren, removedNodes, transaction, context); return nextChildren; }, /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildren Nested child maps. * @return {array} An array of mounted representations. * @internal */ mountChildren: function (nestedChildren, transaction, context) { var children = this._reconcilerInstantiateChildren(nestedChildren, transaction, context); this._renderedChildren = children; var mountImages = []; var index = 0; for (var name in children) { if (children.hasOwnProperty(name)) { var child = children[name]; var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._nativeContainerInfo, context); child._mountIndex = index++; mountImages.push(mountImage); } } return mountImages; }, /** * Replaces any rendered children with a text content string. * * @param {string} nextContent String of content. * @internal */ updateTextContent: function (nextContent) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : invariant(false) : void 0; } } // Set new text content. var updates = [makeTextContent(nextContent)]; processQueue(this, updates); }, /** * Replaces any rendered children with a markup string. * * @param {string} nextMarkup String of markup. * @internal */ updateMarkup: function (nextMarkup) { var prevChildren = this._renderedChildren; // Remove any rendered children. ReactChildReconciler.unmountChildren(prevChildren, false); for (var name in prevChildren) { if (prevChildren.hasOwnProperty(name)) { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'updateTextContent called on non-empty component.') : invariant(false) : void 0; } } var updates = [makeSetMarkup(nextMarkup)]; processQueue(this, updates); }, /** * Updates the rendered children with new children. * * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @internal */ updateChildren: function (nextNestedChildrenElements, transaction, context) { // Hook used by React ART this._updateChildren(nextNestedChildrenElements, transaction, context); }, /** * @param {?object} nextNestedChildrenElements Nested child element maps. * @param {ReactReconcileTransaction} transaction * @final * @protected */ _updateChildren: function (nextNestedChildrenElements, transaction, context) { var prevChildren = this._renderedChildren; var removedNodes = {}; var nextChildren = this._reconcilerUpdateChildren(prevChildren, nextNestedChildrenElements, removedNodes, transaction, context); if (!nextChildren && !prevChildren) { return; } var updates = null; var name; // `nextIndex` will increment for each child in `nextChildren`, but // `lastIndex` will be the last index visited in `prevChildren`. var lastIndex = 0; var nextIndex = 0; var lastPlacedNode = null; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } var prevChild = prevChildren && prevChildren[name]; var nextChild = nextChildren[name]; if (prevChild === nextChild) { updates = enqueue(updates, this.moveChild(prevChild, lastPlacedNode, nextIndex, lastIndex)); lastIndex = Math.max(prevChild._mountIndex, lastIndex); prevChild._mountIndex = nextIndex; } else { if (prevChild) { // Update `lastIndex` before `_mountIndex` gets unset by unmounting. lastIndex = Math.max(prevChild._mountIndex, lastIndex); // The `removedNodes` loop below will actually remove the child. } // The child must be instantiated before it's mounted. updates = enqueue(updates, this._mountChildAtIndex(nextChild, lastPlacedNode, nextIndex, transaction, context)); } nextIndex++; lastPlacedNode = ReactReconciler.getNativeNode(nextChild); } // Remove children that are no longer present. for (name in removedNodes) { if (removedNodes.hasOwnProperty(name)) { updates = enqueue(updates, this._unmountChild(prevChildren[name], removedNodes[name])); } } if (updates) { processQueue(this, updates); } this._renderedChildren = nextChildren; }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. It does not actually perform any * backend operations. * * @internal */ unmountChildren: function (safely) { var renderedChildren = this._renderedChildren; ReactChildReconciler.unmountChildren(renderedChildren, safely); this._renderedChildren = null; }, /** * Moves a child component to the supplied index. * * @param {ReactComponent} child Component to move. * @param {number} toIndex Destination index of the element. * @param {number} lastIndex Last index visited of the siblings of `child`. * @protected */ moveChild: function (child, afterNode, toIndex, lastIndex) { // If the index of `child` is less than `lastIndex`, then it needs to // be moved. Otherwise, we do not need to move it because a child will be // inserted or moved before `child`. if (child._mountIndex < lastIndex) { return makeMove(child, afterNode, toIndex); } }, /** * Creates a child component. * * @param {ReactComponent} child Component to create. * @param {string} mountImage Markup to insert. * @protected */ createChild: function (child, afterNode, mountImage) { return makeInsertMarkup(mountImage, afterNode, child._mountIndex); }, /** * Removes a child component. * * @param {ReactComponent} child Child to remove. * @protected */ removeChild: function (child, node) { return makeRemove(child, node); }, /** * Mounts a child with the supplied name. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to mount. * @param {string} name Name of the child. * @param {number} index Index at which to insert the child. * @param {ReactReconcileTransaction} transaction * @private */ _mountChildAtIndex: function (child, afterNode, index, transaction, context) { var mountImage = ReactReconciler.mountComponent(child, transaction, this, this._nativeContainerInfo, context); child._mountIndex = index; return this.createChild(child, afterNode, mountImage); }, /** * Unmounts a rendered child. * * NOTE: This is part of `updateChildren` and is here for readability. * * @param {ReactComponent} child Component to unmount. * @private */ _unmountChild: function (child, node) { var update = this.removeChild(child, node); child._mountIndex = null; return update; } } }; module.exports = ReactMultiChild; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactComponentEnvironment */ 'use strict'; var invariant = __webpack_require__(7); var injected = false; var ReactComponentEnvironment = { /** * Optionally injectable environment dependent cleanup hook. (server vs. * browser etc). Example: A browser system caches DOM nodes based on component * ID and must remove that cache entry when this instance is unmounted. */ unmountIDFromEnvironment: null, /** * Optionally injectable hook for swapping out mount images in the middle of * the tree. */ replaceNodeWithMarkup: null, /** * Optionally injectable hook for processing a queue of child updates. Will * later move into MultiChildComponents. */ processChildrenUpdates: null, injection: { injectEnvironment: function (environment) { !!injected ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactCompositeComponent: injectEnvironment() can only be called once.') : invariant(false) : void 0; ReactComponentEnvironment.unmountIDFromEnvironment = environment.unmountIDFromEnvironment; ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactChildReconciler */ 'use strict'; var ReactReconciler = __webpack_require__(59); var instantiateReactComponent = __webpack_require__(116); var KeyEscapeUtils = __webpack_require__(15); var shouldUpdateReactComponent = __webpack_require__(121); var traverseAllChildren = __webpack_require__(13); var warning = __webpack_require__(10); function instantiateChild(childInstances, child, name) { // We found a component instance. var keyUnique = childInstances[name] === undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', KeyEscapeUtils.unescape(name)) : void 0; } if (child != null && keyUnique) { childInstances[name] = instantiateReactComponent(child); } } /** * ReactChildReconciler provides helpers for initializing or updating a set of * children. Its output is suitable for passing it onto ReactMultiChild which * does diffed reordering and insertion. */ var ReactChildReconciler = { /** * Generates a "mount image" for each of the supplied children. In the case * of `ReactDOMComponent`, a mount image is a string of markup. * * @param {?object} nestedChildNodes Nested child maps. * @return {?object} A set of child instances. * @internal */ instantiateChildren: function (nestedChildNodes, transaction, context) { if (nestedChildNodes == null) { return null; } var childInstances = {}; traverseAllChildren(nestedChildNodes, instantiateChild, childInstances); return childInstances; }, /** * Updates the rendered children and returns a new set of children. * * @param {?object} prevChildren Previously initialized set of children. * @param {?object} nextChildren Flat child element maps. * @param {ReactReconcileTransaction} transaction * @param {object} context * @return {?object} A new set of child instances. * @internal */ updateChildren: function (prevChildren, nextChildren, removedNodes, transaction, context) { // We currently don't have a way to track moves here but if we use iterators // instead of for..in we can zip the iterators and check if an item has // moved. // TODO: If nothing has changed, return the prevChildren object so that we // can quickly bailout if nothing has changed. if (!nextChildren && !prevChildren) { return; } var name; var prevChild; for (name in nextChildren) { if (!nextChildren.hasOwnProperty(name)) { continue; } prevChild = prevChildren && prevChildren[name]; var prevElement = prevChild && prevChild._currentElement; var nextElement = nextChildren[name]; if (prevChild != null && shouldUpdateReactComponent(prevElement, nextElement)) { ReactReconciler.receiveComponent(prevChild, nextElement, transaction, context); nextChildren[name] = prevChild; } else { if (prevChild) { removedNodes[name] = ReactReconciler.getNativeNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } // The child must be instantiated before it's mounted. var nextChildInstance = instantiateReactComponent(nextElement); nextChildren[name] = nextChildInstance; } } // Unmount children that are no longer present. for (name in prevChildren) { if (prevChildren.hasOwnProperty(name) && !(nextChildren && nextChildren.hasOwnProperty(name))) { prevChild = prevChildren[name]; removedNodes[name] = ReactReconciler.getNativeNode(prevChild); ReactReconciler.unmountComponent(prevChild, false); } } }, /** * Unmounts all rendered children. This should be used to clean up children * when this component is unmounted. * * @param {?object} renderedChildren Previously initialized set of children. * @internal */ unmountChildren: function (renderedChildren, safely) { for (var name in renderedChildren) { if (renderedChildren.hasOwnProperty(name)) { var renderedChild = renderedChildren[name]; ReactReconciler.unmountComponent(renderedChild, safely); } } } }; module.exports = ReactChildReconciler; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule instantiateReactComponent */ 'use strict'; var _assign = __webpack_require__(4); var ReactCompositeComponent = __webpack_require__(117); var ReactEmptyComponent = __webpack_require__(122); var ReactNativeComponent = __webpack_require__(123); var invariant = __webpack_require__(7); var warning = __webpack_require__(10); // To avoid a cyclic dependency, we create the final class in this module var ReactCompositeComponentWrapper = function (element) { this.construct(element); }; _assign(ReactCompositeComponentWrapper.prototype, ReactCompositeComponent.Mixin, { _instantiateReactComponent: instantiateReactComponent }); function getDeclarationErrorAddendum(owner) { if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } /** * Check if the type reference is a known internal type. I.e. not a user * provided composite type. * * @param {function} type * @return {boolean} Returns true if this is a valid internal type. */ function isInternalComponentType(type) { return typeof type === 'function' && typeof type.prototype !== 'undefined' && typeof type.prototype.mountComponent === 'function' && typeof type.prototype.receiveComponent === 'function'; } /** * Given a ReactNode, create an instance that will actually be mounted. * * @param {ReactNode} node * @return {object} A new instance of the element's constructor. * @protected */ function instantiateReactComponent(node) { var instance; if (node === null || node === false) { instance = ReactEmptyComponent.create(instantiateReactComponent); } else if (typeof node === 'object') { var element = node; !(element && (typeof element.type === 'function' || typeof element.type === 'string')) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element type is invalid: expected a string (for built-in components) ' + 'or a class/function (for composite components) but got: %s.%s', element.type == null ? element.type : typeof element.type, getDeclarationErrorAddendum(element._owner)) : invariant(false) : void 0; // Special case string values if (typeof element.type === 'string') { instance = ReactNativeComponent.createInternalComponent(element); } else if (isInternalComponentType(element.type)) { // This is temporarily available for custom components that are not string // representations. I.e. ART. Once those are updated to use the string // representation, we can drop this code path. instance = new element.type(element); } else { instance = new ReactCompositeComponentWrapper(element); } } else if (typeof node === 'string' || typeof node === 'number') { instance = ReactNativeComponent.createInstanceForText(node); } else { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Encountered invalid React node of type %s', typeof node) : invariant(false) : void 0; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(typeof instance.mountComponent === 'function' && typeof instance.receiveComponent === 'function' && typeof instance.getNativeNode === 'function' && typeof instance.unmountComponent === 'function', 'Only React Components can be mounted.') : void 0; } // These two fields are used by the DOM and ART diffing algorithms // respectively. Instead of using expandos on components, we should be // storing the state needed by the diffing algorithms elsewhere. instance._mountIndex = 0; instance._mountImage = null; if (process.env.NODE_ENV !== 'production') { instance._isOwnerNecessary = false; instance._warnedAboutRefsInRender = false; } // Internal instances should fully constructed at this point, so they should // not get any new fields added to them at this point. if (process.env.NODE_ENV !== 'production') { if (Object.preventExtensions) { Object.preventExtensions(instance); } } return instance; } module.exports = instantiateReactComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactCompositeComponent */ 'use strict'; var _assign = __webpack_require__(4); var ReactComponentEnvironment = __webpack_require__(114); var ReactCurrentOwner = __webpack_require__(9); var ReactElement = __webpack_require__(8); var ReactErrorUtils = __webpack_require__(45); var ReactInstanceMap = __webpack_require__(118); var ReactInstrumentation = __webpack_require__(18); var ReactNodeTypes = __webpack_require__(119); var ReactPerf = __webpack_require__(58); var ReactPropTypeLocations = __webpack_require__(23); var ReactPropTypeLocationNames = __webpack_require__(25); var ReactReconciler = __webpack_require__(59); var ReactUpdateQueue = __webpack_require__(120); var emptyObject = __webpack_require__(21); var invariant = __webpack_require__(7); var shouldUpdateReactComponent = __webpack_require__(121); var warning = __webpack_require__(10); function getDeclarationErrorAddendum(component) { var owner = component._currentElement._owner || null; if (owner) { var name = owner.getName(); if (name) { return ' Check the render method of `' + name + '`.'; } } return ''; } function StatelessComponent(Component) {} StatelessComponent.prototype.render = function () { var Component = ReactInstanceMap.get(this)._currentElement.type; var element = Component(this.props, this.context, this.updater); warnIfInvalidElement(Component, element); return element; }; function warnIfInvalidElement(Component, element) { if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(element === null || element === false || ReactElement.isValidElement(element), '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : void 0; } } function shouldConstruct(Component) { return Component.prototype && Component.prototype.isReactComponent; } /** * ------------------ The Life-Cycle of a Composite Component ------------------ * * - constructor: Initialization of state. The instance is now retained. * - componentWillMount * - render * - [children's constructors] * - [children's componentWillMount and render] * - [children's componentDidMount] * - componentDidMount * * Update Phases: * - componentWillReceiveProps (only called if parent updated) * - shouldComponentUpdate * - componentWillUpdate * - render * - [children's constructors or receive props phases] * - componentDidUpdate * * - componentWillUnmount * - [children's componentWillUnmount] * - [children destroyed] * - (destroyed): The instance is now blank, released by React and ready for GC. * * ----------------------------------------------------------------------------- */ /** * An incrementing ID assigned to each component when it is mounted. This is * used to enforce the order in which `ReactUpdates` updates dirty components. * * @private */ var nextMountID = 1; /** * @lends {ReactCompositeComponent.prototype} */ var ReactCompositeComponentMixin = { /** * Base constructor for all composite component. * * @param {ReactElement} element * @final * @internal */ construct: function (element) { this._currentElement = element; this._rootNodeID = null; this._instance = null; this._nativeParent = null; this._nativeContainerInfo = null; // See ReactUpdateQueue this._pendingElement = null; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._renderedNodeType = null; this._renderedComponent = null; this._context = null; this._mountOrder = 0; this._topLevelWrapper = null; // See ReactUpdates and ReactUpdateQueue. this._pendingCallbacks = null; // ComponentWillUnmount shall only be called once this._calledComponentWillUnmount = false; }, /** * Initializes the component, renders markup, and registers event listeners. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @param {?object} nativeParent * @param {?object} nativeContainerInfo * @param {?object} context * @return {?string} Rendered markup to be inserted into the DOM. * @final * @internal */ mountComponent: function (transaction, nativeParent, nativeContainerInfo, context) { this._context = context; this._mountOrder = nextMountID++; this._nativeParent = nativeParent; this._nativeContainerInfo = nativeContainerInfo; var publicProps = this._processProps(this._currentElement.props); var publicContext = this._processContext(context); var Component = this._currentElement.type; // Initialize the public class var inst = this._constructComponent(publicProps, publicContext); var renderedElement; // Support functional components if (!shouldConstruct(Component) && (inst == null || inst.render == null)) { renderedElement = inst; warnIfInvalidElement(Component, renderedElement); !(inst === null || inst === false || ReactElement.isValidElement(inst)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', Component.displayName || Component.name || 'Component') : invariant(false) : void 0; inst = new StatelessComponent(Component); } if (process.env.NODE_ENV !== 'production') { // This will throw later in _renderValidatedComponent, but add an early // warning now to help debugging if (inst.render == null) { process.env.NODE_ENV !== 'production' ? warning(false, '%s(...): No `render` method found on the returned component ' + 'instance: you may have forgotten to define `render`.', Component.displayName || Component.name || 'Component') : void 0; } var propsMutated = inst.props !== publicProps; var componentName = Component.displayName || Component.name || 'Component'; process.env.NODE_ENV !== 'production' ? warning(inst.props === undefined || !propsMutated, '%s(...): When calling super() in `%s`, make sure to pass ' + 'up the same props that your component\'s constructor was passed.', componentName, componentName) : void 0; } // These should be set up in the constructor, but as a convenience for // simpler class abstractions, we set them up after the fact. inst.props = publicProps; inst.context = publicContext; inst.refs = emptyObject; inst.updater = ReactUpdateQueue; this._instance = inst; // Store a reference from the instance back to the internal representation ReactInstanceMap.set(inst, this); if (process.env.NODE_ENV !== 'production') { // Since plain JS classes are defined without any special initialization // logic, we can not catch common errors early. Therefore, we have to // catch them here, at initialization time, instead. process.env.NODE_ENV !== 'production' ? warning(!inst.getInitialState || inst.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; process.env.NODE_ENV !== 'production' ? warning(!inst.getDefaultProps || inst.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; process.env.NODE_ENV !== 'production' ? warning(!inst.propTypes, 'propTypes was defined as an instance property on %s. Use a static ' + 'property to define propTypes instead.', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(!inst.contextTypes, 'contextTypes was defined as an instance property on %s. Use a ' + 'static property to define contextTypes instead.', this.getName() || 'a component') : void 0; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentShouldUpdate !== 'function', '%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; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentDidUnmount !== 'function', '%s has a method called ' + 'componentDidUnmount(). But there is no such lifecycle method. ' + 'Did you mean componentWillUnmount()?', this.getName() || 'A component') : void 0; process.env.NODE_ENV !== 'production' ? warning(typeof inst.componentWillRecieveProps !== 'function', '%s has a method called ' + 'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?', this.getName() || 'A component') : void 0; } var initialState = inst.state; if (initialState === undefined) { inst.state = initialState = null; } !(typeof initialState === 'object' && !Array.isArray(initialState)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.state: must be set to an object or null', this.getName() || 'ReactCompositeComponent') : invariant(false) : void 0; this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; var markup; if (inst.unstable_handleError) { markup = this.performInitialMountWithErrorHandling(renderedElement, nativeParent, nativeContainerInfo, transaction, context); } else { markup = this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context); } if (inst.componentDidMount) { transaction.getReactMountReady().enqueue(inst.componentDidMount, inst); } return markup; }, _constructComponent: function (publicProps, publicContext) { if (process.env.NODE_ENV !== 'production') { ReactCurrentOwner.current = this; try { return this._constructComponentWithoutOwner(publicProps, publicContext); } finally { ReactCurrentOwner.current = null; } } else { return this._constructComponentWithoutOwner(publicProps, publicContext); } }, _constructComponentWithoutOwner: function (publicProps, publicContext) { var Component = this._currentElement.type; if (shouldConstruct(Component)) { return new Component(publicProps, publicContext, ReactUpdateQueue); } else { return Component(publicProps, publicContext, ReactUpdateQueue); } }, performInitialMountWithErrorHandling: function (renderedElement, nativeParent, nativeContainerInfo, transaction, context) { var markup; var checkpoint = transaction.checkpoint(); try { markup = this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context); } catch (e) { // Roll back to checkpoint, handle error (which may add items to the transaction), and take a new checkpoint transaction.rollback(checkpoint); this._instance.unstable_handleError(e); if (this._pendingStateQueue) { this._instance.state = this._processPendingState(this._instance.props, this._instance.context); } checkpoint = transaction.checkpoint(); this._renderedComponent.unmountComponent(true); transaction.rollback(checkpoint); // Try again - we've informed the component about the error, so they can render an error message this time. // If this throws again, the error will bubble up (and can be caught by a higher error boundary). markup = this.performInitialMount(renderedElement, nativeParent, nativeContainerInfo, transaction, context); } return markup; }, performInitialMount: function (renderedElement, nativeParent, nativeContainerInfo, transaction, context) { var inst = this._instance; if (inst.componentWillMount) { inst.componentWillMount(); // When mounting, calls to `setState` by `componentWillMount` will set // `this._pendingStateQueue` without triggering a re-render. if (this._pendingStateQueue) { inst.state = this._processPendingState(inst.props, inst.context); } } // If not a stateless component, we now render if (renderedElement === undefined) { renderedElement = this._renderValidatedComponent(); } this._renderedNodeType = ReactNodeTypes.getType(renderedElement); this._renderedComponent = this._instantiateReactComponent(renderedElement); var markup = ReactReconciler.mountComponent(this._renderedComponent, transaction, nativeParent, nativeContainerInfo, this._processChildContext(context)); return markup; }, getNativeNode: function () { return ReactReconciler.getNativeNode(this._renderedComponent); }, /** * Releases any resources allocated by `mountComponent`. * * @final * @internal */ unmountComponent: function (safely) { if (!this._renderedComponent) { return; } var inst = this._instance; if (inst.componentWillUnmount && !inst._calledComponentWillUnmount) { inst._calledComponentWillUnmount = true; if (safely) { var name = this.getName() + '.componentWillUnmount()'; ReactErrorUtils.invokeGuardedCallback(name, inst.componentWillUnmount.bind(inst)); } else { inst.componentWillUnmount(); } } if (this._renderedComponent) { ReactReconciler.unmountComponent(this._renderedComponent, safely); this._renderedNodeType = null; this._renderedComponent = null; this._instance = null; } // Reset pending fields // Even if this component is scheduled for another update in ReactUpdates, // it would still be ignored because these fields are reset. this._pendingStateQueue = null; this._pendingReplaceState = false; this._pendingForceUpdate = false; this._pendingCallbacks = null; this._pendingElement = null; // These fields do not really need to be reset since this object is no // longer accessible. this._context = null; this._rootNodeID = null; this._topLevelWrapper = null; // Delete the reference from the instance to this internal representation // which allow the internals to be properly cleaned up even if the user // leaks a reference to the public instance. ReactInstanceMap.remove(inst); // Some existing components rely on inst.props even after they've been // destroyed (in event handlers). // TODO: inst.props = null; // TODO: inst.state = null; // TODO: inst.context = null; }, /** * Filters the context object to only contain keys specified in * `contextTypes` * * @param {object} context * @return {?object} * @private */ _maskContext: function (context) { var Component = this._currentElement.type; var contextTypes = Component.contextTypes; if (!contextTypes) { return emptyObject; } var maskedContext = {}; for (var contextName in contextTypes) { maskedContext[contextName] = context[contextName]; } return maskedContext; }, /** * Filters the context object to only contain keys specified in * `contextTypes`, and asserts that they are valid. * * @param {object} context * @return {?object} * @private */ _processContext: function (context) { var maskedContext = this._maskContext(context); if (process.env.NODE_ENV !== 'production') { var Component = this._currentElement.type; if (Component.contextTypes) { this._checkPropTypes(Component.contextTypes, maskedContext, ReactPropTypeLocations.context); } } return maskedContext; }, /** * @param {object} currentContext * @return {object} * @private */ _processChildContext: function (currentContext) { var Component = this._currentElement.type; var inst = this._instance; if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onBeginProcessingChildContext(); } var childContext = inst.getChildContext && inst.getChildContext(); if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onEndProcessingChildContext(); } if (childContext) { !(typeof Component.childContextTypes === 'object') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): childContextTypes must be defined in order to ' + 'use getChildContext().', this.getName() || 'ReactCompositeComponent') : invariant(false) : void 0; if (process.env.NODE_ENV !== 'production') { this._checkPropTypes(Component.childContextTypes, childContext, ReactPropTypeLocations.childContext); } for (var name in childContext) { !(name in Component.childContextTypes) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.getChildContext(): key "%s" is not defined in childContextTypes.', this.getName() || 'ReactCompositeComponent', name) : invariant(false) : void 0; } return _assign({}, currentContext, childContext); } return currentContext; }, /** * Processes props by setting default values for unspecified props and * asserting that the props are valid. Does not mutate its argument; returns * a new props object with defaults merged in. * * @param {object} newProps * @return {object} * @private */ _processProps: function (newProps) { if (process.env.NODE_ENV !== 'production') { var Component = this._currentElement.type; if (Component.propTypes) { this._checkPropTypes(Component.propTypes, newProps, ReactPropTypeLocations.prop); } } return newProps; }, /** * Assert that the props are valid * * @param {object} propTypes Map of prop name to a ReactPropType * @param {object} props * @param {string} location e.g. "prop", "context", "child context" * @private */ _checkPropTypes: function (propTypes, props, location) { // TODO: Stop validating prop types here and only use the element // validation. var componentName = this.getName(); for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error; try { // This is intentionally an invariant that gets caught. It's the same // behavior as without this statement except with a better message. !(typeof propTypes[propName] === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s: %s type `%s` is invalid; it must be a function, usually ' + 'from React.PropTypes.', componentName || 'React class', ReactPropTypeLocationNames[location], propName) : invariant(false) : void 0; error = propTypes[propName](props, propName, componentName, location); } catch (ex) { error = ex; } if (error instanceof Error) { // We may want to extend this logic for similar errors in // top-level render calls, so I'm abstracting it away into // a function to minimize refactoring in the future var addendum = getDeclarationErrorAddendum(this); if (location === ReactPropTypeLocations.prop) { // Preface gives us something to blacklist in warning module process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Composite propType: %s%s', error.message, addendum) : void 0; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'Failed Context Types: %s%s', error.message, addendum) : void 0; } } } } }, receiveComponent: function (nextElement, transaction, nextContext) { var prevElement = this._currentElement; var prevContext = this._context; this._pendingElement = null; this.updateComponent(transaction, prevElement, nextElement, prevContext, nextContext); }, /** * If any of `_pendingElement`, `_pendingStateQueue`, or `_pendingForceUpdate` * is set, update the component. * * @param {ReactReconcileTransaction} transaction * @internal */ performUpdateIfNecessary: function (transaction) { if (this._pendingElement != null) { ReactReconciler.receiveComponent(this, this._pendingElement, transaction, this._context); } if (this._pendingStateQueue !== null || this._pendingForceUpdate) { this.updateComponent(transaction, this._currentElement, this._currentElement, this._context, this._context); } }, /** * Perform an update to a mounted component. The componentWillReceiveProps and * shouldComponentUpdate methods are called, then (assuming the update isn't * skipped) the remaining update lifecycle methods are called and the DOM * representation is updated. * * By default, this implements React's rendering and reconciliation algorithm. * Sophisticated clients may wish to override this. * * @param {ReactReconcileTransaction} transaction * @param {ReactElement} prevParentElement * @param {ReactElement} nextParentElement * @internal * @overridable */ updateComponent: function (transaction, prevParentElement, nextParentElement, prevUnmaskedContext, nextUnmaskedContext) { var inst = this._instance; var willReceive = false; var nextContext; var nextProps; // Determine if the context has changed or not if (this._context === nextUnmaskedContext) { nextContext = inst.context; } else { nextContext = this._processContext(nextUnmaskedContext); willReceive = true; } // Distinguish between a props update versus a simple state update if (prevParentElement === nextParentElement) { // Skip checking prop types again -- we don't read inst.props to avoid // warning for DOM component props in this upgrade nextProps = nextParentElement.props; } else { nextProps = this._processProps(nextParentElement.props); willReceive = true; } // An update here will schedule an update but immediately set // _pendingStateQueue which will ensure that any state updates gets // immediately reconciled instead of waiting for the next batch. if (willReceive && inst.componentWillReceiveProps) { inst.componentWillReceiveProps(nextProps, nextContext); } var nextState = this._processPendingState(nextProps, nextContext); var shouldUpdate = this._pendingForceUpdate || !inst.shouldComponentUpdate || inst.shouldComponentUpdate(nextProps, nextState, nextContext); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(shouldUpdate !== undefined, '%s.shouldComponentUpdate(): Returned undefined instead of a ' + 'boolean value. Make sure to return true or false.', this.getName() || 'ReactCompositeComponent') : void 0; } if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate(nextParentElement, nextProps, nextState, nextContext, transaction, nextUnmaskedContext); } else { // If it's determined that a component should not update, we still want // to set props and state but we shortcut the rest of the update. this._currentElement = nextParentElement; this._context = nextUnmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; } }, _processPendingState: function (props, context) { var inst = this._instance; var queue = this._pendingStateQueue; var replace = this._pendingReplaceState; this._pendingReplaceState = false; this._pendingStateQueue = null; if (!queue) { return inst.state; } if (replace && queue.length === 1) { return queue[0]; } var nextState = _assign({}, replace ? queue[0] : inst.state); for (var i = replace ? 1 : 0; i < queue.length; i++) { var partial = queue[i]; _assign(nextState, typeof partial === 'function' ? partial.call(inst, nextState, props, context) : partial); } return nextState; }, /** * Merges new props and state, notifies delegate methods of update and * performs update. * * @param {ReactElement} nextElement Next element * @param {object} nextProps Next public object to set as properties. * @param {?object} nextState Next object to set as state. * @param {?object} nextContext Next public object to set as context. * @param {ReactReconcileTransaction} transaction * @param {?object} unmaskedContext * @private */ _performComponentUpdate: function (nextElement, nextProps, nextState, nextContext, transaction, unmaskedContext) { var inst = this._instance; var hasComponentDidUpdate = Boolean(inst.componentDidUpdate); var prevProps; var prevState; var prevContext; if (hasComponentDidUpdate) { prevProps = inst.props; prevState = inst.state; prevContext = inst.context; } if (inst.componentWillUpdate) { inst.componentWillUpdate(nextProps, nextState, nextContext); } this._currentElement = nextElement; this._context = unmaskedContext; inst.props = nextProps; inst.state = nextState; inst.context = nextContext; this._updateRenderedComponent(transaction, unmaskedContext); if (hasComponentDidUpdate) { transaction.getReactMountReady().enqueue(inst.componentDidUpdate.bind(inst, prevProps, prevState, prevContext), inst); } }, /** * Call the component's `render` method and update the DOM accordingly. * * @param {ReactReconcileTransaction} transaction * @internal */ _updateRenderedComponent: function (transaction, context) { var prevComponentInstance = this._renderedComponent; var prevRenderedElement = prevComponentInstance._currentElement; var nextRenderedElement = this._renderValidatedComponent(); if (shouldUpdateReactComponent(prevRenderedElement, nextRenderedElement)) { ReactReconciler.receiveComponent(prevComponentInstance, nextRenderedElement, transaction, this._processChildContext(context)); } else { var oldNativeNode = ReactReconciler.getNativeNode(prevComponentInstance); ReactReconciler.unmountComponent(prevComponentInstance, false); this._renderedNodeType = ReactNodeTypes.getType(nextRenderedElement); this._renderedComponent = this._instantiateReactComponent(nextRenderedElement); var nextMarkup = ReactReconciler.mountComponent(this._renderedComponent, transaction, this._nativeParent, this._nativeContainerInfo, this._processChildContext(context)); this._replaceNodeWithMarkup(oldNativeNode, nextMarkup); } }, /** * Overridden in shallow rendering. * * @protected */ _replaceNodeWithMarkup: function (oldNativeNode, nextMarkup) { ReactComponentEnvironment.replaceNodeWithMarkup(oldNativeNode, nextMarkup); }, /** * @protected */ _renderValidatedComponentWithoutOwnerOrContext: function () { var inst = this._instance; var renderedComponent = inst.render(); if (process.env.NODE_ENV !== 'production') { // We allow auto-mocks to proceed as if they're returning null. if (renderedComponent === undefined && inst.render._isMockFunction) { // This is probably bad practice. Consider warning here and // deprecating this convenience. renderedComponent = null; } } return renderedComponent; }, /** * @private */ _renderValidatedComponent: function () { var renderedComponent; ReactCurrentOwner.current = this; try { renderedComponent = this._renderValidatedComponentWithoutOwnerOrContext(); } finally { ReactCurrentOwner.current = null; } !( // TODO: An `isValidNode` function would probably be more appropriate renderedComponent === null || renderedComponent === false || ReactElement.isValidElement(renderedComponent)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s.render(): A valid React element (or null) must be returned. You may have ' + 'returned undefined, an array or some other invalid object.', this.getName() || 'ReactCompositeComponent') : invariant(false) : void 0; return renderedComponent; }, /** * Lazily allocates the refs object and stores `component` as `ref`. * * @param {string} ref Reference name. * @param {component} component Component to store as `ref`. * @final * @private */ attachRef: function (ref, component) { var inst = this.getPublicInstance(); !(inst != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Stateless function components cannot have refs.') : invariant(false) : void 0; var publicComponentInstance = component.getPublicInstance(); if (process.env.NODE_ENV !== 'production') { var componentName = component && component.getName ? component.getName() : 'a component'; process.env.NODE_ENV !== 'production' ? warning(publicComponentInstance != null, 'Stateless function components cannot be given refs ' + '(See ref "%s" in %s created by %s). ' + 'Attempts to access this ref will fail.', ref, componentName, this.getName()) : void 0; } var refs = inst.refs === emptyObject ? inst.refs = {} : inst.refs; refs[ref] = publicComponentInstance; }, /** * Detaches a reference name. * * @param {string} ref Name to dereference. * @final * @private */ detachRef: function (ref) { var refs = this.getPublicInstance().refs; delete refs[ref]; }, /** * Get a text description of the component that can be used to identify it * in error messages. * @return {string} The name or null. * @internal */ getName: function () { var type = this._currentElement.type; var constructor = this._instance && this._instance.constructor; return type.displayName || constructor && constructor.displayName || type.name || constructor && constructor.name || null; }, /** * Get the publicly accessible representation of this component - i.e. what * is exposed by refs and returned by render. Can be null for stateless * components. * * @return {ReactComponent} the public component instance. * @internal */ getPublicInstance: function () { var inst = this._instance; if (inst instanceof StatelessComponent) { return null; } return inst; }, // Stub _instantiateReactComponent: null }; ReactPerf.measureMethods(ReactCompositeComponentMixin, 'ReactCompositeComponent', { mountComponent: 'mountComponent', updateComponent: 'updateComponent', _renderValidatedComponent: '_renderValidatedComponent' }); var ReactCompositeComponent = { Mixin: ReactCompositeComponentMixin }; module.exports = ReactCompositeComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 118 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInstanceMap */ 'use strict'; /** * `ReactInstanceMap` maintains a mapping from a public facing stateful * instance (key) and the internal representation (value). This allows public * methods to accept the user facing instance as an argument and map them back * to internal methods. */ // TODO: Replace this with ES6: var ReactInstanceMap = new Map(); var ReactInstanceMap = { /** * This API should be called `delete` but we'd have to make sure to always * transform these to strings for IE support. When this transform is fully * supported we can rename it. */ remove: function (key) { key._reactInternalInstance = undefined; }, get: function (key) { return key._reactInternalInstance; }, has: function (key) { return key._reactInternalInstance !== undefined; }, set: function (key, value) { key._reactInternalInstance = value; } }; module.exports = ReactInstanceMap; /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNodeTypes */ 'use strict'; var ReactElement = __webpack_require__(8); var invariant = __webpack_require__(7); var ReactNodeTypes = { NATIVE: 0, COMPOSITE: 1, EMPTY: 2, getType: function (node) { if (node === null || node === false) { return ReactNodeTypes.EMPTY; } else if (ReactElement.isValidElement(node)) { if (typeof node.type === 'function') { return ReactNodeTypes.COMPOSITE; } else { return ReactNodeTypes.NATIVE; } } true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Unexpected node: %s', node) : invariant(false) : void 0; } }; module.exports = ReactNodeTypes; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactUpdateQueue */ 'use strict'; var ReactCurrentOwner = __webpack_require__(9); var ReactInstanceMap = __webpack_require__(118); var ReactUpdates = __webpack_require__(55); var invariant = __webpack_require__(7); var warning = __webpack_require__(10); function enqueueUpdate(internalInstance) { ReactUpdates.enqueueUpdate(internalInstance); } function formatUnexpectedArgument(arg) { var type = typeof arg; if (type !== 'object') { return type; } var displayName = arg.constructor && arg.constructor.name || type; var keys = Object.keys(arg); if (keys.length > 0 && keys.length < 20) { return displayName + ' (keys: ' + keys.join(', ') + ')'; } return displayName; } function getInternalInstanceReadyForUpdate(publicInstance, callerName) { var internalInstance = ReactInstanceMap.get(publicInstance); if (!internalInstance) { if (process.env.NODE_ENV !== 'production') { // Only warn when we have a callerName. Otherwise we should be silent. // We're probably calling from enqueueCallback. We don't want to warn // there because we already warned for the corresponding lifecycle method. process.env.NODE_ENV !== 'production' ? warning(!callerName, '%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.', callerName, callerName, publicInstance.constructor.displayName) : void 0; } return null; } if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '%s(...): Cannot update during an existing state transition (such as ' + 'within `render` or another component\'s constructor). Render methods ' + 'should be a pure function of props and state; constructor ' + 'side-effects are an anti-pattern, but can be moved to ' + '`componentWillMount`.', callerName) : void 0; } return internalInstance; } /** * ReactUpdateQueue allows for state updates to be scheduled into a later * reconciliation step. */ var ReactUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function (publicInstance) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._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.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } var internalInstance = ReactInstanceMap.get(publicInstance); if (internalInstance) { // During componentWillMount and render this will still be null but after // that will always render to something. At least for now. So we can use // this hack. return !!internalInstance._renderedComponent; } else { return false; } }, /** * Enqueue a callback that will be executed after all the pending updates * have processed. * * @param {ReactClass} publicInstance The instance to use as `this` context. * @param {?function} callback Called after state is updated. * @param {string} callerName Name of the calling function in the public API. * @internal */ enqueueCallback: function (publicInstance, callback, callerName) { ReactUpdateQueue.validateCallback(callback, callerName); var internalInstance = getInternalInstanceReadyForUpdate(publicInstance); // Previously we would throw an error if we didn't have an internal // instance. Since we want to make it a no-op instead, we mirror the same // behavior we have in other enqueue* methods. // We also need to ignore callbacks in componentWillMount. See // enqueueUpdates. if (!internalInstance) { return null; } if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } // TODO: The callback here is ignored when setState is called from // componentWillMount. Either fix it or disallow doing so completely in // favor of getInitialState. Alternatively, we can disallow // componentWillMount during server-side rendering. enqueueUpdate(internalInstance); }, enqueueCallbackInternal: function (internalInstance, callback) { if (internalInstance._pendingCallbacks) { internalInstance._pendingCallbacks.push(callback); } else { internalInstance._pendingCallbacks = [callback]; } enqueueUpdate(internalInstance); }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @internal */ enqueueForceUpdate: function (publicInstance) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'forceUpdate'); if (!internalInstance) { return; } internalInstance._pendingForceUpdate = true; enqueueUpdate(internalInstance); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @internal */ enqueueReplaceState: function (publicInstance, completeState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'replaceState'); if (!internalInstance) { return; } internalInstance._pendingStateQueue = [completeState]; internalInstance._pendingReplaceState = true; enqueueUpdate(internalInstance); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @internal */ enqueueSetState: function (publicInstance, partialState) { var internalInstance = getInternalInstanceReadyForUpdate(publicInstance, 'setState'); if (!internalInstance) { return; } var queue = internalInstance._pendingStateQueue || (internalInstance._pendingStateQueue = []); queue.push(partialState); enqueueUpdate(internalInstance); }, enqueueElementInternal: function (internalInstance, newElement) { internalInstance._pendingElement = newElement; enqueueUpdate(internalInstance); }, validateCallback: function (callback, callerName) { !(!callback || typeof callback === 'function') ? process.env.NODE_ENV !== 'production' ? invariant(false, '%s(...): Expected the last optional `callback` argument to be a ' + 'function. Instead received: %s.', callerName, formatUnexpectedArgument(callback)) : invariant(false) : void 0; } }; module.exports = ReactUpdateQueue; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 121 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule shouldUpdateReactComponent */ 'use strict'; /** * Given a `prevElement` and `nextElement`, determines if the existing * instance should be updated as opposed to being destroyed or replaced by a new * instance. Both arguments are elements. This ensures that this logic can * operate on stateless trees without any backing instance. * * @param {?object} prevElement * @param {?object} nextElement * @return {boolean} True if the existing instance should be updated. * @protected */ function shouldUpdateReactComponent(prevElement, nextElement) { var prevEmpty = prevElement === null || prevElement === false; var nextEmpty = nextElement === null || nextElement === false; if (prevEmpty || nextEmpty) { return prevEmpty === nextEmpty; } var prevType = typeof prevElement; var nextType = typeof nextElement; if (prevType === 'string' || prevType === 'number') { return nextType === 'string' || nextType === 'number'; } else { return nextType === 'object' && prevElement.type === nextElement.type && prevElement.key === nextElement.key; } } module.exports = shouldUpdateReactComponent; /***/ }, /* 122 */ /***/ function(module, exports) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEmptyComponent */ 'use strict'; var emptyComponentFactory; var ReactEmptyComponentInjection = { injectEmptyComponentFactory: function (factory) { emptyComponentFactory = factory; } }; var ReactEmptyComponent = { create: function (instantiate) { return emptyComponentFactory(instantiate); } }; ReactEmptyComponent.injection = ReactEmptyComponentInjection; module.exports = ReactEmptyComponent; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactNativeComponent */ 'use strict'; var _assign = __webpack_require__(4); var invariant = __webpack_require__(7); var autoGenerateWrapperClass = null; var genericComponentClass = null; // This registry keeps track of wrapper classes around native tags. var tagToComponentClass = {}; var textComponentClass = null; var ReactNativeComponentInjection = { // This accepts a class that receives the tag string. This is a catch all // that can render any kind of tag. injectGenericComponentClass: function (componentClass) { genericComponentClass = componentClass; }, // This accepts a text component class that takes the text string to be // rendered as props. injectTextComponentClass: function (componentClass) { textComponentClass = componentClass; }, // This accepts a keyed object with classes as values. Each key represents a // tag. That particular tag will use this class instead of the generic one. injectComponentClasses: function (componentClasses) { _assign(tagToComponentClass, componentClasses); } }; /** * Get a composite component wrapper class for a specific tag. * * @param {ReactElement} element The tag for which to get the class. * @return {function} The React class constructor function. */ function getComponentClassForElement(element) { if (typeof element.type === 'function') { return element.type; } var tag = element.type; var componentClass = tagToComponentClass[tag]; if (componentClass == null) { tagToComponentClass[tag] = componentClass = autoGenerateWrapperClass(tag); } return componentClass; } /** * Get a native internal component class for a specific tag. * * @param {ReactElement} element The element to create. * @return {function} The internal class constructor function. */ function createInternalComponent(element) { !genericComponentClass ? process.env.NODE_ENV !== 'production' ? invariant(false, 'There is no registered component for the tag %s', element.type) : invariant(false) : void 0; return new genericComponentClass(element); } /** * @param {ReactText} text * @return {ReactComponent} */ function createInstanceForText(text) { return new textComponentClass(text); } /** * @param {ReactComponent} component * @return {boolean} */ function isTextComponent(component) { return component instanceof textComponentClass; } var ReactNativeComponent = { getComponentClassForElement: getComponentClassForElement, createInternalComponent: createInternalComponent, createInstanceForText: createInstanceForText, isTextComponent: isTextComponent, injection: ReactNativeComponentInjection }; module.exports = ReactNativeComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule flattenChildren */ 'use strict'; var KeyEscapeUtils = __webpack_require__(15); var traverseAllChildren = __webpack_require__(13); var warning = __webpack_require__(10); /** * @param {function} traverseContext Context passed through traversal. * @param {?ReactComponent} child React child component. * @param {!string} name String name of key path to child. */ function flattenSingleChildIntoContext(traverseContext, child, name) { // We found a component instance. var result = traverseContext; var keyUnique = result[name] === undefined; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(keyUnique, 'flattenChildren(...): Encountered two children with the same key, ' + '`%s`. Child keys must be unique; when two children share a key, only ' + 'the first child will be used.', KeyEscapeUtils.unescape(name)) : void 0; } if (keyUnique && child != null) { result[name] = child; } } /** * Flattens children that are typically specified as `props.children`. Any null * children will not be included in the resulting object. * @return {!object} flattened children keyed by name. */ function flattenChildren(children) { if (children == null) { return children; } var result = {}; traverseAllChildren(children, flattenSingleChildIntoContext, result); return result; } module.exports = flattenChildren; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 125 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks * */ /*eslint-disable no-self-compare */ 'use strict'; var hasOwnProperty = Object.prototype.hasOwnProperty; /** * inlined Object.is polyfill to avoid requiring consumers ship their own * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is */ function is(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 // Steps 6.b-6.e: +0 != -0 return x !== 0 || 1 / x === 1 / y; } else { // Step 6.a: NaN == NaN return x !== x && y !== y; } } /** * Performs equality by iterating through keys on an object and returning false * when any key has values which are not strictly equal between the arguments. * Returns true when the values of all keys are strictly equal. */ function shallowEqual(objA, objB) { if (is(objA, objB)) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. for (var i = 0; i < keysA.length; i++) { if (!hasOwnProperty.call(objB, keysA[i]) || !is(objA[keysA[i]], objB[keysA[i]])) { return false; } } return true; } module.exports = shallowEqual; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule validateDOMNesting */ 'use strict'; var _assign = __webpack_require__(4); var emptyFunction = __webpack_require__(11); var warning = __webpack_require__(10); var validateDOMNesting = emptyFunction; if (process.env.NODE_ENV !== 'production') { // This validation code was written based on the HTML5 parsing spec: // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope // // Note: this does not catch all invalid nesting, nor does it try to (as it's // not clear what practical benefit doing so provides); instead, we warn only // for cases where the parser will give a parse tree differing from what React // intended. For example, <b><div></div></b> is invalid but we don't warn // because it still parses correctly; we do warn for other cases like nested // <p> tags where the beginning of the second element implicitly closes the // first, causing a confusing mess. // https://html.spec.whatwg.org/multipage/syntax.html#special var specialTags = ['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']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-scope var inScopeTags = ['applet', 'caption', 'html', 'table', 'td', 'th', 'marquee', 'object', 'template', // https://html.spec.whatwg.org/multipage/syntax.html#html-integration-point // TODO: Distinguish by namespace here -- for <title>, including it here // errs on the side of fewer warnings 'foreignObject', 'desc', 'title']; // https://html.spec.whatwg.org/multipage/syntax.html#has-an-element-in-button-scope var buttonScopeTags = inScopeTags.concat(['button']); // https://html.spec.whatwg.org/multipage/syntax.html#generate-implied-end-tags var impliedEndTags = ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt']; var emptyAncestorInfo = { current: null, formTag: null, aTagInScope: null, buttonTagInScope: null, nobrTagInScope: null, pTagInButtonScope: null, listItemTagAutoclosing: null, dlItemTagAutoclosing: null }; var updatedAncestorInfo = function (oldInfo, tag, instance) { var ancestorInfo = _assign({}, oldInfo || emptyAncestorInfo); var info = { tag: tag, instance: instance }; if (inScopeTags.indexOf(tag) !== -1) { ancestorInfo.aTagInScope = null; ancestorInfo.buttonTagInScope = null; ancestorInfo.nobrTagInScope = null; } if (buttonScopeTags.indexOf(tag) !== -1) { ancestorInfo.pTagInButtonScope = null; } // See rules for 'li', 'dd', 'dt' start tags in // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody if (specialTags.indexOf(tag) !== -1 && tag !== 'address' && tag !== 'div' && tag !== 'p') { ancestorInfo.listItemTagAutoclosing = null; ancestorInfo.dlItemTagAutoclosing = null; } ancestorInfo.current = info; if (tag === 'form') { ancestorInfo.formTag = info; } if (tag === 'a') { ancestorInfo.aTagInScope = info; } if (tag === 'button') { ancestorInfo.buttonTagInScope = info; } if (tag === 'nobr') { ancestorInfo.nobrTagInScope = info; } if (tag === 'p') { ancestorInfo.pTagInButtonScope = info; } if (tag === 'li') { ancestorInfo.listItemTagAutoclosing = info; } if (tag === 'dd' || tag === 'dt') { ancestorInfo.dlItemTagAutoclosing = info; } return ancestorInfo; }; /** * Returns whether */ var isTagValidWithParent = function (tag, parentTag) { // First, let's check if we're in an unusual parsing mode... switch (parentTag) { // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inselect case 'select': return tag === 'option' || tag === 'optgroup' || tag === '#text'; case 'optgroup': return tag === 'option' || tag === '#text'; // Strictly speaking, seeing an <option> doesn't mean we're in a <select> // but case 'option': return tag === '#text'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intd // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incaption // No special behavior since these rules fall back to "in body" mode for // all except special table nodes which cause bad parsing behavior anyway. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intr case 'tr': return tag === 'th' || tag === 'td' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intbody case 'tbody': case 'thead': case 'tfoot': return tag === 'tr' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-incolgroup case 'colgroup': return tag === 'col' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-intable case 'table': return tag === 'caption' || tag === 'colgroup' || tag === 'tbody' || tag === 'tfoot' || tag === 'thead' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inhead case 'head': return tag === 'base' || tag === 'basefont' || tag === 'bgsound' || tag === 'link' || tag === 'meta' || tag === 'title' || tag === 'noscript' || tag === 'noframes' || tag === 'style' || tag === 'script' || tag === 'template'; // https://html.spec.whatwg.org/multipage/semantics.html#the-html-element case 'html': return tag === 'head' || tag === 'body'; case '#document': return tag === 'html'; } // Probably in the "in body" parsing mode, so we outlaw only tag combos // where the parsing rules cause implicit opens or closes to be added. // https://html.spec.whatwg.org/multipage/syntax.html#parsing-main-inbody switch (tag) { case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': return parentTag !== 'h1' && parentTag !== 'h2' && parentTag !== 'h3' && parentTag !== 'h4' && parentTag !== 'h5' && parentTag !== 'h6'; case 'rp': case 'rt': return impliedEndTags.indexOf(parentTag) === -1; case 'body': case 'caption': case 'col': case 'colgroup': case 'frame': case 'head': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': // These tags are only valid with a few parents that have special child // parsing rules -- if we're down here, then none of those matched and // so we allow it only if we don't know what the parent is, as all other // cases are invalid. return parentTag == null; } return true; }; /** * Returns whether */ var findInvalidAncestorForTag = function (tag, ancestorInfo) { switch (tag) { 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 ancestorInfo.pTagInButtonScope; case 'form': return ancestorInfo.formTag || ancestorInfo.pTagInButtonScope; case 'li': return ancestorInfo.listItemTagAutoclosing; case 'dd': case 'dt': return ancestorInfo.dlItemTagAutoclosing; case 'button': return ancestorInfo.buttonTagInScope; case 'a': // Spec says something about storing a list of markers, but it sounds // equivalent to this check. return ancestorInfo.aTagInScope; case 'nobr': return ancestorInfo.nobrTagInScope; } return null; }; /** * Given a ReactCompositeComponent instance, return a list of its recursive * owners, starting at the root and ending with the instance itself. */ var findOwnerStack = function (instance) { if (!instance) { return []; } var stack = []; do { stack.push(instance); } while (instance = instance._currentElement._owner); stack.reverse(); return stack; }; var didWarn = {}; validateDOMNesting = function (childTag, childInstance, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; var invalidParent = isTagValidWithParent(childTag, parentTag) ? null : parentInfo; var invalidAncestor = invalidParent ? null : findInvalidAncestorForTag(childTag, ancestorInfo); var problematic = invalidParent || invalidAncestor; if (problematic) { var ancestorTag = problematic.tag; var ancestorInstance = problematic.instance; var childOwner = childInstance && childInstance._currentElement._owner; var ancestorOwner = ancestorInstance && ancestorInstance._currentElement._owner; var childOwners = findOwnerStack(childOwner); var ancestorOwners = findOwnerStack(ancestorOwner); var minStackLen = Math.min(childOwners.length, ancestorOwners.length); var i; var deepestCommon = -1; for (i = 0; i < minStackLen; i++) { if (childOwners[i] === ancestorOwners[i]) { deepestCommon = i; } else { break; } } var UNKNOWN = '(unknown)'; var childOwnerNames = childOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ancestorOwnerNames = ancestorOwners.slice(deepestCommon + 1).map(function (inst) { return inst.getName() || UNKNOWN; }); var ownerInfo = [].concat( // If the parent and child instances have a common owner ancestor, start // with that -- otherwise we just start with the parent's owners. deepestCommon !== -1 ? childOwners[deepestCommon].getName() || UNKNOWN : [], ancestorOwnerNames, ancestorTag, // If we're warning about an invalid (non-parent) ancestry, add '...' invalidAncestor ? ['...'] : [], childOwnerNames, childTag).join(' > '); var warnKey = !!invalidParent + '|' + childTag + '|' + ancestorTag + '|' + ownerInfo; if (didWarn[warnKey]) { return; } didWarn[warnKey] = true; var tagDisplayName = childTag; if (childTag !== '#text') { tagDisplayName = '<' + childTag + '>'; } if (invalidParent) { var info = ''; if (ancestorTag === 'table' && childTag === 'tr') { info += ' Add a <tbody> to your code to match the DOM tree generated by ' + 'the browser.'; } process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a child of <%s>. ' + 'See %s.%s', tagDisplayName, ancestorTag, ownerInfo, info) : void 0; } else { process.env.NODE_ENV !== 'production' ? warning(false, 'validateDOMNesting(...): %s cannot appear as a descendant of ' + '<%s>. See %s.', tagDisplayName, ancestorTag, ownerInfo) : void 0; } } }; validateDOMNesting.updatedAncestorInfo = updatedAncestorInfo; // For testing validateDOMNesting.isTagValidInContext = function (tag, ancestorInfo) { ancestorInfo = ancestorInfo || emptyAncestorInfo; var parentInfo = ancestorInfo.current; var parentTag = parentInfo && parentInfo.tag; return isTagValidWithParent(tag, parentTag) && !findInvalidAncestorForTag(tag, ancestorInfo); }; } module.exports = validateDOMNesting; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMEmptyComponent */ 'use strict'; var _assign = __webpack_require__(4); var DOMLazyTree = __webpack_require__(75); var ReactDOMComponentTree = __webpack_require__(35); var ReactDOMEmptyComponent = function (instantiate) { // ReactCompositeComponent uses this: this._currentElement = null; // ReactDOMComponentTree uses these: this._nativeNode = null; this._nativeParent = null; this._nativeContainerInfo = null; this._domID = null; }; _assign(ReactDOMEmptyComponent.prototype, { mountComponent: function (transaction, nativeParent, nativeContainerInfo, context) { var domID = nativeContainerInfo._idCounter++; this._domID = domID; this._nativeParent = nativeParent; this._nativeContainerInfo = nativeContainerInfo; var nodeValue = ' react-empty: ' + this._domID + ' '; if (transaction.useCreateElement) { var ownerDocument = nativeContainerInfo._ownerDocument; var node = ownerDocument.createComment(nodeValue); ReactDOMComponentTree.precacheNode(this, node); return DOMLazyTree(node); } else { if (transaction.renderToStaticMarkup) { // Normally we'd insert a comment node, but since this is a situation // where React won't take over (static pages), we can simply return // nothing. return ''; } return '<!--' + nodeValue + '-->'; } }, receiveComponent: function () {}, getNativeNode: function () { return ReactDOMComponentTree.getNodeFromInstance(this); }, unmountComponent: function () { ReactDOMComponentTree.uncacheNode(this); } }); module.exports = ReactDOMEmptyComponent; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTreeTraversal */ 'use strict'; var invariant = __webpack_require__(7); /** * Return the lowest common ancestor of A and B, or null if they are in * different trees. */ function getLowestCommonAncestor(instA, instB) { !('_nativeNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : invariant(false) : void 0; !('_nativeNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getNodeFromInstance: Invalid argument.') : invariant(false) : void 0; var depthA = 0; for (var tempA = instA; tempA; tempA = tempA._nativeParent) { depthA++; } var depthB = 0; for (var tempB = instB; tempB; tempB = tempB._nativeParent) { depthB++; } // If A is deeper, crawl up. while (depthA - depthB > 0) { instA = instA._nativeParent; depthA--; } // If B is deeper, crawl up. while (depthB - depthA > 0) { instB = instB._nativeParent; depthB--; } // Walk in lockstep until we find a match. var depth = depthA; while (depth--) { if (instA === instB) { return instA; } instA = instA._nativeParent; instB = instB._nativeParent; } return null; } /** * Return if A is an ancestor of B. */ function isAncestor(instA, instB) { !('_nativeNode' in instA) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : invariant(false) : void 0; !('_nativeNode' in instB) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'isAncestor: Invalid argument.') : invariant(false) : void 0; while (instB) { if (instB === instA) { return true; } instB = instB._nativeParent; } return false; } /** * Return the parent instance of the passed-in instance. */ function getParentInstance(inst) { !('_nativeNode' in inst) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'getParentInstance: Invalid argument.') : invariant(false) : void 0; return inst._nativeParent; } /** * Simulates the traversal of a two-phase, capture/bubble event dispatch. */ function traverseTwoPhase(inst, fn, arg) { var path = []; while (inst) { path.push(inst); inst = inst._nativeParent; } var i; for (i = path.length; i-- > 0;) { fn(path[i], false, arg); } for (i = 0; i < path.length; i++) { fn(path[i], true, arg); } } /** * Traverses the ID hierarchy and invokes the supplied `cb` on any IDs that * should would receive a `mouseEnter` or `mouseLeave` event. * * Does not invoke the callback on the nearest common ancestor because nothing * "entered" or "left" that element. */ function traverseEnterLeave(from, to, fn, argFrom, argTo) { var common = from && to ? getLowestCommonAncestor(from, to) : null; var pathFrom = []; while (from && from !== common) { pathFrom.push(from); from = from._nativeParent; } var pathTo = []; while (to && to !== common) { pathTo.push(to); to = to._nativeParent; } var i; for (i = 0; i < pathFrom.length; i++) { fn(pathFrom[i], true, argFrom); } for (i = pathTo.length; i-- > 0;) { fn(pathTo[i], false, argTo); } } module.exports = { isAncestor: isAncestor, getLowestCommonAncestor: getLowestCommonAncestor, getParentInstance: getParentInstance, traverseTwoPhase: traverseTwoPhase, traverseEnterLeave: traverseEnterLeave }; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMTextComponent */ 'use strict'; var _assign = __webpack_require__(4); var DOMChildrenOperations = __webpack_require__(74); var DOMLazyTree = __webpack_require__(75); var ReactDOMComponentTree = __webpack_require__(35); var ReactPerf = __webpack_require__(58); var escapeTextContentForBrowser = __webpack_require__(78); var invariant = __webpack_require__(7); var validateDOMNesting = __webpack_require__(126); /** * Text nodes violate a couple assumptions that React makes about components: * * - When mounting text into the DOM, adjacent text nodes are merged. * - Text nodes cannot be assigned a React root ID. * * This component is used to wrap strings between comment nodes so that they * can undergo the same reconciliation that is applied to elements. * * TODO: Investigate representing React components in the DOM with text nodes. * * @class ReactDOMTextComponent * @extends ReactComponent * @internal */ var ReactDOMTextComponent = function (text) { // TODO: This is really a ReactText (ReactNode), not a ReactElement this._currentElement = text; this._stringText = '' + text; // ReactDOMComponentTree uses these: this._nativeNode = null; this._nativeParent = null; // Properties this._domID = null; this._mountIndex = 0; this._closingComment = null; this._commentNodes = null; }; _assign(ReactDOMTextComponent.prototype, { /** * Creates the markup for this text node. This node is not intended to have * any features besides containing text content. * * @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction * @return {string} Markup for this text node. * @internal */ mountComponent: function (transaction, nativeParent, nativeContainerInfo, context) { if (process.env.NODE_ENV !== 'production') { var parentInfo; if (nativeParent != null) { parentInfo = nativeParent._ancestorInfo; } else if (nativeContainerInfo != null) { parentInfo = nativeContainerInfo._ancestorInfo; } if (parentInfo) { // parentInfo should always be present except for the top-level // component when server rendering validateDOMNesting('#text', this, parentInfo); } } var domID = nativeContainerInfo._idCounter++; var openingValue = ' react-text: ' + domID + ' '; var closingValue = ' /react-text '; this._domID = domID; this._nativeParent = nativeParent; if (transaction.useCreateElement) { var ownerDocument = nativeContainerInfo._ownerDocument; var openingComment = ownerDocument.createComment(openingValue); var closingComment = ownerDocument.createComment(closingValue); var lazyTree = DOMLazyTree(ownerDocument.createDocumentFragment()); DOMLazyTree.queueChild(lazyTree, DOMLazyTree(openingComment)); if (this._stringText) { DOMLazyTree.queueChild(lazyTree, DOMLazyTree(ownerDocument.createTextNode(this._stringText))); } DOMLazyTree.queueChild(lazyTree, DOMLazyTree(closingComment)); ReactDOMComponentTree.precacheNode(this, openingComment); this._closingComment = closingComment; return lazyTree; } else { var escapedText = escapeTextContentForBrowser(this._stringText); if (transaction.renderToStaticMarkup) { // Normally we'd wrap this between comment nodes for the reasons stated // above, but since this is a situation where React won't take over // (static pages), we can simply return the text as it is. return escapedText; } return '<!--' + openingValue + '-->' + escapedText + '<!--' + closingValue + '-->'; } }, /** * Updates this component by updating the text content. * * @param {ReactText} nextText The next text content * @param {ReactReconcileTransaction} transaction * @internal */ receiveComponent: function (nextText, transaction) { if (nextText !== this._currentElement) { this._currentElement = nextText; var nextStringText = '' + nextText; if (nextStringText !== this._stringText) { // TODO: Save this as pending props and use performUpdateIfNecessary // and/or updateComponent to do the actual update for consistency with // other component types? this._stringText = nextStringText; var commentNodes = this.getNativeNode(); DOMChildrenOperations.replaceDelimitedText(commentNodes[0], commentNodes[1], nextStringText); } } }, getNativeNode: function () { var nativeNode = this._commentNodes; if (nativeNode) { return nativeNode; } if (!this._closingComment) { var openingComment = ReactDOMComponentTree.getNodeFromInstance(this); var node = openingComment.nextSibling; while (true) { !(node != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Missing closing comment for text component %s', this._domID) : invariant(false) : void 0; if (node.nodeType === 8 && node.nodeValue === ' /react-text ') { this._closingComment = node; break; } node = node.nextSibling; } } nativeNode = [this._nativeNode, this._closingComment]; this._commentNodes = nativeNode; return nativeNode; }, unmountComponent: function () { this._closingComment = null; this._commentNodes = null; ReactDOMComponentTree.uncacheNode(this); } }); ReactPerf.measureMethods(ReactDOMTextComponent.prototype, 'ReactDOMTextComponent', { mountComponent: 'mountComponent', receiveComponent: 'receiveComponent' }); module.exports = ReactDOMTextComponent; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultBatchingStrategy */ 'use strict'; var _assign = __webpack_require__(4); var ReactUpdates = __webpack_require__(55); var Transaction = __webpack_require__(62); var emptyFunction = __webpack_require__(11); var RESET_BATCHED_UPDATES = { initialize: emptyFunction, close: function () { ReactDefaultBatchingStrategy.isBatchingUpdates = false; } }; var FLUSH_BATCHED_UPDATES = { initialize: emptyFunction, close: ReactUpdates.flushBatchedUpdates.bind(ReactUpdates) }; var TRANSACTION_WRAPPERS = [FLUSH_BATCHED_UPDATES, RESET_BATCHED_UPDATES]; function ReactDefaultBatchingStrategyTransaction() { this.reinitializeTransaction(); } _assign(ReactDefaultBatchingStrategyTransaction.prototype, Transaction.Mixin, { getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; } }); var transaction = new ReactDefaultBatchingStrategyTransaction(); var ReactDefaultBatchingStrategy = { isBatchingUpdates: false, /** * Call the provided function in a context within which calls to `setState` * and friends are batched such that components aren't updated unnecessarily. */ batchedUpdates: function (callback, a, b, c, d, e) { var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates; ReactDefaultBatchingStrategy.isBatchingUpdates = true; // The code is written this way to avoid extra allocations if (alreadyBatchingUpdates) { callback(a, b, c, d, e); } else { transaction.perform(callback, null, a, b, c, d, e); } } }; module.exports = ReactDefaultBatchingStrategy; /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactEventListener */ 'use strict'; var _assign = __webpack_require__(4); var EventListener = __webpack_require__(132); var ExecutionEnvironment = __webpack_require__(48); var PooledClass = __webpack_require__(6); var ReactDOMComponentTree = __webpack_require__(35); var ReactUpdates = __webpack_require__(55); var getEventTarget = __webpack_require__(63); var getUnboundedScrollPosition = __webpack_require__(133); /** * Find the deepest React component completely containing the root of the * passed-in instance (for use when entire React trees are nested within each * other). If React trees are not nested, returns null. */ function findParent(inst) { // TODO: It may be a good idea to cache this to prevent unnecessary DOM // traversal, but caching is difficult to do correctly without using a // mutation observer to listen for all DOM changes. while (inst._nativeParent) { inst = inst._nativeParent; } var rootNode = ReactDOMComponentTree.getNodeFromInstance(inst); var container = rootNode.parentNode; return ReactDOMComponentTree.getClosestInstanceFromNode(container); } // Used to store ancestor hierarchy in top level callback function TopLevelCallbackBookKeeping(topLevelType, nativeEvent) { this.topLevelType = topLevelType; this.nativeEvent = nativeEvent; this.ancestors = []; } _assign(TopLevelCallbackBookKeeping.prototype, { destructor: function () { this.topLevelType = null; this.nativeEvent = null; this.ancestors.length = 0; } }); PooledClass.addPoolingTo(TopLevelCallbackBookKeeping, PooledClass.twoArgumentPooler); function handleTopLevelImpl(bookKeeping) { var nativeEventTarget = getEventTarget(bookKeeping.nativeEvent); var targetInst = ReactDOMComponentTree.getClosestInstanceFromNode(nativeEventTarget); // Loop through the hierarchy, in case there's any nested components. // It's important that we build the array of ancestors before calling any // event handlers, because event handlers can modify the DOM, leading to // inconsistencies with ReactMount's node cache. See #1105. var ancestor = targetInst; do { bookKeeping.ancestors.push(ancestor); ancestor = ancestor && findParent(ancestor); } while (ancestor); for (var i = 0; i < bookKeeping.ancestors.length; i++) { targetInst = bookKeeping.ancestors[i]; ReactEventListener._handleTopLevel(bookKeeping.topLevelType, targetInst, bookKeeping.nativeEvent, getEventTarget(bookKeeping.nativeEvent)); } } function scrollValueMonitor(cb) { var scrollPosition = getUnboundedScrollPosition(window); cb(scrollPosition); } var ReactEventListener = { _enabled: true, _handleTopLevel: null, WINDOW_HANDLE: ExecutionEnvironment.canUseDOM ? window : null, setHandleTopLevel: function (handleTopLevel) { ReactEventListener._handleTopLevel = handleTopLevel; }, setEnabled: function (enabled) { ReactEventListener._enabled = !!enabled; }, isEnabled: function () { return ReactEventListener._enabled; }, /** * Traps top-level events by using event bubbling. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapBubbledEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.listen(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, /** * Traps a top-level event by using event capturing. * * @param {string} topLevelType Record from `EventConstants`. * @param {string} handlerBaseName Event name (e.g. "click"). * @param {object} handle Element on which to attach listener. * @return {?object} An object with a remove function which will forcefully * remove the listener. * @internal */ trapCapturedEvent: function (topLevelType, handlerBaseName, handle) { var element = handle; if (!element) { return null; } return EventListener.capture(element, handlerBaseName, ReactEventListener.dispatchEvent.bind(null, topLevelType)); }, monitorScrollValue: function (refresh) { var callback = scrollValueMonitor.bind(null, refresh); EventListener.listen(window, 'scroll', callback); }, dispatchEvent: function (topLevelType, nativeEvent) { if (!ReactEventListener._enabled) { return; } var bookKeeping = TopLevelCallbackBookKeeping.getPooled(topLevelType, nativeEvent); try { // Event queue being processed in the same cycle allows // `preventDefault`. ReactUpdates.batchedUpdates(handleTopLevelImpl, bookKeeping); } finally { TopLevelCallbackBookKeeping.release(bookKeeping); } } }; module.exports = ReactEventListener; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @typechecks */ var emptyFunction = __webpack_require__(11); /** * Upstream version of event listener. Does not take into account specific * nature of platform. */ var EventListener = { /** * Listen to DOM events during the bubble phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ listen: function (target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function () { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function () { target.detachEvent('on' + eventType, callback); } }; } }, /** * Listen to DOM events during the capture phase. * * @param {DOMEventTarget} target DOM element to register listener on. * @param {string} eventType Event type, e.g. 'click' or 'mouseover'. * @param {function} callback Callback function. * @return {object} Object with a `remove` method. */ capture: function (target, eventType, callback) { if (target.addEventListener) { target.addEventListener(eventType, callback, true); return { remove: function () { target.removeEventListener(eventType, callback, true); } }; } else { if (process.env.NODE_ENV !== 'production') { console.error('Attempted to listen to events during the capture phase on a ' + 'browser that does not support the capture phase. Your application ' + 'will not receive some events.'); } return { remove: emptyFunction }; } }, registerDefault: function () {} }; module.exports = EventListener; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 133 */ /***/ function(module, exports) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; /** * Gets the scroll position of the supplied element or window. * * The return values are unbounded, unlike `getScrollPosition`. This means they * may be negative or exceed the element boundaries (which is possible using * inertial scrolling). * * @param {DOMWindow|DOMElement} scrollable * @return {object} Map with `x` and `y` keys. */ function getUnboundedScrollPosition(scrollable) { if (scrollable === window) { return { x: window.pageXOffset || document.documentElement.scrollLeft, y: window.pageYOffset || document.documentElement.scrollTop }; } return { x: scrollable.scrollLeft, y: scrollable.scrollTop }; } module.exports = getUnboundedScrollPosition; /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInjection */ 'use strict'; var DOMProperty = __webpack_require__(36); var EventPluginHub = __webpack_require__(42); var EventPluginUtils = __webpack_require__(44); var ReactComponentEnvironment = __webpack_require__(114); var ReactClass = __webpack_require__(22); var ReactEmptyComponent = __webpack_require__(122); var ReactBrowserEventEmitter = __webpack_require__(103); var ReactNativeComponent = __webpack_require__(123); var ReactPerf = __webpack_require__(58); var ReactUpdates = __webpack_require__(55); var ReactInjection = { Component: ReactComponentEnvironment.injection, Class: ReactClass.injection, DOMProperty: DOMProperty.injection, EmptyComponent: ReactEmptyComponent.injection, EventPluginHub: EventPluginHub.injection, EventPluginUtils: EventPluginUtils.injection, EventEmitter: ReactBrowserEventEmitter.injection, NativeComponent: ReactNativeComponent.injection, Perf: ReactPerf.injection, Updates: ReactUpdates.injection }; module.exports = ReactInjection; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactReconcileTransaction */ 'use strict'; var _assign = __webpack_require__(4); var CallbackQueue = __webpack_require__(56); var PooledClass = __webpack_require__(6); var ReactBrowserEventEmitter = __webpack_require__(103); var ReactInputSelection = __webpack_require__(136); var Transaction = __webpack_require__(62); /** * Ensures that, when possible, the selection range (currently selected text * input) is not disturbed by performing the transaction. */ var SELECTION_RESTORATION = { /** * @return {Selection} Selection information. */ initialize: ReactInputSelection.getSelectionInformation, /** * @param {Selection} sel Selection information returned from `initialize`. */ close: ReactInputSelection.restoreSelection }; /** * Suppresses events (blur/focus) that could be inadvertently dispatched due to * high level DOM manipulations (like temporarily removing a text input from the * DOM). */ var EVENT_SUPPRESSION = { /** * @return {boolean} The enabled status of `ReactBrowserEventEmitter` before * the reconciliation. */ initialize: function () { var currentlyEnabled = ReactBrowserEventEmitter.isEnabled(); ReactBrowserEventEmitter.setEnabled(false); return currentlyEnabled; }, /** * @param {boolean} previouslyEnabled Enabled status of * `ReactBrowserEventEmitter` before the reconciliation occurred. `close` * restores the previous value. */ close: function (previouslyEnabled) { ReactBrowserEventEmitter.setEnabled(previouslyEnabled); } }; /** * Provides a queue for collecting `componentDidMount` and * `componentDidUpdate` callbacks during the transaction. */ var ON_DOM_READY_QUEUEING = { /** * Initializes the internal `onDOMReady` queue. */ initialize: function () { this.reactMountReady.reset(); }, /** * After DOM is flushed, invoke all registered `onDOMReady` callbacks. */ close: function () { this.reactMountReady.notifyAll(); } }; /** * Executed within the scope of the `Transaction` instance. Consider these as * being member methods, but with an implied ordering while being isolated from * each other. */ var TRANSACTION_WRAPPERS = [SELECTION_RESTORATION, EVENT_SUPPRESSION, ON_DOM_READY_QUEUEING]; /** * Currently: * - The order that these are listed in the transaction is critical: * - Suppresses events. * - Restores selection range. * * Future: * - Restore document/overflow scroll positions that were unintentionally * modified via DOM insertions above the top viewport boundary. * - Implement/integrate with customized constraint based layout system and keep * track of which dimensions must be remeasured. * * @class ReactReconcileTransaction */ function ReactReconcileTransaction(useCreateElement) { this.reinitializeTransaction(); // Only server-side rendering really needs this option (see // `ReactServerRendering`), but server-side uses // `ReactServerRenderingTransaction` instead. This option is here so that it's // accessible and defaults to false when `ReactDOMComponent` and // `ReactTextComponent` checks it in `mountComponent`.` this.renderToStaticMarkup = false; this.reactMountReady = CallbackQueue.getPooled(null); this.useCreateElement = useCreateElement; } var Mixin = { /** * @see Transaction * @abstract * @final * @return {array<object>} List of operation wrap procedures. * TODO: convert to array<TransactionWrapper> */ getTransactionWrappers: function () { return TRANSACTION_WRAPPERS; }, /** * @return {object} The queue to collect `onDOMReady` callbacks with. */ getReactMountReady: function () { return this.reactMountReady; }, /** * Save current transaction state -- if the return value from this method is * passed to `rollback`, the transaction will be reset to that state. */ checkpoint: function () { // reactMountReady is the our only stateful wrapper return this.reactMountReady.checkpoint(); }, rollback: function (checkpoint) { this.reactMountReady.rollback(checkpoint); }, /** * `PooledClass` looks for this, and will invoke this before allowing this * instance to be reused. */ destructor: function () { CallbackQueue.release(this.reactMountReady); this.reactMountReady = null; } }; _assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin); PooledClass.addPoolingTo(ReactReconcileTransaction); module.exports = ReactReconcileTransaction; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactInputSelection */ 'use strict'; var ReactDOMSelection = __webpack_require__(137); var containsNode = __webpack_require__(139); var focusNode = __webpack_require__(88); var getActiveElement = __webpack_require__(142); function isInDocument(node) { return containsNode(document.documentElement, node); } /** * @ReactInputSelection: React input selection module. Based on Selection.js, * but modified to be suitable for react and has a couple of bug fixes (doesn't * assume buttons have range selections allowed). * Input selection module for React. */ var ReactInputSelection = { hasSelectionCapabilities: function (elem) { var nodeName = elem && elem.nodeName && elem.nodeName.toLowerCase(); return nodeName && (nodeName === 'input' && elem.type === 'text' || nodeName === 'textarea' || elem.contentEditable === 'true'); }, getSelectionInformation: function () { var focusedElem = getActiveElement(); return { focusedElem: focusedElem, selectionRange: ReactInputSelection.hasSelectionCapabilities(focusedElem) ? ReactInputSelection.getSelection(focusedElem) : null }; }, /** * @restoreSelection: If any selection information was potentially lost, * restore it. This is useful when performing operations that could remove dom * nodes and place them back in, resulting in focus being lost. */ restoreSelection: function (priorSelectionInformation) { var curFocusedElem = getActiveElement(); var priorFocusedElem = priorSelectionInformation.focusedElem; var priorSelectionRange = priorSelectionInformation.selectionRange; if (curFocusedElem !== priorFocusedElem && isInDocument(priorFocusedElem)) { if (ReactInputSelection.hasSelectionCapabilities(priorFocusedElem)) { ReactInputSelection.setSelection(priorFocusedElem, priorSelectionRange); } focusNode(priorFocusedElem); } }, /** * @getSelection: Gets the selection bounds of a focused textarea, input or * contentEditable node. * -@input: Look up selection bounds of this input * -@return {start: selectionStart, end: selectionEnd} */ getSelection: function (input) { var selection; if ('selectionStart' in input) { // Modern browser with input or textarea. selection = { start: input.selectionStart, end: input.selectionEnd }; } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { // IE8 input. var range = document.selection.createRange(); // There can only be one selection per document in IE, so it must // be in our element. if (range.parentElement() === input) { selection = { start: -range.moveStart('character', -input.value.length), end: -range.moveEnd('character', -input.value.length) }; } } else { // Content editable or old IE textarea. selection = ReactDOMSelection.getOffsets(input); } return selection || { start: 0, end: 0 }; }, /** * @setSelection: Sets the selection bounds of a textarea or input and focuses * the input. * -@input Set selection bounds of this input or textarea * -@offsets Object of same form that is returned from get* */ setSelection: function (input, offsets) { var start = offsets.start; var end = offsets.end; if (end === undefined) { end = start; } if ('selectionStart' in input) { input.selectionStart = start; input.selectionEnd = Math.min(end, input.value.length); } else if (document.selection && input.nodeName && input.nodeName.toLowerCase() === 'input') { var range = input.createTextRange(); range.collapse(true); range.moveStart('character', start); range.moveEnd('character', end - start); range.select(); } else { ReactDOMSelection.setOffsets(input, offsets); } } }; module.exports = ReactInputSelection; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMSelection */ 'use strict'; var ExecutionEnvironment = __webpack_require__(48); var getNodeForCharacterOffset = __webpack_require__(138); var getTextContentAccessor = __webpack_require__(50); /** * While `isCollapsed` is available on the Selection object and `collapsed` * is available on the Range object, IE11 sometimes gets them wrong. * If the anchor/focus nodes and offsets are the same, the range is collapsed. */ function isCollapsed(anchorNode, anchorOffset, focusNode, focusOffset) { return anchorNode === focusNode && anchorOffset === focusOffset; } /** * Get the appropriate anchor and focus node/offset pairs for IE. * * The catch here is that IE's selection API doesn't provide information * about whether the selection is forward or backward, so we have to * behave as though it's always forward. * * IE text differs from modern selection in that it behaves as though * block elements end with a new line. This means character offsets will * differ between the two APIs. * * @param {DOMElement} node * @return {object} */ function getIEOffsets(node) { var selection = document.selection; var selectedRange = selection.createRange(); var selectedLength = selectedRange.text.length; // Duplicate selection so we can move range without breaking user selection. var fromStart = selectedRange.duplicate(); fromStart.moveToElementText(node); fromStart.setEndPoint('EndToStart', selectedRange); var startOffset = fromStart.text.length; var endOffset = startOffset + selectedLength; return { start: startOffset, end: endOffset }; } /** * @param {DOMElement} node * @return {?object} */ function getModernOffsets(node) { var selection = window.getSelection && window.getSelection(); if (!selection || selection.rangeCount === 0) { return null; } var anchorNode = selection.anchorNode; var anchorOffset = selection.anchorOffset; var focusNode = selection.focusNode; var focusOffset = selection.focusOffset; var currentRange = selection.getRangeAt(0); // In Firefox, range.startContainer and range.endContainer can be "anonymous // divs", e.g. the up/down buttons on an <input type="number">. Anonymous // divs do not seem to expose properties, triggering a "Permission denied // error" if any of its properties are accessed. The only seemingly possible // way to avoid erroring is to access a property that typically works for // non-anonymous divs and catch any error that may otherwise arise. See // https://bugzilla.mozilla.org/show_bug.cgi?id=208427 try { /* eslint-disable no-unused-expressions */ currentRange.startContainer.nodeType; currentRange.endContainer.nodeType; /* eslint-enable no-unused-expressions */ } catch (e) { return null; } // If the node and offset values are the same, the selection is collapsed. // `Selection.isCollapsed` is available natively, but IE sometimes gets // this value wrong. var isSelectionCollapsed = isCollapsed(selection.anchorNode, selection.anchorOffset, selection.focusNode, selection.focusOffset); var rangeLength = isSelectionCollapsed ? 0 : currentRange.toString().length; var tempRange = currentRange.cloneRange(); tempRange.selectNodeContents(node); tempRange.setEnd(currentRange.startContainer, currentRange.startOffset); var isTempRangeCollapsed = isCollapsed(tempRange.startContainer, tempRange.startOffset, tempRange.endContainer, tempRange.endOffset); var start = isTempRangeCollapsed ? 0 : tempRange.toString().length; var end = start + rangeLength; // Detect whether the selection is backward. var detectionRange = document.createRange(); detectionRange.setStart(anchorNode, anchorOffset); detectionRange.setEnd(focusNode, focusOffset); var isBackward = detectionRange.collapsed; return { start: isBackward ? end : start, end: isBackward ? start : end }; } /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setIEOffsets(node, offsets) { var range = document.selection.createRange().duplicate(); var start, end; if (offsets.end === undefined) { start = offsets.start; end = start; } else if (offsets.start > offsets.end) { start = offsets.end; end = offsets.start; } else { start = offsets.start; end = offsets.end; } range.moveToElementText(node); range.moveStart('character', start); range.setEndPoint('EndToStart', range); range.moveEnd('character', end - start); range.select(); } /** * In modern non-IE browsers, we can support both forward and backward * selections. * * Note: IE10+ supports the Selection object, but it does not support * the `extend` method, which means that even in modern IE, it's not possible * to programmatically create a backward selection. Thus, for all IE * versions, we use the old IE API to create our selections. * * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ function setModernOffsets(node, offsets) { if (!window.getSelection) { return; } var selection = window.getSelection(); var length = node[getTextContentAccessor()].length; var start = Math.min(offsets.start, length); var end = offsets.end === undefined ? start : Math.min(offsets.end, length); // IE 11 uses modern selection, but doesn't support the extend method. // Flip backward selections, so we can set with a single range. if (!selection.extend && start > end) { var temp = end; end = start; start = temp; } var startMarker = getNodeForCharacterOffset(node, start); var endMarker = getNodeForCharacterOffset(node, end); if (startMarker && endMarker) { var range = document.createRange(); range.setStart(startMarker.node, startMarker.offset); selection.removeAllRanges(); if (start > end) { selection.addRange(range); selection.extend(endMarker.node, endMarker.offset); } else { range.setEnd(endMarker.node, endMarker.offset); selection.addRange(range); } } } var useIEOffsets = ExecutionEnvironment.canUseDOM && 'selection' in document && !('getSelection' in window); var ReactDOMSelection = { /** * @param {DOMElement} node */ getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets, /** * @param {DOMElement|DOMTextNode} node * @param {object} offsets */ setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets }; module.exports = ReactDOMSelection; /***/ }, /* 138 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getNodeForCharacterOffset */ 'use strict'; /** * Given any node return the first leaf node without children. * * @param {DOMElement|DOMTextNode} node * @return {DOMElement|DOMTextNode} */ function getLeafNode(node) { while (node && node.firstChild) { node = node.firstChild; } return node; } /** * Get the next sibling within a container. This will walk up the * DOM if a node's siblings have been exhausted. * * @param {DOMElement|DOMTextNode} node * @return {?DOMElement|DOMTextNode} */ function getSiblingNode(node) { while (node) { if (node.nextSibling) { return node.nextSibling; } node = node.parentNode; } } /** * Get object describing the nodes which contain characters at offset. * * @param {DOMElement|DOMTextNode} root * @param {number} offset * @return {?object} */ function getNodeForCharacterOffset(root, offset) { var node = getLeafNode(root); var nodeStart = 0; var nodeEnd = 0; while (node) { if (node.nodeType === 3) { nodeEnd = nodeStart + node.textContent.length; if (nodeStart <= offset && nodeEnd >= offset) { return { node: node, offset: offset - nodeStart }; } nodeStart = nodeEnd; } node = getLeafNode(getSiblingNode(node)); } } module.exports = getNodeForCharacterOffset; /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var isTextNode = __webpack_require__(140); /*eslint-disable no-bitwise */ /** * Checks if a given DOM node contains or is another DOM node. * * @param {?DOMNode} outerNode Outer DOM node. * @param {?DOMNode} innerNode Inner DOM node. * @return {boolean} True if `outerNode` contains or is `innerNode`. */ function containsNode(outerNode, innerNode) { if (!outerNode || !innerNode) { return false; } else if (outerNode === innerNode) { return true; } else if (isTextNode(outerNode)) { return false; } else if (isTextNode(innerNode)) { return containsNode(outerNode, innerNode.parentNode); } else if (outerNode.contains) { return outerNode.contains(innerNode); } else if (outerNode.compareDocumentPosition) { return !!(outerNode.compareDocumentPosition(innerNode) & 16); } else { return false; } } module.exports = containsNode; /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var isNode = __webpack_require__(141); /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM text node. */ function isTextNode(object) { return isNode(object) && object.nodeType == 3; } module.exports = isTextNode; /***/ }, /* 141 */ /***/ function(module, exports) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /** * @param {*} object The object to check. * @return {boolean} Whether or not the object is a DOM node. */ function isNode(object) { return !!(object && (typeof Node === 'function' ? object instanceof Node : typeof object === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string')); } module.exports = isNode; /***/ }, /* 142 */ /***/ function(module, exports) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ /* eslint-disable fb-www/typeof-undefined */ /** * Same as document.activeElement but wraps in a try-catch block. In IE it is * not safe to call document.activeElement if there is nothing focused. * * The activeElement will be null only if the document or document body is not * yet defined. */ function getActiveElement() /*?DOMElement*/{ if (typeof document === 'undefined') { return null; } try { return document.activeElement || document.body; } catch (e) { return document.body; } } module.exports = getActiveElement; /***/ }, /* 143 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SVGDOMPropertyConfig */ 'use strict'; var NS = { xlink: 'http://www.w3.org/1999/xlink', xml: 'http://www.w3.org/XML/1998/namespace' }; // We use attributes for everything SVG so let's avoid some duplication and run // code instead. // The following are all specified in the HTML config already so we exclude here. // - class (as className) // - color // - height // - id // - lang // - max // - media // - method // - min // - name // - style // - target // - type // - width var ATTRS = { accentHeight: 'accent-height', accumulate: 0, additive: 0, alignmentBaseline: 'alignment-baseline', allowReorder: 'allowReorder', alphabetic: 0, amplitude: 0, arabicForm: 'arabic-form', ascent: 0, attributeName: 'attributeName', attributeType: 'attributeType', autoReverse: 'autoReverse', azimuth: 0, baseFrequency: 'baseFrequency', baseProfile: 'baseProfile', baselineShift: 'baseline-shift', bbox: 0, begin: 0, bias: 0, by: 0, calcMode: 'calcMode', capHeight: 'cap-height', clip: 0, clipPath: 'clip-path', clipRule: 'clip-rule', clipPathUnits: 'clipPathUnits', colorInterpolation: 'color-interpolation', colorInterpolationFilters: 'color-interpolation-filters', colorProfile: 'color-profile', colorRendering: 'color-rendering', contentScriptType: 'contentScriptType', contentStyleType: 'contentStyleType', cursor: 0, cx: 0, cy: 0, d: 0, decelerate: 0, descent: 0, diffuseConstant: 'diffuseConstant', direction: 0, display: 0, divisor: 0, dominantBaseline: 'dominant-baseline', dur: 0, dx: 0, dy: 0, edgeMode: 'edgeMode', elevation: 0, enableBackground: 'enable-background', end: 0, exponent: 0, externalResourcesRequired: 'externalResourcesRequired', fill: 0, fillOpacity: 'fill-opacity', fillRule: 'fill-rule', filter: 0, filterRes: 'filterRes', filterUnits: 'filterUnits', floodColor: 'flood-color', floodOpacity: 'flood-opacity', focusable: 0, fontFamily: 'font-family', fontSize: 'font-size', fontSizeAdjust: 'font-size-adjust', fontStretch: 'font-stretch', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', format: 0, from: 0, fx: 0, fy: 0, g1: 0, g2: 0, glyphName: 'glyph-name', glyphOrientationHorizontal: 'glyph-orientation-horizontal', glyphOrientationVertical: 'glyph-orientation-vertical', glyphRef: 'glyphRef', gradientTransform: 'gradientTransform', gradientUnits: 'gradientUnits', hanging: 0, horizAdvX: 'horiz-adv-x', horizOriginX: 'horiz-origin-x', ideographic: 0, imageRendering: 'image-rendering', 'in': 0, in2: 0, intercept: 0, k: 0, k1: 0, k2: 0, k3: 0, k4: 0, kernelMatrix: 'kernelMatrix', kernelUnitLength: 'kernelUnitLength', kerning: 0, keyPoints: 'keyPoints', keySplines: 'keySplines', keyTimes: 'keyTimes', lengthAdjust: 'lengthAdjust', letterSpacing: 'letter-spacing', lightingColor: 'lighting-color', limitingConeAngle: 'limitingConeAngle', local: 0, markerEnd: 'marker-end', markerMid: 'marker-mid', markerStart: 'marker-start', markerHeight: 'markerHeight', markerUnits: 'markerUnits', markerWidth: 'markerWidth', mask: 0, maskContentUnits: 'maskContentUnits', maskUnits: 'maskUnits', mathematical: 0, mode: 0, numOctaves: 'numOctaves', offset: 0, opacity: 0, operator: 0, order: 0, orient: 0, orientation: 0, origin: 0, overflow: 0, overlinePosition: 'overline-position', overlineThickness: 'overline-thickness', paintOrder: 'paint-order', panose1: 'panose-1', pathLength: 'pathLength', patternContentUnits: 'patternContentUnits', patternTransform: 'patternTransform', patternUnits: 'patternUnits', pointerEvents: 'pointer-events', points: 0, pointsAtX: 'pointsAtX', pointsAtY: 'pointsAtY', pointsAtZ: 'pointsAtZ', preserveAlpha: 'preserveAlpha', preserveAspectRatio: 'preserveAspectRatio', primitiveUnits: 'primitiveUnits', r: 0, radius: 0, refX: 'refX', refY: 'refY', renderingIntent: 'rendering-intent', repeatCount: 'repeatCount', repeatDur: 'repeatDur', requiredExtensions: 'requiredExtensions', requiredFeatures: 'requiredFeatures', restart: 0, result: 0, rotate: 0, rx: 0, ry: 0, scale: 0, seed: 0, shapeRendering: 'shape-rendering', slope: 0, spacing: 0, specularConstant: 'specularConstant', specularExponent: 'specularExponent', speed: 0, spreadMethod: 'spreadMethod', startOffset: 'startOffset', stdDeviation: 'stdDeviation', stemh: 0, stemv: 0, stitchTiles: 'stitchTiles', stopColor: 'stop-color', stopOpacity: 'stop-opacity', strikethroughPosition: 'strikethrough-position', strikethroughThickness: 'strikethrough-thickness', string: 0, stroke: 0, strokeDasharray: 'stroke-dasharray', strokeDashoffset: 'stroke-dashoffset', strokeLinecap: 'stroke-linecap', strokeLinejoin: 'stroke-linejoin', strokeMiterlimit: 'stroke-miterlimit', strokeOpacity: 'stroke-opacity', strokeWidth: 'stroke-width', surfaceScale: 'surfaceScale', systemLanguage: 'systemLanguage', tableValues: 'tableValues', targetX: 'targetX', targetY: 'targetY', textAnchor: 'text-anchor', textDecoration: 'text-decoration', textRendering: 'text-rendering', textLength: 'textLength', to: 0, transform: 0, u1: 0, u2: 0, underlinePosition: 'underline-position', underlineThickness: 'underline-thickness', unicode: 0, unicodeBidi: 'unicode-bidi', unicodeRange: 'unicode-range', unitsPerEm: 'units-per-em', vAlphabetic: 'v-alphabetic', vHanging: 'v-hanging', vIdeographic: 'v-ideographic', vMathematical: 'v-mathematical', values: 0, vectorEffect: 'vector-effect', version: 0, vertAdvY: 'vert-adv-y', vertOriginX: 'vert-origin-x', vertOriginY: 'vert-origin-y', viewBox: 'viewBox', viewTarget: 'viewTarget', visibility: 0, widths: 0, wordSpacing: 'word-spacing', writingMode: 'writing-mode', x: 0, xHeight: 'x-height', x1: 0, x2: 0, xChannelSelector: 'xChannelSelector', xlinkActuate: 'xlink:actuate', xlinkArcrole: 'xlink:arcrole', xlinkHref: 'xlink:href', xlinkRole: 'xlink:role', xlinkShow: 'xlink:show', xlinkTitle: 'xlink:title', xlinkType: 'xlink:type', xmlBase: 'xml:base', xmlLang: 'xml:lang', xmlSpace: 'xml:space', y: 0, y1: 0, y2: 0, yChannelSelector: 'yChannelSelector', z: 0, zoomAndPan: 'zoomAndPan' }; var SVGDOMPropertyConfig = { Properties: {}, DOMAttributeNamespaces: { xlinkActuate: NS.xlink, xlinkArcrole: NS.xlink, xlinkHref: NS.xlink, xlinkRole: NS.xlink, xlinkShow: NS.xlink, xlinkTitle: NS.xlink, xlinkType: NS.xlink, xmlBase: NS.xml, xmlLang: NS.xml, xmlSpace: NS.xml }, DOMAttributeNames: {} }; Object.keys(ATTRS).forEach(function (key) { SVGDOMPropertyConfig.Properties[key] = 0; if (ATTRS[key]) { SVGDOMPropertyConfig.DOMAttributeNames[key] = ATTRS[key]; } }); module.exports = SVGDOMPropertyConfig; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SelectEventPlugin */ 'use strict'; var EventConstants = __webpack_require__(40); var EventPropagators = __webpack_require__(41); var ExecutionEnvironment = __webpack_require__(48); var ReactDOMComponentTree = __webpack_require__(35); var ReactInputSelection = __webpack_require__(136); var SyntheticEvent = __webpack_require__(52); var getActiveElement = __webpack_require__(142); var isTextInputElement = __webpack_require__(65); var keyOf = __webpack_require__(26); var shallowEqual = __webpack_require__(125); var topLevelTypes = EventConstants.topLevelTypes; var skipSelectionChangeEvent = ExecutionEnvironment.canUseDOM && 'documentMode' in document && document.documentMode <= 11; var eventTypes = { select: { phasedRegistrationNames: { bubbled: keyOf({ onSelect: null }), captured: keyOf({ onSelectCapture: null }) }, dependencies: [topLevelTypes.topBlur, topLevelTypes.topContextMenu, topLevelTypes.topFocus, topLevelTypes.topKeyDown, topLevelTypes.topMouseDown, topLevelTypes.topMouseUp, topLevelTypes.topSelectionChange] } }; var activeElement = null; var activeElementInst = null; var lastSelection = null; var mouseDown = false; // Track whether a listener exists for this plugin. If none exist, we do // not extract events. See #3639. var hasListener = false; var ON_SELECT_KEY = keyOf({ onSelect: null }); /** * Get an object which is a unique representation of the current selection. * * The return value will not be consistent across nodes or browsers, but * two identical selections on the same node will return identical objects. * * @param {DOMElement} node * @return {object} */ function getSelection(node) { if ('selectionStart' in node && ReactInputSelection.hasSelectionCapabilities(node)) { return { start: node.selectionStart, end: node.selectionEnd }; } else if (window.getSelection) { var selection = window.getSelection(); return { anchorNode: selection.anchorNode, anchorOffset: selection.anchorOffset, focusNode: selection.focusNode, focusOffset: selection.focusOffset }; } else if (document.selection) { var range = document.selection.createRange(); return { parentElement: range.parentElement(), text: range.text, top: range.boundingTop, left: range.boundingLeft }; } } /** * Poll selection to see whether it's changed. * * @param {object} nativeEvent * @return {?SyntheticEvent} */ function constructSelectEvent(nativeEvent, nativeEventTarget) { // Ensure we have the right element, and that the user is not dragging a // selection (this matches native `select` event behavior). In HTML5, select // fires only on input and textarea thus if there's no focused element we // won't dispatch. if (mouseDown || activeElement == null || activeElement !== getActiveElement()) { return null; } // Only fire when selection has actually changed. var currentSelection = getSelection(activeElement); if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) { lastSelection = currentSelection; var syntheticEvent = SyntheticEvent.getPooled(eventTypes.select, activeElementInst, nativeEvent, nativeEventTarget); syntheticEvent.type = 'select'; syntheticEvent.target = activeElement; EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent); return syntheticEvent; } return null; } /** * This plugin creates an `onSelect` event that normalizes select events * across form elements. * * Supported elements are: * - input (see `isTextInputElement`) * - textarea * - contentEditable * * This differs from native browser implementations in the following ways: * - Fires on contentEditable fields as well as inputs. * - Fires for collapsed selection. * - Fires after user input. */ var SelectEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { if (!hasListener) { return null; } var targetNode = targetInst ? ReactDOMComponentTree.getNodeFromInstance(targetInst) : window; switch (topLevelType) { // Track the input node that has focus. case topLevelTypes.topFocus: if (isTextInputElement(targetNode) || targetNode.contentEditable === 'true') { activeElement = targetNode; activeElementInst = targetInst; lastSelection = null; } break; case topLevelTypes.topBlur: activeElement = null; activeElementInst = null; lastSelection = null; break; // Don't fire the event while the user is dragging. This matches the // semantics of the native select event. case topLevelTypes.topMouseDown: mouseDown = true; break; case topLevelTypes.topContextMenu: case topLevelTypes.topMouseUp: mouseDown = false; return constructSelectEvent(nativeEvent, nativeEventTarget); // Chrome and IE fire non-standard event when selection is changed (and // sometimes when it hasn't). IE's event fires out of order with respect // to key and input events on deletion, so we discard it. // // Firefox doesn't support selectionchange, so check selection status // after each key entry. The selection changes after keydown and before // keyup, but we check on keydown as well in the case of holding down a // key, when multiple keydown events are fired but only one keyup is. // This is also our approach for IE handling, for the reason above. case topLevelTypes.topSelectionChange: if (skipSelectionChangeEvent) { break; } // falls through case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: return constructSelectEvent(nativeEvent, nativeEventTarget); } return null; }, didPutListener: function (inst, registrationName, listener) { if (registrationName === ON_SELECT_KEY) { hasListener = true; } } }; module.exports = SelectEventPlugin; /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SimpleEventPlugin */ 'use strict'; var EventConstants = __webpack_require__(40); var EventListener = __webpack_require__(132); var EventPropagators = __webpack_require__(41); var ReactDOMComponentTree = __webpack_require__(35); var SyntheticAnimationEvent = __webpack_require__(146); var SyntheticClipboardEvent = __webpack_require__(147); var SyntheticEvent = __webpack_require__(52); var SyntheticFocusEvent = __webpack_require__(148); var SyntheticKeyboardEvent = __webpack_require__(149); var SyntheticMouseEvent = __webpack_require__(68); var SyntheticDragEvent = __webpack_require__(152); var SyntheticTouchEvent = __webpack_require__(153); var SyntheticTransitionEvent = __webpack_require__(154); var SyntheticUIEvent = __webpack_require__(69); var SyntheticWheelEvent = __webpack_require__(155); var emptyFunction = __webpack_require__(11); var getEventCharCode = __webpack_require__(150); var invariant = __webpack_require__(7); var keyOf = __webpack_require__(26); var topLevelTypes = EventConstants.topLevelTypes; var eventTypes = { abort: { phasedRegistrationNames: { bubbled: keyOf({ onAbort: true }), captured: keyOf({ onAbortCapture: true }) } }, animationEnd: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationEnd: true }), captured: keyOf({ onAnimationEndCapture: true }) } }, animationIteration: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationIteration: true }), captured: keyOf({ onAnimationIterationCapture: true }) } }, animationStart: { phasedRegistrationNames: { bubbled: keyOf({ onAnimationStart: true }), captured: keyOf({ onAnimationStartCapture: true }) } }, blur: { phasedRegistrationNames: { bubbled: keyOf({ onBlur: true }), captured: keyOf({ onBlurCapture: true }) } }, canPlay: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlay: true }), captured: keyOf({ onCanPlayCapture: true }) } }, canPlayThrough: { phasedRegistrationNames: { bubbled: keyOf({ onCanPlayThrough: true }), captured: keyOf({ onCanPlayThroughCapture: true }) } }, click: { phasedRegistrationNames: { bubbled: keyOf({ onClick: true }), captured: keyOf({ onClickCapture: true }) } }, contextMenu: { phasedRegistrationNames: { bubbled: keyOf({ onContextMenu: true }), captured: keyOf({ onContextMenuCapture: true }) } }, copy: { phasedRegistrationNames: { bubbled: keyOf({ onCopy: true }), captured: keyOf({ onCopyCapture: true }) } }, cut: { phasedRegistrationNames: { bubbled: keyOf({ onCut: true }), captured: keyOf({ onCutCapture: true }) } }, doubleClick: { phasedRegistrationNames: { bubbled: keyOf({ onDoubleClick: true }), captured: keyOf({ onDoubleClickCapture: true }) } }, drag: { phasedRegistrationNames: { bubbled: keyOf({ onDrag: true }), captured: keyOf({ onDragCapture: true }) } }, dragEnd: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnd: true }), captured: keyOf({ onDragEndCapture: true }) } }, dragEnter: { phasedRegistrationNames: { bubbled: keyOf({ onDragEnter: true }), captured: keyOf({ onDragEnterCapture: true }) } }, dragExit: { phasedRegistrationNames: { bubbled: keyOf({ onDragExit: true }), captured: keyOf({ onDragExitCapture: true }) } }, dragLeave: { phasedRegistrationNames: { bubbled: keyOf({ onDragLeave: true }), captured: keyOf({ onDragLeaveCapture: true }) } }, dragOver: { phasedRegistrationNames: { bubbled: keyOf({ onDragOver: true }), captured: keyOf({ onDragOverCapture: true }) } }, dragStart: { phasedRegistrationNames: { bubbled: keyOf({ onDragStart: true }), captured: keyOf({ onDragStartCapture: true }) } }, drop: { phasedRegistrationNames: { bubbled: keyOf({ onDrop: true }), captured: keyOf({ onDropCapture: true }) } }, durationChange: { phasedRegistrationNames: { bubbled: keyOf({ onDurationChange: true }), captured: keyOf({ onDurationChangeCapture: true }) } }, emptied: { phasedRegistrationNames: { bubbled: keyOf({ onEmptied: true }), captured: keyOf({ onEmptiedCapture: true }) } }, encrypted: { phasedRegistrationNames: { bubbled: keyOf({ onEncrypted: true }), captured: keyOf({ onEncryptedCapture: true }) } }, ended: { phasedRegistrationNames: { bubbled: keyOf({ onEnded: true }), captured: keyOf({ onEndedCapture: true }) } }, error: { phasedRegistrationNames: { bubbled: keyOf({ onError: true }), captured: keyOf({ onErrorCapture: true }) } }, focus: { phasedRegistrationNames: { bubbled: keyOf({ onFocus: true }), captured: keyOf({ onFocusCapture: true }) } }, input: { phasedRegistrationNames: { bubbled: keyOf({ onInput: true }), captured: keyOf({ onInputCapture: true }) } }, invalid: { phasedRegistrationNames: { bubbled: keyOf({ onInvalid: true }), captured: keyOf({ onInvalidCapture: true }) } }, keyDown: { phasedRegistrationNames: { bubbled: keyOf({ onKeyDown: true }), captured: keyOf({ onKeyDownCapture: true }) } }, keyPress: { phasedRegistrationNames: { bubbled: keyOf({ onKeyPress: true }), captured: keyOf({ onKeyPressCapture: true }) } }, keyUp: { phasedRegistrationNames: { bubbled: keyOf({ onKeyUp: true }), captured: keyOf({ onKeyUpCapture: true }) } }, load: { phasedRegistrationNames: { bubbled: keyOf({ onLoad: true }), captured: keyOf({ onLoadCapture: true }) } }, loadedData: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedData: true }), captured: keyOf({ onLoadedDataCapture: true }) } }, loadedMetadata: { phasedRegistrationNames: { bubbled: keyOf({ onLoadedMetadata: true }), captured: keyOf({ onLoadedMetadataCapture: true }) } }, loadStart: { phasedRegistrationNames: { bubbled: keyOf({ onLoadStart: true }), captured: keyOf({ onLoadStartCapture: true }) } }, // Note: We do not allow listening to mouseOver events. Instead, use the // onMouseEnter/onMouseLeave created by `EnterLeaveEventPlugin`. mouseDown: { phasedRegistrationNames: { bubbled: keyOf({ onMouseDown: true }), captured: keyOf({ onMouseDownCapture: true }) } }, mouseMove: { phasedRegistrationNames: { bubbled: keyOf({ onMouseMove: true }), captured: keyOf({ onMouseMoveCapture: true }) } }, mouseOut: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOut: true }), captured: keyOf({ onMouseOutCapture: true }) } }, mouseOver: { phasedRegistrationNames: { bubbled: keyOf({ onMouseOver: true }), captured: keyOf({ onMouseOverCapture: true }) } }, mouseUp: { phasedRegistrationNames: { bubbled: keyOf({ onMouseUp: true }), captured: keyOf({ onMouseUpCapture: true }) } }, paste: { phasedRegistrationNames: { bubbled: keyOf({ onPaste: true }), captured: keyOf({ onPasteCapture: true }) } }, pause: { phasedRegistrationNames: { bubbled: keyOf({ onPause: true }), captured: keyOf({ onPauseCapture: true }) } }, play: { phasedRegistrationNames: { bubbled: keyOf({ onPlay: true }), captured: keyOf({ onPlayCapture: true }) } }, playing: { phasedRegistrationNames: { bubbled: keyOf({ onPlaying: true }), captured: keyOf({ onPlayingCapture: true }) } }, progress: { phasedRegistrationNames: { bubbled: keyOf({ onProgress: true }), captured: keyOf({ onProgressCapture: true }) } }, rateChange: { phasedRegistrationNames: { bubbled: keyOf({ onRateChange: true }), captured: keyOf({ onRateChangeCapture: true }) } }, reset: { phasedRegistrationNames: { bubbled: keyOf({ onReset: true }), captured: keyOf({ onResetCapture: true }) } }, scroll: { phasedRegistrationNames: { bubbled: keyOf({ onScroll: true }), captured: keyOf({ onScrollCapture: true }) } }, seeked: { phasedRegistrationNames: { bubbled: keyOf({ onSeeked: true }), captured: keyOf({ onSeekedCapture: true }) } }, seeking: { phasedRegistrationNames: { bubbled: keyOf({ onSeeking: true }), captured: keyOf({ onSeekingCapture: true }) } }, stalled: { phasedRegistrationNames: { bubbled: keyOf({ onStalled: true }), captured: keyOf({ onStalledCapture: true }) } }, submit: { phasedRegistrationNames: { bubbled: keyOf({ onSubmit: true }), captured: keyOf({ onSubmitCapture: true }) } }, suspend: { phasedRegistrationNames: { bubbled: keyOf({ onSuspend: true }), captured: keyOf({ onSuspendCapture: true }) } }, timeUpdate: { phasedRegistrationNames: { bubbled: keyOf({ onTimeUpdate: true }), captured: keyOf({ onTimeUpdateCapture: true }) } }, touchCancel: { phasedRegistrationNames: { bubbled: keyOf({ onTouchCancel: true }), captured: keyOf({ onTouchCancelCapture: true }) } }, touchEnd: { phasedRegistrationNames: { bubbled: keyOf({ onTouchEnd: true }), captured: keyOf({ onTouchEndCapture: true }) } }, touchMove: { phasedRegistrationNames: { bubbled: keyOf({ onTouchMove: true }), captured: keyOf({ onTouchMoveCapture: true }) } }, touchStart: { phasedRegistrationNames: { bubbled: keyOf({ onTouchStart: true }), captured: keyOf({ onTouchStartCapture: true }) } }, transitionEnd: { phasedRegistrationNames: { bubbled: keyOf({ onTransitionEnd: true }), captured: keyOf({ onTransitionEndCapture: true }) } }, volumeChange: { phasedRegistrationNames: { bubbled: keyOf({ onVolumeChange: true }), captured: keyOf({ onVolumeChangeCapture: true }) } }, waiting: { phasedRegistrationNames: { bubbled: keyOf({ onWaiting: true }), captured: keyOf({ onWaitingCapture: true }) } }, wheel: { phasedRegistrationNames: { bubbled: keyOf({ onWheel: true }), captured: keyOf({ onWheelCapture: true }) } } }; var topLevelEventsToDispatchConfig = { topAbort: eventTypes.abort, topAnimationEnd: eventTypes.animationEnd, topAnimationIteration: eventTypes.animationIteration, topAnimationStart: eventTypes.animationStart, topBlur: eventTypes.blur, topCanPlay: eventTypes.canPlay, topCanPlayThrough: eventTypes.canPlayThrough, topClick: eventTypes.click, topContextMenu: eventTypes.contextMenu, topCopy: eventTypes.copy, topCut: eventTypes.cut, topDoubleClick: eventTypes.doubleClick, topDrag: eventTypes.drag, topDragEnd: eventTypes.dragEnd, topDragEnter: eventTypes.dragEnter, topDragExit: eventTypes.dragExit, topDragLeave: eventTypes.dragLeave, topDragOver: eventTypes.dragOver, topDragStart: eventTypes.dragStart, topDrop: eventTypes.drop, topDurationChange: eventTypes.durationChange, topEmptied: eventTypes.emptied, topEncrypted: eventTypes.encrypted, topEnded: eventTypes.ended, topError: eventTypes.error, topFocus: eventTypes.focus, topInput: eventTypes.input, topInvalid: eventTypes.invalid, topKeyDown: eventTypes.keyDown, topKeyPress: eventTypes.keyPress, topKeyUp: eventTypes.keyUp, topLoad: eventTypes.load, topLoadedData: eventTypes.loadedData, topLoadedMetadata: eventTypes.loadedMetadata, topLoadStart: eventTypes.loadStart, topMouseDown: eventTypes.mouseDown, topMouseMove: eventTypes.mouseMove, topMouseOut: eventTypes.mouseOut, topMouseOver: eventTypes.mouseOver, topMouseUp: eventTypes.mouseUp, topPaste: eventTypes.paste, topPause: eventTypes.pause, topPlay: eventTypes.play, topPlaying: eventTypes.playing, topProgress: eventTypes.progress, topRateChange: eventTypes.rateChange, topReset: eventTypes.reset, topScroll: eventTypes.scroll, topSeeked: eventTypes.seeked, topSeeking: eventTypes.seeking, topStalled: eventTypes.stalled, topSubmit: eventTypes.submit, topSuspend: eventTypes.suspend, topTimeUpdate: eventTypes.timeUpdate, topTouchCancel: eventTypes.touchCancel, topTouchEnd: eventTypes.touchEnd, topTouchMove: eventTypes.touchMove, topTouchStart: eventTypes.touchStart, topTransitionEnd: eventTypes.transitionEnd, topVolumeChange: eventTypes.volumeChange, topWaiting: eventTypes.waiting, topWheel: eventTypes.wheel }; for (var type in topLevelEventsToDispatchConfig) { topLevelEventsToDispatchConfig[type].dependencies = [type]; } var ON_CLICK_KEY = keyOf({ onClick: null }); var onClickListeners = {}; var SimpleEventPlugin = { eventTypes: eventTypes, extractEvents: function (topLevelType, targetInst, nativeEvent, nativeEventTarget) { var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType]; if (!dispatchConfig) { return null; } var EventConstructor; switch (topLevelType) { case topLevelTypes.topAbort: case topLevelTypes.topCanPlay: case topLevelTypes.topCanPlayThrough: case topLevelTypes.topDurationChange: case topLevelTypes.topEmptied: case topLevelTypes.topEncrypted: case topLevelTypes.topEnded: case topLevelTypes.topError: case topLevelTypes.topInput: case topLevelTypes.topInvalid: case topLevelTypes.topLoad: case topLevelTypes.topLoadedData: case topLevelTypes.topLoadedMetadata: case topLevelTypes.topLoadStart: case topLevelTypes.topPause: case topLevelTypes.topPlay: case topLevelTypes.topPlaying: case topLevelTypes.topProgress: case topLevelTypes.topRateChange: case topLevelTypes.topReset: case topLevelTypes.topSeeked: case topLevelTypes.topSeeking: case topLevelTypes.topStalled: case topLevelTypes.topSubmit: case topLevelTypes.topSuspend: case topLevelTypes.topTimeUpdate: case topLevelTypes.topVolumeChange: case topLevelTypes.topWaiting: // HTML Events // @see http://www.w3.org/TR/html5/index.html#events-0 EventConstructor = SyntheticEvent; break; case topLevelTypes.topKeyPress: // Firefox creates a keypress event for function keys too. This removes // the unwanted keypress events. Enter is however both printable and // non-printable. One would expect Tab to be as well (but it isn't). if (getEventCharCode(nativeEvent) === 0) { return null; } /* falls through */ case topLevelTypes.topKeyDown: case topLevelTypes.topKeyUp: EventConstructor = SyntheticKeyboardEvent; break; case topLevelTypes.topBlur: case topLevelTypes.topFocus: EventConstructor = SyntheticFocusEvent; break; case topLevelTypes.topClick: // Firefox creates a click event on right mouse clicks. This removes the // unwanted click events. if (nativeEvent.button === 2) { return null; } /* falls through */ case topLevelTypes.topContextMenu: case topLevelTypes.topDoubleClick: case topLevelTypes.topMouseDown: case topLevelTypes.topMouseMove: case topLevelTypes.topMouseOut: case topLevelTypes.topMouseOver: case topLevelTypes.topMouseUp: EventConstructor = SyntheticMouseEvent; break; case topLevelTypes.topDrag: case topLevelTypes.topDragEnd: case topLevelTypes.topDragEnter: case topLevelTypes.topDragExit: case topLevelTypes.topDragLeave: case topLevelTypes.topDragOver: case topLevelTypes.topDragStart: case topLevelTypes.topDrop: EventConstructor = SyntheticDragEvent; break; case topLevelTypes.topTouchCancel: case topLevelTypes.topTouchEnd: case topLevelTypes.topTouchMove: case topLevelTypes.topTouchStart: EventConstructor = SyntheticTouchEvent; break; case topLevelTypes.topAnimationEnd: case topLevelTypes.topAnimationIteration: case topLevelTypes.topAnimationStart: EventConstructor = SyntheticAnimationEvent; break; case topLevelTypes.topTransitionEnd: EventConstructor = SyntheticTransitionEvent; break; case topLevelTypes.topScroll: EventConstructor = SyntheticUIEvent; break; case topLevelTypes.topWheel: EventConstructor = SyntheticWheelEvent; break; case topLevelTypes.topCopy: case topLevelTypes.topCut: case topLevelTypes.topPaste: EventConstructor = SyntheticClipboardEvent; break; } !EventConstructor ? process.env.NODE_ENV !== 'production' ? invariant(false, 'SimpleEventPlugin: Unhandled event type, `%s`.', topLevelType) : invariant(false) : void 0; var event = EventConstructor.getPooled(dispatchConfig, targetInst, nativeEvent, nativeEventTarget); EventPropagators.accumulateTwoPhaseDispatches(event); return event; }, didPutListener: function (inst, registrationName, listener) { // Mobile Safari does not fire properly bubble click events on // non-interactive elements, which means delegated click listeners do not // fire. The workaround for this bug involves attaching an empty click // listener on the target node. if (registrationName === ON_CLICK_KEY) { var id = inst._rootNodeID; var node = ReactDOMComponentTree.getNodeFromInstance(inst); if (!onClickListeners[id]) { onClickListeners[id] = EventListener.listen(node, 'click', emptyFunction); } } }, willDeleteListener: function (inst, registrationName) { if (registrationName === ON_CLICK_KEY) { var id = inst._rootNodeID; onClickListeners[id].remove(); delete onClickListeners[id]; } } }; module.exports = SimpleEventPlugin; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticAnimationEvent */ 'use strict'; var SyntheticEvent = __webpack_require__(52); /** * @interface Event * @see http://www.w3.org/TR/css3-animations/#AnimationEvent-interface * @see https://developer.mozilla.org/en-US/docs/Web/API/AnimationEvent */ var AnimationEventInterface = { animationName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticAnimationEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticAnimationEvent, AnimationEventInterface); module.exports = SyntheticAnimationEvent; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticClipboardEvent */ 'use strict'; var SyntheticEvent = __webpack_require__(52); /** * @interface Event * @see http://www.w3.org/TR/clipboard-apis/ */ var ClipboardEventInterface = { clipboardData: function (event) { return 'clipboardData' in event ? event.clipboardData : window.clipboardData; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticClipboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface); module.exports = SyntheticClipboardEvent; /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticFocusEvent */ 'use strict'; var SyntheticUIEvent = __webpack_require__(69); /** * @interface FocusEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var FocusEventInterface = { relatedTarget: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticFocusEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface); module.exports = SyntheticFocusEvent; /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticKeyboardEvent */ 'use strict'; var SyntheticUIEvent = __webpack_require__(69); var getEventCharCode = __webpack_require__(150); var getEventKey = __webpack_require__(151); var getEventModifierState = __webpack_require__(71); /** * @interface KeyboardEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var KeyboardEventInterface = { key: getEventKey, location: null, ctrlKey: null, shiftKey: null, altKey: null, metaKey: null, repeat: null, locale: null, getModifierState: getEventModifierState, // Legacy Interface charCode: function (event) { // `charCode` is the result of a KeyPress event and represents the value of // the actual printable character. // KeyPress is deprecated, but its replacement is not yet final and not // implemented in any major browser. Only KeyPress has charCode. if (event.type === 'keypress') { return getEventCharCode(event); } return 0; }, keyCode: function (event) { // `keyCode` is the result of a KeyDown/Up event and represents the value of // physical keyboard key. // The actual meaning of the value depends on the users' keyboard layout // which cannot be detected. Assuming that it is a US keyboard layout // provides a surprisingly accurate mapping for US and European users. // Due to this, it is left to the user to implement at this time. if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; }, which: function (event) { // `which` is an alias for either `keyCode` or `charCode` depending on the // type of the event. if (event.type === 'keypress') { return getEventCharCode(event); } if (event.type === 'keydown' || event.type === 'keyup') { return event.keyCode; } return 0; } }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticKeyboardEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface); module.exports = SyntheticKeyboardEvent; /***/ }, /* 150 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventCharCode */ 'use strict'; /** * `charCode` represents the actual "character code" and is safe to use with * `String.fromCharCode`. As such, only keys that correspond to printable * characters produce a valid `charCode`, the only exception to this is Enter. * The Tab-key is considered non-printable and does not have a `charCode`, * presumably because it does not produce a tab-character in browsers. * * @param {object} nativeEvent Native browser event. * @return {number} Normalized `charCode` property. */ function getEventCharCode(nativeEvent) { var charCode; var keyCode = nativeEvent.keyCode; if ('charCode' in nativeEvent) { charCode = nativeEvent.charCode; // FF does not set `charCode` for the Enter-key, check against `keyCode`. if (charCode === 0 && keyCode === 13) { charCode = 13; } } else { // IE8 does not implement `charCode`, but `keyCode` has the correct value. charCode = keyCode; } // Some non-printable keys are reported in `charCode`/`keyCode`, discard them. // Must not discard the (non-)printable Enter-key. if (charCode >= 32 || charCode === 13) { return charCode; } return 0; } module.exports = getEventCharCode; /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getEventKey */ 'use strict'; var getEventCharCode = __webpack_require__(150); /** * Normalization of deprecated HTML5 `key` values * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var normalizeKey = { 'Esc': 'Escape', 'Spacebar': ' ', 'Left': 'ArrowLeft', 'Up': 'ArrowUp', 'Right': 'ArrowRight', 'Down': 'ArrowDown', 'Del': 'Delete', 'Win': 'OS', 'Menu': 'ContextMenu', 'Apps': 'ContextMenu', 'Scroll': 'ScrollLock', 'MozPrintableKey': 'Unidentified' }; /** * Translation from legacy `keyCode` to HTML5 `key` * Only special keys supported, all others depend on keyboard layout or browser * @see https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent#Key_names */ var translateToKey = { 8: 'Backspace', 9: 'Tab', 12: 'Clear', 13: 'Enter', 16: 'Shift', 17: 'Control', 18: 'Alt', 19: 'Pause', 20: 'CapsLock', 27: 'Escape', 32: ' ', 33: 'PageUp', 34: 'PageDown', 35: 'End', 36: 'Home', 37: 'ArrowLeft', 38: 'ArrowUp', 39: 'ArrowRight', 40: 'ArrowDown', 45: 'Insert', 46: 'Delete', 112: 'F1', 113: 'F2', 114: 'F3', 115: 'F4', 116: 'F5', 117: 'F6', 118: 'F7', 119: 'F8', 120: 'F9', 121: 'F10', 122: 'F11', 123: 'F12', 144: 'NumLock', 145: 'ScrollLock', 224: 'Meta' }; /** * @param {object} nativeEvent Native browser event. * @return {string} Normalized `key` property. */ function getEventKey(nativeEvent) { if (nativeEvent.key) { // Normalize inconsistent values reported by browsers due to // implementations of a working draft specification. // FireFox implements `key` but returns `MozPrintableKey` for all // printable characters (normalized to `Unidentified`), ignore it. var key = normalizeKey[nativeEvent.key] || nativeEvent.key; if (key !== 'Unidentified') { return key; } } // Browser does not implement `key`, polyfill as much of it as we can. if (nativeEvent.type === 'keypress') { var charCode = getEventCharCode(nativeEvent); // The enter-key is technically both printable and non-printable and can // thus be captured by `keypress`, no other non-printable key should. return charCode === 13 ? 'Enter' : String.fromCharCode(charCode); } if (nativeEvent.type === 'keydown' || nativeEvent.type === 'keyup') { // While user keyboard layout determines the actual meaning of each // `keyCode` value, almost all function keys have a universal value. return translateToKey[nativeEvent.keyCode] || 'Unidentified'; } return ''; } module.exports = getEventKey; /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticDragEvent */ 'use strict'; var SyntheticMouseEvent = __webpack_require__(68); /** * @interface DragEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var DragEventInterface = { dataTransfer: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticDragEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface); module.exports = SyntheticDragEvent; /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTouchEvent */ 'use strict'; var SyntheticUIEvent = __webpack_require__(69); var getEventModifierState = __webpack_require__(71); /** * @interface TouchEvent * @see http://www.w3.org/TR/touch-events/ */ var TouchEventInterface = { touches: null, targetTouches: null, changedTouches: null, altKey: null, metaKey: null, ctrlKey: null, shiftKey: null, getModifierState: getEventModifierState }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticUIEvent} */ function SyntheticTouchEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface); module.exports = SyntheticTouchEvent; /***/ }, /* 154 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticTransitionEvent */ 'use strict'; var SyntheticEvent = __webpack_require__(52); /** * @interface Event * @see http://www.w3.org/TR/2009/WD-css3-transitions-20090320/#transition-events- * @see https://developer.mozilla.org/en-US/docs/Web/API/TransitionEvent */ var TransitionEventInterface = { propertyName: null, elapsedTime: null, pseudoElement: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticEvent} */ function SyntheticTransitionEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticEvent.augmentClass(SyntheticTransitionEvent, TransitionEventInterface); module.exports = SyntheticTransitionEvent; /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule SyntheticWheelEvent */ 'use strict'; var SyntheticMouseEvent = __webpack_require__(68); /** * @interface WheelEvent * @see http://www.w3.org/TR/DOM-Level-3-Events/ */ var WheelEventInterface = { deltaX: function (event) { return 'deltaX' in event ? event.deltaX : // Fallback to `wheelDeltaX` for Webkit and normalize (right is positive). 'wheelDeltaX' in event ? -event.wheelDeltaX : 0; }, deltaY: function (event) { return 'deltaY' in event ? event.deltaY : // Fallback to `wheelDeltaY` for Webkit and normalize (down is positive). 'wheelDeltaY' in event ? -event.wheelDeltaY : // Fallback to `wheelDelta` for IE<9 and normalize (down is positive). 'wheelDelta' in event ? -event.wheelDelta : 0; }, deltaZ: null, // Browsers without "deltaMode" is reporting in raw wheel delta where one // notch on the scroll is always +/- 120, roughly equivalent to pixels. // A good approximation of DOM_DELTA_LINE (1) is 5% of viewport size or // ~40 pixels, for DOM_DELTA_SCREEN (2) it is 87.5% of viewport size. deltaMode: null }; /** * @param {object} dispatchConfig Configuration used to dispatch this event. * @param {string} dispatchMarker Marker identifying the event target. * @param {object} nativeEvent Native browser event. * @extends {SyntheticMouseEvent} */ function SyntheticWheelEvent(dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget) { return SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent, nativeEventTarget); } SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface); module.exports = SyntheticWheelEvent; /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerf */ 'use strict'; var DOMProperty = __webpack_require__(36); var ReactDOMComponentTree = __webpack_require__(35); var ReactDefaultPerfAnalysis = __webpack_require__(157); var ReactMount = __webpack_require__(158); var ReactPerf = __webpack_require__(58); var performanceNow = __webpack_require__(163); var warning = __webpack_require__(10); function roundFloat(val) { return Math.floor(val * 100) / 100; } function addValue(obj, key, val) { obj[key] = (obj[key] || 0) + val; } // Composite/text components don't have any built-in ID: we have to make our own var compositeIDMap; var compositeIDCounter = 17000; function getIDOfComposite(inst) { if (!compositeIDMap) { compositeIDMap = new WeakMap(); } if (compositeIDMap.has(inst)) { return compositeIDMap.get(inst); } else { var id = compositeIDCounter++; compositeIDMap.set(inst, id); return id; } } function getID(inst) { if (inst.hasOwnProperty('_rootNodeID')) { return inst._rootNodeID; } else { return getIDOfComposite(inst); } } function stripComplexValues(key, value) { if (typeof value !== 'object' || Array.isArray(value) || value == null) { return value; } var prototype = Object.getPrototypeOf(value); if (!prototype || prototype === Object.prototype) { return value; } return '<not serializable>'; } // This implementation of ReactPerf is going away some time mid 15.x. // While we plan to keep most of the API, the actual format of measurements // will change dramatically. To signal this, we wrap them into an opaque-ish // object to discourage reaching into it until the API stabilizes. function wrapLegacyMeasurements(measurements) { return { __unstable_this_format_will_change: measurements }; } function unwrapLegacyMeasurements(measurements) { return measurements && measurements.__unstable_this_format_will_change || measurements; } var warnedAboutPrintDOM = false; var warnedAboutGetMeasurementsSummaryMap = false; var ReactDefaultPerf = { _allMeasurements: [], // last item in the list is the current one _mountStack: [0], _compositeStack: [], _injected: false, start: function () { if (!ReactDefaultPerf._injected) { ReactPerf.injection.injectMeasure(ReactDefaultPerf.measure); } ReactDefaultPerf._allMeasurements.length = 0; ReactPerf.enableMeasure = true; }, stop: function () { ReactPerf.enableMeasure = false; }, getLastMeasurements: function () { return wrapLegacyMeasurements(ReactDefaultPerf._allMeasurements); }, printExclusive: function (measurements) { measurements = unwrapLegacyMeasurements(measurements || ReactDefaultPerf._allMeasurements); var summary = ReactDefaultPerfAnalysis.getExclusiveSummary(measurements); console.table(summary.map(function (item) { return { 'Component class name': item.componentName, 'Total inclusive time (ms)': roundFloat(item.inclusive), 'Exclusive mount time (ms)': roundFloat(item.exclusive), 'Exclusive render time (ms)': roundFloat(item.render), 'Mount time per instance (ms)': roundFloat(item.exclusive / item.count), 'Render time per instance (ms)': roundFloat(item.render / item.count), 'Instances': item.count }; })); // TODO: ReactDefaultPerfAnalysis.getTotalTime() does not return the correct // number. }, printInclusive: function (measurements) { measurements = unwrapLegacyMeasurements(measurements || ReactDefaultPerf._allMeasurements); var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements); console.table(summary.map(function (item) { return { 'Owner > component': item.componentName, 'Inclusive time (ms)': roundFloat(item.time), 'Instances': item.count }; })); console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); }, getMeasurementsSummaryMap: function (measurements) { process.env.NODE_ENV !== 'production' ? warning(warnedAboutGetMeasurementsSummaryMap, '`ReactPerf.getMeasurementsSummaryMap(...)` is deprecated. Use ' + '`ReactPerf.getWasted(...)` instead.') : void 0; warnedAboutGetMeasurementsSummaryMap = true; return ReactDefaultPerf.getWasted(measurements); }, getWasted: function (measurements) { measurements = unwrapLegacyMeasurements(measurements); var summary = ReactDefaultPerfAnalysis.getInclusiveSummary(measurements, true); return summary.map(function (item) { return { 'Owner > component': item.componentName, 'Wasted time (ms)': item.time, 'Instances': item.count }; }); }, printWasted: function (measurements) { measurements = unwrapLegacyMeasurements(measurements || ReactDefaultPerf._allMeasurements); console.table(ReactDefaultPerf.getWasted(measurements)); console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); }, printDOM: function (measurements) { process.env.NODE_ENV !== 'production' ? warning(warnedAboutPrintDOM, '`ReactPerf.printDOM(...)` is deprecated. Use ' + '`ReactPerf.printOperations(...)` instead.') : void 0; warnedAboutPrintDOM = true; return ReactDefaultPerf.printOperations(measurements); }, printOperations: function (measurements) { measurements = unwrapLegacyMeasurements(measurements || ReactDefaultPerf._allMeasurements); var summary = ReactDefaultPerfAnalysis.getDOMSummary(measurements); console.table(summary.map(function (item) { var result = {}; result[DOMProperty.ID_ATTRIBUTE_NAME] = item.id; result.type = item.type; result.args = JSON.stringify(item.args, stripComplexValues); return result; })); console.log('Total time:', ReactDefaultPerfAnalysis.getTotalTime(measurements).toFixed(2) + ' ms'); }, _recordWrite: function (id, fnName, totalTime, args) { // TODO: totalTime isn't that useful since it doesn't count paints/reflows var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1]; var writes = entry.writes; writes[id] = writes[id] || []; writes[id].push({ type: fnName, time: totalTime, args: args }); }, measure: function (moduleName, fnName, func) { return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } var totalTime; var rv; var start; var entry = ReactDefaultPerf._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1]; if (fnName === '_renderNewRootComponent' || fnName === 'flushBatchedUpdates') { // A "measurement" is a set of metrics recorded for each flush. We want // to group the metrics for a given flush together so we can look at the // components that rendered and the DOM operations that actually // happened to determine the amount of "wasted work" performed. ReactDefaultPerf._allMeasurements.push(entry = { exclusive: {}, inclusive: {}, render: {}, counts: {}, writes: {}, displayNames: {}, hierarchy: {}, totalTime: 0, created: {} }); start = performanceNow(); rv = func.apply(this, args); entry.totalTime = performanceNow() - start; return rv; } else if (fnName === '_mountImageIntoNode' || moduleName === 'ReactDOMIDOperations' || moduleName === 'CSSPropertyOperations' || moduleName === 'DOMChildrenOperations' || moduleName === 'DOMPropertyOperations' || moduleName === 'ReactComponentBrowserEnvironment') { start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; if (fnName === '_mountImageIntoNode') { ReactDefaultPerf._recordWrite('', fnName, totalTime, args[0]); } else if (fnName === 'dangerouslyProcessChildrenUpdates') { // special format args[1].forEach(function (update) { var writeArgs = {}; if (update.fromIndex !== null) { writeArgs.fromIndex = update.fromIndex; } if (update.toIndex !== null) { writeArgs.toIndex = update.toIndex; } if (update.content !== null) { writeArgs.content = update.content; } ReactDefaultPerf._recordWrite(args[0]._rootNodeID, update.type, totalTime, writeArgs); }); } else { // basic format var id = args[0]; if (moduleName === 'EventPluginHub') { id = id._rootNodeID; } else if (fnName === 'replaceNodeWithMarkup') { // Old node is already unmounted; can't get its instance id = ReactDOMComponentTree.getInstanceFromNode(args[1].node)._rootNodeID; } else if (fnName === 'replaceDelimitedText') { id = getID(ReactDOMComponentTree.getInstanceFromNode(args[0])); } else if (typeof id === 'object') { id = getID(ReactDOMComponentTree.getInstanceFromNode(args[0])); } ReactDefaultPerf._recordWrite(id, fnName, totalTime, Array.prototype.slice.call(args, 1)); } return rv; } else if (moduleName === 'ReactCompositeComponent' && (fnName === 'mountComponent' || fnName === 'updateComponent' || // TODO: receiveComponent()? fnName === '_renderValidatedComponent')) { if (this._currentElement.type === ReactMount.TopLevelWrapper) { return func.apply(this, args); } var rootNodeID = getIDOfComposite(this); var isRender = fnName === '_renderValidatedComponent'; var isMount = fnName === 'mountComponent'; var mountStack = ReactDefaultPerf._mountStack; if (isRender) { addValue(entry.counts, rootNodeID, 1); } else if (isMount) { entry.created[rootNodeID] = true; mountStack.push(0); } ReactDefaultPerf._compositeStack.push(rootNodeID); start = performanceNow(); rv = func.apply(this, args); totalTime = performanceNow() - start; ReactDefaultPerf._compositeStack.pop(); if (isRender) { addValue(entry.render, rootNodeID, totalTime); } else if (isMount) { var subMountTime = mountStack.pop(); mountStack[mountStack.length - 1] += totalTime; addValue(entry.exclusive, rootNodeID, totalTime - subMountTime); addValue(entry.inclusive, rootNodeID, totalTime); } else { addValue(entry.inclusive, rootNodeID, totalTime); } entry.displayNames[rootNodeID] = { current: this.getName(), owner: this._currentElement._owner ? this._currentElement._owner.getName() : '<root>' }; return rv; } else if ((moduleName === 'ReactDOMComponent' || moduleName === 'ReactDOMTextComponent') && (fnName === 'mountComponent' || fnName === 'receiveComponent')) { rv = func.apply(this, args); entry.hierarchy[getID(this)] = ReactDefaultPerf._compositeStack.slice(); return rv; } else { return func.apply(this, args); } }; } }; module.exports = ReactDefaultPerf; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 157 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDefaultPerfAnalysis */ 'use strict'; // Don't try to save users less than 1.2ms (a number I made up) var _assign = __webpack_require__(4); var DONT_CARE_THRESHOLD = 1.2; var DOM_OPERATION_TYPES = { '_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', 'replaceDelimitedText': 'replace' }; function getTotalTime(measurements) { // TODO: return number of DOM ops? could be misleading. // TODO: measure dropped frames after reconcile? // TODO: log total time of each reconcile and the top-level component // class that triggered it. var totalTime = 0; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; totalTime += measurement.totalTime; } return totalTime; } function getDOMSummary(measurements) { var items = []; measurements.forEach(function (measurement) { Object.keys(measurement.writes).forEach(function (id) { measurement.writes[id].forEach(function (write) { items.push({ id: id, type: DOM_OPERATION_TYPES[write.type] || write.type, args: write.args }); }); }); }); return items; } function getExclusiveSummary(measurements) { var candidates = {}; var displayName; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = _assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { displayName = measurement.displayNames[id].current; candidates[displayName] = candidates[displayName] || { componentName: displayName, inclusive: 0, exclusive: 0, render: 0, count: 0 }; if (measurement.render[id]) { candidates[displayName].render += measurement.render[id]; } if (measurement.exclusive[id]) { candidates[displayName].exclusive += measurement.exclusive[id]; } if (measurement.inclusive[id]) { candidates[displayName].inclusive += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[displayName].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (displayName in candidates) { if (candidates[displayName].exclusive >= DONT_CARE_THRESHOLD) { arr.push(candidates[displayName]); } } arr.sort(function (a, b) { return b.exclusive - a.exclusive; }); return arr; } function getInclusiveSummary(measurements, onlyClean) { var candidates = {}; var inclusiveKey; for (var i = 0; i < measurements.length; i++) { var measurement = measurements[i]; var allIDs = _assign({}, measurement.exclusive, measurement.inclusive); var cleanComponents; if (onlyClean) { cleanComponents = getUnchangedComponents(measurement); } for (var id in allIDs) { if (onlyClean && !cleanComponents[id]) { continue; } var displayName = measurement.displayNames[id]; // Inclusive time is not useful for many components without knowing where // they are instantiated. So we aggregate inclusive time with both the // owner and current displayName as the key. inclusiveKey = displayName.owner + ' > ' + displayName.current; candidates[inclusiveKey] = candidates[inclusiveKey] || { componentName: inclusiveKey, time: 0, count: 0 }; if (measurement.inclusive[id]) { candidates[inclusiveKey].time += measurement.inclusive[id]; } if (measurement.counts[id]) { candidates[inclusiveKey].count += measurement.counts[id]; } } } // Now make a sorted array with the results. var arr = []; for (inclusiveKey in candidates) { if (candidates[inclusiveKey].time >= DONT_CARE_THRESHOLD) { arr.push(candidates[inclusiveKey]); } } arr.sort(function (a, b) { return b.time - a.time; }); return arr; } function getUnchangedComponents(measurement) { // For a given reconcile, look at which components did not actually // render anything to the DOM and return a mapping of their ID to // the amount of time it took to render the entire subtree. var cleanComponents = {}; var writes = measurement.writes; var hierarchy = measurement.hierarchy; var dirtyComposites = {}; Object.keys(writes).forEach(function (id) { writes[id].forEach(function (write) { // Root mounting (innerHTML set) is recorded with an ID of '' if (id !== '' && hierarchy.hasOwnProperty(id)) { hierarchy[id].forEach(function (c) { return dirtyComposites[c] = true; }); } }); }); var allIDs = _assign({}, measurement.exclusive, measurement.inclusive); for (var id in allIDs) { var isDirty = false; // See if any of the DOM operations applied to this component's subtree. if (dirtyComposites[id]) { isDirty = true; } // check if component newly created if (measurement.created[id]) { isDirty = true; } if (!isDirty && measurement.counts[id] > 0) { cleanComponents[id] = true; } } return cleanComponents; } var ReactDefaultPerfAnalysis = { getExclusiveSummary: getExclusiveSummary, getInclusiveSummary: getInclusiveSummary, getDOMSummary: getDOMSummary, getTotalTime: getTotalTime }; module.exports = ReactDefaultPerfAnalysis; /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMount */ 'use strict'; var DOMLazyTree = __webpack_require__(75); var DOMProperty = __webpack_require__(36); var ReactBrowserEventEmitter = __webpack_require__(103); var ReactCurrentOwner = __webpack_require__(9); var ReactDOMComponentTree = __webpack_require__(35); var ReactDOMContainerInfo = __webpack_require__(159); var ReactDOMFeatureFlags = __webpack_require__(160); var ReactElement = __webpack_require__(8); var ReactFeatureFlags = __webpack_require__(57); var ReactInstrumentation = __webpack_require__(18); var ReactMarkupChecksum = __webpack_require__(161); var ReactPerf = __webpack_require__(58); var ReactReconciler = __webpack_require__(59); var ReactUpdateQueue = __webpack_require__(120); var ReactUpdates = __webpack_require__(55); var emptyObject = __webpack_require__(21); var instantiateReactComponent = __webpack_require__(116); var invariant = __webpack_require__(7); var setInnerHTML = __webpack_require__(79); var shouldUpdateReactComponent = __webpack_require__(121); var warning = __webpack_require__(10); var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME; var ROOT_ATTR_NAME = DOMProperty.ROOT_ATTRIBUTE_NAME; var ELEMENT_NODE_TYPE = 1; var DOC_NODE_TYPE = 9; var DOCUMENT_FRAGMENT_NODE_TYPE = 11; var instancesByReactRootID = {}; /** * Finds the index of the first character * that's not common between the two given strings. * * @return {number} the index of the character where the strings diverge */ function firstDifferenceIndex(string1, string2) { var minLen = Math.min(string1.length, string2.length); for (var i = 0; i < minLen; i++) { if (string1.charAt(i) !== string2.charAt(i)) { return i; } } return string1.length === string2.length ? -1 : minLen; } /** * @param {DOMElement|DOMDocument} container DOM element that may contain * a React component * @return {?*} DOM element that may have the reactRoot ID, or null. */ function getReactRootElementInContainer(container) { if (!container) { return null; } if (container.nodeType === DOC_NODE_TYPE) { return container.documentElement; } else { return container.firstChild; } } function internalGetID(node) { // If node is something like a window, document, or text node, none of // which support attributes or a .getAttribute method, gracefully return // the empty string, as if the attribute were missing. return node.getAttribute && node.getAttribute(ATTR_NAME) || ''; } /** * Mounts this component and inserts it into the DOM. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {ReactReconcileTransaction} transaction * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function mountComponentIntoNode(wrapperInstance, container, transaction, shouldReuseMarkup, context) { var markerName; if (ReactFeatureFlags.logTopLevelRenders) { var wrappedElement = wrapperInstance._currentElement.props; var type = wrappedElement.type; markerName = 'React mount: ' + (typeof type === 'string' ? type : type.displayName || type.name); console.time(markerName); } var markup = ReactReconciler.mountComponent(wrapperInstance, transaction, null, ReactDOMContainerInfo(wrapperInstance, container), context); if (markerName) { console.timeEnd(markerName); } wrapperInstance._renderedComponent._topLevelWrapper = wrapperInstance; ReactMount._mountImageIntoNode(markup, container, wrapperInstance, shouldReuseMarkup, transaction); } /** * Batched mount. * * @param {ReactComponent} componentInstance The instance to mount. * @param {DOMElement} container DOM element to mount into. * @param {boolean} shouldReuseMarkup If true, do not insert markup */ function batchedMountComponentIntoNode(componentInstance, container, shouldReuseMarkup, context) { var transaction = ReactUpdates.ReactReconcileTransaction.getPooled( /* useCreateElement */ !shouldReuseMarkup && ReactDOMFeatureFlags.useCreateElement); transaction.perform(mountComponentIntoNode, null, componentInstance, container, transaction, shouldReuseMarkup, context); ReactUpdates.ReactReconcileTransaction.release(transaction); } /** * Unmounts a component and removes it from the DOM. * * @param {ReactComponent} instance React component instance. * @param {DOMElement} container DOM element to unmount from. * @final * @internal * @see {ReactMount.unmountComponentAtNode} */ function unmountComponentFromNode(instance, container, safely) { ReactReconciler.unmountComponent(instance, safely); if (container.nodeType === DOC_NODE_TYPE) { container = container.documentElement; } // http://jsperf.com/emptying-a-node while (container.lastChild) { container.removeChild(container.lastChild); } } /** * True if the supplied DOM node has a direct React-rendered child that is * not a React root element. Useful for warning in `render`, * `unmountComponentAtNode`, etc. * * @param {?DOMElement} node The candidate DOM node. * @return {boolean} True if the DOM element contains a direct child that was * rendered by React but is not a root element. * @internal */ function hasNonRootReactChild(container) { var rootEl = getReactRootElementInContainer(container); if (rootEl) { var inst = ReactDOMComponentTree.getInstanceFromNode(rootEl); return !!(inst && inst._nativeParent); } } function getNativeRootInstanceInContainer(container) { var rootEl = getReactRootElementInContainer(container); var prevNativeInstance = rootEl && ReactDOMComponentTree.getInstanceFromNode(rootEl); return prevNativeInstance && !prevNativeInstance._nativeParent ? prevNativeInstance : null; } function getTopLevelWrapperInContainer(container) { var root = getNativeRootInstanceInContainer(container); return root ? root._nativeContainerInfo._topLevelWrapper : null; } /** * Temporary (?) hack so that we can store all top-level pending updates on * composites instead of having to worry about different types of components * here. */ var topLevelRootCounter = 1; var TopLevelWrapper = function () { this.rootID = topLevelRootCounter++; }; TopLevelWrapper.prototype.isReactComponent = {}; if (process.env.NODE_ENV !== 'production') { TopLevelWrapper.displayName = 'TopLevelWrapper'; } TopLevelWrapper.prototype.render = function () { // this.props is actually a ReactElement return this.props; }; /** * Mounting is the process of initializing a React component by creating its * representative DOM elements and inserting them into a supplied `container`. * Any prior content inside `container` is destroyed in the process. * * ReactMount.render( * component, * document.getElementById('container') * ); * * <div id="container"> <-- Supplied `container`. * <div data-reactid=".3"> <-- Rendered reactRoot of React * // ... component. * </div> * </div> * * Inside of `container`, the first element rendered is the "reactRoot". */ var ReactMount = { TopLevelWrapper: TopLevelWrapper, /** * Used by devtools. The keys are not important. */ _instancesByReactRootID: instancesByReactRootID, /** * This is a hook provided to support rendering React components while * ensuring that the apparent scroll position of its `container` does not * change. * * @param {DOMElement} container The `container` being rendered into. * @param {function} renderCallback This must be called once to do the render. */ scrollMonitor: function (container, renderCallback) { renderCallback(); }, /** * Take a component that's already mounted into the DOM and replace its props * @param {ReactComponent} prevComponent component instance already in the DOM * @param {ReactElement} nextElement component instance to render * @param {DOMElement} container container to render into * @param {?function} callback function triggered on completion */ _updateRootComponent: function (prevComponent, nextElement, container, callback) { ReactMount.scrollMonitor(container, function () { ReactUpdateQueue.enqueueElementInternal(prevComponent, nextElement); if (callback) { ReactUpdateQueue.enqueueCallbackInternal(prevComponent, callback); } }); return prevComponent; }, /** * Render a new component into the DOM. Hooked by devtools! * * @param {ReactElement} nextElement element to render * @param {DOMElement} container container to render into * @param {boolean} shouldReuseMarkup if we should skip the markup insertion * @return {ReactComponent} nextComponent */ _renderNewRootComponent: function (nextElement, container, shouldReuseMarkup, context) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, '_renderNewRootComponent(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from ' + 'render is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, '_registerComponent(...): Target container is not a DOM element.') : invariant(false) : void 0; ReactBrowserEventEmitter.ensureScrollValueMonitoring(); var componentInstance = instantiateReactComponent(nextElement); // The initial render is synchronous but any updates that happen during // rendering, in componentWillMount or componentDidMount, will be batched // according to the current batching strategy. ReactUpdates.batchedUpdates(batchedMountComponentIntoNode, componentInstance, container, shouldReuseMarkup, context); var wrapperID = componentInstance._instance.rootID; instancesByReactRootID[wrapperID] = componentInstance; if (process.env.NODE_ENV !== 'production') { ReactInstrumentation.debugTool.onMountRootComponent(componentInstance); } return componentInstance; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactComponent} parentComponent The conceptual parent of this render tree. * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { !(parentComponent != null && parentComponent._reactInternalInstance != null) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'parentComponent must be a valid React Component') : invariant(false) : void 0; return ReactMount._renderSubtreeIntoContainer(parentComponent, nextElement, container, callback); }, _renderSubtreeIntoContainer: function (parentComponent, nextElement, container, callback) { ReactUpdateQueue.validateCallback(callback, 'ReactDOM.render'); !ReactElement.isValidElement(nextElement) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'ReactDOM.render(): Invalid component element.%s', typeof nextElement === 'string' ? ' Instead of passing a string like \'div\', pass ' + 'React.createElement(\'div\') or <div />.' : typeof nextElement === 'function' ? ' Instead of passing a class like Foo, pass ' + 'React.createElement(Foo) or <Foo />.' : // Check if it quacks like an element nextElement != null && nextElement.props !== undefined ? ' This may be caused by unintentionally loading two independent ' + 'copies of React.' : '') : invariant(false) : void 0; process.env.NODE_ENV !== 'production' ? warning(!container || !container.tagName || container.tagName.toUpperCase() !== 'BODY', '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 nextWrappedElement = ReactElement(TopLevelWrapper, null, null, null, null, null, nextElement); var prevComponent = getTopLevelWrapperInContainer(container); if (prevComponent) { var prevWrappedElement = prevComponent._currentElement; var prevElement = prevWrappedElement.props; if (shouldUpdateReactComponent(prevElement, nextElement)) { var publicInst = prevComponent._renderedComponent.getPublicInstance(); var updatedCallback = callback && function () { callback.call(publicInst); }; ReactMount._updateRootComponent(prevComponent, nextWrappedElement, container, updatedCallback); return publicInst; } else { ReactMount.unmountComponentAtNode(container); } } var reactRootElement = getReactRootElementInContainer(container); var containerHasReactMarkup = reactRootElement && !!internalGetID(reactRootElement); var containerHasNonRootReactChild = hasNonRootReactChild(container); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, '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; if (!containerHasReactMarkup || reactRootElement.nextSibling) { var rootElementSibling = reactRootElement; while (rootElementSibling) { if (internalGetID(rootElementSibling)) { process.env.NODE_ENV !== 'production' ? warning(false, '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; } rootElementSibling = rootElementSibling.nextSibling; } } } var shouldReuseMarkup = containerHasReactMarkup && !prevComponent && !containerHasNonRootReactChild; var component = ReactMount._renderNewRootComponent(nextWrappedElement, container, shouldReuseMarkup, parentComponent != null ? parentComponent._reactInternalInstance._processChildContext(parentComponent._reactInternalInstance._context) : emptyObject)._renderedComponent.getPublicInstance(); if (callback) { callback.call(component); } return component; }, /** * Renders a React component into the DOM in the supplied `container`. * * If the React component was previously rendered into `container`, this will * perform an update on it and only mutate the DOM as necessary to reflect the * latest React component. * * @param {ReactElement} nextElement Component element to render. * @param {DOMElement} container DOM element to render into. * @param {?function} callback function triggered on completion * @return {ReactComponent} Component instance rendered in `container`. */ render: function (nextElement, container, callback) { return ReactMount._renderSubtreeIntoContainer(null, nextElement, container, callback); }, /** * Unmounts and destroys the React component rendered in the `container`. * * @param {DOMElement} container DOM element containing a React component. * @return {boolean} True if a component was found in and unmounted from * `container` */ unmountComponentAtNode: function (container) { // Various parts of our code (such as ReactCompositeComponent's // _renderValidatedComponent) assume that calls to render aren't nested; // verify that that's the case. (Strictly speaking, unmounting won't cause a // render but we still don't expect to be in a render call here.) process.env.NODE_ENV !== 'production' ? warning(ReactCurrentOwner.current == null, 'unmountComponentAtNode(): Render methods should be a pure function ' + 'of props and state; triggering nested component updates from render ' + 'is not allowed. If necessary, trigger nested updates in ' + 'componentDidUpdate. Check the render method of %s.', ReactCurrentOwner.current && ReactCurrentOwner.current.getName() || 'ReactCompositeComponent') : void 0; !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'unmountComponentAtNode(...): Target container is not a DOM element.') : invariant(false) : void 0; var prevComponent = getTopLevelWrapperInContainer(container); if (!prevComponent) { // Check if the node being unmounted was rendered by React, but isn't a // root node. var containerHasNonRootReactChild = hasNonRootReactChild(container); // Check if the container itself is a React root node. var isContainerReactRoot = container.nodeType === 1 && container.hasAttribute(ROOT_ATTR_NAME); if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(!containerHasNonRootReactChild, 'unmountComponentAtNode(): The node you\'re attempting to unmount ' + 'was rendered by React and is not a top-level container. %s', isContainerReactRoot ? '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; } return false; } delete instancesByReactRootID[prevComponent._instance.rootID]; ReactUpdates.batchedUpdates(unmountComponentFromNode, prevComponent, container, false); return true; }, _mountImageIntoNode: function (markup, container, instance, shouldReuseMarkup, transaction) { !(container && (container.nodeType === ELEMENT_NODE_TYPE || container.nodeType === DOC_NODE_TYPE || container.nodeType === DOCUMENT_FRAGMENT_NODE_TYPE)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'mountComponentIntoNode(...): Target container is not valid.') : invariant(false) : void 0; if (shouldReuseMarkup) { var rootElement = getReactRootElementInContainer(container); if (ReactMarkupChecksum.canReuseMarkup(markup, rootElement)) { ReactDOMComponentTree.precacheNode(instance, rootElement); return; } else { var checksum = rootElement.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); rootElement.removeAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); var rootMarkup = rootElement.outerHTML; rootElement.setAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME, checksum); var normalizedMarkup = markup; if (process.env.NODE_ENV !== 'production') { // because rootMarkup is retrieved from the DOM, various normalizations // will have occurred which will not be present in `markup`. Here, // insert markup into a <div> or <iframe> depending on the container // type to perform the same normalizations before comparing. var normalizer; if (container.nodeType === ELEMENT_NODE_TYPE) { normalizer = document.createElement('div'); normalizer.innerHTML = markup; normalizedMarkup = normalizer.innerHTML; } else { normalizer = document.createElement('iframe'); document.body.appendChild(normalizer); normalizer.contentDocument.write(markup); normalizedMarkup = normalizer.contentDocument.documentElement.outerHTML; document.body.removeChild(normalizer); } } var diffIndex = firstDifferenceIndex(normalizedMarkup, rootMarkup); var difference = ' (client) ' + normalizedMarkup.substring(diffIndex - 20, diffIndex + 20) + '\n (server) ' + rootMarkup.substring(diffIndex - 20, diffIndex + 20); !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, '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', difference) : invariant(false) : void 0; if (process.env.NODE_ENV !== 'production') { process.env.NODE_ENV !== 'production' ? warning(false, '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', difference) : void 0; } } } !(container.nodeType !== DOC_NODE_TYPE) ? process.env.NODE_ENV !== 'production' ? invariant(false, '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.') : invariant(false) : void 0; if (transaction.useCreateElement) { while (container.lastChild) { container.removeChild(container.lastChild); } DOMLazyTree.insertTreeBefore(container, markup, null); } else { setInnerHTML(container, markup); ReactDOMComponentTree.precacheNode(instance, container.firstChild); } } }; ReactPerf.measureMethods(ReactMount, 'ReactMount', { _renderNewRootComponent: '_renderNewRootComponent', _mountImageIntoNode: '_mountImageIntoNode' }); module.exports = ReactMount; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMContainerInfo */ 'use strict'; var validateDOMNesting = __webpack_require__(126); var DOC_NODE_TYPE = 9; function ReactDOMContainerInfo(topLevelWrapper, node) { var info = { _topLevelWrapper: topLevelWrapper, _idCounter: 1, _ownerDocument: node ? node.nodeType === DOC_NODE_TYPE ? node : node.ownerDocument : null, _node: node, _tag: node ? node.nodeName.toLowerCase() : null, _namespaceURI: node ? node.namespaceURI : null }; if (process.env.NODE_ENV !== 'production') { info._ancestorInfo = node ? validateDOMNesting.updatedAncestorInfo(null, info._tag, null) : null; } return info; } module.exports = ReactDOMContainerInfo; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 160 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactDOMFeatureFlags */ 'use strict'; var ReactDOMFeatureFlags = { useCreateElement: true }; module.exports = ReactDOMFeatureFlags; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactMarkupChecksum */ 'use strict'; var adler32 = __webpack_require__(162); var TAG_END = /\/?>/; var COMMENT_START = /^<\!\-\-/; var ReactMarkupChecksum = { CHECKSUM_ATTR_NAME: 'data-react-checksum', /** * @param {string} markup Markup string * @return {string} Markup string with checksum attribute attached */ addChecksumToMarkup: function (markup) { var checksum = adler32(markup); // Add checksum (handle both parent tags, comments and self-closing tags) if (COMMENT_START.test(markup)) { return markup; } else { return markup.replace(TAG_END, ' ' + ReactMarkupChecksum.CHECKSUM_ATTR_NAME + '="' + checksum + '"$&'); } }, /** * @param {string} markup to use * @param {DOMElement} element root React element * @returns {boolean} whether or not the markup is the same */ canReuseMarkup: function (markup, element) { var existingChecksum = element.getAttribute(ReactMarkupChecksum.CHECKSUM_ATTR_NAME); existingChecksum = existingChecksum && parseInt(existingChecksum, 10); var markupChecksum = adler32(markup); return markupChecksum === existingChecksum; } }; module.exports = ReactMarkupChecksum; /***/ }, /* 162 */ /***/ function(module, exports) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule adler32 */ 'use strict'; var MOD = 65521; // adler32 is not cryptographically strong, and is only used to sanity check that // markup generated on the server matches the markup generated on the client. // This implementation (a modified version of the SheetJS version) has been optimized // for our use case, at the expense of conforming to the adler32 specification // for non-ascii inputs. function adler32(data) { var a = 1; var b = 0; var i = 0; var l = data.length; var m = l & ~0x3; while (i < m) { var n = Math.min(i + 4096, m); for (; i < n; i += 4) { b += (a += data.charCodeAt(i)) + (a += data.charCodeAt(i + 1)) + (a += data.charCodeAt(i + 2)) + (a += data.charCodeAt(i + 3)); } a %= MOD; b %= MOD; } for (; i < l; i++) { b += a += data.charCodeAt(i); } a %= MOD; b %= MOD; return a | b << 16; } module.exports = adler32; /***/ }, /* 163 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ var performance = __webpack_require__(164); var performanceNow; /** * Detect if we can use `window.performance.now()` and gracefully fallback to * `Date.now()` if it doesn't exist. We need to support Firefox < 15 for now * because of Facebook's testing infrastructure. */ if (performance.now) { performanceNow = function () { return performance.now(); }; } else { performanceNow = function () { return Date.now(); }; } module.exports = performanceNow; /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @typechecks */ 'use strict'; var ExecutionEnvironment = __webpack_require__(48); var performance; if (ExecutionEnvironment.canUseDOM) { performance = window.performance || window.msPerformance || window.webkitPerformance; } module.exports = performance || {}; /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {/** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule findDOMNode */ 'use strict'; var ReactCurrentOwner = __webpack_require__(9); var ReactDOMComponentTree = __webpack_require__(35); var ReactInstanceMap = __webpack_require__(118); var getNativeComponentFromComposite = __webpack_require__(166); var invariant = __webpack_require__(7); var warning = __webpack_require__(10); /** * Returns the DOM node rendered by this element. * * @param {ReactComponent|DOMElement} componentOrElement * @return {?DOMElement} The root node of this element. */ function findDOMNode(componentOrElement) { if (process.env.NODE_ENV !== 'production') { var owner = ReactCurrentOwner.current; if (owner !== null) { process.env.NODE_ENV !== 'production' ? warning(owner._warnedAboutRefsInRender, '%s is accessing 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.', owner.getName() || 'A component') : void 0; owner._warnedAboutRefsInRender = true; } } if (componentOrElement == null) { return null; } if (componentOrElement.nodeType === 1) { return componentOrElement; } var inst = ReactInstanceMap.get(componentOrElement); if (inst) { inst = getNativeComponentFromComposite(inst); return inst ? ReactDOMComponentTree.getNodeFromInstance(inst) : null; } if (typeof componentOrElement.render === 'function') { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'findDOMNode was called on an unmounted component.') : invariant(false) : void 0; } else { true ? process.env.NODE_ENV !== 'production' ? invariant(false, 'Element appears to be neither ReactComponent nor DOMNode (keys: %s)', Object.keys(componentOrElement)) : invariant(false) : void 0; } } module.exports = findDOMNode; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3))) /***/ }, /* 166 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule getNativeComponentFromComposite */ 'use strict'; var ReactNodeTypes = __webpack_require__(119); function getNativeComponentFromComposite(inst) { var type; while ((type = inst._renderedNodeType) === ReactNodeTypes.COMPOSITE) { inst = inst._renderedComponent; } if (type === ReactNodeTypes.NATIVE) { return inst._renderedComponent; } else if (type === ReactNodeTypes.EMPTY) { return null; } } module.exports = getNativeComponentFromComposite; /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule renderSubtreeIntoContainer */ 'use strict'; var ReactMount = __webpack_require__(158); module.exports = ReactMount.renderSubtreeIntoContainer; /***/ } /******/ ]);
src/app.js
Ciunkos/ciunkos.com
import 'core-js/stable' import React from 'react' import { render } from 'react-dom' import 'styles/foundation' import 'styles/common' import Main from './Main' const rerender = Component => { const root = document.getElementById('app') render(<Component />, root) } rerender(Main) if (module.hot) { module.hot.accept('./Main', () => { rerender(Main) }) }
node_modules/react-navigation/src/views/CardStack/CardStack.js
jiangqizheng/ReactNative-BookProject
/* @flow */ import React, { Component } from 'react'; import clamp from 'clamp'; import { Animated, StyleSheet, PanResponder, Platform, View, I18nManager, Easing, } from 'react-native'; import Card from './Card'; import Header from '../Header/Header'; import NavigationActions from '../../NavigationActions'; import addNavigationHelpers from '../../addNavigationHelpers'; import SceneView from '../SceneView'; import type { NavigationAction, NavigationLayout, NavigationScreenProp, NavigationScene, NavigationRouter, NavigationState, NavigationScreenDetails, NavigationStackScreenOptions, HeaderMode, ViewStyleProp, TransitionConfig, } from '../../TypeDefinition'; import TransitionConfigs from './TransitionConfigs'; const emptyFunction = () => {}; type Props = { screenProps?: {}, headerMode: HeaderMode, headerComponent?: ReactClass<*>, mode: 'card' | 'modal', navigation: NavigationScreenProp<NavigationState, NavigationAction>, router: NavigationRouter< NavigationState, NavigationAction, NavigationStackScreenOptions >, cardStyle?: ViewStyleProp, onTransitionStart?: () => void, onTransitionEnd?: () => void, style?: any, // TODO: Remove /** * Optional custom animation when transitioning between screens. */ transitionConfig?: () => TransitionConfig, // NavigationTransitionProps: layout: NavigationLayout, navigation: NavigationScreenProp<NavigationState, NavigationAction>, position: Animated.Value, progress: Animated.Value, scenes: Array<NavigationScene>, scene: NavigationScene, index: number, }; /** * The max duration of the card animation in milliseconds after released gesture. * The actual duration should be always less then that because the rest distance * is always less then the full distance of the layout. */ const ANIMATION_DURATION = 500; /** * The gesture distance threshold to trigger the back behavior. For instance, * `1/2` means that moving greater than 1/2 of the width of the screen will * trigger a back action */ const POSITION_THRESHOLD = 1 / 2; /** * The threshold (in pixels) to start the gesture action. */ const RESPOND_THRESHOLD = 20; /** * The distance of touch start from the edge of the screen where the gesture will be recognized */ const GESTURE_RESPONSE_DISTANCE_HORIZONTAL = 25; const GESTURE_RESPONSE_DISTANCE_VERTICAL = 135; const animatedSubscribeValue = (animatedValue: Animated.Value) => { if (!animatedValue.__isNative) { return; } if (Object.keys(animatedValue._listeners).length === 0) { animatedValue.addListener(emptyFunction); } }; class CardStack extends Component { /** * Used to identify the starting point of the position when the gesture starts, such that it can * be updated according to its relative position. This means that a card can effectively be * "caught"- If a gesture starts while a card is animating, the card does not jump into a * corresponding location for the touch. */ _gestureStartValue: number = 0; // tracks if a touch is currently happening _isResponding: boolean = false; /** * immediateIndex is used to represent the expected index that we will be on after a * transition. To achieve a smooth animation when swiping back, the action to go back * doesn't actually fire until the transition completes. The immediateIndex is used during * the transition so that gestures can be handled correctly. This is a work-around for * cases when the user quickly swipes back several times. */ _immediateIndex: ?number = null; _screenDetails: { [key: string]: ?NavigationScreenDetails<NavigationStackScreenOptions>, } = {}; props: Props; componentWillReceiveProps(props: Props) { if (props.screenProps !== this.props.screenProps) { this._screenDetails = {}; } props.scenes.forEach((newScene: *) => { if ( this._screenDetails[newScene.key] && this._screenDetails[newScene.key].state !== newScene.route ) { this._screenDetails[newScene.key] = null; } }); } _getScreenDetails = (scene: NavigationScene): NavigationScreenDetails<*> => { const { screenProps, navigation, router } = this.props; let screenDetails = this._screenDetails[scene.key]; if (!screenDetails || screenDetails.state !== scene.route) { const screenNavigation = addNavigationHelpers({ ...navigation, state: scene.route, }); screenDetails = { state: scene.route, navigation: screenNavigation, options: router.getScreenOptions(screenNavigation, screenProps), }; this._screenDetails[scene.key] = screenDetails; } return screenDetails; }; _renderHeader( scene: NavigationScene, headerMode: HeaderMode ): ?React.Element<*> { const { header } = this._getScreenDetails(scene).options; if (typeof header !== 'undefined' && typeof header !== 'function') { return header; } const renderHeader = header || ((props: *) => <Header {...props} />); // We need to explicitly exclude `mode` since Flow doesn't see // mode: headerMode override below and reports prop mismatch const { mode, ...passProps } = this.props; return renderHeader({ ...passProps, scene, mode: headerMode, getScreenDetails: this._getScreenDetails, }); } // eslint-disable-next-line class-methods-use-this _animatedSubscribe(props: Props) { // Hack to make this work with native driven animations. We add a single listener // so the JS value of the following animated values gets updated. We rely on // some Animated private APIs and not doing so would require using a bunch of // value listeners but we'd have to remove them to not leak and I'm not sure // when we'd do that with the current structure we have. `stopAnimation` callback // is also broken with native animated values that have no listeners so if we // want to remove this we have to fix this too. animatedSubscribeValue(props.layout.width); animatedSubscribeValue(props.layout.height); animatedSubscribeValue(props.position); } _reset(resetToIndex: number, duration: number): void { Animated.timing(this.props.position, { toValue: resetToIndex, duration, easing: Easing.linear(), useNativeDriver: this.props.position.__isNative, }).start(); } _goBack(backFromIndex: number, duration: number) { const { navigation, position, scenes } = this.props; const toValue = Math.max(backFromIndex - 1, 0); // set temporary index for gesture handler to respect until the action is // dispatched at the end of the transition. this._immediateIndex = toValue; Animated.timing(position, { toValue, duration, easing: Easing.linear(), useNativeDriver: position.__isNative, }).start(() => { this._immediateIndex = null; const backFromScene = scenes.find((s: *) => s.index === toValue + 1); if (!this._isResponding && backFromScene) { navigation.dispatch( NavigationActions.back({ key: backFromScene.route.key }) ); } }); } render(): React.Element<*> { let floatingHeader = null; const headerMode = this._getHeaderMode(); if (headerMode === 'float') { floatingHeader = this._renderHeader(this.props.scene, headerMode); } const { navigation, position, layout, scene, scenes, mode } = this.props; const { index } = navigation.state; const isVertical = mode === 'modal'; const responder = PanResponder.create({ onPanResponderTerminate: () => { this._isResponding = false; this._reset(index, 0); }, onPanResponderGrant: () => { position.stopAnimation((value: number) => { this._isResponding = true; this._gestureStartValue = value; }); }, onMoveShouldSetPanResponder: ( event: { nativeEvent: { pageY: number, pageX: number } }, gesture: any ) => { if (index !== scene.index) { return false; } const immediateIndex = this._immediateIndex == null ? index : this._immediateIndex; const currentDragDistance = gesture[isVertical ? 'dy' : 'dx']; const currentDragPosition = event.nativeEvent[isVertical ? 'pageY' : 'pageX']; const axisLength = isVertical ? layout.height.__getValue() : layout.width.__getValue(); const axisHasBeenMeasured = !!axisLength; // Measure the distance from the touch to the edge of the screen const screenEdgeDistance = currentDragPosition - currentDragDistance; // Compare to the gesture distance relavant to card or modal const { gestureResponseDistance: userGestureResponseDistance = {}, } = this._getScreenDetails(scene).options; const gestureResponseDistance = isVertical ? userGestureResponseDistance.vertical || GESTURE_RESPONSE_DISTANCE_VERTICAL : userGestureResponseDistance.horizontal || GESTURE_RESPONSE_DISTANCE_HORIZONTAL; // GESTURE_RESPONSE_DISTANCE is about 25 or 30. Or 135 for modals if (screenEdgeDistance > gestureResponseDistance) { // Reject touches that started in the middle of the screen return false; } const hasDraggedEnough = Math.abs(currentDragDistance) > RESPOND_THRESHOLD; const isOnFirstCard = immediateIndex === 0; const shouldSetResponder = hasDraggedEnough && axisHasBeenMeasured && !isOnFirstCard; return shouldSetResponder; }, onPanResponderMove: (event: any, gesture: any) => { // Handle the moving touches for our granted responder const startValue = this._gestureStartValue; const axis = isVertical ? 'dy' : 'dx'; const axisDistance = isVertical ? layout.height.__getValue() : layout.width.__getValue(); const currentValue = I18nManager.isRTL && axis === 'dx' ? startValue + gesture[axis] / axisDistance : startValue - gesture[axis] / axisDistance; const value = clamp(index - 1, currentValue, index); position.setValue(value); }, onPanResponderTerminationRequest: () => // Returning false will prevent other views from becoming responder while // the navigation view is the responder (mid-gesture) false, onPanResponderRelease: (event: any, gesture: any) => { if (!this._isResponding) { return; } this._isResponding = false; const immediateIndex = this._immediateIndex == null ? index : this._immediateIndex; // Calculate animate duration according to gesture speed and moved distance const axisDistance = isVertical ? layout.height.__getValue() : layout.width.__getValue(); const movedDistance = gesture[isVertical ? 'dy' : 'dx']; const gestureVelocity = gesture[isVertical ? 'vy' : 'vx']; const defaultVelocity = axisDistance / ANIMATION_DURATION; const velocity = Math.max(Math.abs(gestureVelocity), defaultVelocity); const resetDuration = movedDistance / velocity; const goBackDuration = (axisDistance - movedDistance) / velocity; // To asyncronously get the current animated value, we need to run stopAnimation: position.stopAnimation((value: number) => { // If the speed of the gesture release is significant, use that as the indication // of intent if (gestureVelocity < -0.5) { this._reset(immediateIndex, resetDuration); return; } if (gestureVelocity > 0.5) { this._goBack(immediateIndex, goBackDuration); return; } // Then filter based on the distance the screen was moved. Over a third of the way swiped, // and the back will happen. if (value <= index - POSITION_THRESHOLD) { this._goBack(immediateIndex, goBackDuration); } else { this._reset(immediateIndex, resetDuration); } }); }, }); const { options } = this._getScreenDetails(scene); const gesturesEnabled = typeof options.gesturesEnabled === 'boolean' ? options.gesturesEnabled : Platform.OS === 'ios'; const handlers = gesturesEnabled ? responder.panHandlers : {}; const containerStyle = [ styles.container, this._getTransitionConfig().containerStyle, ]; return ( <View {...handlers} style={containerStyle}> <View style={styles.scenes}> {scenes.map((s: *) => this._renderCard(s))} </View> {floatingHeader} </View> ); } _getHeaderMode(): HeaderMode { if (this.props.headerMode) { return this.props.headerMode; } if (Platform.OS === 'android' || this.props.mode === 'modal') { return 'screen'; } return 'float'; } _renderInnerScene( SceneComponent: ReactClass<*>, scene: NavigationScene ): React.Element<any> { const { navigation } = this._getScreenDetails(scene); const { screenProps } = this.props; const headerMode = this._getHeaderMode(); if (headerMode === 'screen') { return ( <View style={styles.container}> <View style={{ flex: 1 }}> <SceneView screenProps={screenProps} navigation={navigation} component={SceneComponent} /> </View> {this._renderHeader(scene, headerMode)} </View> ); } return ( <SceneView screenProps={this.props.screenProps} navigation={navigation} component={SceneComponent} /> ); } _getTransitionConfig = () => { const isModal = this.props.mode === 'modal'; /* $FlowFixMe */ return TransitionConfigs.getTransitionConfig( this.props.transitionConfig, {}, {}, isModal ); }; _renderCard = (scene: NavigationScene): React.Element<*> => { const { screenInterpolator } = this._getTransitionConfig(); const style = screenInterpolator && screenInterpolator({ ...this.props, scene }); const SceneComponent = this.props.router.getComponentForRouteName( scene.route.routeName ); return ( <Card {...this.props} key={`card_${scene.key}`} style={[style, this.props.cardStyle]} scene={scene} > {this._renderInnerScene(SceneComponent, scene)} </Card> ); }; } const styles = StyleSheet.create({ container: { flex: 1, // Header is physically rendered after scenes so that Header won't be // covered by the shadows of the scenes. // That said, we'd have use `flexDirection: 'column-reverse'` to move // Header above the scenes. flexDirection: 'column-reverse', }, scenes: { flex: 1, }, }); export default CardStack;
node_modules/react-icons/io/ios-cloudy-night-outline.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const IoIosCloudyNightOutline = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m14.8 17.5c-2.7 0-5 2.2-5 4.8v1l0.1 0.8c-0.4 0-0.9 0-1.1 0-1.5 0.3-2.5 1.4-2.5 2.9 0 0.8 0.2 1.5 0.7 2.1s1.3 0.8 2.1 0.8h12.2c2.1 0 3.9-1.7 3.9-3.8s-1.8-3.9-3.9-3.9c-0.1 0-0.3 0.1-0.4 0.1l-1.1 0.1-0.3-1.1c-0.2-1.1-0.8-2-1.7-2.7s-1.9-1.1-3-1.1z m0-1.2c2.9 0 5.3 2 5.9 4.7h0.6c2.8 0 5.1 2.3 5.1 5.1s-2.3 5.2-5.1 5.2h-12.2c-2.2 0-4.1-1.9-4.1-4.2 0-2.1 1.6-4 3.7-4.1v-0.7c0-3.3 2.7-6.1 6.1-6.1z m18.4 7.6c0.6 0 1.2-0.1 1.8-0.3-0.3 0.5-0.7 1.1-1.1 1.6-1.6 1.8-3.9 3.2-6.6 3.5 0.4-0.5 0.5-1 0.7-1.5 1.5-0.3 2.8-1 3.9-2-1.4 0-2.8-0.4-3.9-1-1.8-0.8-3.3-2.2-4.4-4-1.1-1.6-1.7-3.7-1.7-5.8 0-1.2 0.1-2.4 0.5-3.5-1.9 1-3.3 2.6-4.1 4.6-0.4-0.1-1-0.3-1.4-0.3 1.1-2.9 3.5-5.1 6.4-6.1 0.6-0.1 1.2-0.3 1.9-0.4-0.4 0.5-0.7 1.1-1 1.6-0.6 1.3-0.9 2.7-0.9 4.1 0 2.5 0.9 4.9 2.7 6.7s4.2 2.8 6.7 2.8h0.5z"/></g> </Icon> ) export default IoIosCloudyNightOutline
test/regressions/tests/Menu/MenuContentAnchors.js
kybarg/material-ui
import React from 'react'; import PropTypes from 'prop-types'; import Grid from '@material-ui/core/Grid'; import Button from '@material-ui/core/Button'; import Menu from '@material-ui/core/Menu'; import MenuItem from '@material-ui/core/MenuItem'; import { makeStyles } from '@material-ui/core/styles'; const useMenuStyles = makeStyles({ anchorEl: { // give the anchor enough space so that the menu can align the selected item margin: '80px 0', }, }); /** * Item 1 or 2 can be pre-selected to check alignment between anchorEl and menuitem */ function SimpleMenu({ selectedItem, ...props }) { const [anchorEl, setAnchorEl] = React.useState(null); const classes = useMenuStyles(); return ( <Grid item> <Button className={classes.anchorEl} ref={setAnchorEl}> open button </Button> <Menu anchorEl={anchorEl} open={Boolean(anchorEl)} transitionDuration={0} {...props}> {null} <MenuItem selected={selectedItem === 1}>Item 1</MenuItem> <MenuItem selected={selectedItem === 2}>Item 2</MenuItem> <MenuItem>Item 3</MenuItem> </Menu> </Grid> ); } SimpleMenu.propTypes = { selectedItem: PropTypes.number }; export default function MenuContentAnchors() { return ( <Grid container> <SimpleMenu variant="selectedMenu" /> <SimpleMenu variant="menu" /> <SimpleMenu selectedItem={1} variant="selectedMenu" /> <SimpleMenu selectedItem={1} variant="menu" /> <SimpleMenu selectedItem={2} variant="selectedMenu" /> <SimpleMenu selectedItem={2} variant="menu" /> </Grid> ); }
app/javascript/mastodon/components/button.js
kirakiratter/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export default class Button extends React.PureComponent { static propTypes = { text: PropTypes.node, onClick: PropTypes.func, disabled: PropTypes.bool, block: PropTypes.bool, secondary: PropTypes.bool, size: PropTypes.number, className: PropTypes.string, title: PropTypes.string, style: PropTypes.object, children: PropTypes.node, }; static defaultProps = { size: 36, }; handleClick = (e) => { if (!this.props.disabled) { this.props.onClick(e); } } setRef = (c) => { this.node = c; } focus() { this.node.focus(); } render () { const style = { padding: `0 ${this.props.size / 2.25}px`, height: `${this.props.size}px`, lineHeight: `${this.props.size}px`, ...this.props.style, }; const className = classNames('button', this.props.className, { 'button-secondary': this.props.secondary, 'button--block': this.props.block, }); return ( <button className={className} disabled={this.props.disabled} onClick={this.handleClick} ref={this.setRef} style={style} title={this.props.title} > {this.props.text || this.props.children} </button> ); } }
src/components/WaveDot/index.js
lumio/waveblock
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'styled-components'; function stretchValue( scale, min, max ) { return ( ( max - min ) * scale ) + min; } function styleByMode( value, mode ) { if ( mode === 'square' ) { return `scale( ${ value } )`; } return `scaleX( .2 ) scaleY( ${ value } )`; } const Dot = styled.div` width: ${ props => ( props.mode === 'square' ? '33.33%' : '6%' ) }; height: 33.33%; transition: background-color 1s, transform .05s ease; border-radius: ${ props => ( props.mode === 'square' ? '100%' : '0' ) }; `; const WaveDot = props => ( <Dot mode={ props.mode } style={ { transform: styleByMode( stretchValue( props.scale, props.min, props.max ), props.mode, ), opacity: stretchValue( props.scale, .25, 1 ), backgroundColor: props.color, } } /> ); WaveDot.propTypes = { scale: PropTypes.number.isRequired, min: PropTypes.number, max: PropTypes.number, mode: PropTypes.string, color: PropTypes.string, }; WaveDot.defaultProps = { min: .08, max: 1, mode: 'square', color: '#fff', }; export default WaveDot;
src/svg-icons/action/exit-to-app.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionExitToApp = (props) => ( <SvgIcon {...props}> <path d="M10.09 15.59L11.5 17l5-5-5-5-1.41 1.41L12.67 11H3v2h9.67l-2.58 2.59zM19 3H5c-1.11 0-2 .9-2 2v4h2V5h14v14H5v-4H3v4c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ActionExitToApp = pure(ActionExitToApp); ActionExitToApp.displayName = 'ActionExitToApp'; ActionExitToApp.muiName = 'SvgIcon'; export default ActionExitToApp;
portfolio-site/src/scenes/home/home.js
dave5801/Portfolio
import React, { Component } from 'react'; import './home.css'; import Navbar from './navigation/navbar'; import Footer from './Footer/footer'; class Home extends Component { render() { return ( <div className="Home"> <Navbar></Navbar> <Footer></Footer> </div> ); } } export default Home;
js/src/Signer/PendingList/pendingList.js
destenson/ethcore--parity
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import BigNumber from 'bignumber.js'; import React from 'react'; import { FormattedMessage } from 'react-intl'; import PropTypes from 'prop-types'; import PendingItem from '../PendingItem'; import styles from './pendingList.css'; export default function PendingList ({ accounts, className, gasLimit, netVersion, onConfirm, onReject, pendingItems }) { if (!pendingItems.length) { return ( <div className={ `${styles.none} ${className}` }> <FormattedMessage id='signer.embedded.noPending' defaultMessage='There are currently no pending requests awaiting your confirmation' /> </div> ); } return ( <div className={ `${styles.list} ${className}` }> { pendingItems .sort((a, b) => new BigNumber(a.id).cmp(b.id)) .map((data, index) => ( <PendingItem accounts={ accounts } data={ data } gasLimit={ gasLimit } isFocussed={ index === 0 } key={ data.id } netVersion={ netVersion } onConfirm={ onConfirm } onReject={ onReject } /> )) } </div> ); } PendingList.propTypes = { accounts: PropTypes.object.isRequired, className: PropTypes.string, gasLimit: PropTypes.object.isRequired, netVersion: PropTypes.string.isRequired, onConfirm: PropTypes.func.isRequired, onReject: PropTypes.func.isRequired, pendingItems: PropTypes.object.isRequired };
web-app/js-lib/dojo-release-1.5.0-src/dojox/widget/FisheyeLite.js
dotunolafunmiloye/owf-framework
dojo.provide("dojox.widget.FisheyeLite"); dojo.experimental("dojox.widget.FisheyeLite"); dojo.require("dijit._Widget"); dojo.require("dojo.fx.easing"); dojo.declare("dojox.widget.FisheyeLite", dijit._Widget, { // summary: A Light-weight Fisheye Component, or an exhanced version // of dojo.fx.Toggler ... // // description: // A Simple FisheyeList-like widget which (in the interest of // performance) relies on well-styled content for positioning, // and natural page layout for rendering. // // use position:absolute/relative nodes to prevent layout // changes, and use caution when seleting properties to // scale. Negative scaling works, but some properties // react poorly to being set to negative values, IE being // particularly annoying in that regard. // // quirk: uses the domNode as the target of the animation // unless it finds a node class="fisheyeTarget" in the container // being turned into a FisheyeLite instance // // example: // | // make all the LI's in a node Fisheye's: // | dojo.query("#node li").forEach(function(n){ // | new dojox.widget.FisheyeLite({},n); // | }); // // // example: // | new dojox.widget.FisheyeLite({ // | properties:{ // | // height is literal, width is multiplied // | height:{ end: 200 }, width:2.3 // | } // | }, "someNode"); // // duationIn: Integer // The time (in ms) the run the show animation durationIn: 350, // easeIn: Function // An easing function to use for the show animation easeIn: dojo.fx.easing.backOut, // durationOut: Integer // The Time (in ms) to run the hide animation durationOut: 1420, // easeOut: Function // An easing function to use for the hide animation easeOut: dojo.fx.easing.elasticOut, // properties: Object // An object of "property":scale pairs, or "property":{} pairs. // defaults to font-size with a scale of 2.75 // If a named property is an integer or float, the "scale multiplier" // is used. If the named property is an object, that object is mixed // into the animation directly. eg: height:{ end:20, units:"em" } properties: null, // units: String // Sometimes, you need to specify a unit. Should be part of // properties attrib, but was trying to shorthand the logic there units:"px", constructor: function(props, node){ this.properties = props.properties || { fontSize: 2.75 } }, postCreate: function(){ this.inherited(arguments); this._target = dojo.query(".fisheyeTarget", this.domNode)[0] || this.domNode; this._makeAnims(); this.connect(this.domNode, "onmouseover", "show"); this.connect(this.domNode, "onmouseout", "hide"); this.connect(this._target, "onclick", "onClick"); }, show: function(){ // summary: // Show this Fisheye item. this._runningOut.stop(); this._runningIn.play(); }, hide: function(){ // summary: // Hide this fisheye item on mouse leave this._runningIn.stop(); this._runningOut.play(); }, _makeAnims: function(){ // summary: // Pre-generate the animations // create two properties: objects, one for each "state" var _in = {}, _out = {}, cs = dojo.getComputedStyle(this._target); for(var p in this.properties){ var prop = this.properties[p], deep = dojo.isObject(prop), v = parseInt(cs[p]) ; // note: do not set negative scale for [a list of properties] for IE support // note: filter:'s are your own issue, too ;) // FIXME: this.unit here is bad, likely. d._toPixelValue ? _out[p] = { end: v, units:this.units }; _in[p] = deep ? prop : { end: prop * v, units:this.units }; } this._runningIn = dojo.animateProperty({ node: this._target, easing: this.easeIn, duration: this.durationIn, properties: _in }); this._runningOut = dojo.animateProperty({ node: this._target, duration: this.durationOut, easing: this.easeOut, properties: _out }); this.connect(this._runningIn, "onEnd", dojo.hitch(this, "onSelected", this)); }, onClick: function(/* Event */e){ // summary: stub function fired when target is clicked // connect or override to use. }, onSelected: function(/* Object */e){ // summary: stub function fired when Fisheye Item is fully visible and // hovered. connect or override use. } });
client/modules/core/components/navigation.js
markoshust/mantra-sample-blog-app
import React from 'react'; const Navigation = () => ( <div> <b> Navigation: </b> <a href="/">Home</a> | <a href="/new-post">New Post</a> </div> ); export default Navigation;
src/svg-icons/maps/hotel.js
rhaedes/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsHotel = (props) => ( <SvgIcon {...props}> <path d="M7 13c1.66 0 3-1.34 3-3S8.66 7 7 7s-3 1.34-3 3 1.34 3 3 3zm12-6h-8v7H3V5H1v15h2v-3h18v3h2v-9c0-2.21-1.79-4-4-4z"/> </SvgIcon> ); MapsHotel = pure(MapsHotel); MapsHotel.displayName = 'MapsHotel'; export default MapsHotel;
ajax/libs/apexcharts/3.6.11/apexcharts.js
cdnjs/cdnjs
/*! * ApexCharts v3.6.10 * (c) 2018-2019 Juned Chhipa * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = global || self, global.ApexCharts = factory()); }(this, function () { 'use strict'; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _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 _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } } function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } /* ** Generic functions which are not dependent on ApexCharts */ var Utils = /*#__PURE__*/ function () { function Utils() { _classCallCheck(this, Utils); } _createClass(Utils, [{ key: "shadeRGBColor", value: function shadeRGBColor(percent, color) { var f = color.split(','), t = percent < 0 ? 0 : 255, p = percent < 0 ? percent * -1 : percent, R = parseInt(f[0].slice(4)), G = parseInt(f[1]), B = parseInt(f[2]); return 'rgb(' + (Math.round((t - R) * p) + R) + ',' + (Math.round((t - G) * p) + G) + ',' + (Math.round((t - B) * p) + B) + ')'; } }, { key: "shadeHexColor", value: function shadeHexColor(percent, color) { var f = parseInt(color.slice(1), 16), t = percent < 0 ? 0 : 255, p = percent < 0 ? percent * -1 : percent, R = f >> 16, G = f >> 8 & 0x00ff, B = f & 0x0000ff; return '#' + (0x1000000 + (Math.round((t - R) * p) + R) * 0x10000 + (Math.round((t - G) * p) + G) * 0x100 + (Math.round((t - B) * p) + B)).toString(16).slice(1); } // beautiful color shading blending code // http://stackoverflow.com/questions/5560248/programmatically-lighten-or-darken-a-hex-color-or-rgb-and-blend-colors }, { key: "shadeColor", value: function shadeColor(p, color) { if (color.length > 7) return this.shadeRGBColor(p, color);else return this.shadeHexColor(p, color); } }], [{ key: "bind", value: function bind(fn, me) { return function () { return fn.apply(me, arguments); }; } }, { key: "isObject", value: function isObject(item) { return item && _typeof(item) === 'object' && !Array.isArray(item) && item != null; } }, { key: "listToArray", value: function listToArray(list) { var i, array = []; for (i = 0; i < list.length; i++) { array[i] = list[i]; } return array; } // to extend defaults with user options // credit: http://stackoverflow.com/questions/27936772/deep-object-merging-in-es6-es7#answer-34749873 }, { key: "extend", value: function extend(target, source) { var _this = this; if (typeof Object.assign !== 'function') { (function () { Object.assign = function (target) { if (target === undefined || target === null) { throw new TypeError('Cannot convert undefined or null to object'); } var output = Object(target); for (var index = 1; index < arguments.length; index++) { var _source = arguments[index]; if (_source !== undefined && _source !== null) { for (var nextKey in _source) { if (_source.hasOwnProperty(nextKey)) { output[nextKey] = _source[nextKey]; } } } } return output; }; })(); } var output = Object.assign({}, target); if (this.isObject(target) && this.isObject(source)) { Object.keys(source).forEach(function (key) { if (_this.isObject(source[key])) { if (!(key in target)) { Object.assign(output, _defineProperty({}, key, source[key])); } else { output[key] = _this.extend(target[key], source[key]); } } else { Object.assign(output, _defineProperty({}, key, source[key])); } }); } return output; } }, { key: "extendArray", value: function extendArray(arrToExtend, resultArr) { var extendedArr = []; arrToExtend.map(function (item) { extendedArr.push(Utils.extend(resultArr, item)); }); arrToExtend = extendedArr; return arrToExtend; } // If month counter exceeds 12, it starts again from 1 }, { key: "monthMod", value: function monthMod(month) { return month % 12; } }, { key: "addProps", value: function addProps(obj, arr, val) { if (typeof arr === 'string') { arr = arr.split('.'); } obj[arr[0]] = obj[arr[0]] || {}; var tmpObj = obj[arr[0]]; if (arr.length > 1) { arr.shift(); this.addProps(tmpObj, arr, val); } else { obj[arr[0]] = val; } return obj; } }, { key: "clone", value: function clone(source) { if (Object.prototype.toString.call(source) === '[object Array]') { var cloneResult = []; for (var i = 0; i < source.length; i++) { cloneResult[i] = this.clone(source[i]); } return cloneResult; } else if (_typeof(source) === 'object') { var _cloneResult = {}; for (var prop in source) { if (source.hasOwnProperty(prop)) { _cloneResult[prop] = this.clone(source[prop]); } } return _cloneResult; } else { return source; } } }, { key: "log10", value: function log10(x) { return Math.log(x) / Math.LN10; } }, { key: "roundToBase10", value: function roundToBase10(x) { return Math.pow(10, Math.floor(Math.log10(x))); } }, { key: "roundToBase", value: function roundToBase(x, base) { return Math.pow(base, Math.floor(Math.log(x) / Math.log(base))); } }, { key: "parseNumber", value: function parseNumber(val) { if (val === null) return val; return parseFloat(val); } }, { key: "noExponents", value: function noExponents(val) { var data = String(val).split(/[eE]/); if (data.length == 1) return data[0]; var z = '', sign = val < 0 ? '-' : '', str = data[0].replace('.', ''), mag = Number(data[1]) + 1; if (mag < 0) { z = sign + '0.'; while (mag++) { z += '0'; } return z + str.replace(/^\-/, ''); } mag -= str.length; while (mag--) { z += '0'; } return str + z; } }, { key: "getDimensions", value: function getDimensions(el) { var computedStyle = getComputedStyle(el); var ret = []; var elementHeight = el.clientHeight; var elementWidth = el.clientWidth; elementHeight -= parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom); elementWidth -= parseFloat(computedStyle.paddingLeft) + parseFloat(computedStyle.paddingRight); ret.push(elementWidth); ret.push(elementHeight); return ret; } }, { key: "getBoundingClientRect", value: function getBoundingClientRect(element) { var rect = element.getBoundingClientRect(); return { top: rect.top, right: rect.right, bottom: rect.bottom, left: rect.left, width: rect.width, height: rect.height, x: rect.x, y: rect.y }; } // http://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb#answer-12342275 }, { key: "hexToRgba", value: function hexToRgba() { var hex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '#999999'; var opacity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0.6; if (hex.substring(0, 1) !== '#') { hex = '#999999'; } var h = hex.replace('#', ''); h = h.match(new RegExp('(.{' + h.length / 3 + '})', 'g')); for (var i = 0; i < h.length; i++) { h[i] = parseInt(h[i].length === 1 ? h[i] + h[i] : h[i], 16); } if (typeof opacity !== 'undefined') h.push(opacity); return 'rgba(' + h.join(',') + ')'; } }, { key: "getOpacityFromRGBA", value: function getOpacityFromRGBA(rgba) { rgba = rgba.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i); return rgba[3]; } }, { key: "rgb2hex", value: function rgb2hex(rgb) { rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i); return rgb && rgb.length === 4 ? '#' + ('0' + parseInt(rgb[1], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[2], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[3], 10).toString(16)).slice(-2) : ''; } }, { key: "isColorHex", value: function isColorHex(color) { return /(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(color); } }, { key: "polarToCartesian", value: function polarToCartesian(centerX, centerY, radius, angleInDegrees) { var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0; return { x: centerX + radius * Math.cos(angleInRadians), y: centerY + radius * Math.sin(angleInRadians) }; } }, { key: "escapeString", value: function escapeString(str) { var escapeWith = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'x'; var newStr = str.toString().slice(); newStr = newStr.replace(/[` ~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi, escapeWith); return newStr; } }, { key: "negToZero", value: function negToZero(val) { return val < 0 ? 0 : val; } }, { key: "moveIndexInArray", value: function moveIndexInArray(arr, old_index, new_index) { if (new_index >= arr.length) { var k = new_index - arr.length + 1; while (k--) { arr.push(undefined); } } arr.splice(new_index, 0, arr.splice(old_index, 1)[0]); return arr; } }, { key: "extractNumber", value: function extractNumber(s) { return parseFloat(s.replace(/[^\d\.]*/g, '')); } }, { key: "randomString", value: function randomString(len) { var text = ''; var possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; for (var i = 0; i < len; i++) { text += possible.charAt(Math.floor(Math.random() * possible.length)); } return text; } }, { key: "findAncestor", value: function findAncestor(el, cls) { while ((el = el.parentElement) && !el.classList.contains(cls)) { } return el; } }, { key: "setELstyles", value: function setELstyles(el, styles) { for (var key in styles) { if (styles.hasOwnProperty(key)) { el.style.key = styles[key]; } } } }, { key: "isNumber", value: function isNumber(value) { return !isNaN(value) && parseFloat(Number(value)) === value && !isNaN(parseInt(value, 10)); } }, { key: "isFloat", value: function isFloat(n) { return Number(n) === n && n % 1 !== 0; } }, { key: "isSafari", value: function isSafari() { return /^((?!chrome|android).)*safari/i.test(navigator.userAgent); } }, { key: "isFirefox", value: function isFirefox() { return navigator.userAgent.toLowerCase().indexOf('firefox') > -1; } }, { key: "isIE11", value: function isIE11() { if (window.navigator.userAgent.indexOf('MSIE') !== -1 || window.navigator.appVersion.indexOf('Trident/') > -1) { return true; } } }, { key: "isIE", value: function isIE() { var ua = window.navigator.userAgent; var msie = ua.indexOf('MSIE '); if (msie > 0) { // IE 10 or older => return version number return parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10); } var trident = ua.indexOf('Trident/'); if (trident > 0) { // IE 11 => return version number var rv = ua.indexOf('rv:'); return parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10); } var edge = ua.indexOf('Edge/'); if (edge > 0) { // Edge (IE 12+) => return version number return parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10); } // other browser return false; } }]); return Utils; }(); /** * ApexCharts Filters Class for setting hover/active states on the paths. * * @module Formatters **/ var Filters = /*#__PURE__*/ function () { function Filters(ctx) { _classCallCheck(this, Filters); this.ctx = ctx; this.w = ctx.w; } // create a re-usable filter which can be appended other filter effects and applied to multiple elements _createClass(Filters, [{ key: "getDefaultFilter", value: function getDefaultFilter(el, i) { var w = this.w; el.unfilter(true); var filter = new window.SVG.Filter(); filter.size('120%', '180%', '-5%', '-40%'); if (w.config.states.normal.filter !== 'none') { this.applyFilter(el, i, w.config.states.normal.filter.type, w.config.states.normal.filter.value); } else { if (w.config.chart.dropShadow.enabled) { this.dropShadow(el, w.config.chart.dropShadow, i); } } } }, { key: "addNormalFilter", value: function addNormalFilter(el, i) { var w = this.w; if (w.config.chart.dropShadow.enabled) { this.dropShadow(el, w.config.chart.dropShadow, i); } } // appends dropShadow to the filter object which can be chained with other filter effects }, { key: "addLightenFilter", value: function addLightenFilter(el, i, attrs) { var _this = this; var w = this.w; var intensity = attrs.intensity; if (Utils.isFirefox()) { return; } el.unfilter(true); var filter = new window.SVG.Filter(); filter.size('120%', '180%', '-5%', '-40%'); el.filter(function (add) { var shadowAttr = w.config.chart.dropShadow; if (shadowAttr.enabled) { filter = _this.addShadow(add, i, shadowAttr); } else { filter = add; } filter.componentTransfer({ rgb: { type: 'linear', slope: 1.5, intercept: intensity } }); }); el.filterer.node.setAttribute('filterUnits', 'userSpaceOnUse'); } // appends dropShadow to the filter object which can be chained with other filter effects }, { key: "addDarkenFilter", value: function addDarkenFilter(el, i, attrs) { var _this2 = this; var w = this.w; var intensity = attrs.intensity; if (Utils.isFirefox()) { return; } el.unfilter(true); var filter = new window.SVG.Filter(); filter.size('120%', '180%', '-5%', '-40%'); el.filter(function (add) { var shadowAttr = w.config.chart.dropShadow; if (shadowAttr.enabled) { filter = _this2.addShadow(add, i, shadowAttr); } else { filter = add; } filter.componentTransfer({ rgb: { type: 'linear', slope: intensity } }); }); el.filterer.node.setAttribute('filterUnits', 'userSpaceOnUse'); } }, { key: "applyFilter", value: function applyFilter(el, i, filter) { var intensity = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0.5; switch (filter) { case 'none': { this.addNormalFilter(el, i); break; } case 'lighten': { this.addLightenFilter(el, i, { intensity: intensity }); break; } case 'darken': { this.addDarkenFilter(el, i, { intensity: intensity }); break; } default: // do nothing break; } } // appends dropShadow to the filter object which can be chained with other filter effects }, { key: "addShadow", value: function addShadow(add, i, attrs) { var blur = attrs.blur, top = attrs.top, left = attrs.left, color = attrs.color, opacity = attrs.opacity; var shadowBlur = add.flood(Array.isArray(color) ? color[i] : color, opacity).composite(add.sourceAlpha, 'in').offset(left, top).gaussianBlur(blur).merge(add.source); return add.blend(add.source, shadowBlur); } // directly adds dropShadow to the element and returns the same element. // the only way it is different from the addShadow() function is that addShadow is chainable to other filters, while this function discards all filters and add dropShadow }, { key: "dropShadow", value: function dropShadow(el, attrs) { var i = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var top = attrs.top, left = attrs.left, blur = attrs.blur, color = attrs.color, opacity = attrs.opacity, noUserSpaceOnUse = attrs.noUserSpaceOnUse; el.unfilter(true); color = Array.isArray(color) ? color[i] : color; var filter = new window.SVG.Filter(); filter.size('120%', '180%', '-5%', '-40%'); el.filter(function (add) { var shadowBlur = null; if (Utils.isSafari() || Utils.isFirefox() || Utils.isIE()) { // safari/firefox has some alternative way to use this filter shadowBlur = add.flood(color, opacity).composite(add.sourceAlpha, 'in').offset(left, top).gaussianBlur(blur); } else { shadowBlur = add.flood(color, opacity).composite(add.sourceAlpha, 'in').offset(left, top).gaussianBlur(blur).merge(add.source); } add.blend(add.source, shadowBlur); }); if (!noUserSpaceOnUse) { el.filterer.node.setAttribute('filterUnits', 'userSpaceOnUse'); } return el; } }, { key: "setSelectionFilter", value: function setSelectionFilter(el, realIndex, dataPointIndex) { var w = this.w; if (typeof w.globals.selectedDataPoints[realIndex] !== 'undefined') { if (w.globals.selectedDataPoints[realIndex].indexOf(dataPointIndex) > -1) { el.node.setAttribute('selected', true); var activeFilter = w.config.states.active.filter; if (activeFilter !== 'none') { this.applyFilter(el, realIndex, activeFilter.type, activeFilter.value); } } } } }]); return Filters; }(); /** * ApexCharts Animation Class. * * @module Animations **/ var Animations = /*#__PURE__*/ function () { function Animations(ctx) { _classCallCheck(this, Animations); this.ctx = ctx; this.w = ctx.w; this.setEasingFunctions(); } _createClass(Animations, [{ key: "setEasingFunctions", value: function setEasingFunctions() { var easing; var userDefinedEasing = this.w.config.chart.animations.easing; switch (userDefinedEasing) { case 'linear': { easing = '-'; break; } case 'easein': { easing = '<'; break; } case 'easeout': { easing = '>'; break; } case 'easeinout': { easing = '<>'; break; } case 'swing': { easing = function easing(pos) { var s = 1.70158; return (pos -= 1) * pos * ((s + 1) * pos + s) + 1; }; break; } case 'bounce': { easing = function easing(pos) { if (pos < 1 / 2.75) { return 7.5625 * pos * pos; } else if (pos < 2 / 2.75) { return 7.5625 * (pos -= 1.5 / 2.75) * pos + 0.75; } else if (pos < 2.5 / 2.75) { return 7.5625 * (pos -= 2.25 / 2.75) * pos + 0.9375; } else { return 7.5625 * (pos -= 2.625 / 2.75) * pos + 0.984375; } }; break; } case 'elastic': { easing = function easing(pos) { if (pos === !!pos) return pos; return Math.pow(2, -10 * pos) * Math.sin((pos - 0.075) * (2 * Math.PI) / 0.3) + 1; }; break; } default: { easing = '<>'; } } this.w.globals.easing = easing; } }, { key: "animateLine", value: function animateLine(el, from, to, speed) { el.attr(from).animate(speed).attr(to); } /* ** Animate radius of a circle element */ }, { key: "animateCircleRadius", value: function animateCircleRadius(el, from, to, speed, easing) { if (!from) from = 0; el.attr({ r: from }).animate(speed, easing).attr({ r: to }); } /* ** Animate radius and position of a circle element */ }, { key: "animateCircle", value: function animateCircle(el, from, to, speed, easing) { el.attr({ r: from.r, cx: from.cx, cy: from.cy }).animate(speed, easing).attr({ r: to.r, cx: to.cx, cy: to.cy }); } /* ** Animate rect properties */ }, { key: "animateRect", value: function animateRect(el, from, to, speed, fn) { el.attr(from).animate(speed).attr(to).afterAll(function () { fn(); }); } }, { key: "animatePathsGradually", value: function animatePathsGradually(params) { var el = params.el, j = params.j, pathFrom = params.pathFrom, pathTo = params.pathTo, speed = params.speed, delay = params.delay, strokeWidth = params.strokeWidth; var me = this; var w = this.w; var delayFactor = 0; if (w.config.chart.animations.animateGradually.enabled) { delayFactor = w.config.chart.animations.animateGradually.delay; } if (w.config.chart.animations.dynamicAnimation.enabled && w.globals.dataChanged) { delayFactor = 0; } me.morphSVG(el, j, pathFrom, pathTo, speed, strokeWidth, delay * delayFactor); } }, { key: "showDelayedElements", value: function showDelayedElements() { this.w.globals.delayedElements.forEach(function (d) { var ele = d.el; ele.classList.remove('hidden'); }); } // SVG.js animation for morphing one path to another }, { key: "morphSVG", value: function morphSVG(el, j, pathFrom, pathTo, speed, strokeWidth, delay) { var _this = this; var w = this.w; if (!pathFrom) { pathFrom = el.attr('pathFrom'); } if (!pathTo) { pathTo = el.attr('pathTo'); } if (!pathFrom || pathFrom.indexOf('undefined') > -1 || pathFrom.indexOf('NaN') > -1) { pathFrom = "M 0 ".concat(w.globals.gridHeight); speed = 1; } if (pathTo.indexOf('undefined') > -1 || pathTo.indexOf('NaN') > -1) { pathTo = "M 0 ".concat(w.globals.gridHeight); speed = 1; } if (!w.globals.shouldAnimate) { speed = 1; } el.plot(pathFrom).animate(1, w.globals.easing, delay).plot(pathFrom).animate(speed, w.globals.easing, delay).plot(pathTo).afterAll(function () { // a flag to indicate that the original mount function can return true now as animation finished here if (Utils.isNumber(j)) { if (j === w.globals.series[w.globals.maxValsInArrayIndex].length - 2 && w.globals.shouldAnimate) { w.globals.animationEnded = true; } } else if (w.globals.shouldAnimate) { w.globals.animationEnded = true; if (typeof w.config.chart.events.animationEnd === 'function') { w.config.chart.events.animationEnd(_this.ctx, w); } } _this.showDelayedElements(); }); } }]); return Animations; }(); /** * ApexCharts Graphics Class for all drawing operations. * * @module Graphics **/ var Graphics = /*#__PURE__*/ function () { function Graphics(ctx) { _classCallCheck(this, Graphics); this.ctx = ctx; this.w = ctx.w; } _createClass(Graphics, [{ key: "drawLine", value: function drawLine(x1, y1, x2, y2) { var lineColor = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : '#a8a8a8'; var dashArray = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 0; var strokeWidth = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; var w = this.w; var line = w.globals.dom.Paper.line().attr({ x1: x1, y1: y1, x2: x2, y2: y2, stroke: lineColor, 'stroke-dasharray': dashArray, 'stroke-width': strokeWidth }); return line; } }, { key: "drawRect", value: function drawRect() { var x1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var y1 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var x2 = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var y2 = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 0; var radius = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; var color = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : '#fefefe'; var opacity = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : 1; var strokeWidth = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; var strokeColor = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; var strokeDashArray = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : 0; var w = this.w; var rect = w.globals.dom.Paper.rect(); rect.attr({ x: x1, y: y1, width: x2 > 0 ? x2 : 0, height: y2 > 0 ? y2 : 0, rx: radius, ry: radius, fill: color, opacity: opacity, 'stroke-width': strokeWidth !== null ? strokeWidth : 0, stroke: strokeColor !== null ? strokeColor : 'none', 'stroke-dasharray': strokeDashArray }); return rect; } }, { key: "drawPolygon", value: function drawPolygon(polygonString) { var stroke = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '#e1e1e1'; var fill = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'none'; var w = this.w; var polygon = w.globals.dom.Paper.polygon(polygonString).attr({ fill: fill, stroke: stroke }); return polygon; } }, { key: "drawCircle", value: function drawCircle(radius) { var attrs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var w = this.w; var c = w.globals.dom.Paper.circle(radius * 2); if (attrs !== null) { c.attr(attrs); } return c; } }, { key: "drawPath", value: function drawPath(_ref) { var _ref$d = _ref.d, d = _ref$d === void 0 ? '' : _ref$d, _ref$stroke = _ref.stroke, stroke = _ref$stroke === void 0 ? '#a8a8a8' : _ref$stroke, _ref$strokeWidth = _ref.strokeWidth, strokeWidth = _ref$strokeWidth === void 0 ? 1 : _ref$strokeWidth, fill = _ref.fill, _ref$fillOpacity = _ref.fillOpacity, fillOpacity = _ref$fillOpacity === void 0 ? 1 : _ref$fillOpacity, _ref$strokeOpacity = _ref.strokeOpacity, strokeOpacity = _ref$strokeOpacity === void 0 ? 1 : _ref$strokeOpacity, classes = _ref.classes, _ref$strokeLinecap = _ref.strokeLinecap, strokeLinecap = _ref$strokeLinecap === void 0 ? null : _ref$strokeLinecap, _ref$strokeDashArray = _ref.strokeDashArray, strokeDashArray = _ref$strokeDashArray === void 0 ? 0 : _ref$strokeDashArray; var w = this.w; if (strokeLinecap === null) { strokeLinecap = w.config.stroke.lineCap; } if (d.indexOf('undefined') > -1 || d.indexOf('NaN') > -1) { d = "M 0 ".concat(w.globals.gridHeight); } var p = w.globals.dom.Paper.path(d).attr({ fill: fill, 'fill-opacity': fillOpacity, stroke: stroke, 'stroke-opacity': strokeOpacity, 'stroke-linecap': strokeLinecap, 'stroke-width': strokeWidth, 'stroke-dasharray': strokeDashArray, class: classes }); return p; } }, { key: "group", value: function group() { var attrs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var w = this.w; var g = w.globals.dom.Paper.group(); if (attrs !== null) { g.attr(attrs); } return g; } }, { key: "move", value: function move(x, y) { var move = ['M', x, y].join(' '); return move; } }, { key: "line", value: function line(x, y) { var hORv = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var line = null; if (hORv === null) { line = ['L', x, y].join(' '); } else if (hORv === 'H') { line = ['H', x].join(' '); } else if (hORv === 'V') { line = ['V', y].join(' '); } return line; } }, { key: "curve", value: function curve(x1, y1, x2, y2, x, y) { var curve = ['C', x1, y1, x2, y2, x, y].join(' '); return curve; } }, { key: "quadraticCurve", value: function quadraticCurve(x1, y1, x, y) { var curve = ['Q', x1, y1, x, y].join(' '); return curve; } }, { key: "arc", value: function arc(rx, ry, axisRotation, largeArcFlag, sweepFlag, x, y) { var relative = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : false; var coord = 'A'; if (relative) coord = 'a'; var arc = [coord, rx, ry, axisRotation, largeArcFlag, sweepFlag, x, y].join(' '); return arc; } /** * @memberof Graphics * @param {object} * i = series's index * realIndex = realIndex is series's actual index when it was drawn time. After several redraws, the iterating "i" may change in loops, but realIndex doesn't * pathFrom = existing pathFrom to animateTo * pathTo = new Path to which d attr will be animated from pathFrom to pathTo * stroke = line Color * strokeWidth = width of path Line * fill = it can be gradient, single color, pattern or image * animationDelay = how much to delay when starting animation (in milliseconds) * dataChangeSpeed = for dynamic animations, when data changes * className = class attribute to add * @return {object} svg.js path object **/ }, { key: "renderPaths", value: function renderPaths(_ref2) { var i = _ref2.i, j = _ref2.j, realIndex = _ref2.realIndex, pathFrom = _ref2.pathFrom, pathTo = _ref2.pathTo, stroke = _ref2.stroke, strokeWidth = _ref2.strokeWidth, strokeLinecap = _ref2.strokeLinecap, fill = _ref2.fill, animationDelay = _ref2.animationDelay, initialSpeed = _ref2.initialSpeed, dataChangeSpeed = _ref2.dataChangeSpeed, className = _ref2.className, id = _ref2.id, _ref2$shouldClipToGri = _ref2.shouldClipToGrid, shouldClipToGrid = _ref2$shouldClipToGri === void 0 ? true : _ref2$shouldClipToGri, _ref2$bindEventsOnPat = _ref2.bindEventsOnPaths, bindEventsOnPaths = _ref2$bindEventsOnPat === void 0 ? true : _ref2$bindEventsOnPat, _ref2$drawShadow = _ref2.drawShadow, drawShadow = _ref2$drawShadow === void 0 ? true : _ref2$drawShadow; var w = this.w; var filters = new Filters(this.ctx); var anim = new Animations(this.ctx); var initialAnim = this.w.config.chart.animations.enabled; var dynamicAnim = initialAnim && this.w.config.chart.animations.dynamicAnimation.enabled; var d; var shouldAnimate = !!(initialAnim && !w.globals.resized || dynamicAnim && w.globals.dataChanged && w.globals.shouldAnimate); if (shouldAnimate) { d = pathFrom; } else { d = pathTo; this.w.globals.animationEnded = true; } var strokeDashArrayOpt = w.config.stroke.dashArray; var strokeDashArray = 0; if (Array.isArray(strokeDashArrayOpt)) { strokeDashArray = strokeDashArrayOpt[realIndex]; } else { strokeDashArray = w.config.stroke.dashArray; } var el = this.drawPath({ d: d, stroke: stroke, strokeWidth: strokeWidth, fill: fill, fillOpacity: 1, classes: className, strokeLinecap: strokeLinecap, strokeDashArray: strokeDashArray }); el.attr('id', "".concat(id, "-").concat(i)); el.attr('index', realIndex); if (shouldClipToGrid) { el.attr({ 'clip-path': "url(#gridRectMask".concat(w.globals.cuid, ")") }); } // const defaultFilter = el.filterer if (w.config.states.normal.filter.type !== 'none') { filters.getDefaultFilter(el, realIndex); } else { if (w.config.chart.dropShadow.enabled && drawShadow) { if (!w.config.chart.dropShadow.enabledSeries || w.config.chart.dropShadow.enabledSeries && w.config.chart.dropShadow.enabledSeries.indexOf(realIndex) !== -1) { var shadow = w.config.chart.dropShadow; filters.dropShadow(el, shadow, realIndex); } } } if (bindEventsOnPaths) { el.node.addEventListener('mouseenter', this.pathMouseEnter.bind(this, el)); el.node.addEventListener('mouseleave', this.pathMouseLeave.bind(this, el)); el.node.addEventListener('mousedown', this.pathMouseDown.bind(this, el)); } el.attr({ pathTo: pathTo, pathFrom: pathFrom }); var defaultAnimateOpts = { el: el, j: j, pathFrom: pathFrom, pathTo: pathTo, strokeWidth: strokeWidth }; if (initialAnim && !w.globals.resized && !w.globals.dataChanged) { anim.animatePathsGradually(_objectSpread({}, defaultAnimateOpts, { speed: initialSpeed, delay: animationDelay })); } else { if (w.globals.resized || !w.globals.dataChanged) { anim.showDelayedElements(); } } if (w.globals.dataChanged && dynamicAnim && shouldAnimate) { anim.animatePathsGradually(_objectSpread({}, defaultAnimateOpts, { speed: dataChangeSpeed })); } return el; } }, { key: "drawPattern", value: function drawPattern(style, width, height) { var stroke = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : '#a8a8a8'; var strokeWidth = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 0; var w = this.w; var p = w.globals.dom.Paper.pattern(width, height, function (add) { if (style === 'horizontalLines') { add.line(0, 0, height, 0).stroke({ color: stroke, width: strokeWidth + 1 }); } else if (style === 'verticalLines') { add.line(0, 0, 0, width).stroke({ color: stroke, width: strokeWidth + 1 }); } else if (style === 'slantedLines') { add.line(0, 0, width, height).stroke({ color: stroke, width: strokeWidth }); } else if (style === 'squares') { add.rect(width, height).fill('none').stroke({ color: stroke, width: strokeWidth }); } else if (style === 'circles') { add.circle(width).fill('none').stroke({ color: stroke, width: strokeWidth }); } }); return p; } }, { key: "drawGradient", value: function drawGradient(style, gfrom, gto, opacityFrom, opacityTo) { var size = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; var stops = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : null; var colorStops = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; var i = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : 0; var w = this.w; var g; gfrom = Utils.hexToRgba(gfrom, opacityFrom); gto = Utils.hexToRgba(gto, opacityTo); var stop1 = 0; var stop2 = 1; var stop3 = 1; var stop4 = null; if (stops !== null) { stop1 = typeof stops[0] !== 'undefined' ? stops[0] / 100 : 0; stop2 = typeof stops[1] !== 'undefined' ? stops[1] / 100 : 1; stop3 = typeof stops[2] !== 'undefined' ? stops[2] / 100 : 1; stop4 = typeof stops[3] !== 'undefined' ? stops[3] / 100 : null; } var radial = !!(w.config.chart.type === 'donut' || w.config.chart.type === 'pie' || w.config.chart.type === 'bubble'); if (colorStops === null || colorStops.length === 0) { g = w.globals.dom.Paper.gradient(radial ? 'radial' : 'linear', function (stop) { stop.at(stop1, gfrom, opacityFrom); stop.at(stop2, gto, opacityTo); stop.at(stop3, gto, opacityTo); if (stop4 !== null) { stop.at(stop4, gfrom, opacityFrom); } }); } else { g = w.globals.dom.Paper.gradient(radial ? 'radial' : 'linear', function (stop) { var stops = Array.isArray(colorStops[i]) ? colorStops[i] : colorStops; stops.forEach(function (s) { stop.at(s.offset / 100, s.color, s.opacity); }); }); } if (!radial) { if (style === 'vertical') { g.from(0, 0).to(0, 1); } else if (style === 'diagonal') { g.from(0, 0).to(1, 1); } else if (style === 'horizontal') { g.from(0, 1).to(1, 1); } else if (style === 'diagonal2') { g.from(0, 1).to(2, 2); } } else { var offx = w.globals.gridWidth / 2; var offy = w.globals.gridHeight / 2; if (w.config.chart.type !== 'bubble') { g.attr({ gradientUnits: 'userSpaceOnUse', cx: offx, cy: offy, r: size }); } else { g.attr({ cx: 0.5, cy: 0.5, r: 0.8, fx: 0.2, fy: 0.2 }); } } return g; } }, { key: "drawText", value: function drawText(opts) { var w = this.w; var x = opts.x, y = opts.y, text = opts.text, textAnchor = opts.textAnchor, fontSize = opts.fontSize, fontFamily = opts.fontFamily, foreColor = opts.foreColor, opacity = opts.opacity; if (typeof text === 'undefined') text = ''; if (!textAnchor) { textAnchor = 'start'; } if (!foreColor) { foreColor = w.config.chart.foreColor; } fontFamily = fontFamily || w.config.chart.fontFamily; var elText; if (Array.isArray(text)) { elText = w.globals.dom.Paper.text(function (add) { for (var i = 0; i < text.length; i++) { add.tspan(text[i]); } }); } else { elText = w.globals.dom.Paper.plain(text); } elText.attr({ x: x, y: y, 'text-anchor': textAnchor, 'dominant-baseline': 'auto', 'font-size': fontSize, 'font-family': fontFamily, fill: foreColor, class: 'apexcharts-text ' + opts.cssClass ? opts.cssClass : '' }); elText.node.style.fontFamily = fontFamily; elText.node.style.opacity = opacity; return elText; } }, { key: "addTspan", value: function addTspan(textEl, text, fontFamily) { var tspan = textEl.tspan(text); if (!fontFamily) { fontFamily = this.w.config.chart.fontFamily; } tspan.node.style.fontFamily = fontFamily; } }, { key: "drawMarker", value: function drawMarker(x, y, opts) { x = x || 0; var size = opts.pSize || 0; var elPoint = null; if (opts.shape === 'square') { var radius = opts.pRadius === undefined ? size / 2 : opts.pRadius; if (y === null) { size = 0; radius = 0; } var nSize = size * 1.2 + radius; var p = this.drawRect(nSize, nSize, nSize, nSize, radius); p.attr({ x: x - nSize / 2, y: y - nSize / 2, cx: x, cy: y, class: opts.class ? opts.class : '', fill: opts.pointFillColor, 'fill-opacity': opts.pointFillOpacity ? opts.pointFillOpacity : 1, stroke: opts.pointStrokeColor, 'stroke-width': opts.pWidth ? opts.pWidth : 0, 'stroke-opacity': opts.pointStrokeOpacity ? opts.pointStrokeOpacity : 1 }); elPoint = p; } else if (opts.shape === 'circle') { if (!Utils.isNumber(y)) { size = 0; y = 0; } // let nSize = size - opts.pRadius / 2 < 0 ? 0 : size - opts.pRadius / 2 elPoint = this.drawCircle(size, { cx: x, cy: y, class: opts.class ? opts.class : '', stroke: opts.pointStrokeColor, fill: opts.pointFillColor, 'fill-opacity': opts.pointFillOpacity ? opts.pointFillOpacity : 1, 'stroke-width': opts.pWidth ? opts.pWidth : 0, 'stroke-opacity': opts.pointStrokeOpacity ? opts.pointStrokeOpacity : 1 }); } return elPoint; } }, { key: "pathMouseEnter", value: function pathMouseEnter(path, e) { var w = this.w; var filters = new Filters(this.ctx); var i = parseInt(path.node.getAttribute('index')); var j = parseInt(path.node.getAttribute('j')); if (typeof w.config.chart.events.dataPointMouseEnter === 'function') { w.config.chart.events.dataPointMouseEnter(e, this.ctx, { seriesIndex: i, dataPointIndex: j, w: w }); } this.ctx.fireEvent('dataPointMouseEnter', [e, this.ctx, { seriesIndex: i, dataPointIndex: j, w: w }]); if (w.config.states.active.filter.type !== 'none') { if (path.node.getAttribute('selected') === 'true') { return; } } if (w.config.states.hover.filter.type !== 'none') { if (w.config.states.active.filter.type !== 'none' && !w.globals.isTouchDevice) { var hoverFilter = w.config.states.hover.filter; filters.applyFilter(path, i, hoverFilter.type, hoverFilter.value); } } } }, { key: "pathMouseLeave", value: function pathMouseLeave(path, e) { var w = this.w; var filters = new Filters(this.ctx); var i = parseInt(path.node.getAttribute('index')); var j = parseInt(path.node.getAttribute('j')); if (typeof w.config.chart.events.dataPointMouseLeave === 'function') { w.config.chart.events.dataPointMouseLeave(e, this.ctx, { seriesIndex: i, dataPointIndex: j, w: w }); } this.ctx.fireEvent('dataPointMouseLeave', [e, this.ctx, { seriesIndex: i, dataPointIndex: j, w: w }]); if (w.config.states.active.filter.type !== 'none') { if (path.node.getAttribute('selected') === 'true') { return; } } if (w.config.states.hover.filter.type !== 'none') { filters.getDefaultFilter(path, i); } } }, { key: "pathMouseDown", value: function pathMouseDown(path, e) { var w = this.w; var filters = new Filters(this.ctx); var i = parseInt(path.node.getAttribute('index')); var j = parseInt(path.node.getAttribute('j')); var selected = 'false'; if (path.node.getAttribute('selected') === 'true') { path.node.setAttribute('selected', 'false'); if (w.globals.selectedDataPoints[i].indexOf(j) > -1) { var index = w.globals.selectedDataPoints[i].indexOf(j); w.globals.selectedDataPoints[i].splice(index, 1); } } else { if (!w.config.states.active.allowMultipleDataPointsSelection && w.globals.selectedDataPoints.length > 0) { w.globals.selectedDataPoints = []; var elPaths = w.globals.dom.Paper.select('.apexcharts-series path').members; var elCircles = w.globals.dom.Paper.select('.apexcharts-series circle, .apexcharts-series rect').members; elPaths.forEach(function (elPath) { elPath.node.setAttribute('selected', 'false'); filters.getDefaultFilter(elPath, i); }); elCircles.forEach(function (circle) { circle.node.setAttribute('selected', 'false'); filters.getDefaultFilter(circle, i); }); } path.node.setAttribute('selected', 'true'); selected = 'true'; if (typeof w.globals.selectedDataPoints[i] === 'undefined') { w.globals.selectedDataPoints[i] = []; } w.globals.selectedDataPoints[i].push(j); } if (selected === 'true') { var activeFilter = w.config.states.active.filter; if (activeFilter !== 'none') { filters.applyFilter(path, i, activeFilter.type, activeFilter.value); } } else { if (w.config.states.active.filter.type !== 'none') { filters.getDefaultFilter(path, i); } } if (typeof w.config.chart.events.dataPointSelection === 'function') { w.config.chart.events.dataPointSelection(e, this.ctx, { selectedDataPoints: w.globals.selectedDataPoints, seriesIndex: i, dataPointIndex: j, w: w }); } this.ctx.fireEvent('dataPointSelection', [e, this.ctx, { selectedDataPoints: w.globals.selectedDataPoints, seriesIndex: i, dataPointIndex: j, w: w }]); // if (this.w.config.chart.selection.selectedPoints !== undefined) { // this.w.config.chart.selection.selectedPoints(w.globals.selectedDataPoints) // } } }, { key: "rotateAroundCenter", value: function rotateAroundCenter(el) { var coord = el.getBBox(); var x = coord.x + coord.width / 2; var y = coord.y + coord.height / 2; return { x: x, y: y }; } }, { key: "getTextRects", value: function getTextRects(text, fontSize, fontFamily, transform) { var useBBox = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; var w = this.w; var virtualText = this.drawText({ x: -200, y: -200, text: text, textAnchor: 'start', fontSize: fontSize, fontFamily: fontFamily, foreColor: '#fff', opacity: 0 }); if (transform) { virtualText.attr('transform', transform); } w.globals.dom.Paper.add(virtualText); var rect = virtualText.bbox(); if (!useBBox) { rect = virtualText.node.getBoundingClientRect(); } virtualText.remove(); return { width: rect.width, height: rect.height }; } /** * append ... to long text * http://stackoverflow.com/questions/9241315/trimming-text-to-a-given-pixel-width-in-svg * @memberof Graphics **/ }, { key: "placeTextWithEllipsis", value: function placeTextWithEllipsis(textObj, textString, width) { textObj.textContent = textString; if (textString.length > 0) { // ellipsis is needed if (textObj.getSubStringLength(0, textString.length) >= width) { for (var x = textString.length - 3; x > 0; x -= 3) { if (textObj.getSubStringLength(0, x) <= width) { textObj.textContent = textString.substring(0, x) + '...'; return; } } textObj.textContent = '...'; // can't place at all } } } }], [{ key: "setAttrs", value: function setAttrs(el, attrs) { for (var key in attrs) { if (attrs.hasOwnProperty(key)) { el.setAttribute(key, attrs[key]); } } } }]); return Graphics; }(); const name = "en"; const options = { months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ], days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ], toolbar: { exportToSVG: "Download SVG", exportToPNG: "Download PNG", menu: "Menu", selection: "Selection", selectionZoom: "Selection Zoom", zoomIn: "Zoom In", zoomOut: "Zoom Out", pan: "Panning", reset: "Reset Zoom" } }; var en = { name: name, options: options }; var Options = /*#__PURE__*/ function () { function Options() { _classCallCheck(this, Options); this.yAxis = { show: true, showAlways: false, seriesName: undefined, opposite: false, reversed: false, logarithmic: false, tickAmount: undefined, forceNiceScale: false, max: undefined, min: undefined, floating: false, decimalsInFloat: undefined, labels: { show: true, minWidth: 0, maxWidth: 160, offsetX: 0, offsetY: 0, align: undefined, rotate: 0, padding: 20, style: { colors: [], fontSize: '11px', fontFamily: undefined, cssClass: '' }, formatter: undefined }, axisBorder: { show: false, color: '#78909C', offsetX: 0, offsetY: 0 }, axisTicks: { show: false, color: '#78909C', width: 6, offsetX: 0, offsetY: 0 }, title: { text: undefined, rotate: 90, offsetY: 0, offsetX: 0, style: { color: undefined, fontSize: '11px', fontFamily: undefined, cssClass: '' } }, tooltip: { enabled: false, offsetX: 0 }, crosshairs: { show: true, position: 'front', stroke: { color: '#b6b6b6', width: 1, dashArray: 0 } } }; this.xAxisAnnotation = { x: 0, x2: null, strokeDashArray: 1, fillColor: '#c2c2c2', borderColor: '#c2c2c2', opacity: 0.3, offsetX: 0, offsetY: 0, label: { borderColor: '#c2c2c2', borderWidth: 1, text: undefined, textAnchor: 'middle', orientation: 'vertical', position: 'top', offsetX: 0, offsetY: 0, style: { background: '#fff', color: undefined, fontSize: '11px', fontFamily: undefined, cssClass: '', padding: { left: 5, right: 5, top: 2, bottom: 2 } } } }; this.yAxisAnnotation = { y: 0, y2: null, strokeDashArray: 1, fillColor: '#c2c2c2', borderColor: '#c2c2c2', opacity: 0.3, offsetX: 0, offsetY: 0, yAxisIndex: 0, label: { borderColor: '#c2c2c2', borderWidth: 1, text: undefined, textAnchor: 'end', position: 'right', offsetX: 0, offsetY: -3, style: { background: '#fff', color: undefined, fontSize: '11px', fontFamily: undefined, cssClass: '', padding: { left: 5, right: 5, top: 0, bottom: 2 } } } }; this.pointAnnotation = { x: 0, y: null, yAxisIndex: 0, seriesIndex: 0, marker: { size: 0, fillColor: '#fff', strokeWidth: 2, strokeColor: '#333', shape: 'circle', offsetX: 0, offsetY: 0, radius: 2, cssClass: '' }, label: { borderColor: '#c2c2c2', borderWidth: 1, text: undefined, textAnchor: 'middle', offsetX: 0, offsetY: -15, style: { background: '#fff', color: undefined, fontSize: '11px', fontFamily: undefined, cssClass: '', padding: { left: 5, right: 5, top: 0, bottom: 2 } } }, customSVG: { SVG: undefined, cssClass: undefined, offsetX: 0, offsetY: 0 } }; } _createClass(Options, [{ key: "init", value: function init() { return { annotations: { position: 'front', yaxis: [this.yAxisAnnotation], xaxis: [this.xAxisAnnotation], points: [this.pointAnnotation] }, chart: { animations: { enabled: true, easing: 'easeinout', // linear, easeout, easein, easeinout, swing, bounce, elastic speed: 800, animateGradually: { delay: 150, enabled: true }, dynamicAnimation: { enabled: true, speed: 350 } }, background: 'transparent', locales: [en], defaultLocale: 'en', dropShadow: { enabled: false, enabledSeries: undefined, top: 2, left: 2, blur: 4, color: '#000', opacity: 0.35 }, events: { animationEnd: undefined, beforeMount: undefined, mounted: undefined, updated: undefined, click: undefined, legendClick: undefined, markerClick: undefined, selection: undefined, dataPointSelection: undefined, dataPointMouseEnter: undefined, dataPointMouseLeave: undefined, beforeZoom: undefined, zoomed: undefined, scrolled: undefined }, foreColor: '#373d3f', fontFamily: 'Helvetica, Arial, sans-serif', height: 'auto', parentHeightOffset: 15, id: undefined, group: undefined, offsetX: 0, offsetY: 0, selection: { enabled: false, type: 'x', // selectedPoints: undefined, // default datapoints that should be selected automatically fill: { color: '#24292e', opacity: 0.1 }, stroke: { width: 1, color: '#24292e', opacity: 0.4, dashArray: 3 }, xaxis: { min: undefined, max: undefined }, yaxis: { min: undefined, max: undefined } }, sparkline: { enabled: false }, brush: { enabled: false, autoScaleYaxis: false, target: undefined }, stacked: false, stackType: 'normal', toolbar: { show: true, tools: { download: true, selection: true, zoom: true, zoomin: true, zoomout: true, pan: true, reset: true, customIcons: [] }, autoSelected: 'zoom' // accepts -> zoom, pan, selection }, type: 'line', width: '100%', zoom: { enabled: true, type: 'x', // autoScaleYaxis: false, // TODO: rewrite the autoScaleY function zoomedArea: { fill: { color: '#90CAF9', opacity: 0.4 }, stroke: { color: '#0D47A1', opacity: 0.4, width: 1 } } } }, plotOptions: { bar: { horizontal: false, columnWidth: '70%', // should be in percent 0 - 100 barHeight: '70%', // should be in percent 0 - 100 distributed: false, endingShape: 'flat', colors: { ranges: [], backgroundBarColors: [], backgroundBarOpacity: 1 }, dataLabels: { maxItems: 100, hideOverflowingLabels: true, position: 'top' // top, center, bottom // TODO: provide stackedLabels for stacked charts which gives additions of values } }, candlestick: { colors: { upward: '#00B746', downward: '#EF403C' }, wick: { useFillColor: true } }, heatmap: { radius: 2, enableShades: true, shadeIntensity: 0.5, distributed: false, colorScale: { inverse: false, ranges: [], min: undefined, max: undefined } }, radialBar: { size: undefined, inverseOrder: false, startAngle: 0, endAngle: 360, offsetX: 0, offsetY: 0, hollow: { margin: 5, size: '50%', background: 'transparent', image: undefined, imageWidth: 150, imageHeight: 150, imageOffsetX: 0, imageOffsetY: 0, imageClipped: true, position: 'front', dropShadow: { enabled: false, top: 0, left: 0, blur: 3, color: '#000', opacity: 0.5 } }, track: { show: true, startAngle: undefined, endAngle: undefined, background: '#f2f2f2', strokeWidth: '97%', opacity: 1, margin: 5, // margin is in pixels dropShadow: { enabled: false, top: 0, left: 0, blur: 3, color: '#000', opacity: 0.5 } }, dataLabels: { show: true, name: { show: true, fontSize: '16px', fontFamily: undefined, color: undefined, offsetY: 0 }, value: { show: true, fontSize: '14px', fontFamily: undefined, color: undefined, offsetY: 16, formatter: function formatter(val) { return val + '%'; } }, total: { show: false, label: 'Total', color: undefined, formatter: function formatter(w) { return w.globals.seriesTotals.reduce(function (a, b) { return a + b; }, 0) / w.globals.series.length + '%'; } } } }, rangeBar: {}, pie: { size: undefined, customScale: 1, offsetX: 0, offsetY: 0, expandOnClick: true, dataLabels: { // These are the percentage values which are displayed on slice offset: 0, // offset by which labels will move outside minAngleToShowLabel: 10 }, donut: { size: '65%', background: 'transparent', labels: { // These are the inner labels appearing inside donut show: false, name: { show: true, fontSize: '16px', fontFamily: undefined, color: undefined, offsetY: -10 }, value: { show: true, fontSize: '20px', fontFamily: undefined, color: undefined, offsetY: 10, formatter: function formatter(val) { return val; } }, total: { show: false, label: 'Total', color: undefined, formatter: function formatter(w) { return w.globals.seriesTotals.reduce(function (a, b) { return a + b; }, 0); } } } } }, radar: { size: undefined, offsetX: 0, offsetY: 0, polygons: { // strokeColor: '#e8e8e8', // should be deprecated in the minor version i.e 3.2 strokeColors: '#e8e8e8', connectorColors: '#e8e8e8', fill: { colors: undefined } } } }, colors: undefined, dataLabels: { enabled: true, enabledOnSeries: undefined, formatter: function formatter(val) { return val; }, textAnchor: 'middle', offsetX: 0, offsetY: 0, style: { fontSize: '12px', fontFamily: undefined, colors: undefined }, dropShadow: { enabled: false, top: 1, left: 1, blur: 1, color: '#000', opacity: 0.45 } }, fill: { type: 'solid', colors: undefined, // array of colors opacity: 0.85, gradient: { shade: 'dark', type: 'horizontal', shadeIntensity: 0.5, gradientToColors: undefined, inverseColors: true, opacityFrom: 1, opacityTo: 1, stops: [0, 50, 100], colorStops: [] }, image: { src: [], width: undefined, // optional height: undefined // optional }, pattern: { style: 'sqaures', // String | Array of Strings width: 6, height: 6, strokeWidth: 2 } }, grid: { show: true, borderColor: '#e0e0e0', strokeDashArray: 0, position: 'back', xaxis: { lines: { show: false, animate: false } }, yaxis: { lines: { show: true, animate: false } }, row: { colors: undefined, // takes as array which will be repeated on rows opacity: 0.5 }, column: { colors: undefined, // takes an array which will be repeated on columns opacity: 0.5 }, padding: { top: 0, right: 10, bottom: 0, left: 12 } }, labels: [], legend: { show: true, showForSingleSeries: false, showForNullSeries: true, showForZeroSeries: true, floating: false, position: 'bottom', // whether to position legends in 1 of 4 // direction - top, bottom, left, right horizontalAlign: 'center', // when position top/bottom, you can specify whether to align legends left, right or center fontSize: '12px', fontFamily: undefined, width: undefined, height: undefined, formatter: undefined, offsetX: -20, offsetY: 0, labels: { colors: undefined, useSeriesColors: false }, markers: { width: 12, height: 12, strokeWidth: 0, strokeColor: '#fff', radius: 12, customHTML: undefined, offsetX: 0, offsetY: 0, onClick: undefined }, itemMargin: { horizontal: 0, vertical: 5 }, onItemClick: { toggleDataSeries: true }, onItemHover: { highlightDataSeries: true } }, markers: { discrete: [], size: 0, colors: undefined, //strokeColor: '#fff', // TODO: deprecate in major version 4.0 strokeColors: '#fff', strokeWidth: 2, strokeOpacity: 0.9, fillOpacity: 1, shape: 'circle', radius: 2, offsetX: 0, offsetY: 0, hover: { size: undefined, sizeOffset: 3 } }, noData: { text: undefined, align: 'center', verticalAlign: 'middle', offsetX: 0, offsetY: 0, style: { color: undefined, fontSize: '14px', fontFamily: undefined } }, responsive: [], // breakpoints should follow ascending order 400, then 700, then 1000 series: undefined, states: { normal: { filter: { type: 'none', value: 0 } }, hover: { filter: { type: 'lighten', value: 0.15 } }, active: { allowMultipleDataPointsSelection: false, filter: { type: 'darken', value: 0.65 } } }, title: { text: undefined, align: 'left', margin: 10, offsetX: 0, offsetY: 0, floating: false, style: { fontSize: '14px', fontFamily: undefined, color: undefined } }, subtitle: { text: undefined, align: 'left', margin: 10, offsetX: 0, offsetY: 30, floating: false, style: { fontSize: '12px', fontFamily: undefined, color: undefined } }, stroke: { show: true, curve: 'smooth', // "smooth" / "straight" / "stepline" lineCap: 'butt', // round, butt , square width: 2, colors: undefined, // array of colors dashArray: 0 // single value or array of values }, tooltip: { enabled: true, shared: true, followCursor: false, // when disabled, the tooltip will show on top of the series instead of mouse position intersect: false, // when enabled, tooltip will only show when user directly hovers over point inverseOrder: false, custom: undefined, fillSeriesColor: false, theme: 'light', style: { fontSize: '12px', fontFamily: undefined }, onDatasetHover: { highlightDataSeries: false }, x: { // x value show: true, format: 'dd MMM', // dd/MM, dd MMM yy, dd MMM yyyy formatter: undefined // a custom user supplied formatter function }, y: { formatter: undefined, title: { formatter: function formatter(seriesName) { return seriesName; } } }, z: { formatter: undefined, title: 'Size: ' }, marker: { show: true }, items: { display: 'flex' }, fixed: { enabled: false, position: 'topRight', // topRight, topLeft, bottomRight, bottomLeft offsetX: 0, offsetY: 0 } }, xaxis: { type: 'category', categories: [], offsetX: 0, offsetY: 0, labels: { show: true, rotate: -45, rotateAlways: false, hideOverlappingLabels: true, trim: true, minHeight: undefined, maxHeight: 120, showDuplicates: true, style: { colors: [], fontSize: '12px', fontFamily: undefined, cssClass: '' }, offsetX: 0, offsetY: 0, format: undefined, formatter: undefined, // custom formatter function which will override format datetimeFormatter: { year: 'yyyy', month: "MMM 'yy", day: 'dd MMM', hour: 'HH:mm', minute: 'HH:mm:ss' } }, axisBorder: { show: true, color: '#78909C', width: '100%', height: 1, offsetX: 0, offsetY: 0 }, axisTicks: { show: true, color: '#78909C', height: 6, offsetX: 0, offsetY: 0 }, tickAmount: undefined, tickPlacement: 'on', min: undefined, max: undefined, range: undefined, floating: false, position: 'bottom', title: { text: undefined, offsetX: 0, offsetY: 0, style: { color: undefined, fontSize: '12px', fontFamily: undefined, cssClass: '' } }, crosshairs: { show: true, width: 1, // tickWidth/barWidth or an integer position: 'back', opacity: 0.9, stroke: { color: '#b6b6b6', width: 1, dashArray: 3 }, fill: { type: 'solid', // solid, gradient color: '#B1B9C4', gradient: { colorFrom: '#D8E3F0', colorTo: '#BED1E6', stops: [0, 100], opacityFrom: 0.4, opacityTo: 0.5 } }, dropShadow: { enabled: false, left: 0, top: 0, blur: 1, opacity: 0.4 } }, tooltip: { enabled: true, offsetY: 0, formatter: undefined, style: { fontSize: '12px', fontFamily: undefined } } }, yaxis: this.yAxis, theme: { mode: 'light', palette: 'palette1', // If defined, it will overwrite globals.colors variable monochrome: { // monochrome allows you to select just 1 color and fill out the rest with light/dark shade (intensity can be selected) enabled: false, color: '#008FFB', shadeTo: 'light', shadeIntensity: 0.65 } } }; } }]); return Options; }(); /** * ApexCharts Annotations Class for drawing lines/rects on both xaxis and yaxis. * * @module Annotations **/ var Annotations = /*#__PURE__*/ function () { function Annotations(ctx) { _classCallCheck(this, Annotations); this.ctx = ctx; this.w = ctx.w; this.graphics = new Graphics(this.ctx); if (this.w.globals.isBarHorizontal) { this.invertAxis = true; } this.xDivision = this.w.globals.gridWidth / this.w.globals.dataPoints; } _createClass(Annotations, [{ key: "drawAnnotations", value: function drawAnnotations() { var w = this.w; if (w.globals.axisCharts) { var yAnnotations = this.drawYAxisAnnotations(); var xAnnotations = this.drawXAxisAnnotations(); var pointAnnotations = this.drawPointAnnotations(); var initialAnim = w.config.chart.animations.enabled; var annoArray = [yAnnotations, xAnnotations, pointAnnotations]; var annoElArray = [xAnnotations.node, yAnnotations.node, pointAnnotations.node]; for (var i = 0; i < 3; i++) { w.globals.dom.elGraphical.add(annoArray[i]); if (initialAnim && !w.globals.resized && !w.globals.dataChanged) { annoElArray[i].classList.add('hidden'); } w.globals.delayedElements.push({ el: annoElArray[i], index: 0 }); } // after placing the annotations on svg, set any vertically placed annotations this.setOrientations(w.config.annotations.xaxis); // background sizes needs to be calculated after text is drawn, so calling them last this.annotationsBackground(); } } }, { key: "addXaxisAnnotation", value: function addXaxisAnnotation(anno, parent, index) { var w = this.w; var min = this.invertAxis ? w.globals.minY : w.globals.minX; var range = this.invertAxis ? w.globals.yRange[0] : w.globals.xRange; var x1 = (anno.x - min) / (range / w.globals.gridWidth); var text = anno.label.text; if (w.config.xaxis.type === 'category' || w.config.xaxis.convertedCatToNumeric) { var catIndex = w.globals.labels.indexOf(anno.x); var xLabel = w.globals.dom.baseEl.querySelector('.apexcharts-xaxis-texts-g text:nth-child(' + (catIndex + 1) + ')'); if (xLabel) { x1 = parseFloat(xLabel.getAttribute('x')); } } var strokeDashArray = anno.strokeDashArray; if (x1 < 0 || x1 > w.globals.gridWidth) return; if (anno.x2 === null) { var line = this.graphics.drawLine(x1 + anno.offsetX, // x1 0 + anno.offsetY, // y1 x1 + anno.offsetX, // x2 w.globals.gridHeight + anno.offsetY, // y2 anno.borderColor, // lineColor strokeDashArray //dashArray ); parent.appendChild(line.node); } else { var x2 = (anno.x2 - min) / (range / w.globals.gridWidth); if (x2 < x1) { var temp = x1; x1 = x2; x2 = temp; } if (text) { var rect = this.graphics.drawRect(x1 + anno.offsetX, // x1 0 + anno.offsetY, // y1 x2 - x1, // x2 w.globals.gridHeight + anno.offsetY, // y2 0, // radius anno.fillColor, // color anno.opacity, // opacity, 1, // strokeWidth anno.borderColor, // strokeColor strokeDashArray // stokeDashArray ); parent.appendChild(rect.node); } } var textY = anno.label.position === 'top' ? -3 : w.globals.gridHeight; var elText = this.graphics.drawText({ x: x1 + anno.label.offsetX, y: textY + anno.label.offsetY, text: text, textAnchor: anno.label.textAnchor, fontSize: anno.label.style.fontSize, fontFamily: anno.label.style.fontFamily, foreColor: anno.label.style.color, cssClass: 'apexcharts-xaxis-annotation-label ' + anno.label.style.cssClass }); elText.attr({ rel: index }); parent.appendChild(elText.node); } }, { key: "drawXAxisAnnotations", value: function drawXAxisAnnotations() { var _this = this; var w = this.w; var elg = this.graphics.group({ class: 'apexcharts-xaxis-annotations' }); w.config.annotations.xaxis.map(function (anno, index) { _this.addXaxisAnnotation(anno, elg.node, index); }); return elg; } }, { key: "addYaxisAnnotation", value: function addYaxisAnnotation(anno, parent, index) { var w = this.w; var strokeDashArray = anno.strokeDashArray; var y1; var y2; if (this.invertAxis) { var catIndex = w.globals.labels.indexOf(anno.y); var xLabel = w.globals.dom.baseEl.querySelector('.apexcharts-yaxis-texts-g text:nth-child(' + (catIndex + 1) + ')'); if (xLabel) { y1 = parseFloat(xLabel.getAttribute('y')); } } else { y1 = w.globals.gridHeight - (anno.y - w.globals.minYArr[anno.yAxisIndex]) / (w.globals.yRange[anno.yAxisIndex] / w.globals.gridHeight); if (w.config.yaxis[anno.yAxisIndex] && w.config.yaxis[anno.yAxisIndex].reversed) { y1 = (anno.y - w.globals.minYArr[anno.yAxisIndex]) / (w.globals.yRange[anno.yAxisIndex] / w.globals.gridHeight); } } var text = anno.label.text; if (anno.y2 === null) { var line = this.graphics.drawLine(0 + anno.offsetX, // x1 y1 + anno.offsetY, // y1 w.globals.gridWidth + anno.offsetX, // x2 y1 + anno.offsetY, // y2 anno.borderColor, // lineColor strokeDashArray // dashArray ); parent.appendChild(line.node); } else { if (this.invertAxis) { var _catIndex = w.globals.labels.indexOf(anno.y2); var _xLabel = w.globals.dom.baseEl.querySelector('.apexcharts-yaxis-texts-g text:nth-child(' + (_catIndex + 1) + ')'); if (_xLabel) { y2 = parseFloat(_xLabel.getAttribute('y')); } } else { y2 = w.globals.gridHeight - (anno.y2 - w.globals.minYArr[anno.yAxisIndex]) / (w.globals.yRange[anno.yAxisIndex] / w.globals.gridHeight); if (w.config.yaxis[anno.yAxisIndex] && w.config.yaxis[anno.yAxisIndex].reversed) { y2 = (anno.y2 - w.globals.minYArr[anno.yAxisIndex]) / (w.globals.yRange[anno.yAxisIndex] / w.globals.gridHeight); } } if (y2 > y1) { var temp = y1; y1 = y2; y2 = temp; } if (text) { var rect = this.graphics.drawRect(0 + anno.offsetX, // x1 y2 + anno.offsetY, // y1 w.globals.gridWidth + anno.offsetX, // x2 y1 - y2, // y2 0, // radius anno.fillColor, // color anno.opacity, // opacity, 1, // strokeWidth anno.borderColor, // strokeColor strokeDashArray // stokeDashArray ); parent.appendChild(rect.node); } } var textX = anno.label.position === 'right' ? w.globals.gridWidth : 0; var elText = this.graphics.drawText({ x: textX + anno.label.offsetX, y: (y2 || y1) + anno.label.offsetY - 3, text: text, textAnchor: anno.label.textAnchor, fontSize: anno.label.style.fontSize, fontFamily: anno.label.style.fontFamily, foreColor: anno.label.style.color, cssClass: 'apexcharts-yaxis-annotation-label ' + anno.label.style.cssClass }); elText.attr({ rel: index }); parent.appendChild(elText.node); } }, { key: "drawYAxisAnnotations", value: function drawYAxisAnnotations() { var _this2 = this; var w = this.w; var elg = this.graphics.group({ class: 'apexcharts-yaxis-annotations' }); w.config.annotations.yaxis.map(function (anno, index) { _this2.addYaxisAnnotation(anno, elg.node, index); }); return elg; } }, { key: "clearAnnotations", value: function clearAnnotations(ctx) { var w = ctx.w; var annos = w.globals.dom.baseEl.querySelectorAll('.apexcharts-yaxis-annotations, .apexcharts-xaxis-annotations, .apexcharts-point-annotations'); annos = Utils.listToArray(annos); annos.forEach(function (a) { while (a.firstChild) { a.removeChild(a.firstChild); } }); } }, { key: "addPointAnnotation", value: function addPointAnnotation(anno, parent, index) { var w = this.w; var x = 0; var y = 0; var pointY = 0; if (this.invertAxis) { console.warn('Point annotation is not supported in horizontal bar charts.'); } if (typeof anno.x === 'string') { var catIndex = w.globals.labels.indexOf(anno.x); var xLabel = w.globals.dom.baseEl.querySelector('.apexcharts-xaxis-texts-g text:nth-child(' + (catIndex + 1) + ')'); var xPos = parseFloat(xLabel.getAttribute('x')); x = xPos; var annoY = anno.y; if (anno.y === null) { annoY = w.globals.series[anno.seriesIndex][catIndex]; } y = w.globals.gridHeight - (annoY - w.globals.minYArr[anno.yAxisIndex]) / (w.globals.yRange[anno.yAxisIndex] / w.globals.gridHeight) - parseInt(anno.label.style.fontSize) - anno.marker.size; pointY = w.globals.gridHeight - (annoY - w.globals.minYArr[anno.yAxisIndex]) / (w.globals.yRange[anno.yAxisIndex] / w.globals.gridHeight); if (w.config.yaxis[anno.yAxisIndex] && w.config.yaxis[anno.yAxisIndex].reversed) { y = (annoY - w.globals.minYArr[anno.yAxisIndex]) / (w.globals.yRange[anno.yAxisIndex] / w.globals.gridHeight) + parseInt(anno.label.style.fontSize) + anno.marker.size; pointY = (annoY - w.globals.minYArr[anno.yAxisIndex]) / (w.globals.yRange[anno.yAxisIndex] / w.globals.gridHeight); } } else { x = (anno.x - w.globals.minX) / (w.globals.xRange / w.globals.gridWidth); y = w.globals.gridHeight - (parseFloat(anno.y) - w.globals.minYArr[anno.yAxisIndex]) / (w.globals.yRange[anno.yAxisIndex] / w.globals.gridHeight) - parseInt(anno.label.style.fontSize) - anno.marker.size; pointY = w.globals.gridHeight - (anno.y - w.globals.minYArr[anno.yAxisIndex]) / (w.globals.yRange[anno.yAxisIndex] / w.globals.gridHeight); if (w.config.yaxis[anno.yAxisIndex] && w.config.yaxis[anno.yAxisIndex].reversed) { y = (parseFloat(anno.y) - w.globals.minYArr[anno.yAxisIndex]) / (w.globals.yRange[anno.yAxisIndex] / w.globals.gridHeight) - parseInt(anno.label.style.fontSize) - anno.marker.size; pointY = (anno.y - w.globals.minYArr[anno.yAxisIndex]) / (w.globals.yRange[anno.yAxisIndex] / w.globals.gridHeight); } } if (x < 0 || x > w.globals.gridWidth) return; var optsPoints = { pSize: anno.marker.size, pWidth: anno.marker.strokeWidth, pointFillColor: anno.marker.fillColor, pointStrokeColor: anno.marker.strokeColor, shape: anno.marker.shape, radius: anno.marker.radius, class: 'apexcharts-point-annotation-marker ' + anno.marker.cssClass }; var point = this.graphics.drawMarker(x + anno.marker.offsetX, pointY + anno.marker.offsetY, optsPoints); parent.appendChild(point.node); var text = anno.label.text ? anno.label.text : ''; var elText = this.graphics.drawText({ x: x + anno.label.offsetX, y: y + anno.label.offsetY, text: text, textAnchor: anno.label.textAnchor, fontSize: anno.label.style.fontSize, fontFamily: anno.label.style.fontFamily, foreColor: anno.label.style.color, cssClass: 'apexcharts-point-annotation-label ' + anno.label.style.cssClass }); elText.attr({ rel: index }); parent.appendChild(elText.node); if (anno.customSVG.SVG) { var g = this.graphics.group({ class: 'apexcharts-point-annotations-custom-svg ' + anno.customSVG.cssClass }); g.attr({ transform: "translate(".concat(x + anno.customSVG.offsetX, ", ").concat(y + anno.customSVG.offsetY, ")") }); g.node.innerHTML = anno.customSVG.SVG; parent.appendChild(g.node); } } }, { key: "drawPointAnnotations", value: function drawPointAnnotations() { var _this3 = this; var w = this.w; var elg = this.graphics.group({ class: 'apexcharts-point-annotations' }); w.config.annotations.points.map(function (anno, index) { _this3.addPointAnnotation(anno, elg.node, index); }); return elg; } }, { key: "setOrientations", value: function setOrientations(annos) { var _this4 = this; var annoIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var w = this.w; annos.map(function (anno, index) { if (anno.label.orientation === 'vertical') { var i = annoIndex !== null ? annoIndex : index; var xAnno = w.globals.dom.baseEl.querySelector(".apexcharts-xaxis-annotations .apexcharts-xaxis-annotation-label[rel='".concat(i, "']")); if (xAnno !== null) { var xAnnoCoord = xAnno.getBoundingClientRect(); xAnno.setAttribute('x', parseFloat(xAnno.getAttribute('x')) - xAnnoCoord.height + 4); if (anno.label.position === 'top') { xAnno.setAttribute('y', parseFloat(xAnno.getAttribute('y')) + xAnnoCoord.width); } else { xAnno.setAttribute('y', parseFloat(xAnno.getAttribute('y')) - xAnnoCoord.width); } var annoRotatingCenter = _this4.graphics.rotateAroundCenter(xAnno); var x = annoRotatingCenter.x; var y = annoRotatingCenter.y; xAnno.setAttribute('transform', "rotate(-90 ".concat(x, " ").concat(y, ")")); } } }); } }, { key: "addBackgroundToAnno", value: function addBackgroundToAnno(annoEl, anno) { var w = this.w; if (!anno.label.text) return null; var elGridRect = w.globals.dom.baseEl.querySelector('.apexcharts-grid').getBoundingClientRect(); var coords = annoEl.getBoundingClientRect(); var pleft = anno.label.style.padding.left; var pright = anno.label.style.padding.right; var ptop = anno.label.style.padding.top; var pbottom = anno.label.style.padding.bottom; if (anno.label.orientation === 'vertical') { ptop = anno.label.style.padding.left; pbottom = anno.label.style.padding.right; pleft = anno.label.style.padding.top; pright = anno.label.style.padding.bottom; } var x1 = coords.left - elGridRect.left - pleft; var y1 = coords.top - elGridRect.top - ptop; var elRect = this.graphics.drawRect(x1, y1, coords.width + pleft + pright, coords.height + ptop + pbottom, 0, anno.label.style.background, 1, anno.label.borderWidth, anno.label.borderColor, 0); return elRect; } }, { key: "annotationsBackground", value: function annotationsBackground() { var _this5 = this; var w = this.w; var add = function add(anno, i, type) { var annoLabel = w.globals.dom.baseEl.querySelector(".apexcharts-".concat(type, "-annotations .apexcharts-").concat(type, "-annotation-label[rel='").concat(i, "']")); if (annoLabel) { var parent = annoLabel.parentNode; var elRect = _this5.addBackgroundToAnno(annoLabel, anno); if (elRect) { parent.insertBefore(elRect.node, annoLabel); } } }; w.config.annotations.xaxis.map(function (anno, i) { add(anno, i, 'xaxis'); }); w.config.annotations.yaxis.map(function (anno, i) { add(anno, i, 'yaxis'); }); w.config.annotations.points.map(function (anno, i) { add(anno, i, 'point'); }); } }, { key: "addText", value: function addText(params, pushToMemory, context) { var x = params.x, y = params.y, text = params.text, textAnchor = params.textAnchor, _params$appendTo = params.appendTo, appendTo = _params$appendTo === void 0 ? '.apexcharts-inner' : _params$appendTo, foreColor = params.foreColor, fontSize = params.fontSize, fontFamily = params.fontFamily, cssClass = params.cssClass, backgroundColor = params.backgroundColor, borderWidth = params.borderWidth, strokeDashArray = params.strokeDashArray, radius = params.radius, borderColor = params.borderColor, _params$paddingLeft = params.paddingLeft, paddingLeft = _params$paddingLeft === void 0 ? 4 : _params$paddingLeft, _params$paddingRight = params.paddingRight, paddingRight = _params$paddingRight === void 0 ? 4 : _params$paddingRight, _params$paddingBottom = params.paddingBottom, paddingBottom = _params$paddingBottom === void 0 ? 2 : _params$paddingBottom, _params$paddingTop = params.paddingTop, paddingTop = _params$paddingTop === void 0 ? 2 : _params$paddingTop; var me = context; var w = me.w; var parentNode = w.globals.dom.baseEl.querySelector(appendTo); var elText = this.graphics.drawText({ x: x, y: y, text: text, textAnchor: textAnchor || 'start', fontSize: fontSize || '12px', fontFamily: fontFamily || w.config.chart.fontFamily, foreColor: foreColor || w.config.chart.foreColor, cssClass: 'apexcharts-text ' + cssClass ? cssClass : '' }); parentNode.appendChild(elText.node); var textRect = elText.bbox(); if (text) { var elRect = this.graphics.drawRect(textRect.x - paddingLeft, textRect.y - paddingTop, textRect.width + paddingLeft + paddingRight, textRect.height + paddingBottom + paddingTop, radius, backgroundColor, 1, borderWidth, borderColor, strokeDashArray); elText.before(elRect); } if (pushToMemory) { w.globals.memory.methodsToExec.push({ context: me, method: me.addText, params: { x: x, y: y, text: text, textAnchor: textAnchor, appendTo: appendTo, foreColor: foreColor, fontSize: fontSize, cssClass: cssClass, backgroundColor: backgroundColor, borderWidth: borderWidth, strokeDashArray: strokeDashArray, radius: radius, borderColor: borderColor, paddingLeft: paddingLeft, paddingRight: paddingRight, paddingBottom: paddingBottom, paddingTop: paddingTop } }); } return context; } }, { key: "addPointAnnotationExternal", value: function addPointAnnotationExternal(params, pushToMemory, context) { this.addAnnotationExternal({ params: params, pushToMemory: pushToMemory, context: context, type: 'point', contextMethod: context.addPointAnnotation }); return context; } }, { key: "addYaxisAnnotationExternal", value: function addYaxisAnnotationExternal(params, pushToMemory, context) { this.addAnnotationExternal({ params: params, pushToMemory: pushToMemory, context: context, type: 'yaxis', contextMethod: context.addYaxisAnnotation }); return context; } // The addXaxisAnnotation method requires a parent class, and user calling this method externally on the chart instance may not specify parent, hence a different method }, { key: "addXaxisAnnotationExternal", value: function addXaxisAnnotationExternal(params, pushToMemory, context) { this.addAnnotationExternal({ params: params, pushToMemory: pushToMemory, context: context, type: 'xaxis', contextMethod: context.addXaxisAnnotation }); return context; } }, { key: "addAnnotationExternal", value: function addAnnotationExternal(_ref) { var params = _ref.params, pushToMemory = _ref.pushToMemory, context = _ref.context, type = _ref.type, contextMethod = _ref.contextMethod; var me = context; var w = me.w; var parent = w.globals.dom.baseEl.querySelector(".apexcharts-".concat(type, "-annotations")); var index = parent.childNodes.length + 1; var opt = new Options(); var axesAnno = Object.assign({}, type === 'xaxis' ? opt.xAxisAnnotation : type === 'yaxis' ? opt.yAxisAnnotation : opt.pointAnnotation); var anno = Utils.extend(axesAnno, params); switch (type) { case 'xaxis': this.addXaxisAnnotation(anno, parent, index); break; case 'yaxis': this.addYaxisAnnotation(anno, parent, index); break; case 'point': this.addPointAnnotation(anno, parent, index); break; } // add background var axesAnnoLabel = w.globals.dom.baseEl.querySelector(".apexcharts-".concat(type, "-annotations .apexcharts-").concat(type, "-annotation-label[rel='").concat(index, "']")); var elRect = this.addBackgroundToAnno(axesAnnoLabel, anno); if (elRect) { parent.insertBefore(elRect.node, axesAnnoLabel); } if (pushToMemory) { w.globals.memory.methodsToExec.push({ context: me, method: contextMethod, params: params }); } return context; } }]); return Annotations; }(); /** * DateTime Class to manipulate datetime values. * * @module DateTime **/ var DateTime = /*#__PURE__*/ function () { function DateTime(ctx) { _classCallCheck(this, DateTime); this.ctx = ctx; this.w = ctx.w; this.months31 = [1, 3, 5, 7, 8, 10, 12]; this.months30 = [2, 4, 6, 9, 11]; this.daysCntOfYear = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334]; } _createClass(DateTime, [{ key: "isValidDate", value: function isValidDate(date) { return !isNaN(this.parseDate(date)); } }, { key: "getUTCTimeStamp", value: function getUTCTimeStamp(dateStr) { if (!Date.parse(dateStr)) { return dateStr; } return new Date(new Date(dateStr).toISOString().substr(0, 25)).getTime(); } }, { key: "parseDate", value: function parseDate(dateStr) { var parsed = Date.parse(dateStr); if (!isNaN(parsed)) { return this.getUTCTimeStamp(dateStr); } var output = Date.parse(dateStr.replace(/-/g, '/').replace(/[a-z]+/gi, ' ')); output = this.getUTCTimeStamp(output); return output; } // https://stackoverflow.com/a/11252167/6495043 }, { key: "treatAsUtc", value: function treatAsUtc(dateStr) { var result = new Date(dateStr); result.setMinutes(result.getMinutes() - result.getTimezoneOffset()); return result; } // http://stackoverflow.com/questions/14638018/current-time-formatting-with-javascript#answer-14638191 }, { key: "formatDate", value: function formatDate(date, format) { var utc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var convertToUTC = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; var locale = this.w.globals.locale; var MMMM = ['\x00'].concat(_toConsumableArray(locale.months)); var MMM = ['\x01'].concat(_toConsumableArray(locale.shortMonths)); var dddd = ['\x02'].concat(_toConsumableArray(locale.days)); var ddd = ['\x03'].concat(_toConsumableArray(locale.shortDays)); function ii(i, len) { var s = i + ''; len = len || 2; while (s.length < len) { s = '0' + s; } return s; } if (convertToUTC) { date = this.treatAsUtc(date); } var y = utc ? date.getUTCFullYear() : date.getFullYear(); format = format.replace(/(^|[^\\])yyyy+/g, '$1' + y); format = format.replace(/(^|[^\\])yy/g, '$1' + y.toString().substr(2, 2)); format = format.replace(/(^|[^\\])y/g, '$1' + y); var M = (utc ? date.getUTCMonth() : date.getMonth()) + 1; format = format.replace(/(^|[^\\])MMMM+/g, '$1' + MMMM[0]); format = format.replace(/(^|[^\\])MMM/g, '$1' + MMM[0]); format = format.replace(/(^|[^\\])MM/g, '$1' + ii(M)); format = format.replace(/(^|[^\\])M/g, '$1' + M); var d = utc ? date.getUTCDate() : date.getDate(); format = format.replace(/(^|[^\\])dddd+/g, '$1' + dddd[0]); format = format.replace(/(^|[^\\])ddd/g, '$1' + ddd[0]); format = format.replace(/(^|[^\\])dd/g, '$1' + ii(d)); format = format.replace(/(^|[^\\])d/g, '$1' + d); var H = utc ? date.getUTCHours() : date.getHours(); format = format.replace(/(^|[^\\])HH+/g, '$1' + ii(H)); format = format.replace(/(^|[^\\])H/g, '$1' + H); var h = H > 12 ? H - 12 : H === 0 ? 12 : H; format = format.replace(/(^|[^\\])hh+/g, '$1' + ii(h)); format = format.replace(/(^|[^\\])h/g, '$1' + h); var m = utc ? date.getUTCMinutes() : date.getMinutes(); format = format.replace(/(^|[^\\])mm+/g, '$1' + ii(m)); format = format.replace(/(^|[^\\])m/g, '$1' + m); var s = utc ? date.getUTCSeconds() : date.getSeconds(); format = format.replace(/(^|[^\\])ss+/g, '$1' + ii(s)); format = format.replace(/(^|[^\\])s/g, '$1' + s); var f = utc ? date.getUTCMilliseconds() : date.getMilliseconds(); format = format.replace(/(^|[^\\])fff+/g, '$1' + ii(f, 3)); f = Math.round(f / 10); format = format.replace(/(^|[^\\])ff/g, '$1' + ii(f)); f = Math.round(f / 10); format = format.replace(/(^|[^\\])f/g, '$1' + f); var T = H < 12 ? 'AM' : 'PM'; format = format.replace(/(^|[^\\])TT+/g, '$1' + T); format = format.replace(/(^|[^\\])T/g, '$1' + T.charAt(0)); var t = T.toLowerCase(); format = format.replace(/(^|[^\\])tt+/g, '$1' + t); format = format.replace(/(^|[^\\])t/g, '$1' + t.charAt(0)); var tz = -date.getTimezoneOffset(); var K = utc || !tz ? 'Z' : tz > 0 ? '+' : '-'; if (!utc) { tz = Math.abs(tz); var tzHrs = Math.floor(tz / 60); var tzMin = tz % 60; K += ii(tzHrs) + ':' + ii(tzMin); } format = format.replace(/(^|[^\\])K/g, '$1' + K); var day = (utc ? date.getUTCDay() : date.getDay()) + 1; format = format.replace(new RegExp(dddd[0], 'g'), dddd[day]); format = format.replace(new RegExp(ddd[0], 'g'), ddd[day]); format = format.replace(new RegExp(MMMM[0], 'g'), MMMM[M]); format = format.replace(new RegExp(MMM[0], 'g'), MMM[M]); format = format.replace(/\\(.)/g, '$1'); return format; } }, { key: "getTimeUnitsfromTimestamp", value: function getTimeUnitsfromTimestamp(minX, maxX) { var w = this.w; if (w.config.xaxis.min !== undefined) { minX = w.config.xaxis.min; } if (w.config.xaxis.max !== undefined) { maxX = w.config.xaxis.max; } var minYear = new Date(minX).getFullYear(); var maxYear = new Date(maxX).getFullYear(); var minMonth = new Date(minX).getMonth(); var maxMonth = new Date(maxX).getMonth(); var minDate = new Date(minX).getDate(); var maxDate = new Date(maxX).getDate(); var minHour = new Date(minX).getHours(); var maxHour = new Date(maxX).getHours(); var minMinute = new Date(minX).getMinutes(); var maxMinute = new Date(maxX).getMinutes(); return { minMinute: minMinute, maxMinute: maxMinute, minHour: minHour, maxHour: maxHour, minDate: minDate, maxDate: maxDate, minMonth: minMonth, maxMonth: maxMonth, minYear: minYear, maxYear: maxYear }; } }, { key: "isLeapYear", value: function isLeapYear(year) { return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0; } }, { key: "calculcateLastDaysOfMonth", value: function calculcateLastDaysOfMonth(month, year, subtract) { var days = this.determineDaysOfMonths(month, year); // whatever days we get, subtract the number of days asked return days - subtract; } }, { key: "determineDaysOfYear", value: function determineDaysOfYear(year) { var days = 365; if (this.isLeapYear(year)) { days = 366; } return days; } }, { key: "determineRemainingDaysOfYear", value: function determineRemainingDaysOfYear(year, month, date) { var dayOfYear = this.daysCntOfYear[month] + date; if (month > 1 && this.isLeapYear()) dayOfYear++; return dayOfYear; } }, { key: "determineDaysOfMonths", value: function determineDaysOfMonths(month, year) { var days = 30; month = Utils.monthMod(month); switch (true) { case this.months30.indexOf(month) > -1: if (month === 2) { if (this.isLeapYear(year)) { days = 29; } else { days = 28; } } break; case this.months31.indexOf(month) > -1: days = 31; break; default: days = 31; break; } return days; } }]); return DateTime; }(); /** * ApexCharts Default Class for setting default options for all chart types. * * @module Defaults **/ var Defaults = /*#__PURE__*/ function () { function Defaults(opts) { _classCallCheck(this, Defaults); this.opts = opts; } _createClass(Defaults, [{ key: "line", value: function line() { return { chart: { animations: { easing: 'swing' } }, dataLabels: { enabled: false }, stroke: { width: 5, curve: 'straight' }, markers: { size: 0, hover: { sizeOffset: 6 } }, xaxis: { crosshairs: { width: 1 } } }; } }, { key: "sparkline", value: function sparkline(defaults) { this.opts.yaxis[0].labels.show = false; this.opts.yaxis[0].floating = true; var ret = { grid: { show: false, padding: { left: 0, right: 0, top: 0, bottom: 0 } }, legend: { show: false }, xaxis: { labels: { show: false }, tooltip: { enabled: false }, axisBorder: { show: false } }, chart: { toolbar: { show: false }, zoom: { enabled: false } }, dataLabels: { enabled: false } }; return Utils.extend(defaults, ret); } }, { key: "bar", value: function bar() { return { chart: { stacked: false, animations: { easing: 'swing' } }, plotOptions: { bar: { dataLabels: { position: 'center' } } }, dataLabels: { style: { colors: ['#fff'] } }, stroke: { width: 0 }, fill: { opacity: 0.85 }, legend: { markers: { shape: 'square', radius: 2, size: 8 } }, tooltip: { shared: false }, xaxis: { tooltip: { enabled: false }, crosshairs: { width: 'barWidth', position: 'back', fill: { type: 'gradient' }, dropShadow: { enabled: false }, stroke: { width: 0 } } } }; } }, { key: "candlestick", value: function candlestick() { return { stroke: { width: 1, colors: ['#333'] }, dataLabels: { enabled: false }, tooltip: { shared: true, custom: function custom(_ref) { var seriesIndex = _ref.seriesIndex, dataPointIndex = _ref.dataPointIndex, w = _ref.w; var o = w.globals.seriesCandleO[seriesIndex][dataPointIndex]; var h = w.globals.seriesCandleH[seriesIndex][dataPointIndex]; var l = w.globals.seriesCandleL[seriesIndex][dataPointIndex]; var c = w.globals.seriesCandleC[seriesIndex][dataPointIndex]; return '<div class="apexcharts-tooltip-candlestick">' + '<div>Open: <span class="value">' + o + '</span></div>' + '<div>High: <span class="value">' + h + '</span></div>' + '<div>Low: <span class="value">' + l + '</span></div>' + '<div>Close: <span class="value">' + c + '</span></div>' + '</div>'; } }, states: { active: { filter: { type: 'none' } } }, xaxis: { crosshairs: { width: 1 } } }; } }, { key: "rangeBar", value: function rangeBar() { return { stroke: { width: 0 }, plotOptions: { bar: { dataLabels: { position: 'center' } } }, dataLabels: { enabled: false, formatter: function formatter(val, _ref2) { var ctx = _ref2.ctx, seriesIndex = _ref2.seriesIndex, dataPointIndex = _ref2.dataPointIndex, w = _ref2.w; var start = w.globals.seriesRangeStart[seriesIndex][dataPointIndex]; var end = w.globals.seriesRangeEnd[seriesIndex][dataPointIndex]; return end - start; }, style: { colors: ['#fff'] } }, tooltip: { shared: false, followCursor: true, custom: function custom(_ref3) { var ctx = _ref3.ctx, seriesIndex = _ref3.seriesIndex, dataPointIndex = _ref3.dataPointIndex, w = _ref3.w; var start = w.globals.seriesRangeStart[seriesIndex][dataPointIndex]; var end = w.globals.seriesRangeEnd[seriesIndex][dataPointIndex]; var startVal = ''; var endVal = ''; var color = w.globals.colors[seriesIndex]; if (w.config.tooltip.x.formatter === undefined) { if (w.config.xaxis.type === 'datetime') { var datetimeObj = new DateTime(ctx); startVal = datetimeObj.formatDate(new Date(start), w.config.tooltip.x.format, true, true); endVal = datetimeObj.formatDate(new Date(end), w.config.tooltip.x.format, true, true); } else { startVal = start; endVal = end; } } else { startVal = w.config.tooltip.x.formatter(start); endVal = w.config.tooltip.x.formatter(end); } var ylabel = w.globals.labels[dataPointIndex]; return '<div class="apexcharts-tooltip-rangebar">' + '<div> <span class="series-name" style="color: ' + color + '">' + (w.config.series[seriesIndex].name ? w.config.series[seriesIndex].name : '') + '</span></div>' + '<div> <span class="category">' + ylabel + ': </span> <span class="value start-value">' + startVal + '</span> <span class="separator">-</span> <span class="value end-value">' + endVal + '</span></div>' + '</div>'; } }, xaxis: { tooltip: { enabled: false }, crosshairs: { stroke: { width: 0 } } } }; } }, { key: "area", value: function area() { return { stroke: { width: 4 }, fill: { type: 'gradient', gradient: { inverseColors: false, shade: 'light', type: 'vertical', opacityFrom: 0.65, opacityTo: 0.5, stops: [0, 100, 100] } }, markers: { size: 0, hover: { sizeOffset: 6 } }, tooltip: { followCursor: false } }; } }, { key: "brush", value: function brush(defaults) { var ret = { chart: { toolbar: { autoSelected: 'selection', show: false }, zoom: { enabled: false } }, dataLabels: { enabled: false }, stroke: { width: 1 }, tooltip: { enabled: false }, xaxis: { tooltip: { enabled: false } } }; return Utils.extend(defaults, ret); } }, { key: "stacked100", value: function stacked100() { var _this = this; this.opts.dataLabels = this.opts.dataLabels || {}; this.opts.dataLabels.formatter = this.opts.dataLabels.formatter || undefined; var existingDataLabelFormatter = this.opts.dataLabels.formatter; this.opts.yaxis.forEach(function (yaxe, index) { _this.opts.yaxis[index].min = 0; _this.opts.yaxis[index].max = 100; }); var isBar = this.opts.chart.type === 'bar'; if (isBar) { this.opts.dataLabels.formatter = existingDataLabelFormatter || function (val) { if (typeof val === 'number') { return val ? val.toFixed(0) + '%' : val; } return val; }; } } // This function removes the left and right spacing in chart for line/area/scatter if xaxis type = category for those charts by converting xaxis = numeric. Numeric/Datetime xaxis prevents the unnecessary spacing in the left/right of the chart area }, { key: "bubble", value: function bubble() { return { dataLabels: { style: { colors: ['#fff'] } }, tooltip: { shared: false, intersect: true }, xaxis: { crosshairs: { width: 0 } }, fill: { type: 'solid', gradient: { shade: 'light', inverse: true, shadeIntensity: 0.55, opacityFrom: 0.4, opacityTo: 0.8 } } }; } }, { key: "scatter", value: function scatter() { return { dataLabels: { enabled: false }, tooltip: { shared: false, intersect: true }, markers: { size: 6, strokeWidth: 2, hover: { sizeOffset: 2 } } }; } }, { key: "heatmap", value: function heatmap() { return { chart: { stacked: false, zoom: { enabled: false } }, fill: { opacity: 1 }, dataLabels: { style: { colors: ['#fff'] } }, stroke: { colors: ['#fff'] }, tooltip: { followCursor: true, marker: { show: false }, x: { show: false } }, legend: { position: 'top', markers: { shape: 'square', size: 10, offsetY: 2 } }, grid: { padding: { right: 20 } } }; } }, { key: "pie", value: function pie() { return { chart: { toolbar: { show: false } }, plotOptions: { pie: { donut: { labels: { show: false } } } }, dataLabels: { formatter: function formatter(val) { return val.toFixed(1) + '%'; }, style: { colors: ['#fff'] }, dropShadow: { enabled: true } }, stroke: { colors: ['#fff'] }, fill: { opacity: 1, gradient: { shade: 'dark', shadeIntensity: 0.35, inverseColors: false, stops: [0, 100, 100] } }, padding: { right: 0, left: 0 }, tooltip: { theme: 'dark', fillSeriesColor: true }, legend: { position: 'right' } }; } }, { key: "donut", value: function donut() { return { chart: { toolbar: { show: false } }, dataLabels: { formatter: function formatter(val) { return val.toFixed(1) + '%'; }, style: { colors: ['#fff'] }, dropShadow: { enabled: true } }, stroke: { colors: ['#fff'] }, fill: { opacity: 1, gradient: { shade: 'dark', shadeIntensity: 0.4, inverseColors: false, type: 'vertical', opacityFrom: 1, opacityTo: 1, stops: [70, 98, 100] } }, padding: { right: 0, left: 0 }, tooltip: { theme: 'dark', fillSeriesColor: true }, legend: { position: 'right' } }; } }, { key: "radar", value: function radar() { this.opts.yaxis[0].labels.style.fontSize = '13px'; this.opts.yaxis[0].labels.offsetY = 6; return { dataLabels: { enabled: true, style: { colors: ['#a8a8a8'], fontSize: '11px' } }, stroke: { width: 2 }, markers: { size: 3, strokeWidth: 1, strokeOpacity: 1 }, fill: { opacity: 0.2 }, tooltip: { shared: false, intersect: true, followCursor: true }, grid: { show: false }, xaxis: { tooltip: { enabled: false }, crosshairs: { show: false } } }; } }, { key: "radialBar", value: function radialBar() { return { chart: { animations: { dynamicAnimation: { enabled: true, speed: 800 } }, toolbar: { show: false } }, fill: { gradient: { shade: 'dark', shadeIntensity: 0.4, inverseColors: false, type: 'diagonal2', opacityFrom: 1, opacityTo: 1, stops: [70, 98, 100] } }, padding: { right: 0, left: 0 }, legend: { show: false, position: 'right' }, tooltip: { enabled: false, fillSeriesColor: true } }; } }], [{ key: "convertCatToNumeric", value: function convertCatToNumeric(opts) { opts.xaxis.type = 'numeric'; opts.xaxis.convertedCatToNumeric = true; opts.xaxis.labels = opts.xaxis.labels || {}; opts.xaxis.labels.formatter = opts.xaxis.labels.formatter || function (val) { return val; }; opts.chart = opts.chart || {}; opts.chart.zoom = opts.chart.zoom || window.Apex.chart && window.Apex.chart.zoom || {}; var defaultFormatter = opts.xaxis.labels.formatter; var labels = opts.xaxis.categories && opts.xaxis.categories.length ? opts.xaxis.categories : opts.labels; if (labels && labels.length) { opts.xaxis.labels.formatter = function (val) { return defaultFormatter(labels[val - 1]); }; } opts.xaxis.categories = []; opts.labels = []; opts.chart.zoom.enabled = opts.chart.zoom.enabled || false; return opts; } }]); return Defaults; }(); /* ** Util functions which are dependent on ApexCharts instance */ var CoreUtils = /*#__PURE__*/ function () { function CoreUtils(ctx) { _classCallCheck(this, CoreUtils); this.ctx = ctx; this.w = ctx.w; } _createClass(CoreUtils, [{ key: "getStackedSeriesTotals", /** * @memberof CoreUtils * returns the sum of all individual values in a multiple stacked series * Eg. w.globals.series = [[32,33,43,12], [2,3,5,1]] * @return [34,36,48,13] **/ value: function getStackedSeriesTotals() { var w = this.w; var total = []; for (var i = 0; i < w.globals.series[w.globals.maxValsInArrayIndex].length; i++) { var t = 0; for (var j = 0; j < w.globals.series.length; j++) { t += w.globals.series[j][i]; } total.push(t); } w.globals.stackedSeriesTotals = total; return total; } // get total of the all values inside all series }, { key: "getSeriesTotalByIndex", value: function getSeriesTotalByIndex() { var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; if (index === null) { // non-plot chart types - pie / donut / circle return this.w.config.series.reduce(function (acc, cur) { return acc + cur; }, 0); } else { // axis charts - supporting multiple series return this.w.globals.series[index].reduce(function (acc, cur) { return acc + cur; }, 0); } } }, { key: "isSeriesNull", value: function isSeriesNull() { var index = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var r = []; if (index === null) { // non-plot chart types - pie / donut / circle r = this.w.config.series.filter(function (d) { return d !== null; }); } else { // axis charts - supporting multiple series r = this.w.globals.series[index].filter(function (d) { return d !== null; }); } return r.length === 0; } }, { key: "seriesHaveSameValues", value: function seriesHaveSameValues(index) { return this.w.globals.series[index].every(function (val, i, arr) { return val === arr[0]; }); } // maxValsInArrayIndex is the index of series[] which has the largest number of items }, { key: "getLargestSeries", value: function getLargestSeries() { var w = this.w; w.globals.maxValsInArrayIndex = w.globals.series.map(function (a) { return a.length; }).indexOf(Math.max.apply(Math, w.globals.series.map(function (a) { return a.length; }))); } }, { key: "getLargestMarkerSize", value: function getLargestMarkerSize() { var w = this.w; var size = 0; w.globals.markers.size.forEach(function (m) { size = Math.max(size, m); }); w.globals.markers.largestSize = size; return size; } /** * @memberof Core * returns the sum of all values in a series * Eg. w.globals.series = [[32,33,43,12], [2,3,5,1]] * @return [120, 11] **/ }, { key: "getSeriesTotals", value: function getSeriesTotals() { var w = this.w; w.globals.seriesTotals = w.globals.series.map(function (ser, index) { var total = 0; if (Array.isArray(ser)) { for (var j = 0; j < ser.length; j++) { total += ser[j]; } } else { // for pie/donuts/gauges total += ser; } return total; }); } }, { key: "getSeriesTotalsXRange", value: function getSeriesTotalsXRange(minX, maxX) { var w = this.w; var seriesTotalsXRange = w.globals.series.map(function (ser, index) { var total = 0; for (var j = 0; j < ser.length; j++) { if (w.globals.seriesX[index][j] > minX && w.globals.seriesX[index][j] < maxX) { total += ser[j]; } } return total; }); return seriesTotalsXRange; } /** * @memberof CoreUtils * returns the percentage value of all individual values which can be used in a 100% stacked series * Eg. w.globals.series = [[32, 33, 43, 12], [2, 3, 5, 1]] * @return [[94.11, 91.66, 89.58, 92.30], [5.88, 8.33, 10.41, 7.7]] **/ }, { key: "getPercentSeries", value: function getPercentSeries() { var w = this.w; w.globals.seriesPercent = w.globals.series.map(function (ser, index) { var seriesPercent = []; if (Array.isArray(ser)) { for (var j = 0; j < ser.length; j++) { var total = w.globals.stackedSeriesTotals[j]; var percent = 100 * ser[j] / total; seriesPercent.push(percent); } } else { var _total = w.globals.seriesTotals.reduce(function (acc, val) { return acc + val; }, 0); var _percent = 100 * ser / _total; seriesPercent.push(_percent); } return seriesPercent; }); } }, { key: "getCalculatedRatios", value: function getCalculatedRatios() { var gl = this.w.globals; var yRatio = []; var invertedYRatio = 0; var xRatio = 0; var initialXRatio = 0; var invertedXRatio = 0; var zRatio = 0; var baseLineY = []; var baseLineInvertedY = 0.1; var baseLineX = 0; gl.yRange = []; if (gl.isMultipleYAxis) { for (var i = 0; i < gl.minYArr.length; i++) { gl.yRange.push(Math.abs(gl.minYArr[i] - gl.maxYArr[i])); baseLineY.push(0); } } else { gl.yRange.push(Math.abs(gl.minY - gl.maxY)); } gl.xRange = Math.abs(gl.maxX - gl.minX); gl.zRange = Math.abs(gl.maxZ - gl.minZ); // multiple y axis for (var _i = 0; _i < gl.yRange.length; _i++) { yRatio.push(gl.yRange[_i] / gl.gridHeight); } xRatio = gl.xRange / gl.gridWidth; initialXRatio = Math.abs(gl.initialmaxX - gl.initialminX) / gl.gridWidth; invertedYRatio = gl.yRange / gl.gridWidth; invertedXRatio = gl.xRange / gl.gridHeight; zRatio = gl.zRange / gl.gridHeight * 16; if (gl.minY !== Number.MIN_VALUE && Math.abs(gl.minY) !== 0) { // Negative numbers present in series gl.hasNegs = true; } if (gl.isMultipleYAxis) { baseLineY = []; // baseline variables is the 0 of the yaxis which will be needed when there are negatives for (var _i2 = 0; _i2 < yRatio.length; _i2++) { baseLineY.push(-gl.minYArr[_i2] / yRatio[_i2]); } } else { baseLineY.push(-gl.minY / yRatio[0]); if (gl.minY !== Number.MIN_VALUE && Math.abs(gl.minY) !== 0) { baseLineInvertedY = -gl.minY / invertedYRatio; // this is for bar chart baseLineX = gl.minX / xRatio; } } return { yRatio: yRatio, invertedYRatio: invertedYRatio, zRatio: zRatio, xRatio: xRatio, initialXRatio: initialXRatio, invertedXRatio: invertedXRatio, baseLineInvertedY: baseLineInvertedY, baseLineY: baseLineY, baseLineX: baseLineX }; } }, { key: "getLogSeries", value: function getLogSeries(series) { var w = this.w; w.globals.seriesLog = series.map(function (s, i) { if (w.config.yaxis[i] && w.config.yaxis[i].logarithmic) { return s.map(function (d) { if (d === null) return null; var logVal = (Math.log(d) - Math.log(w.globals.minYArr[i])) / (Math.log(w.globals.maxYArr[i]) - Math.log(w.globals.minYArr[i])); return logVal; }); } else { return s; } }); return w.globals.seriesLog; } }, { key: "getLogYRatios", value: function getLogYRatios(yRatio) { var _this = this; var w = this.w; var gl = this.w.globals; gl.yLogRatio = yRatio.slice(); gl.logYRange = gl.yRange.map(function (yRange, i) { if (w.config.yaxis[i] && _this.w.config.yaxis[i].logarithmic) { var maxY = -Number.MAX_VALUE; var minY = Number.MIN_VALUE; var range = 1; gl.seriesLog.forEach(function (s, si) { s.forEach(function (v) { if (w.config.yaxis[si] && w.config.yaxis[si].logarithmic) { maxY = Math.max(v, maxY); minY = Math.min(v, minY); } }); }); range = Math.pow(gl.yRange[i], Math.abs(minY - maxY) / gl.yRange[i]); gl.yLogRatio[i] = range / gl.gridHeight; return range; } }); return gl.yLogRatio; } // Some config objects can be array - and we need to extend them correctly }], [{ key: "checkComboSeries", value: function checkComboSeries(series) { var comboCharts = false; var comboChartsHasBars = false; // if user specified a type in series too, turn on comboCharts flag if (series.length && typeof series[0].type !== 'undefined') { comboCharts = true; series.forEach(function (s) { if (s.type === 'bar' || s.type === 'column') { comboChartsHasBars = true; } }); } return { comboCharts: comboCharts, comboChartsHasBars: comboChartsHasBars }; } }, { key: "extendArrayProps", value: function extendArrayProps(configInstance, options) { if (options.yaxis) { options = configInstance.extendYAxis(options); } if (options.annotations) { if (options.annotations.yaxis) { options = configInstance.extendYAxisAnnotations(options); } if (options.annotations.xaxis) { options = configInstance.extendXAxisAnnotations(options); } if (options.annotations.points) { options = configInstance.extendPointAnnotations(options); } } return options; } }]); return CoreUtils; }(); /** * ApexCharts Config Class for extending user options with pre-defined ApexCharts config. * * @module Config **/ var Config = /*#__PURE__*/ function () { function Config(opts) { _classCallCheck(this, Config); this.opts = opts; } _createClass(Config, [{ key: "init", value: function init() { var opts = this.opts; var options = new Options(); var defaults = new Defaults(opts); this.chartType = opts.chart.type; if (this.chartType === 'histogram') { // technically, a histogram can be drawn by a column chart with no spaces in between opts.chart.type = 'bar'; opts = Utils.extend({ plotOptions: { bar: { columnWidth: '99.99%' } } }, opts); } opts.series = this.checkEmptySeries(opts.series); opts = this.extendYAxis(opts); opts = this.extendAnnotations(opts); var config = options.init(); var newDefaults = {}; if (opts && _typeof(opts) === 'object') { var chartDefaults = {}; switch (this.chartType) { case 'line': chartDefaults = defaults.line(); break; case 'area': chartDefaults = defaults.area(); break; case 'bar': chartDefaults = defaults.bar(); break; case 'candlestick': chartDefaults = defaults.candlestick(); break; case 'rangeBar': chartDefaults = defaults.rangeBar(); break; case 'histogram': chartDefaults = defaults.bar(); break; case 'bubble': chartDefaults = defaults.bubble(); break; case 'scatter': chartDefaults = defaults.scatter(); break; case 'heatmap': chartDefaults = defaults.heatmap(); break; case 'pie': chartDefaults = defaults.pie(); break; case 'donut': chartDefaults = defaults.donut(); break; case 'radar': chartDefaults = defaults.radar(); break; case 'radialBar': chartDefaults = defaults.radialBar(); break; default: chartDefaults = defaults.line(); } if (opts.chart.brush && opts.chart.brush.enabled) { chartDefaults = defaults.brush(chartDefaults); } if (opts.chart.stacked && opts.chart.stackType === '100%') { defaults.stacked100(); } // If user has specified a dark theme, make the tooltip dark too this.checkForDarkTheme(window.Apex); // check global window Apex options this.checkForDarkTheme(opts); // check locally passed options opts.xaxis = opts.xaxis || window.Apex.xaxis || {}; var combo = CoreUtils.checkComboSeries(opts.series); if ((opts.chart.type === 'line' || opts.chart.type === 'area' || opts.chart.type === 'scatter') && !combo.comboChartsHasBars && opts.xaxis.type !== 'datetime' && opts.xaxis.type !== 'numeric' && opts.xaxis.tickPlacement !== 'between') { opts = Defaults.convertCatToNumeric(opts); } if (opts.chart.sparkline && opts.chart.sparkline.enabled || window.Apex.chart && window.Apex.chart.sparkline && window.Apex.chart.sparkline.enabled) { chartDefaults = defaults.sparkline(chartDefaults); } newDefaults = Utils.extend(config, chartDefaults); } // config should cascade in this fashion // default-config < global-apex-variable-config < user-defined-config // get GLOBALLY defined options and merge with the default config var mergedWithDefaultConfig = Utils.extend(newDefaults, window.Apex); // get the merged config and extend with user defined config config = Utils.extend(mergedWithDefaultConfig, opts); // some features are not supported. those mismatches should be handled config = this.handleUserInputErrors(config); return config; } }, { key: "extendYAxis", value: function extendYAxis(opts) { var options = new Options(); if (typeof opts.yaxis === 'undefined') { opts.yaxis = {}; } // extend global yaxis config (only if object is provided / not an array) if (opts.yaxis.constructor !== Array && window.Apex.yaxis && window.Apex.yaxis.constructor !== Array) { opts.yaxis = Utils.extend(opts.yaxis, window.Apex.yaxis); } // as we can't extend nested object's array with extend, we need to do it first // user can provide either an array or object in yaxis config if (opts.yaxis.constructor !== Array) { // convert the yaxis to array if user supplied object opts.yaxis = [Utils.extend(options.yAxis, opts.yaxis)]; } else { opts.yaxis = Utils.extendArray(opts.yaxis, options.yAxis); } return opts; } // annotations also accepts array, so we need to extend them manually }, { key: "extendAnnotations", value: function extendAnnotations(opts) { if (typeof opts.annotations === 'undefined') { opts.annotations = {}; opts.annotations.yaxis = []; opts.annotations.xaxis = []; opts.annotations.points = []; } opts = this.extendYAxisAnnotations(opts); opts = this.extendXAxisAnnotations(opts); opts = this.extendPointAnnotations(opts); return opts; } }, { key: "extendYAxisAnnotations", value: function extendYAxisAnnotations(opts) { var options = new Options(); opts.annotations.yaxis = Utils.extendArray(typeof opts.annotations.yaxis !== 'undefined' ? opts.annotations.yaxis : [], options.yAxisAnnotation); return opts; } }, { key: "extendXAxisAnnotations", value: function extendXAxisAnnotations(opts) { var options = new Options(); opts.annotations.xaxis = Utils.extendArray(typeof opts.annotations.xaxis !== 'undefined' ? opts.annotations.xaxis : [], options.xAxisAnnotation); return opts; } }, { key: "extendPointAnnotations", value: function extendPointAnnotations(opts) { var options = new Options(); opts.annotations.points = Utils.extendArray(typeof opts.annotations.points !== 'undefined' ? opts.annotations.points : [], options.pointAnnotation); return opts; } }, { key: "checkForDarkTheme", value: function checkForDarkTheme(opts) { if (opts.theme && opts.theme.mode === 'dark') { if (!opts.tooltip) { opts.tooltip = {}; } if (opts.tooltip.theme !== 'light') { opts.tooltip.theme = 'dark'; } if (!opts.chart.foreColor) { opts.chart.foreColor = '#f6f7f8'; } if (!opts.theme.palette) { opts.theme.palette = 'palette4'; } } } }, { key: "checkEmptySeries", value: function checkEmptySeries(ser) { if (ser.length === 0) { return [{ data: [] }]; } return ser; } }, { key: "handleUserInputErrors", value: function handleUserInputErrors(opts) { var config = opts; // conflicting tooltip option. intersect makes sure to focus on 1 point at a time. Shared cannot be used along with it if (config.tooltip.shared && config.tooltip.intersect) { throw new Error('tooltip.shared cannot be enabled when tooltip.intersect is true. Turn off any other option by setting it to false.'); } if (config.chart.scroller) { console.warn('Scroller has been deprecated since v2.0.0. Please remove the configuration for chart.scroller'); } if ((config.chart.type === 'bar' || config.chart.type === 'rangeBar') && config.plotOptions.bar.horizontal) { // No multiple yaxis for bars if (config.yaxis.length > 1) { throw new Error('Multiple Y Axis for bars are not supported. Switch to column chart by setting plotOptions.bar.horizontal=false'); } // if yaxis is reversed in horizontal bar chart, you should draw the y-axis on right side if (config.yaxis[0].reversed) { config.yaxis[0].opposite = true; } config.xaxis.tooltip.enabled = false; // no xaxis tooltip for horizontal bar config.yaxis[0].tooltip.enabled = false; // no xaxis tooltip for horizontal bar config.chart.zoom.enabled = false; // no zooming for horz bars } if (config.chart.type === 'bar' || config.chart.type === 'rangeBar') { if (config.tooltip.shared) { if (config.xaxis.crosshairs.width === 'barWidth' && config.series.length > 1) { console.warn('crosshairs.width = "barWidth" is only supported in single series, not in a multi-series barChart.'); config.xaxis.crosshairs.width = 'tickWidth'; } if (config.plotOptions.bar.horizontal) { config.states.hover.type = 'none'; config.tooltip.shared = false; } if (!config.tooltip.followCursor) { console.warn('followCursor option in shared columns cannot be turned off. Please set %ctooltip.followCursor: true', 'color: blue;'); config.tooltip.followCursor = true; } } } if (config.chart.type === 'candlestick') { if (config.yaxis[0].reversed) { console.warn('Reversed y-axis in candlestick chart is not supported.'); config.yaxis[0].reversed = false; } } if (config.chart.group && config.yaxis[0].labels.minWidth === 0) { console.warn('It looks like you have multiple charts in synchronization. You must provide yaxis.labels.minWidth which must be EQUAL for all grouped charts to prevent incorrect behaviour.'); } // if user supplied array for stroke width, it will only be applicable to line/area charts, for any other charts, revert back to Number if (Array.isArray(config.stroke.width)) { if (config.chart.type !== 'line' && config.chart.type !== 'area') { console.warn('stroke.width option accepts array only for line and area charts. Reverted back to Number'); config.stroke.width = config.stroke.width[0]; } } return config; } }]); return Config; }(); var Globals = /*#__PURE__*/ function () { function Globals() { _classCallCheck(this, Globals); } _createClass(Globals, [{ key: "globalVars", value: function globalVars(config) { return { chartID: null, // chart ID - apexcharts-cuid cuid: null, // chart ID - random numbers excluding "apexcharts" part events: { beforeMount: [], mounted: [], updated: [], clicked: [], selection: [], dataPointSelection: [], zoomed: [], scrolled: [] }, colors: [], clientX: null, clientY: null, fill: { colors: [] }, stroke: { colors: [] }, dataLabels: { style: { colors: [] } }, radarPolygons: { fill: { colors: [] } }, markers: { colors: [], size: config.markers.size, largestSize: 0 }, animationEnded: false, isTouchDevice: 'ontouchstart' in window || navigator.msMaxTouchPoints, isDirty: false, // chart has been updated after the initial render. This is different than dataChanged property. isDirty means user manually called some method to update initialConfig: null, // we will store the first config user has set to go back when user finishes interactions like zooming and come out of it lastXAxis: [], lastYAxis: [], series: [], // the MAIN series array (y values) seriesRangeStart: [], // the clone of series becomes the start in range seriesRangeEnd: [], // the end values in range chart seriesPercent: [], // the percentage values of the given series seriesTotals: [], stackedSeriesTotals: [], seriesX: [], // store the numeric x values in this array (x values) seriesZ: [], // The 3rd "Z" dimension for bubbles chart (z values) labels: [], // store the text to draw on x axis // Don't mutate the labels, many things including tooltips depends on it! timelineLabels: [], // store the timeline Labels in another variable invertedTimelineLabels: [], // for rangebar timeline seriesNames: [], // same as labels, used in non axis charts noLabelsProvided: false, // if user didn't provide any categories/labels or x values, fallback to 1,2,3,4... allSeriesCollapsed: false, collapsedSeries: [], // when user collapses a series, it goes into this array collapsedSeriesIndices: [], // this stores the index of the collapsedSeries instead of whole object for quick access ancillaryCollapsedSeries: [], // when user collapses an "alwaysVisible" series, it goes into this array ancillaryCollapsedSeriesIndices: [], // this stores the index of the ancillaryCollapsedSeries whose y-axis is always visible risingSeries: [], // when user re-opens a collapsed series, it goes here dataFormatXNumeric: false, // boolean value to indicate user has passed numeric x values selectedDataPoints: [], ignoreYAxisIndexes: [], // when series are being collapsed in multiple y axes, ignore certain index padHorizontal: 0, maxValsInArrayIndex: 0, zoomEnabled: config.chart.toolbar.autoSelected === 'zoom' && config.chart.toolbar.tools.zoom && config.chart.zoom.enabled, panEnabled: config.chart.toolbar.autoSelected === 'pan' && config.chart.toolbar.tools.pan, selectionEnabled: config.chart.toolbar.autoSelected === 'selection' && config.chart.toolbar.tools.selection, yaxis: null, minY: Number.MIN_VALUE, // is 5e-324, i.e. the smallest positive number // NOTE: If there are multiple y axis, the first yaxis array element will be considered for all y values calculations. Rest all will be calculated based on that maxY: -Number.MAX_VALUE, // is -1.7976931348623157e+308 // NOTE: The above note for minY applies here as well minYArr: [], maxYArr: [], maxX: -Number.MAX_VALUE, // is -1.7976931348623157e+308 initialmaxX: -Number.MAX_VALUE, minX: Number.MIN_VALUE, // is 5e-324, i.e. the smallest positive number initialminX: Number.MIN_VALUE, minZ: Number.MIN_VALUE, // Max Z value in charts with Z axis maxZ: -Number.MAX_VALUE, // Max Z value in charts with Z axis minXDiff: Number.MAX_VALUE, mousedown: false, lastClientPosition: {}, // don't reset this variable this the chart is destroyed. It is used to detect right or left mousemove in panning visibleXRange: undefined, yRange: [], // this property is the absolute sum of positive and negative values [eg (-100 + 200 = 300)] - yAxis zRange: 0, // zAxis Range (for bubble charts) xRange: 0, // xAxis range yValueDecimal: 0, // are there floating numbers in the series. If yes, this represent the len of the decimals total: 0, SVGNS: 'http://www.w3.org/2000/svg', // svg namespace svgWidth: 0, // the whole svg width svgHeight: 0, // the whole svg height noData: false, // whether there is any data to display or not locale: {}, // the current locale values will be preserved here for global access dom: {}, // for storing all dom nodes in this particular property // elWrap: null, // the element that wraps everything // elGraphical: null, // this contains lines/areas/bars/pies // elGridRect: null, // paths going outside this area will be clipped // elGridRectMask: null, // clipping will happen with this mask // elGridRectMarkerMask: null, // clipping will happen with this mask // elLegendWrap: null, // the whole legend area // elDefs: null, // [defs] element memory: { methodsToExec: [] }, shouldAnimate: true, skipLastTimelinelabel: false, // when last label is cropped, skip drawing it delayedElements: [], // element which appear after animation has finished axisCharts: true, // chart type = line or area or bar // (refer them also as plot charts in the code) isXNumeric: false, // bool: data was provided in a {[x,y], [x,y]} pattern isDataXYZ: false, // bool: data was provided in a {[x,y,z]} pattern resized: false, // bool: user has resized resizeTimer: null, // timeout function to make a small delay before // drawing when user resized comboCharts: false, // bool: whether it's a combination of line/column comboChartsHasBars: false, // bool: whether it's a combination of line/column dataChanged: false, // bool: has data changed dynamically previousPaths: [], // array: when data is changed, it will animate from // previous paths seriesXvalues: [], // we will need this in tooltip (it's x position) // when we will have unequal x values, we will need // some way to get x value depending on mouse pointer seriesYvalues: [], // we will need this when deciding which series // user hovered on seriesCandleO: [], // candle stick open values seriesCandleH: [], // candle stick high values seriesCandleL: [], // candle stick low values seriesCandleC: [], // candle stick close values allSeriesHasEqualX: true, dataPoints: 0, // the longest series length pointsArray: [], // store the points positions here to draw later on hover // format is - [[x,y],[x,y]... [x,y]] dataLabelsRects: [], // store the positions of datalabels to prevent collision lastDrawnDataLabelsIndexes: [], hasNullValues: false, // bool: whether series contains null values easing: null, // function: animation effect to apply zoomed: false, // whether user has zoomed or not gridWidth: 0, // drawable width of actual graphs (series paths) gridHeight: 0, // drawable height of actual graphs (series paths) yAxisScale: [], xAxisScale: null, xAxisTicksPositions: [], timescaleTicks: [], rotateXLabels: false, defaultLabels: false, xLabelFormatter: undefined, // formatter for x axis labels yLabelFormatters: [], xaxisTooltipFormatter: undefined, // formatter for x axis tooltip ttKeyFormatter: undefined, ttVal: undefined, ttZFormatter: undefined, LINE_HEIGHT_RATIO: 1.618, xAxisLabelsHeight: 0, yAxisLabelsWidth: 0, scaleX: 1, scaleY: 1, translateX: 0, translateY: 0, translateYAxisX: [], yLabelsCoords: [], yTitleCoords: [], yAxisWidths: [], translateXAxisY: 0, translateXAxisX: 0, tooltip: null, tooltipOpts: null }; } }, { key: "init", value: function init(config) { var globals = this.globalVars(config); globals.initialConfig = Utils.extend({}, config); globals.initialSeries = JSON.parse(JSON.stringify(globals.initialConfig.series)); globals.lastXAxis = JSON.parse(JSON.stringify(globals.initialConfig.xaxis)); globals.lastYAxis = JSON.parse(JSON.stringify(globals.initialConfig.yaxis)); return globals; } }]); return Globals; }(); /** * ApexCharts Base Class for extending user options with pre-defined ApexCharts config. * * @module Base **/ var Base = /*#__PURE__*/ function () { function Base(opts) { _classCallCheck(this, Base); this.opts = opts; } _createClass(Base, [{ key: "init", value: function init() { var config = new Config(this.opts).init(); var globals = new Globals().init(config); var w = { config: config, globals: globals }; return w; } }]); return Base; }(); /** * ApexCharts Fill Class for setting fill options of the paths. * * @module Fill **/ var Fill = /*#__PURE__*/ function () { function Fill(ctx) { _classCallCheck(this, Fill); this.ctx = ctx; this.w = ctx.w; this.opts = null; this.seriesIndex = 0; } _createClass(Fill, [{ key: "clippedImgArea", value: function clippedImgArea(params) { var w = this.w; var cnf = w.config; var svgW = parseInt(w.globals.gridWidth); var svgH = parseInt(w.globals.gridHeight); var size = svgW > svgH ? svgW : svgH; var fillImg = params.image; var imgWidth = 0; var imgHeight = 0; if (typeof params.width === 'undefined' && typeof params.height === 'undefined') { if (cnf.fill.image.width !== undefined && cnf.fill.image.height !== undefined) { imgWidth = cnf.fill.image.width + 1; imgHeight = cnf.fill.image.height; } else { imgWidth = size + 1; imgHeight = size; } } else { imgWidth = params.width; imgHeight = params.height; } var elPattern = document.createElementNS(w.globals.SVGNS, 'pattern'); Graphics.setAttrs(elPattern, { id: params.patternID, patternUnits: params.patternUnits ? params.patternUnits : 'userSpaceOnUse', width: imgWidth + 'px', height: imgHeight + 'px' }); var elImage = document.createElementNS(w.globals.SVGNS, 'image'); elPattern.appendChild(elImage); elImage.setAttributeNS('http://www.w3.org/1999/xlink', 'href', fillImg); Graphics.setAttrs(elImage, { x: 0, y: 0, preserveAspectRatio: 'none', width: imgWidth + 'px', height: imgHeight + 'px' }); elImage.style.opacity = params.opacity; w.globals.dom.elDefs.node.appendChild(elPattern); } }, { key: "getSeriesIndex", value: function getSeriesIndex(opts) { var w = this.w; if (w.config.chart.type === 'bar' && w.config.plotOptions.bar.distributed || w.config.chart.type === 'heatmap') { this.seriesIndex = opts.seriesNumber; } else { this.seriesIndex = opts.seriesNumber % w.globals.series.length; } return this.seriesIndex; } }, { key: "fillPath", value: function fillPath(opts) { var w = this.w; this.opts = opts; var cnf = this.w.config; var pathFill; var patternFill, gradientFill; this.seriesIndex = this.getSeriesIndex(opts); var fillColors = this.getFillColors(); var fillColor = fillColors[this.seriesIndex]; if (typeof fillColor === 'function') { fillColor = fillColor({ seriesIndex: this.seriesIndex, value: opts.value, w: w }); } var fillType = this.getFillType(this.seriesIndex); var fillOpacity = Array.isArray(cnf.fill.opacity) ? cnf.fill.opacity[this.seriesIndex] : cnf.fill.opacity; var defaultColor = fillColor; if (opts.color) { fillColor = opts.color; } if (fillColor.indexOf('rgb') === -1) { defaultColor = Utils.hexToRgba(fillColor, fillOpacity); } else { if (fillColor.indexOf('rgba') > -1) { fillOpacity = 0 + '.' + Utils.getOpacityFromRGBA(fillColors[this.seriesIndex]); } } if (fillType === 'pattern') { patternFill = this.handlePatternFill(patternFill, fillColor, fillOpacity, defaultColor); } if (fillType === 'gradient') { gradientFill = this.handleGradientFill(gradientFill, fillColor, fillOpacity, this.seriesIndex); } if (cnf.fill.image.src.length > 0 && fillType === 'image') { if (opts.seriesNumber < cnf.fill.image.src.length) { this.clippedImgArea({ opacity: fillOpacity, image: cnf.fill.image.src[opts.seriesNumber], patternUnits: opts.patternUnits, patternID: "pattern".concat(w.globals.cuid).concat(opts.seriesNumber + 1) }); pathFill = "url(#pattern".concat(w.globals.cuid).concat(opts.seriesNumber + 1, ")"); } else { pathFill = defaultColor; } } else if (fillType === 'gradient') { pathFill = gradientFill; } else if (fillType === 'pattern') { pathFill = patternFill; } else { pathFill = defaultColor; } // override pattern/gradient if opts.solid is true if (opts.solid) { pathFill = defaultColor; } return pathFill; } }, { key: "getFillType", value: function getFillType(seriesIndex) { var w = this.w; if (Array.isArray(w.config.fill.type)) { return w.config.fill.type[seriesIndex]; } else { return w.config.fill.type; } } }, { key: "getFillColors", value: function getFillColors() { var w = this.w; var cnf = w.config; var opts = this.opts; var fillColors = []; if (w.globals.comboCharts) { if (w.config.series[this.seriesIndex].type === 'line') { if (w.globals.stroke.colors instanceof Array) { fillColors = w.globals.stroke.colors; } else { fillColors.push(w.globals.stroke.colors); } } else { if (w.globals.fill.colors instanceof Array) { fillColors = w.globals.fill.colors; } else { fillColors.push(w.globals.fill.colors); } } } else { if (cnf.chart.type === 'line') { if (w.globals.stroke.colors instanceof Array) { fillColors = w.globals.stroke.colors; } else { fillColors.push(w.globals.stroke.colors); } } else { if (w.globals.fill.colors instanceof Array) { fillColors = w.globals.fill.colors; } else { fillColors.push(w.globals.fill.colors); } } } // colors passed in arguments if (typeof opts.fillColors !== 'undefined') { fillColors = []; if (opts.fillColors instanceof Array) { fillColors = opts.fillColors.slice(); } else { fillColors.push(opts.fillColors); } } return fillColors; } }, { key: "handlePatternFill", value: function handlePatternFill(patternFill, fillColor, fillOpacity, defaultColor) { var cnf = this.w.config; var opts = this.opts; var graphics = new Graphics(this.ctx); var patternStrokeWidth = cnf.fill.pattern.strokeWidth === undefined ? Array.isArray(cnf.stroke.width) ? cnf.stroke.width[this.seriesIndex] : cnf.stroke.width : Array.isArray(cnf.fill.pattern.strokeWidth) ? cnf.fill.pattern.strokeWidth[this.seriesIndex] : cnf.fill.pattern.strokeWidth; var patternLineColor = fillColor; if (cnf.fill.pattern.style instanceof Array) { if (typeof cnf.fill.pattern.style[opts.seriesNumber] !== 'undefined') { var pf = graphics.drawPattern(cnf.fill.pattern.style[opts.seriesNumber], cnf.fill.pattern.width, cnf.fill.pattern.height, patternLineColor, patternStrokeWidth, fillOpacity); patternFill = pf; } else { patternFill = defaultColor; } } else { patternFill = graphics.drawPattern(cnf.fill.pattern.style, cnf.fill.pattern.width, cnf.fill.pattern.height, patternLineColor, patternStrokeWidth, fillOpacity); } return patternFill; } }, { key: "handleGradientFill", value: function handleGradientFill(gradientFill, fillColor, fillOpacity, i) { var cnf = this.w.config; var opts = this.opts; var graphics = new Graphics(this.ctx); var utils = new Utils(); var type = cnf.fill.gradient.type; var gradientFrom, gradientTo; var opacityFrom = cnf.fill.gradient.opacityFrom === undefined ? fillOpacity : Array.isArray(cnf.fill.gradient.opacityFrom) ? cnf.fill.gradient.opacityFrom[i] : cnf.fill.gradient.opacityFrom; var opacityTo = cnf.fill.gradient.opacityTo === undefined ? fillOpacity : Array.isArray(cnf.fill.gradient.opacityTo) ? cnf.fill.gradient.opacityTo[i] : cnf.fill.gradient.opacityTo; gradientFrom = fillColor; if (cnf.fill.gradient.gradientToColors === undefined || cnf.fill.gradient.gradientToColors.length === 0) { if (cnf.fill.gradient.shade === 'dark') { gradientTo = utils.shadeColor(parseFloat(cnf.fill.gradient.shadeIntensity) * -1, fillColor); } else { gradientTo = utils.shadeColor(parseFloat(cnf.fill.gradient.shadeIntensity), fillColor); } } else { gradientTo = cnf.fill.gradient.gradientToColors[opts.seriesNumber]; } if (cnf.fill.gradient.inverseColors) { var t = gradientFrom; gradientFrom = gradientTo; gradientTo = t; } gradientFill = graphics.drawGradient(type, gradientFrom, gradientTo, opacityFrom, opacityTo, opts.size, cnf.fill.gradient.stops, cnf.fill.gradient.colorStops, i); return gradientFill; } }]); return Fill; }(); /** * ApexCharts Markers Class for drawing points on y values in axes charts. * * @module Markers **/ var Markers = /*#__PURE__*/ function () { function Markers(ctx, opts) { _classCallCheck(this, Markers); this.ctx = ctx; this.w = ctx.w; } _createClass(Markers, [{ key: "setGlobalMarkerSize", value: function setGlobalMarkerSize() { var w = this.w; w.globals.markers.size = Array.isArray(w.config.markers.size) ? w.config.markers.size : [w.config.markers.size]; if (w.globals.markers.size.length > 0) { if (w.globals.markers.size.length < w.globals.series.length + 1) { for (var i = 0; i <= w.globals.series.length; i++) { if (typeof w.globals.markers.size[i] === 'undefined') { w.globals.markers.size.push(w.globals.markers.size[0]); } } } } else { w.globals.markers.size = w.config.series.map(function (s) { return w.config.markers.size; }); } } }, { key: "plotChartMarkers", value: function plotChartMarkers(pointsPos, seriesIndex, j) { var _this = this; var w = this.w; var i = seriesIndex; var p = pointsPos; var elPointsWrap = null; var graphics = new Graphics(this.ctx); var point; if (w.globals.markers.size[seriesIndex] > 0) { elPointsWrap = graphics.group({ class: 'apexcharts-series-markers' }); elPointsWrap.attr('clip-path', "url(#gridRectMarkerMask".concat(w.globals.cuid, ")")); } if (p.x instanceof Array) { var _loop = function _loop(q) { var dataPointIndex = j; // a small hack as we have 2 points for the first val to connect it if (j === 1 && q === 0) dataPointIndex = 0; if (j === 1 && q === 1) dataPointIndex = 1; var PointClasses = 'apexcharts-marker'; if ((w.config.chart.type === 'line' || w.config.chart.type === 'area') && !w.globals.comboCharts && !w.config.tooltip.intersect) { PointClasses += ' no-pointer-events'; } var shouldMarkerDraw = Array.isArray(w.config.markers.size) ? w.globals.markers.size[seriesIndex] > 0 : w.config.markers.size > 0; if (shouldMarkerDraw) { if (Utils.isNumber(p.y[q])) { PointClasses += " w".concat((Math.random() + 1).toString(36).substring(4)); } else { PointClasses = 'apexcharts-nullpoint'; } var opts = _this.getMarkerConfig(PointClasses, seriesIndex); // discrete markers is an option where user can specify a particular marker with different size and color w.config.markers.discrete.map(function (marker) { if (marker.seriesIndex === seriesIndex && marker.dataPointIndex === dataPointIndex) { opts.pointStrokeColor = marker.strokeColor; opts.pointFillColor = marker.fillColor; opts.pSize = marker.size; } }); if (w.config.series[i].data[j]) { if (w.config.series[i].data[j].fillColor) { opts.pointFillColor = w.config.series[i].data[j].fillColor; } if (w.config.series[i].data[j].strokeColor) { opts.pointStrokeColor = w.config.series[i].data[j].strokeColor; } } point = graphics.drawMarker(p.x[q], p.y[q], opts); point.attr('rel', dataPointIndex); point.attr('j', dataPointIndex); point.attr('index', seriesIndex); point.node.setAttribute('default-marker-size', opts.pSize); var filters = new Filters(_this.ctx); filters.setSelectionFilter(point, seriesIndex, dataPointIndex); _this.addEvents(point); if (elPointsWrap) { elPointsWrap.add(point); } } else { // dynamic array creation - multidimensional if (typeof w.globals.pointsArray[seriesIndex] === 'undefined') w.globals.pointsArray[seriesIndex] = []; w.globals.pointsArray[seriesIndex].push([p.x[q], p.y[q]]); } }; for (var q = 0; q < p.x.length; q++) { _loop(q); } } return elPointsWrap; } }, { key: "getMarkerConfig", value: function getMarkerConfig(cssClass, seriesIndex) { var w = this.w; var pStyle = this.getMarkerStyle(seriesIndex); var pSize = w.globals.markers.size[seriesIndex]; return { pSize: pSize, pRadius: w.config.markers.radius, pWidth: w.config.markers.strokeWidth, pointStrokeColor: pStyle.pointStrokeColor, pointFillColor: pStyle.pointFillColor, shape: w.config.markers.shape instanceof Array ? w.config.markers.shape[seriesIndex] : w.config.markers.shape, class: cssClass, pointStrokeOpacity: w.config.markers.strokeOpacity, pointFillOpacity: w.config.markers.fillOpacity, seriesIndex: seriesIndex }; } }, { key: "addEvents", value: function addEvents(circle) { var graphics = new Graphics(this.ctx); circle.node.addEventListener('mouseenter', graphics.pathMouseEnter.bind(this.ctx, circle)); circle.node.addEventListener('mouseleave', graphics.pathMouseLeave.bind(this.ctx, circle)); circle.node.addEventListener('mousedown', graphics.pathMouseDown.bind(this.ctx, circle)); circle.node.addEventListener('touchstart', graphics.pathMouseDown.bind(this.ctx, circle), { passive: true }); } }, { key: "getMarkerStyle", value: function getMarkerStyle(seriesIndex) { var w = this.w; var colors = w.globals.markers.colors; var strokeColors = w.config.markers.strokeColor || w.config.markers.strokeColors; var pointStrokeColor = strokeColors instanceof Array ? strokeColors[seriesIndex] : strokeColors; var pointFillColor = colors instanceof Array ? colors[seriesIndex] : colors; return { pointStrokeColor: pointStrokeColor, pointFillColor: pointFillColor }; } }]); return Markers; }(); /** * ApexCharts Scatter Class. * This Class also handles bubbles chart as currently there is no major difference in drawing them, * @module Scatter **/ var Scatter = /*#__PURE__*/ function () { function Scatter(ctx) { _classCallCheck(this, Scatter); this.ctx = ctx; this.w = ctx.w; this.initialAnim = this.w.config.chart.animations.enabled; this.dynamicAnim = this.initialAnim && this.w.config.chart.animations.dynamicAnimation.enabled; // this array will help in centering the label in bubbles this.radiusSizes = []; } _createClass(Scatter, [{ key: "draw", value: function draw(elSeries, j, opts) { var w = this.w; var graphics = new Graphics(this.ctx); var realIndex = opts.realIndex; var pointsPos = opts.pointsPos; var zRatio = opts.zRatio; var elPointsMain = opts.elParent; var elPointsWrap = graphics.group({ class: "apexcharts-series-markers apexcharts-series-".concat(w.config.chart.type) }); elPointsWrap.attr('clip-path', "url(#gridRectMarkerMask".concat(w.globals.cuid, ")")); if (pointsPos.x instanceof Array) { for (var q = 0; q < pointsPos.x.length; q++) { var dataPointIndex = j + 1; var shouldDraw = true; // a small hack as we have 2 points for the first val to connect it if (j === 0 && q === 0) dataPointIndex = 0; if (j === 0 && q === 1) dataPointIndex = 1; var radius = 0; var finishRadius = w.globals.markers.size[realIndex]; if (zRatio !== Infinity) { // means we have a bubble finishRadius = w.globals.seriesZ[realIndex][dataPointIndex] / zRatio; if (typeof this.radiusSizes[realIndex] === 'undefined') { this.radiusSizes.push([]); } this.radiusSizes[realIndex].push(finishRadius); } if (!w.config.chart.animations.enabled) { radius = finishRadius; } var x = pointsPos.x[q]; var y = pointsPos.y[q]; radius = radius || 0; if (x === 0 && y === 0 || y === null || typeof w.globals.series[realIndex][dataPointIndex] === 'undefined') { shouldDraw = false; } if (shouldDraw) { var circle = this.drawPoint(x, y, radius, finishRadius, realIndex, dataPointIndex, j); elPointsWrap.add(circle); } elPointsMain.add(elPointsWrap); } } } }, { key: "drawPoint", value: function drawPoint(x, y, radius, finishRadius, realIndex, dataPointIndex, j) { var w = this.w; var i = realIndex; var anim = new Animations(this.ctx); var filters = new Filters(this.ctx); var fill = new Fill(this.ctx); var markers = new Markers(this.ctx); var graphics = new Graphics(this.ctx); var markerConfig = markers.getMarkerConfig('apexcharts-marker', i); var pathFillCircle = fill.fillPath({ seriesNumber: realIndex, patternUnits: 'objectBoundingBox', value: w.globals.series[realIndex][j] }); var circle = graphics.drawCircle(radius); if (w.config.series[i].data[dataPointIndex]) { if (w.config.series[i].data[dataPointIndex].fillColor) { pathFillCircle = w.config.series[i].data[dataPointIndex].fillColor; } } circle.attr({ cx: x, cy: y, fill: pathFillCircle, stroke: markerConfig.pointStrokeColor, strokeWidth: markerConfig.pWidth }); if (w.config.chart.dropShadow.enabled) { var dropShadow = w.config.chart.dropShadow; filters.dropShadow(circle, dropShadow, realIndex); } if (this.initialAnim && !w.globals.dataChanged) { var speed = 1; if (!w.globals.resized) { speed = w.config.chart.animations.speed; } anim.animateCircleRadius(circle, 0, finishRadius, speed, w.globals.easing); } if (w.globals.dataChanged) { if (this.dynamicAnim) { var _speed = w.config.chart.animations.dynamicAnimation.speed; var prevX, prevY, prevR; var prevPathJ = null; prevPathJ = w.globals.previousPaths[realIndex] && w.globals.previousPaths[realIndex][j]; if (typeof prevPathJ !== 'undefined' && prevPathJ !== null) { // series containing less elements will ignore these values and revert to 0 prevX = prevPathJ.x; prevY = prevPathJ.y; prevR = typeof prevPathJ.r !== 'undefined' ? prevPathJ.r : finishRadius; } for (var cs = 0; cs < w.globals.collapsedSeries.length; cs++) { if (w.globals.collapsedSeries[cs].index === realIndex) { _speed = 1; finishRadius = 0; } } if (x === 0 && y === 0) finishRadius = 0; anim.animateCircle(circle, { cx: prevX, cy: prevY, r: prevR }, { cx: x, cy: y, r: finishRadius }, _speed, w.globals.easing); } else { circle.attr({ r: finishRadius }); } } circle.attr({ rel: dataPointIndex, j: dataPointIndex, index: realIndex, 'default-marker-size': finishRadius }); filters.setSelectionFilter(circle, realIndex, dataPointIndex); markers.addEvents(circle); circle.node.classList.add('apexcharts-marker'); return circle; } }, { key: "centerTextInBubble", value: function centerTextInBubble(y) { var w = this.w; y = y + parseInt(w.config.dataLabels.style.fontSize) / 4; return { y: y }; } }]); return Scatter; }(); /** * ApexCharts DataLabels Class for drawing dataLabels on Axes based Charts. * * @module DataLabels **/ var DataLabels = /*#__PURE__*/ function () { function DataLabels(ctx) { _classCallCheck(this, DataLabels); this.ctx = ctx; this.w = ctx.w; } // When there are many datalabels to be printed, and some of them overlaps each other in the same series, this method will take care of that // Also, when datalabels exceeds the drawable area and get clipped off, we need to adjust and move some pixels to make them visible again _createClass(DataLabels, [{ key: "dataLabelsCorrection", value: function dataLabelsCorrection(x, y, val, i, dataPointIndex, alwaysDrawDataLabel, fontSize) { var w = this.w; var graphics = new Graphics(this.ctx); var drawnextLabel = false; // var textRects = graphics.getTextRects(val, fontSize); var width = textRects.width; var height = textRects.height; // first value in series, so push an empty array if (typeof w.globals.dataLabelsRects[i] === 'undefined') w.globals.dataLabelsRects[i] = []; // then start pushing actual rects in that sub-array w.globals.dataLabelsRects[i].push({ x: x, y: y, width: width, height: height }); var len = w.globals.dataLabelsRects[i].length - 2; var lastDrawnIndex = typeof w.globals.lastDrawnDataLabelsIndexes[i] !== 'undefined' ? w.globals.lastDrawnDataLabelsIndexes[i][w.globals.lastDrawnDataLabelsIndexes[i].length - 1] : 0; if (typeof w.globals.dataLabelsRects[i][len] !== 'undefined') { var lastDataLabelRect = w.globals.dataLabelsRects[i][lastDrawnIndex]; if ( // next label forward and x not intersecting x > lastDataLabelRect.x + lastDataLabelRect.width + 2 || y > lastDataLabelRect.y + lastDataLabelRect.height + 2 || x + width < lastDataLabelRect.x // next label is going to be drawn backwards ) { // the 2 indexes don't override, so OK to draw next label drawnextLabel = true; } } if (dataPointIndex === 0 || alwaysDrawDataLabel) { drawnextLabel = true; } return { x: x, y: y, drawnextLabel: drawnextLabel }; } }, { key: "drawDataLabel", value: function drawDataLabel(pos, i, j) { var align = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'top'; // this method handles line, area, bubble, scatter charts as those charts contains markers/points which have pre-defined x/y positions // all other charts like bars / heatmaps will define their own drawDataLabel routine var w = this.w; var graphics = new Graphics(this.ctx); var dataLabelsConfig = w.config.dataLabels; var x = 0; var y = 0; var dataPointIndex = j; var elDataLabelsWrap = null; if (!dataLabelsConfig.enabled || pos.x instanceof Array !== true) { return elDataLabelsWrap; } elDataLabelsWrap = graphics.group({ class: 'apexcharts-data-labels' }); elDataLabelsWrap.attr('clip-path', "url(#gridRectMarkerMask".concat(w.globals.cuid, ")")); for (var q = 0; q < pos.x.length; q++) { x = pos.x[q] + dataLabelsConfig.offsetX; y = pos.y[q] + dataLabelsConfig.offsetY - w.globals.markers.size[i] - 5; if (align === 'bottom') { y = y + w.globals.markers.size[i] * 2 + parseInt(dataLabelsConfig.style.fontSize) * 1.4; } if (!isNaN(x)) { // a small hack as we have 2 points for the first val to connect it if (j === 1 && q === 0) dataPointIndex = 0; if (j === 1 && q === 1) dataPointIndex = 1; var val = w.globals.series[i][dataPointIndex]; var text = ''; if (w.config.chart.type === 'bubble') { text = w.globals.seriesZ[i][dataPointIndex]; y = pos.y[q] + w.config.dataLabels.offsetY; var scatter = new Scatter(this.ctx); var centerTextInBubbleCoords = scatter.centerTextInBubble(y, i, dataPointIndex); y = centerTextInBubbleCoords.y; } else { if (typeof val !== 'undefined' && val !== null) { text = w.config.dataLabels.formatter(val, { ctx: this.ctx, seriesIndex: i, dataPointIndex: dataPointIndex, w: w }); } } this.plotDataLabelsText({ x: x, y: y, text: text, i: i, j: dataPointIndex, parent: elDataLabelsWrap, offsetCorrection: true, dataLabelsConfig: w.config.dataLabels }); } } return elDataLabelsWrap; } }, { key: "plotDataLabelsText", value: function plotDataLabelsText(opts) { var w = this.w; var graphics = new Graphics(this.ctx); var x = opts.x, y = opts.y, i = opts.i, j = opts.j, text = opts.text, textAnchor = opts.textAnchor, parent = opts.parent, dataLabelsConfig = opts.dataLabelsConfig, alwaysDrawDataLabel = opts.alwaysDrawDataLabel, offsetCorrection = opts.offsetCorrection; if (Array.isArray(w.config.dataLabels.enabledOnSeries)) { if (w.config.dataLabels.enabledOnSeries.indexOf(i) > -1) { return; } } var correctedLabels = { x: x, y: y, drawnextLabel: true }; if (offsetCorrection) { correctedLabels = this.dataLabelsCorrection(x, y, text, i, j, alwaysDrawDataLabel, parseInt(dataLabelsConfig.style.fontSize)); } // when zoomed, we don't need to correct labels offsets, // but if normally, labels get cropped, correct them if (!w.globals.zoomed) { x = correctedLabels.x; y = correctedLabels.y; } if (correctedLabels.drawnextLabel) { var dataLabelText = graphics.drawText({ width: 100, height: parseInt(dataLabelsConfig.style.fontSize), x: x, y: y, foreColor: w.globals.dataLabels.style.colors[i], textAnchor: textAnchor || dataLabelsConfig.textAnchor, text: text, fontSize: dataLabelsConfig.style.fontSize, fontFamily: dataLabelsConfig.style.fontFamily }); dataLabelText.attr({ class: 'apexcharts-datalabel', cx: x, cy: y }); if (dataLabelsConfig.dropShadow.enabled) { var textShadow = dataLabelsConfig.dropShadow; var filters = new Filters(this.ctx); filters.dropShadow(dataLabelText, textShadow); } parent.add(dataLabelText); if (typeof w.globals.lastDrawnDataLabelsIndexes[i] === 'undefined') { w.globals.lastDrawnDataLabelsIndexes[i] = []; } w.globals.lastDrawnDataLabelsIndexes[i].push(j); } } }]); return DataLabels; }(); /** * ApexCharts Bar Class responsible for drawing both Columns and Bars. * * @module Bar **/ var Bar = /*#__PURE__*/ function () { function Bar(ctx, xyRatios) { _classCallCheck(this, Bar); this.ctx = ctx; this.w = ctx.w; var w = this.w; this.barOptions = w.config.plotOptions.bar; this.isHorizontal = this.barOptions.horizontal; this.strokeWidth = w.config.stroke.width; this.isNullValue = false; this.xyRatios = xyRatios; if (this.xyRatios !== null) { this.xRatio = xyRatios.xRatio; this.yRatio = xyRatios.yRatio; this.invertedXRatio = xyRatios.invertedXRatio; this.invertedYRatio = xyRatios.invertedYRatio; this.baseLineY = xyRatios.baseLineY; this.baseLineInvertedY = xyRatios.baseLineInvertedY; } this.yaxisIndex = 0; this.seriesLen = 0; } /** primary draw method which is called on bar object * @memberof Bar * @param {array} series - user supplied series values * @param {int} seriesIndex - the index by which series will be drawn on the svg * @return {node} element which is supplied to parent chart draw method for appending **/ _createClass(Bar, [{ key: "draw", value: function draw(series, seriesIndex) { var w = this.w; var graphics = new Graphics(this.ctx); var coreUtils = new CoreUtils(this.ctx, w); series = coreUtils.getLogSeries(series); this.series = series; this.yRatio = coreUtils.getLogYRatios(this.yRatio); this.initVariables(series); var ret = graphics.group({ class: 'apexcharts-bar-series apexcharts-plot-series' }); if (w.config.dataLabels.enabled) { if (this.totalItems > w.config.plotOptions.bar.dataLabels.maxItems) { console.warn('WARNING: DataLabels are enabled but there are too many to display. This may cause performance issue when rendering.'); } } for (var i = 0, bc = 0; i < series.length; i++, bc++) { var pathTo = void 0, pathFrom = void 0; var x = void 0, y = void 0, xDivision = void 0, // xDivision is the GRIDWIDTH divided by number of datapoints (columns) yDivision = void 0, // yDivision is the GRIDHEIGHT divided by number of datapoints (bars) zeroH = void 0, // zeroH is the baseline where 0 meets y axis zeroW = void 0; // zeroW is the baseline where 0 meets x axis var yArrj = []; // hold y values of current iterating series var xArrj = []; // hold x values of current iterating series var realIndex = w.globals.comboCharts ? seriesIndex[i] : i; // el to which series will be drawn var elSeries = graphics.group({ class: "apexcharts-series ".concat(Utils.escapeString(w.globals.seriesNames[realIndex])), rel: i + 1, 'data:realIndex': realIndex }); this.ctx.series.addCollapsedClassToSeries(elSeries, realIndex); if (series[i].length > 0) { this.visibleI = this.visibleI + 1; } var strokeWidth = 0; var barHeight = 0; var barWidth = 0; if (this.yRatio.length > 1) { this.yaxisIndex = realIndex; } this.isReversed = w.config.yaxis[this.yaxisIndex] && w.config.yaxis[this.yaxisIndex].reversed; var initPositions = this.initialPositions(); y = initPositions.y; barHeight = initPositions.barHeight; yDivision = initPositions.yDivision; zeroW = initPositions.zeroW; x = initPositions.x; barWidth = initPositions.barWidth; xDivision = initPositions.xDivision; zeroH = initPositions.zeroH; if (!this.horizontal) { xArrj.push(x + barWidth / 2); } // eldatalabels var elDataLabelsWrap = graphics.group({ class: 'apexcharts-datalabels' }); for (var j = 0, tj = w.globals.dataPoints; j < w.globals.dataPoints; j++, tj--) { if (typeof this.series[i][j] === 'undefined' || series[i][j] === null) { this.isNullValue = true; } else { this.isNullValue = false; } if (w.config.stroke.show) { if (this.isNullValue) { strokeWidth = 0; } else { strokeWidth = Array.isArray(this.strokeWidth) ? this.strokeWidth[realIndex] : this.strokeWidth; } } var paths = null; if (this.isHorizontal) { paths = this.drawBarPaths({ indexes: { i: i, j: j, realIndex: realIndex, bc: bc }, barHeight: barHeight, strokeWidth: strokeWidth, pathTo: pathTo, pathFrom: pathFrom, zeroW: zeroW, x: x, y: y, yDivision: yDivision, elSeries: elSeries }); barWidth = this.series[i][j] / this.invertedYRatio; } else { paths = this.drawColumnPaths({ indexes: { i: i, j: j, realIndex: realIndex, bc: bc }, x: x, y: y, xDivision: xDivision, pathTo: pathTo, pathFrom: pathFrom, barWidth: barWidth, zeroH: zeroH, strokeWidth: strokeWidth, elSeries: elSeries }); barHeight = this.series[i][j] / this.yRatio[this.yaxisIndex]; } pathTo = paths.pathTo; pathFrom = paths.pathFrom; y = paths.y; x = paths.x; // push current X if (j > 0) { xArrj.push(x + barWidth / 2); } yArrj.push(y); var pathFill = this.getPathFillColor(series, i, j, realIndex); elSeries = this.renderSeries({ realIndex: realIndex, pathFill: pathFill, j: j, i: i, pathFrom: pathFrom, pathTo: pathTo, strokeWidth: strokeWidth, elSeries: elSeries, x: x, y: y, series: series, barHeight: barHeight, barWidth: barWidth, elDataLabelsWrap: elDataLabelsWrap, visibleSeries: this.visibleI, type: 'bar' }); } // push all x val arrays into main xArr w.globals.seriesXvalues[realIndex] = xArrj; w.globals.seriesYvalues[realIndex] = yArrj; ret.add(elSeries); } return ret; } }, { key: "getPathFillColor", value: function getPathFillColor(series, i, j, realIndex) { var w = this.w; var fill = new Fill(this.ctx); var fillColor = null; var seriesNumber = this.barOptions.distributed ? j : i; if (this.barOptions.colors.ranges.length > 0) { var colorRange = this.barOptions.colors.ranges; colorRange.map(function (range) { if (series[i][j] >= range.from && series[i][j] <= range.to) { fillColor = range.color; } }); } if (w.config.series[i].data[j] && w.config.series[i].data[j].fillColor) { fillColor = w.config.series[i].data[j].fillColor; } var pathFill = fill.fillPath({ seriesNumber: this.barOptions.distributed ? seriesNumber : realIndex, color: fillColor, value: series[i][j] }); return pathFill; } }, { key: "renderSeries", value: function renderSeries(_ref) { var realIndex = _ref.realIndex, pathFill = _ref.pathFill, lineFill = _ref.lineFill, j = _ref.j, i = _ref.i, pathFrom = _ref.pathFrom, pathTo = _ref.pathTo, strokeWidth = _ref.strokeWidth, elSeries = _ref.elSeries, x = _ref.x, y = _ref.y, series = _ref.series, barHeight = _ref.barHeight, barWidth = _ref.barWidth, elDataLabelsWrap = _ref.elDataLabelsWrap, visibleSeries = _ref.visibleSeries, type = _ref.type; var w = this.w; var graphics = new Graphics(this.ctx); if (!lineFill) { /* fix apexcharts#341 */ lineFill = this.barOptions.distributed ? w.globals.stroke.colors[j] : w.globals.stroke.colors[realIndex]; } if (w.config.series[i].data[j] && w.config.series[i].data[j].strokeColor) { lineFill = w.config.series[i].data[j].strokeColor; } if (this.isNullValue) { pathFill = 'none'; } var delay = j / w.config.chart.animations.animateGradually.delay * (w.config.chart.animations.speed / w.globals.dataPoints) / 2.4; var renderedPath = graphics.renderPaths({ i: i, j: j, realIndex: realIndex, pathFrom: pathFrom, pathTo: pathTo, stroke: lineFill, strokeWidth: strokeWidth, strokeLineCap: w.config.stroke.lineCap, fill: pathFill, animationDelay: delay, initialSpeed: w.config.chart.animations.speed, dataChangeSpeed: w.config.chart.animations.dynamicAnimation.speed, className: "apexcharts-".concat(type, "-area"), id: "apexcharts-".concat(type, "-area") }); renderedPath.attr('clip-path', "url(#gridRectMask".concat(w.globals.cuid, ")")); var filters = new Filters(this.ctx); filters.setSelectionFilter(renderedPath, realIndex, j); elSeries.add(renderedPath); var dataLabels = this.calculateDataLabelsPos({ x: x, y: y, i: i, j: j, series: series, realIndex: realIndex, barHeight: barHeight, barWidth: barWidth, renderedPath: renderedPath, visibleSeries: visibleSeries }); if (dataLabels !== null) { elDataLabelsWrap.add(dataLabels); } elSeries.add(elDataLabelsWrap); return elSeries; } }, { key: "initVariables", value: function initVariables(series) { var w = this.w; this.series = series; this.totalItems = 0; this.seriesLen = 0; this.visibleI = -1; this.visibleItems = 1; // number of visible bars after user zoomed in/out for (var sl = 0; sl < series.length; sl++) { if (series[sl].length > 0) { this.seriesLen = this.seriesLen + 1; this.totalItems += series[sl].length; } if (w.globals.isXNumeric) { // get max visible items for (var j = 0; j < series[sl].length; j++) { if (w.globals.seriesX[sl][j] > w.globals.minX && w.globals.seriesX[sl][j] < w.globals.maxX) { this.visibleItems++; } } } else { this.visibleItems = w.globals.dataPoints; } } if (this.seriesLen === 0) { // A small adjustment when combo charts are used this.seriesLen = 1; } } }, { key: "initialPositions", value: function initialPositions() { var w = this.w; var x, y, yDivision, xDivision, barHeight, barWidth, zeroH, zeroW; if (this.isHorizontal) { // height divided into equal parts yDivision = w.globals.gridHeight / w.globals.dataPoints; barHeight = yDivision / this.seriesLen; if (w.globals.isXNumeric) { yDivision = w.globals.gridHeight / this.totalItems; barHeight = yDivision / this.seriesLen; } barHeight = barHeight * parseInt(this.barOptions.barHeight) / 100; zeroW = this.baseLineInvertedY + w.globals.padHorizontal + (this.isReversed ? w.globals.gridWidth : 0) - (this.isReversed ? this.baseLineInvertedY * 2 : 0); y = (yDivision - barHeight * this.seriesLen) / 2; } else { // width divided into equal parts xDivision = w.globals.gridWidth / this.visibleItems; barWidth = xDivision / this.seriesLen * parseInt(this.barOptions.columnWidth) / 100; if (w.globals.isXNumeric) { // max barwidth should be equal to minXDiff to avoid overlap xDivision = w.globals.minXDiff / this.xRatio; barWidth = xDivision / this.seriesLen * parseInt(this.barOptions.columnWidth) / 100; } zeroH = w.globals.gridHeight - this.baseLineY[this.yaxisIndex] - (this.isReversed ? w.globals.gridHeight : 0) + (this.isReversed ? this.baseLineY[this.yaxisIndex] * 2 : 0); x = w.globals.padHorizontal + (xDivision - barWidth * this.seriesLen) / 2; } return { x: x, y: y, yDivision: yDivision, xDivision: xDivision, barHeight: barHeight, barWidth: barWidth, zeroH: zeroH, zeroW: zeroW }; } }, { key: "drawBarPaths", value: function drawBarPaths(_ref2) { var indexes = _ref2.indexes, barHeight = _ref2.barHeight, strokeWidth = _ref2.strokeWidth, pathTo = _ref2.pathTo, pathFrom = _ref2.pathFrom, zeroW = _ref2.zeroW, x = _ref2.x, y = _ref2.y, yDivision = _ref2.yDivision, elSeries = _ref2.elSeries; var w = this.w; var graphics = new Graphics(this.ctx); var i = indexes.i; var j = indexes.j; var realIndex = indexes.realIndex; var bc = indexes.bc; if (w.globals.isXNumeric) { y = (w.globals.seriesX[i][j] - w.globals.minX) / this.invertedXRatio - barHeight; } var barYPosition = y + barHeight * this.visibleI; pathTo = graphics.move(zeroW, barYPosition); pathFrom = graphics.move(zeroW, barYPosition); if (w.globals.previousPaths.length > 0) { pathFrom = this.getPathFrom(realIndex, j); } if (typeof this.series[i][j] === 'undefined' || this.series[i][j] === null) { x = zeroW; } else { x = zeroW + this.series[i][j] / this.invertedYRatio - (this.isReversed ? this.series[i][j] / this.invertedYRatio : 0) * 2; } var endingShapeOpts = { barHeight: barHeight, strokeWidth: strokeWidth, barYPosition: barYPosition, x: x, zeroW: zeroW }; var endingShape = this.barEndingShape(w, endingShapeOpts, this.series, i, j); pathTo = pathTo + graphics.line(endingShape.newX, barYPosition) + endingShape.path + graphics.line(zeroW, barYPosition + barHeight - strokeWidth) + graphics.line(zeroW, barYPosition); pathFrom = pathFrom + graphics.line(zeroW, barYPosition) + endingShape.ending_p_from + graphics.line(zeroW, barYPosition + barHeight - strokeWidth) + graphics.line(zeroW, barYPosition + barHeight - strokeWidth) + graphics.line(zeroW, barYPosition); if (!w.globals.isXNumeric) { y = y + yDivision; } if (this.barOptions.colors.backgroundBarColors.length > 0 && i === 0) { if (bc >= this.barOptions.colors.backgroundBarColors.length) { bc = 0; } var bcolor = this.barOptions.colors.backgroundBarColors[bc]; var rect = graphics.drawRect(0, barYPosition - barHeight * this.visibleI, w.globals.gridWidth, barHeight * this.seriesLen, 0, bcolor, this.barOptions.colors.backgroundBarOpacity); elSeries.add(rect); rect.node.classList.add('apexcharts-backgroundBar'); } return { pathTo: pathTo, pathFrom: pathFrom, x: x, y: y, barYPosition: barYPosition }; } }, { key: "drawColumnPaths", value: function drawColumnPaths(_ref3) { var indexes = _ref3.indexes, x = _ref3.x, y = _ref3.y, xDivision = _ref3.xDivision, pathTo = _ref3.pathTo, pathFrom = _ref3.pathFrom, barWidth = _ref3.barWidth, zeroH = _ref3.zeroH, strokeWidth = _ref3.strokeWidth, elSeries = _ref3.elSeries; var w = this.w; var graphics = new Graphics(this.ctx); var i = indexes.i; var j = indexes.j; var realIndex = indexes.realIndex; var bc = indexes.bc; if (w.globals.isXNumeric) { x = (w.globals.seriesX[i][j] - w.globals.minX) / this.xRatio - barWidth / 2; } var barXPosition = x + barWidth * this.visibleI; pathTo = graphics.move(barXPosition, zeroH); pathFrom = graphics.move(barXPosition, zeroH); if (w.globals.previousPaths.length > 0) { pathFrom = this.getPathFrom(realIndex, j); } if (typeof this.series[i][j] === 'undefined' || this.series[i][j] === null) { y = zeroH; } else { y = zeroH - this.series[i][j] / this.yRatio[this.yaxisIndex] + (this.isReversed ? this.series[i][j] / this.yRatio[this.yaxisIndex] : 0) * 2; } var endingShapeOpts = { barWidth: barWidth, strokeWidth: strokeWidth, barXPosition: barXPosition, y: y, zeroH: zeroH }; var endingShape = this.barEndingShape(w, endingShapeOpts, this.series, i, j); pathTo = pathTo + graphics.line(barXPosition, endingShape.newY) + endingShape.path + graphics.line(barXPosition + barWidth - strokeWidth, zeroH) + graphics.line(barXPosition - strokeWidth / 2, zeroH); pathFrom = pathFrom + graphics.line(barXPosition, zeroH) + endingShape.ending_p_from + graphics.line(barXPosition + barWidth - strokeWidth, zeroH) + graphics.line(barXPosition + barWidth - strokeWidth, zeroH) + graphics.line(barXPosition - strokeWidth / 2, zeroH); if (!w.globals.isXNumeric) { x = x + xDivision; } if (this.barOptions.colors.backgroundBarColors.length > 0 && i === 0) { if (bc >= this.barOptions.colors.backgroundBarColors.length) { bc = 0; } var bcolor = this.barOptions.colors.backgroundBarColors[bc]; var rect = graphics.drawRect(barXPosition - barWidth * this.visibleI, 0, barWidth * this.seriesLen, w.globals.gridHeight, 0, bcolor, this.barOptions.colors.backgroundBarOpacity); elSeries.add(rect); rect.node.classList.add('apexcharts-backgroundBar'); } return { pathTo: pathTo, pathFrom: pathFrom, x: x, y: y, barXPosition: barXPosition }; } /** getPathFrom is a common function for bars/columns which is used to get previous paths when data changes. * @memberof Bar * @param {int} realIndex - current iterating i * @param {int} j - current iterating series's j index * @return {string} pathFrom is the string which will be appended in animations **/ }, { key: "getPathFrom", value: function getPathFrom(realIndex, j) { var w = this.w; var pathFrom; for (var pp = 0; pp < w.globals.previousPaths.length; pp++) { var gpp = w.globals.previousPaths[pp]; if (gpp.paths.length > 0 && parseInt(gpp.realIndex) === parseInt(realIndex)) { if (typeof w.globals.previousPaths[pp].paths[j] !== 'undefined') { pathFrom = w.globals.previousPaths[pp].paths[j].d; } } } return pathFrom; } /** calculateBarDataLabels is used to calculate the positions for the data-labels * It also sets the element's data attr for bars and calls drawCalculatedBarDataLabels() * @memberof Bar * @param {object} {barProps} most of the bar properties used throughout the bar * drawing function * @return {object} dataLabels node-element which you can append later **/ }, { key: "calculateDataLabelsPos", value: function calculateDataLabelsPos(_ref4) { var x = _ref4.x, y = _ref4.y, i = _ref4.i, j = _ref4.j, realIndex = _ref4.realIndex, series = _ref4.series, barHeight = _ref4.barHeight, barWidth = _ref4.barWidth, visibleSeries = _ref4.visibleSeries, renderedPath = _ref4.renderedPath; var w = this.w; var graphics = new Graphics(this.ctx); var strokeWidth = Array.isArray(this.strokeWidth) ? this.strokeWidth[realIndex] : this.strokeWidth; var bcx = x + parseFloat(barWidth * visibleSeries); var bcy = y + parseFloat(barHeight * visibleSeries); if (w.globals.isXNumeric && !w.globals.isBarHorizontal) { bcx = x + parseFloat(barWidth * (visibleSeries + 1)) - strokeWidth; bcy = y + parseFloat(barHeight * (visibleSeries + 1)) - strokeWidth; } var dataLabels = null; var dataLabelsX = x; var dataLabelsY = y; var dataLabelsPos = {}; var dataLabelsConfig = w.config.dataLabels; var barDataLabelsConfig = this.barOptions.dataLabels; var offX = dataLabelsConfig.offsetX; var offY = dataLabelsConfig.offsetY; var textRects = { width: 0, height: 0 }; if (w.config.dataLabels.enabled) { textRects = graphics.getTextRects(w.globals.yLabelFormatters[0](w.globals.maxY), parseInt(dataLabelsConfig.style.fontSize)); } if (this.isHorizontal) { dataLabelsPos = this.calculateBarsDataLabelsPosition({ x: x, y: y, i: i, j: j, renderedPath: renderedPath, bcy: bcy, barHeight: barHeight, barWidth: barWidth, textRects: textRects, strokeWidth: strokeWidth, dataLabelsX: dataLabelsX, dataLabelsY: dataLabelsY, barDataLabelsConfig: barDataLabelsConfig, offX: offX, offY: offY }); } else { dataLabelsPos = this.calculateColumnsDataLabelsPosition({ x: x, y: y, i: i, j: j, renderedPath: renderedPath, realIndex: realIndex, bcx: bcx, bcy: bcy, barHeight: barHeight, barWidth: barWidth, textRects: textRects, strokeWidth: strokeWidth, dataLabelsY: dataLabelsY, barDataLabelsConfig: barDataLabelsConfig, offX: offX, offY: offY }); } renderedPath.attr({ cy: dataLabelsPos.bcy, cx: dataLabelsPos.bcx, j: j, val: series[i][j], barHeight: barHeight, barWidth: barWidth }); dataLabels = this.drawCalculatedDataLabels({ x: dataLabelsPos.dataLabelsX, y: dataLabelsPos.dataLabelsY, val: series[i][j], i: realIndex, j: j, barWidth: barWidth, barHeight: barHeight, textRects: textRects, dataLabelsConfig: dataLabelsConfig }); return dataLabels; } }, { key: "calculateColumnsDataLabelsPosition", value: function calculateColumnsDataLabelsPosition(opts) { var w = this.w; var i = opts.i, j = opts.j, y = opts.y, bcx = opts.bcx, barWidth = opts.barWidth, barHeight = opts.barHeight, textRects = opts.textRects, dataLabelsY = opts.dataLabelsY, barDataLabelsConfig = opts.barDataLabelsConfig, strokeWidth = opts.strokeWidth, offX = opts.offX, offY = opts.offY; var dataLabelsX; var dataPointsDividedWidth = w.globals.gridWidth / w.globals.dataPoints; bcx = bcx - strokeWidth / 2; if (w.globals.isXNumeric) { dataLabelsX = bcx - barWidth / 2 + offX; } else { dataLabelsX = bcx - dataPointsDividedWidth + barWidth / 2 + offX; } var valIsNegative = this.series[i][j] <= 0; if (this.isReversed) { y = y - barHeight; } switch (barDataLabelsConfig.position) { case 'center': if (valIsNegative) { dataLabelsY = y + barHeight / 2 + textRects.height / 2 + offY; } else { dataLabelsY = y + barHeight / 2 + textRects.height / 2 - offY; } break; case 'bottom': if (valIsNegative) { dataLabelsY = y + barHeight + textRects.height + strokeWidth + offY; } else { dataLabelsY = y + barHeight - textRects.height / 2 + strokeWidth - offY; } break; case 'top': if (valIsNegative) { dataLabelsY = y - textRects.height / 2 - offY; } else { dataLabelsY = y + textRects.height + offY; } break; } if (!w.config.chart.stacked) { if (dataLabelsY < 0) { dataLabelsY = 0 + strokeWidth; } else if (dataLabelsY + textRects.height / 3 > w.globals.gridHeight) { dataLabelsY = w.globals.gridHeight - strokeWidth; } } return { bcx: bcx, bcy: y, dataLabelsX: dataLabelsX, dataLabelsY: dataLabelsY }; } }, { key: "calculateBarsDataLabelsPosition", value: function calculateBarsDataLabelsPosition(opts) { var w = this.w; var x = opts.x, i = opts.i, j = opts.j, bcy = opts.bcy, barHeight = opts.barHeight, barWidth = opts.barWidth, textRects = opts.textRects, dataLabelsX = opts.dataLabelsX, strokeWidth = opts.strokeWidth, barDataLabelsConfig = opts.barDataLabelsConfig, offX = opts.offX, offY = opts.offY; var dataPointsDividedHeight = w.globals.gridHeight / w.globals.dataPoints; var dataLabelsY = bcy - dataPointsDividedHeight + barHeight / 2 + textRects.height / 2 + offY - 3; var valIsNegative = this.series[i][j] <= 0; if (this.isReversed) { x = x + barWidth; } switch (barDataLabelsConfig.position) { case 'center': if (valIsNegative) { dataLabelsX = x - barWidth / 2 - offX; } else { dataLabelsX = x - barWidth / 2 + offX; } break; case 'bottom': if (valIsNegative) { dataLabelsX = x - barWidth - strokeWidth - Math.round(textRects.width / 2) - offX; } else { dataLabelsX = x - barWidth + strokeWidth + Math.round(textRects.width / 2) + offX; } break; case 'top': if (valIsNegative) { dataLabelsX = x - strokeWidth + Math.round(textRects.width / 2) - offX; } else { dataLabelsX = x - strokeWidth - Math.round(textRects.width / 2) + offX; } break; } if (!w.config.chart.stacked) { if (dataLabelsX < 0) { dataLabelsX = dataLabelsX + textRects.width + strokeWidth; } else if (dataLabelsX + textRects.width / 2 > w.globals.gridWidth) { dataLabelsX = w.globals.gridWidth - textRects.width - strokeWidth; } } return { bcx: x, bcy: bcy, dataLabelsX: dataLabelsX, dataLabelsY: dataLabelsY }; } }, { key: "drawCalculatedDataLabels", value: function drawCalculatedDataLabels(_ref5) { var x = _ref5.x, y = _ref5.y, val = _ref5.val, i = _ref5.i, j = _ref5.j, textRects = _ref5.textRects, barHeight = _ref5.barHeight, barWidth = _ref5.barWidth, dataLabelsConfig = _ref5.dataLabelsConfig; var w = this.w; var dataLabels = new DataLabels(this.ctx); var graphics = new Graphics(this.ctx); var formatter = dataLabelsConfig.formatter; var elDataLabelsWrap = null; var isSeriesNotCollapsed = w.globals.collapsedSeriesIndices.indexOf(i) > -1; if (dataLabelsConfig.enabled && !isSeriesNotCollapsed) { elDataLabelsWrap = graphics.group({ class: 'apexcharts-data-labels' }); var text = ''; if (typeof val !== 'undefined' && val !== null) { text = formatter(val, { seriesIndex: i, dataPointIndex: j, w: w }); } if (val === 0 && w.config.chart.stacked) { // in a stacked bar/column chart, 0 value should be neglected as it will overlap on the next element text = ''; } if (w.config.chart.stacked && this.barOptions.dataLabels.hideOverflowingLabels) { // if there is not enough space to draw the label in the bar/column rect, check hideOverflowingLabels property to prevent overflowing on wrong rect // Note: This issue is only seen in stacked charts if (this.isHorizontal) { barWidth = this.series[i][j] / this.yRatio[this.yaxisIndex]; if (textRects.width / 1.6 > barWidth) { text = ''; } } else { barHeight = this.series[i][j] / this.yRatio[this.yaxisIndex]; if (textRects.height / 1.6 > barHeight) { text = ''; } } } dataLabels.plotDataLabelsText({ x: x, y: y, text: text, i: i, j: j, parent: elDataLabelsWrap, dataLabelsConfig: dataLabelsConfig, alwaysDrawDataLabel: true, offsetCorrection: true }); } return elDataLabelsWrap; } /** barEndingShape draws the various shapes on top of bars/columns * @memberof Bar * @param {object} w - chart context * @param {object} opts - consists several properties like barHeight/barWidth * @param {array} series - global primary series * @param {int} i - current iterating series's index * @param {int} j - series's j of i * @return {object} path - ending shape whether round/arrow * ending_p_from - similar to pathFrom * newY - which is calculated from existing y and new shape's top **/ }, { key: "barEndingShape", value: function barEndingShape(w, opts, series, i, j) { var graphics = new Graphics(this.ctx); if (this.isHorizontal) { var endingShape = null; var endingShapeFrom = ''; var x = opts.x; if (typeof series[i][j] !== 'undefined' || series[i][j] !== null) { var inverse = series[i][j] < 0; var eX = opts.barHeight / 2 - opts.strokeWidth; if (inverse) eX = -opts.barHeight / 2 - opts.strokeWidth; if (!w.config.chart.stacked) { if (this.barOptions.endingShape === 'rounded') { x = opts.x - eX / 2; } } switch (this.barOptions.endingShape) { case 'flat': endingShape = graphics.line(x, opts.barYPosition + opts.barHeight - opts.strokeWidth); break; case 'rounded': endingShape = graphics.quadraticCurve(x + eX, opts.barYPosition + (opts.barHeight - opts.strokeWidth) / 2, x, opts.barYPosition + opts.barHeight - opts.strokeWidth); break; } } return { path: endingShape, ending_p_from: endingShapeFrom, newX: x }; } else { var _endingShape = null; var _endingShapeFrom = ''; var y = opts.y; if (typeof series[i][j] !== 'undefined' || series[i][j] !== null) { var _inverse = series[i][j] < 0; var eY = opts.barWidth / 2 - opts.strokeWidth; if (_inverse) eY = -opts.barWidth / 2 - opts.strokeWidth; if (!w.config.chart.stacked) { // the shape exceeds the chart height, hence reduce y if (this.barOptions.endingShape === 'rounded') { y = y + eY / 2; } } switch (this.barOptions.endingShape) { case 'flat': _endingShape = graphics.line(opts.barXPosition + opts.barWidth - opts.strokeWidth, y); break; case 'rounded': _endingShape = graphics.quadraticCurve(opts.barXPosition + (opts.barWidth - opts.strokeWidth) / 2, y - eY, opts.barXPosition + opts.barWidth - opts.strokeWidth, y); break; } } return { path: _endingShape, ending_p_from: _endingShapeFrom, newY: y }; } } }]); return Bar; }(); /** * ApexCharts BarStacked Class responsible for drawing both Stacked Columns and Bars. * * @module BarStacked * The whole calculation for stacked bar/column is different from normal bar/column, * hence it makes sense to derive a new class for it extending most of the props of Parent Bar **/ var BarStacked = /*#__PURE__*/ function (_Bar) { _inherits(BarStacked, _Bar); function BarStacked() { _classCallCheck(this, BarStacked); return _possibleConstructorReturn(this, _getPrototypeOf(BarStacked).apply(this, arguments)); } _createClass(BarStacked, [{ key: "draw", value: function draw(series, seriesIndex) { var w = this.w; this.graphics = new Graphics(this.ctx); this.fill = new Fill(this.ctx); this.bar = new Bar(this.ctx, this.xyRatios); var coreUtils = new CoreUtils(this.ctx, w); series = coreUtils.getLogSeries(series); this.yRatio = coreUtils.getLogYRatios(this.yRatio); this.initVariables(series); if (w.config.chart.stackType === '100%') { series = w.globals.seriesPercent.slice(); } this.series = series; this.totalItems = 0; this.prevY = []; // y position on chart this.prevX = []; // x position on chart this.prevYF = []; // y position including shapes on chart this.prevXF = []; // x position including shapes on chart this.prevYVal = []; // y values (series[i][j]) in columns this.prevXVal = []; // x values (series[i][j]) in bars this.xArrj = []; // xj indicates x position on graph in bars this.xArrjF = []; // xjF indicates bar's x position + endingshape's positions in bars this.xArrjVal = []; // x val means the actual series's y values in horizontal/bars this.yArrj = []; // yj indicates y position on graph in columns this.yArrjF = []; // yjF indicates bar's y position + endingshape's positions in columns this.yArrjVal = []; // y val means the actual series's y values in columns for (var sl = 0; sl < series.length; sl++) { if (series[sl].length > 0) { this.totalItems += series[sl].length; } } var ret = this.graphics.group({ class: 'apexcharts-bar-series apexcharts-plot-series' }); var x = 0; var y = 0; for (var i = 0, bc = 0; i < series.length; i++, bc++) { var pathTo = void 0, pathFrom = void 0; var xDivision = void 0; // xDivision is the GRIDWIDTH divided by number of datapoints (columns) var yDivision = void 0; // yDivision is the GRIDHEIGHT divided by number of datapoints (bars) var zeroH = void 0; // zeroH is the baseline where 0 meets y axis var zeroW = void 0; // zeroW is the baseline where 0 meets x axis var xArrValues = []; var yArrValues = []; var realIndex = w.globals.comboCharts ? seriesIndex[i] : i; if (this.yRatio.length > 1) { this.yaxisIndex = realIndex; } this.isReversed = w.config.yaxis[this.yaxisIndex] && w.config.yaxis[this.yaxisIndex].reversed; // el to which series will be drawn var elSeries = this.graphics.group({ class: "apexcharts-series ".concat(Utils.escapeString(w.globals.seriesNames[realIndex])), rel: i + 1, 'data:realIndex': realIndex }); // eldatalabels var elDataLabelsWrap = this.graphics.group({ class: 'apexcharts-datalabels' }); var strokeWidth = 0; var barHeight = 0; var barWidth = 0; var initPositions = this.initialPositions(x, y, xDivision, yDivision, zeroH, zeroW); y = initPositions.y; barHeight = initPositions.barHeight; yDivision = initPositions.yDivision; zeroW = initPositions.zeroW; x = initPositions.x; barWidth = initPositions.barWidth; xDivision = initPositions.xDivision; zeroH = initPositions.zeroH; this.yArrj = []; this.yArrjF = []; this.yArrjVal = []; this.xArrj = []; this.xArrjF = []; this.xArrjVal = []; // if (!this.horizontal) { // this.xArrj.push(x + barWidth / 2) // } for (var j = 0; j < w.globals.dataPoints; j++) { if (w.config.stroke.show) { if (this.isNullValue) { strokeWidth = 0; } else { strokeWidth = Array.isArray(this.strokeWidth) ? this.strokeWidth[realIndex] : this.strokeWidth; } } var paths = null; if (this.isHorizontal) { paths = this.drawBarPaths({ indexes: { i: i, j: j, realIndex: realIndex, bc: bc }, barHeight: barHeight, strokeWidth: strokeWidth, pathTo: pathTo, pathFrom: pathFrom, zeroW: zeroW, x: x, y: y, yDivision: yDivision, elSeries: elSeries }); barWidth = this.series[i][j] / this.invertedYRatio; } else { paths = this.drawColumnPaths({ indexes: { i: i, j: j, realIndex: realIndex, bc: bc }, x: x, y: y, xDivision: xDivision, pathTo: pathTo, pathFrom: pathFrom, barWidth: barWidth, zeroH: zeroH, strokeWidth: strokeWidth, elSeries: elSeries }); barHeight = this.series[i][j] / this.yRatio[this.yaxisIndex]; } pathTo = paths.pathTo; pathFrom = paths.pathFrom; y = paths.y; x = paths.x; xArrValues.push(x); yArrValues.push(y); var pathFill = this.bar.getPathFillColor(series, i, j, realIndex); elSeries = this.renderSeries({ realIndex: realIndex, pathFill: pathFill, j: j, i: i, pathFrom: pathFrom, pathTo: pathTo, strokeWidth: strokeWidth, elSeries: elSeries, x: x, y: y, series: series, barHeight: barHeight, barWidth: barWidth, elDataLabelsWrap: elDataLabelsWrap, type: 'bar', visibleSeries: 0 }); } // push all x val arrays into main xArr w.globals.seriesXvalues[realIndex] = xArrValues; w.globals.seriesYvalues[realIndex] = yArrValues; // push all current y values array to main PrevY Array this.prevY.push(this.yArrj); this.prevYF.push(this.yArrjF); this.prevYVal.push(this.yArrjVal); this.prevX.push(this.xArrj); this.prevXF.push(this.xArrjF); this.prevXVal.push(this.xArrjVal); ret.add(elSeries); } return ret; } }, { key: "initialPositions", value: function initialPositions(x, y, xDivision, yDivision, zeroH, zeroW) { var w = this.w; var barHeight, barWidth; if (this.isHorizontal) { // height divided into equal parts yDivision = w.globals.gridHeight / w.globals.dataPoints; barHeight = yDivision; barHeight = barHeight * parseInt(w.config.plotOptions.bar.barHeight) / 100; zeroW = this.baseLineInvertedY + w.globals.padHorizontal + (this.isReversed ? w.globals.gridWidth : 0) - (this.isReversed ? this.baseLineInvertedY * 2 : 0); // initial y position is half of barHeight * half of number of Bars y = (yDivision - barHeight) / 2; } else { // width divided into equal parts xDivision = w.globals.gridWidth / w.globals.dataPoints; barWidth = xDivision; if (w.globals.isXNumeric) { xDivision = w.globals.minXDiff / this.xRatio; barWidth = xDivision * parseInt(this.barOptions.columnWidth) / 100; } else { barWidth = barWidth * parseInt(w.config.plotOptions.bar.columnWidth) / 100; } zeroH = this.baseLineY[this.yaxisIndex] + (this.isReversed ? w.globals.gridHeight : 0) - (this.isReversed ? this.baseLineY[this.yaxisIndex] * 2 : 0); // initial x position is one third of barWidth x = w.globals.padHorizontal + (xDivision - barWidth) / 2; } return { x: x, y: y, yDivision: yDivision, xDivision: xDivision, barHeight: barHeight, barWidth: barWidth, zeroH: zeroH, zeroW: zeroW }; } }, { key: "drawBarPaths", value: function drawBarPaths(_ref) { var indexes = _ref.indexes, barHeight = _ref.barHeight, strokeWidth = _ref.strokeWidth, pathTo = _ref.pathTo, pathFrom = _ref.pathFrom, zeroW = _ref.zeroW, x = _ref.x, y = _ref.y, yDivision = _ref.yDivision, elSeries = _ref.elSeries; var w = this.w; var barYPosition = y; var barXPosition; var i = indexes.i; var j = indexes.j; var realIndex = indexes.realIndex; var bc = indexes.bc; var prevBarW = 0; for (var k = 0; k < this.prevXF.length; k++) { prevBarW = prevBarW + this.prevXF[k][j]; } if (i > 0) { var bXP = zeroW; if (this.prevXVal[i - 1][j] < 0) { if (this.series[i][j] >= 0) { bXP = this.prevX[i - 1][j] + prevBarW - (this.isReversed ? prevBarW : 0) * 2; } else { bXP = this.prevX[i - 1][j]; } } else if (this.prevXVal[i - 1][j] >= 0) { if (this.series[i][j] >= 0) { bXP = this.prevX[i - 1][j]; } else { bXP = this.prevX[i - 1][j] - prevBarW + (this.isReversed ? prevBarW : 0) * 2; } } barXPosition = bXP; } else { // the first series will not have prevX values barXPosition = zeroW; } if (this.series[i][j] === null) { x = barXPosition; } else { x = barXPosition + this.series[i][j] / this.invertedYRatio - (this.isReversed ? this.series[i][j] / this.invertedYRatio : 0) * 2; } var endingShapeOpts = { barHeight: barHeight, strokeWidth: strokeWidth, invertedYRatio: this.invertedYRatio, barYPosition: barYPosition, x: x }; var endingShape = this.bar.barEndingShape(w, endingShapeOpts, this.series, i, j); if (this.series.length > 1 && i !== this.endingShapeOnSeriesNumber) { // revert back to flat shape if not last series endingShape.path = this.graphics.line(endingShape.newX, barYPosition + barHeight - strokeWidth); } this.xArrj.push(endingShape.newX); this.xArrjF.push(Math.abs(barXPosition - endingShape.newX)); this.xArrjVal.push(this.series[i][j]); pathTo = this.graphics.move(barXPosition, barYPosition); pathFrom = this.graphics.move(barXPosition, barYPosition); if (w.globals.previousPaths.length > 0) { pathFrom = this.bar.getPathFrom(realIndex, j, false); } pathTo = pathTo + this.graphics.line(endingShape.newX, barYPosition) + endingShape.path + this.graphics.line(barXPosition, barYPosition + barHeight - strokeWidth) + this.graphics.line(barXPosition, barYPosition); pathFrom = pathFrom + this.graphics.line(barXPosition, barYPosition) + this.graphics.line(barXPosition, barYPosition + barHeight - strokeWidth) + this.graphics.line(barXPosition, barYPosition + barHeight - strokeWidth) + this.graphics.line(barXPosition, barYPosition + barHeight - strokeWidth) + this.graphics.line(barXPosition, barYPosition); if (w.config.plotOptions.bar.colors.backgroundBarColors.length > 0 && i === 0) { if (bc >= w.config.plotOptions.bar.colors.backgroundBarColors.length) { bc = 0; } var bcolor = w.config.plotOptions.bar.colors.backgroundBarColors[bc]; var rect = this.graphics.drawRect(0, barYPosition, w.globals.gridWidth, barHeight, 0, bcolor, w.config.plotOptions.bar.colors.backgroundBarOpacity); elSeries.add(rect); rect.node.classList.add('apexcharts-backgroundBar'); } y = y + yDivision; return { pathTo: pathTo, pathFrom: pathFrom, x: x, y: y }; } }, { key: "drawColumnPaths", value: function drawColumnPaths(_ref2) { var indexes = _ref2.indexes, x = _ref2.x, y = _ref2.y, xDivision = _ref2.xDivision, pathTo = _ref2.pathTo, pathFrom = _ref2.pathFrom, barWidth = _ref2.barWidth, zeroH = _ref2.zeroH, strokeWidth = _ref2.strokeWidth, elSeries = _ref2.elSeries; var w = this.w; var i = indexes.i; var j = indexes.j; var realIndex = indexes.realIndex; var bc = indexes.bc; if (w.globals.isXNumeric) { var seriesVal = w.globals.seriesX[i][j]; if (!seriesVal) seriesVal = 0; x = (seriesVal - w.globals.minX) / this.xRatio - barWidth / 2; } var barXPosition = x; var barYPosition; var prevBarH = 0; for (var k = 0; k < this.prevYF.length; k++) { prevBarH = prevBarH + this.prevYF[k][j]; } if (i > 0 && !w.globals.isXNumeric || i > 0 && w.globals.isXNumeric && w.globals.seriesX[i - 1][j] === w.globals.seriesX[i][j]) { var bYP; var prevYValue = this.prevY[i - 1][j]; if (this.prevYVal[i - 1][j] < 0) { if (this.series[i][j] >= 0) { bYP = prevYValue - prevBarH + (this.isReversed ? prevBarH : 0) * 2; } else { bYP = prevYValue; } } else { if (this.series[i][j] >= 0) { bYP = prevYValue; } else { bYP = prevYValue + prevBarH - (this.isReversed ? prevBarH : 0) * 2; } } barYPosition = bYP; } else { // the first series will not have prevY values, also if the prev index's series X doesn't matches the current index's series X, then start from zero barYPosition = w.globals.gridHeight - zeroH; } y = barYPosition - this.series[i][j] / this.yRatio[this.yaxisIndex] + (this.isReversed ? this.series[i][j] / this.yRatio[this.yaxisIndex] : 0) * 2; var endingShapeOpts = { barWidth: barWidth, strokeWidth: strokeWidth, yRatio: this.yRatio[this.yaxisIndex], barXPosition: barXPosition, y: y }; var endingShape = this.bar.barEndingShape(w, endingShapeOpts, this.series, i, j); this.yArrj.push(endingShape.newY); this.yArrjF.push(Math.abs(barYPosition - endingShape.newY)); this.yArrjVal.push(this.series[i][j]); pathTo = this.graphics.move(barXPosition, barYPosition); pathFrom = this.graphics.move(barXPosition, barYPosition); if (w.globals.previousPaths.length > 0) { pathFrom = this.bar.getPathFrom(realIndex, j, false); } pathTo = pathTo + this.graphics.line(barXPosition, endingShape.newY) + endingShape.path + this.graphics.line(barXPosition + barWidth - strokeWidth, barYPosition) + this.graphics.line(barXPosition - strokeWidth / 2, barYPosition); pathFrom = pathFrom + this.graphics.line(barXPosition, barYPosition) + this.graphics.line(barXPosition + barWidth - strokeWidth, barYPosition) + this.graphics.line(barXPosition + barWidth - strokeWidth, barYPosition) + this.graphics.line(barXPosition + barWidth - strokeWidth, barYPosition) + this.graphics.line(barXPosition - strokeWidth / 2, barYPosition); if (w.config.plotOptions.bar.colors.backgroundBarColors.length > 0 && i === 0) { if (bc >= w.config.plotOptions.bar.colors.backgroundBarColors.length) { bc = 0; } var bcolor = w.config.plotOptions.bar.colors.backgroundBarColors[bc]; var rect = this.graphics.drawRect(barXPosition, 0, barWidth, w.globals.gridHeight, 0, bcolor, w.config.plotOptions.bar.colors.backgroundBarOpacity); elSeries.add(rect); rect.node.classList.add('apexcharts-backgroundBar'); } x = x + xDivision; return { pathTo: pathTo, pathFrom: pathFrom, x: w.globals.isXNumeric ? x - xDivision : x, y: y }; } /* * When user clicks on legends, the collapsed series will be filled with [0,0,0,...,0] * We need to make sure, that the last series is not [0,0,0,...,0] * as we need to draw shapes on the last series (for stacked bars/columns only) * Hence, we are collecting all inner arrays in series which has [0,0,0...,0] **/ }, { key: "checkZeroSeries", value: function checkZeroSeries(_ref3) { var series = _ref3.series; var w = this.w; for (var zs = 0; zs < series.length; zs++) { var total = 0; for (var zsj = 0; zsj < series[w.globals.maxValsInArrayIndex].length; zsj++) { total += series[zs][zsj]; } if (total === 0) { this.zeroSerieses.push(zs); } } // After getting all zeroserieses, we need to ensure whether endingshapeonSeries is not in that zeroseries array for (var s = series.length - 1; s >= 0; s--) { if (this.zeroSerieses.indexOf(s) > -1 && s === this.endingShapeOnSeriesNumber) { this.endingShapeOnSeriesNumber -= 1; } } } }]); return BarStacked; }(Bar); /** * ApexCharts CandleStick Class responsible for drawing both Stacked Columns and Bars. * * @module CandleStick **/ var CandleStick = /*#__PURE__*/ function (_Bar) { _inherits(CandleStick, _Bar); function CandleStick() { _classCallCheck(this, CandleStick); return _possibleConstructorReturn(this, _getPrototypeOf(CandleStick).apply(this, arguments)); } _createClass(CandleStick, [{ key: "draw", value: function draw(series, seriesIndex) { var w = this.w; var graphics = new Graphics(this.ctx); var fill = new Fill(this.ctx); this.candlestickOptions = this.w.config.plotOptions.candlestick; var coreUtils = new CoreUtils(this.ctx, w); series = coreUtils.getLogSeries(series); this.series = series; this.yRatio = coreUtils.getLogYRatios(this.yRatio); this.initVariables(series); var ret = graphics.group({ class: 'apexcharts-candlestick-series apexcharts-plot-series' }); for (var i = 0, bc = 0; i < series.length; i++, bc++) { var pathTo = void 0, pathFrom = void 0; var x = void 0, y = void 0, xDivision = void 0, // xDivision is the GRIDWIDTH divided by number of datapoints (columns) zeroH = void 0; // zeroH is the baseline where 0 meets y axis var yArrj = []; // hold y values of current iterating series var xArrj = []; // hold x values of current iterating series var realIndex = w.globals.comboCharts ? seriesIndex[i] : i; // el to which series will be drawn var elSeries = graphics.group({ class: "apexcharts-series ".concat(Utils.escapeString(w.globals.seriesNames[realIndex])), rel: i + 1, 'data:realIndex': realIndex }); if (series[i].length > 0) { this.visibleI = this.visibleI + 1; } var strokeWidth = 0; var barHeight = 0; var barWidth = 0; if (this.yRatio.length > 1) { this.yaxisIndex = realIndex; } var initPositions = this.initialPositions(); y = initPositions.y; barHeight = initPositions.barHeight; x = initPositions.x; barWidth = initPositions.barWidth; xDivision = initPositions.xDivision; zeroH = initPositions.zeroH; xArrj.push(x + barWidth / 2); // eldatalabels var elDataLabelsWrap = graphics.group({ class: 'apexcharts-datalabels' }); for (var j = 0, tj = w.globals.dataPoints; j < w.globals.dataPoints; j++, tj--) { if (typeof this.series[i][j] === 'undefined' || series[i][j] === null) { this.isNullValue = true; } else { this.isNullValue = false; } if (w.config.stroke.show) { if (this.isNullValue) { strokeWidth = 0; } else { strokeWidth = Array.isArray(this.strokeWidth) ? this.strokeWidth[realIndex] : this.strokeWidth; } } var color = void 0; var paths = this.drawCandleStickPaths({ indexes: { i: i, j: j, realIndex: realIndex, bc: bc }, x: x, y: y, xDivision: xDivision, pathTo: pathTo, pathFrom: pathFrom, barWidth: barWidth, zeroH: zeroH, strokeWidth: strokeWidth, elSeries: elSeries }); pathTo = paths.pathTo; pathFrom = paths.pathFrom; y = paths.y; x = paths.x; color = paths.color; // push current X if (j > 0) { xArrj.push(x + barWidth / 2); } yArrj.push(y); var pathFill = fill.fillPath({ seriesNumber: realIndex, color: color, value: series[i][j] }); var lineFill = this.candlestickOptions.wick.useFillColor ? color : undefined; elSeries = this.renderSeries({ realIndex: realIndex, pathFill: pathFill, lineFill: lineFill, j: j, i: i, pathFrom: pathFrom, pathTo: pathTo, strokeWidth: strokeWidth, elSeries: elSeries, x: x, y: y, series: series, barHeight: barHeight, barWidth: barWidth, elDataLabelsWrap: elDataLabelsWrap, visibleSeries: this.visibleI, type: 'candlestick' }); } // push all x val arrays into main xArr w.globals.seriesXvalues[realIndex] = xArrj; w.globals.seriesYvalues[realIndex] = yArrj; ret.add(elSeries); } return ret; } }, { key: "drawCandleStickPaths", value: function drawCandleStickPaths(_ref) { var indexes = _ref.indexes, x = _ref.x, y = _ref.y, xDivision = _ref.xDivision, pathTo = _ref.pathTo, pathFrom = _ref.pathFrom, barWidth = _ref.barWidth, zeroH = _ref.zeroH, strokeWidth = _ref.strokeWidth; var w = this.w; var graphics = new Graphics(this.ctx); var i = indexes.i; var j = indexes.j; var isPositive = true; var colorPos = w.config.plotOptions.candlestick.colors.upward; var colorNeg = w.config.plotOptions.candlestick.colors.downward; var yRatio = this.yRatio[this.yaxisIndex]; var realIndex = indexes.realIndex; var ohlc = this.getOHLCValue(realIndex, j); var l1 = zeroH; var l2 = zeroH; if (ohlc.o > ohlc.c) { isPositive = false; } var y1 = Math.min(ohlc.o, ohlc.c); var y2 = Math.max(ohlc.o, ohlc.c); if (w.globals.isXNumeric) { x = (w.globals.seriesX[i][j] - w.globals.minX) / this.xRatio - barWidth / 2; } var barXPosition = x + barWidth * this.visibleI; if (typeof this.series[i][j] === 'undefined' || this.series[i][j] === null) { y1 = zeroH; } else { y1 = zeroH - y1 / yRatio; y2 = zeroH - y2 / yRatio; l1 = zeroH - ohlc.h / yRatio; l2 = zeroH - ohlc.l / yRatio; } pathTo = graphics.move(barXPosition, zeroH); pathFrom = graphics.move(barXPosition, y1); if (w.globals.previousPaths.length > 0) { pathFrom = this.getPathFrom(realIndex, j, true); } pathTo = graphics.move(barXPosition, y2) + graphics.line(barXPosition + barWidth / 2, y2) + graphics.line(barXPosition + barWidth / 2, l1) + graphics.line(barXPosition + barWidth / 2, y2) + graphics.line(barXPosition + barWidth, y2) + graphics.line(barXPosition + barWidth, y1) + graphics.line(barXPosition + barWidth / 2, y1) + graphics.line(barXPosition + barWidth / 2, l2) + graphics.line(barXPosition + barWidth / 2, y1) + graphics.line(barXPosition, y1) + graphics.line(barXPosition, y2 - strokeWidth / 2); pathFrom = pathFrom + graphics.move(barXPosition, y1); if (!w.globals.isXNumeric) { x = x + xDivision; } return { pathTo: pathTo, pathFrom: pathFrom, x: x, y: y2, barXPosition: barXPosition, color: isPositive ? colorPos : colorNeg }; } }, { key: "getOHLCValue", value: function getOHLCValue(i, j) { var w = this.w; return { o: w.globals.seriesCandleO[i][j], h: w.globals.seriesCandleH[i][j], l: w.globals.seriesCandleL[i][j], c: w.globals.seriesCandleC[i][j] }; } }]); return CandleStick; }(Bar); var Crosshairs = /*#__PURE__*/ function () { function Crosshairs(ctx) { _classCallCheck(this, Crosshairs); this.ctx = ctx; this.w = ctx.w; } _createClass(Crosshairs, [{ key: "drawXCrosshairs", value: function drawXCrosshairs() { var w = this.w; var graphics = new Graphics(this.ctx); var filters = new Filters(this.ctx); var crosshairGradient = w.config.xaxis.crosshairs.fill.gradient; var crosshairShadow = w.config.xaxis.crosshairs.dropShadow; var fillType = w.config.xaxis.crosshairs.fill.type; var gradientFrom = crosshairGradient.colorFrom; var gradientTo = crosshairGradient.colorTo; var opacityFrom = crosshairGradient.opacityFrom; var opacityTo = crosshairGradient.opacityTo; var stops = crosshairGradient.stops; var shadow = 'none'; var dropShadow = crosshairShadow.enabled; var shadowLeft = crosshairShadow.left; var shadowTop = crosshairShadow.top; var shadowBlur = crosshairShadow.blur; var shadowColor = crosshairShadow.color; var shadowOpacity = crosshairShadow.opacity; var xcrosshairsFill = w.config.xaxis.crosshairs.fill.color; if (w.config.xaxis.crosshairs.show) { if (fillType === 'gradient') { xcrosshairsFill = graphics.drawGradient('vertical', gradientFrom, gradientTo, opacityFrom, opacityTo, null, stops, null); } var xcrosshairs = graphics.drawRect(); if (w.config.xaxis.crosshairs.width === 1) { // to prevent drawing 2 lines, convert rect to line xcrosshairs = graphics.drawLine(); } xcrosshairs.attr({ class: 'apexcharts-xcrosshairs', x: 0, y: 0, y2: w.globals.gridHeight, width: Utils.isNumber(w.config.xaxis.crosshairs.width) ? w.config.xaxis.crosshairs.width : 0, height: w.globals.gridHeight, fill: xcrosshairsFill, filter: shadow, 'fill-opacity': w.config.xaxis.crosshairs.opacity, stroke: w.config.xaxis.crosshairs.stroke.color, 'stroke-width': w.config.xaxis.crosshairs.stroke.width, 'stroke-dasharray': w.config.xaxis.crosshairs.stroke.dashArray }); if (dropShadow) { xcrosshairs = filters.dropShadow(xcrosshairs, { left: shadowLeft, top: shadowTop, blur: shadowBlur, color: shadowColor, opacity: shadowOpacity }); } w.globals.dom.elGraphical.add(xcrosshairs); } } }, { key: "drawYCrosshairs", value: function drawYCrosshairs() { var w = this.w; var graphics = new Graphics(this.ctx); var crosshair = w.config.yaxis[0].crosshairs; if (w.config.yaxis[0].crosshairs.show) { var ycrosshairs = graphics.drawLine(0, 0, w.globals.gridWidth, 0, crosshair.stroke.color, crosshair.stroke.dashArray, crosshair.stroke.width); ycrosshairs.attr({ class: 'apexcharts-ycrosshairs' }); w.globals.dom.elGraphical.add(ycrosshairs); } // draw an invisible crosshair to help in positioning the yaxis tooltip var ycrosshairsHidden = graphics.drawLine(0, 0, w.globals.gridWidth, 0, crosshair.stroke.color, 0, 0); ycrosshairsHidden.attr({ class: 'apexcharts-ycrosshairs-hidden' }); w.globals.dom.elGraphical.add(ycrosshairsHidden); } }]); return Crosshairs; }(); /** * ApexCharts HeatMap Class. * @module HeatMap **/ var HeatMap = /*#__PURE__*/ function () { function HeatMap(ctx, xyRatios) { _classCallCheck(this, HeatMap); this.ctx = ctx; this.w = ctx.w; this.xRatio = xyRatios.xRatio; this.yRatio = xyRatios.yRatio; this.negRange = false; this.dynamicAnim = this.w.config.chart.animations.dynamicAnimation; this.rectRadius = this.w.config.plotOptions.heatmap.radius; this.strokeWidth = this.w.config.stroke.width; } _createClass(HeatMap, [{ key: "draw", value: function draw(series) { var w = this.w; var graphics = new Graphics(this.ctx); var ret = graphics.group({ class: 'apexcharts-heatmap' }); ret.attr('clip-path', "url(#gridRectMask".concat(w.globals.cuid, ")")); // width divided into equal parts var xDivision = w.globals.gridWidth / w.globals.dataPoints; var yDivision = w.globals.gridHeight / w.globals.series.length; var y1 = 0; var rev = false; this.checkColorRange(); var heatSeries = series.slice(); if (w.config.yaxis[0].reversed) { rev = true; heatSeries.reverse(); } for (var i = rev ? 0 : heatSeries.length - 1; rev ? i < heatSeries.length : i >= 0; rev ? i++ : i--) { // el to which series will be drawn var elSeries = graphics.group({ class: "apexcharts-series apexcharts-heatmap-series ".concat(Utils.escapeString(w.globals.seriesNames[i])), rel: i + 1, 'data:realIndex': i }); if (w.config.chart.dropShadow.enabled) { var shadow = w.config.chart.dropShadow; var filters = new Filters(this.ctx); filters.dropShadow(elSeries, shadow, i); } var x1 = 0; for (var j = 0; j < heatSeries[i].length; j++) { var colorShadePercent = 1; var heatColorProps = this.determineHeatColor(i, j); if (w.globals.hasNegs || this.negRange) { var shadeIntensity = w.config.plotOptions.heatmap.shadeIntensity; if (heatColorProps.percent < 0) { colorShadePercent = 1 - (1 + heatColorProps.percent / 100) * shadeIntensity; } else { colorShadePercent = (1 - heatColorProps.percent / 100) * shadeIntensity; } } else { colorShadePercent = 1 - heatColorProps.percent / 100; } var color = heatColorProps.color; if (w.config.plotOptions.heatmap.enableShades) { var utils = new Utils(); color = Utils.hexToRgba(utils.shadeColor(colorShadePercent, heatColorProps.color), w.config.fill.opacity); } var radius = this.rectRadius; var rect = graphics.drawRect(x1, y1, xDivision, yDivision, radius); rect.attr({ cx: x1, cy: y1 }); rect.node.classList.add('apexcharts-heatmap-rect'); elSeries.add(rect); rect.attr({ fill: color, i: i, index: i, j: j, val: heatSeries[i][j], 'stroke-width': this.strokeWidth, stroke: w.globals.stroke.colors[0], color: color }); rect.node.addEventListener('mouseenter', graphics.pathMouseEnter.bind(this, rect)); rect.node.addEventListener('mouseleave', graphics.pathMouseLeave.bind(this, rect)); rect.node.addEventListener('mousedown', graphics.pathMouseDown.bind(this, rect)); if (w.config.chart.animations.enabled && !w.globals.dataChanged) { var speed = 1; if (!w.globals.resized) { speed = w.config.chart.animations.speed; } this.animateHeatMap(rect, x1, y1, xDivision, yDivision, speed); } if (w.globals.dataChanged) { var _speed = 1; if (this.dynamicAnim.enabled && w.globals.shouldAnimate) { _speed = this.dynamicAnim.speed; var colorFrom = w.globals.previousPaths[i] && w.globals.previousPaths[i][j] && w.globals.previousPaths[i][j].color; if (!colorFrom) colorFrom = 'rgba(255, 255, 255, 0)'; this.animateHeatColor(rect, Utils.isColorHex(colorFrom) ? colorFrom : Utils.rgb2hex(colorFrom), Utils.isColorHex(color) ? color : Utils.rgb2hex(color), _speed); } } var dataLabels = this.calculateHeatmapDataLabels({ x: x1, y: y1, i: i, j: j, series: heatSeries, rectHeight: yDivision, rectWidth: xDivision }); if (dataLabels !== null) { elSeries.add(dataLabels); } x1 = x1 + xDivision; } y1 = y1 + yDivision; ret.add(elSeries); } // adjust yaxis labels for heatmap var yAxisScale = w.globals.yAxisScale[0].result.slice(); if (w.config.yaxis[0].reversed) { yAxisScale.unshift(''); } else { yAxisScale.push(''); } w.globals.yAxisScale[0].result = yAxisScale; var divisor = w.globals.gridHeight / w.globals.series.length; w.config.yaxis[0].labels.offsetY = -(divisor / 2); return ret; } }, { key: "checkColorRange", value: function checkColorRange() { var _this = this; var w = this.w; var heatmap = w.config.plotOptions.heatmap; if (heatmap.colorScale.ranges.length > 0) { heatmap.colorScale.ranges.map(function (range, index) { if (range.from < 0) { _this.negRange = true; } }); } } }, { key: "determineHeatColor", value: function determineHeatColor(i, j) { var w = this.w; var val = w.globals.series[i][j]; var heatmap = w.config.plotOptions.heatmap; var seriesNumber = heatmap.colorScale.inverse ? j : i; var color = w.globals.colors[seriesNumber]; var min = Math.min.apply(Math, _toConsumableArray(w.globals.series[i])); var max = Math.max.apply(Math, _toConsumableArray(w.globals.series[i])); if (!heatmap.distributed) { min = w.globals.minY; max = w.globals.maxY; } if (typeof heatmap.colorScale.min !== 'undefined') { min = heatmap.colorScale.min < w.globals.minY ? heatmap.colorScale.min : w.globals.minY; max = heatmap.colorScale.max > w.globals.maxY ? heatmap.colorScale.max : w.globals.maxY; } var total = Math.abs(max) + Math.abs(min); var percent = 100 * val / (total === 0 ? total - 0.000001 : total); if (heatmap.colorScale.ranges.length > 0) { var colorRange = heatmap.colorScale.ranges; colorRange.map(function (range, index) { if (val >= range.from && val <= range.to) { color = range.color; min = range.from; max = range.to; var _total = Math.abs(max) + Math.abs(min); percent = 100 * val / (_total === 0 ? _total - 0.000001 : _total); } }); } return { color: color, percent: percent }; } }, { key: "calculateHeatmapDataLabels", value: function calculateHeatmapDataLabels(_ref) { var x = _ref.x, y = _ref.y, i = _ref.i, j = _ref.j, series = _ref.series, rectHeight = _ref.rectHeight, rectWidth = _ref.rectWidth; var w = this.w; // let graphics = new Graphics(this.ctx) var dataLabelsConfig = w.config.dataLabels; var graphics = new Graphics(this.ctx); var dataLabels = new DataLabels(this.ctx); var formatter = dataLabelsConfig.formatter; var elDataLabelsWrap = null; if (dataLabelsConfig.enabled) { elDataLabelsWrap = graphics.group({ class: 'apexcharts-data-labels' }); var offX = dataLabelsConfig.offsetX; var offY = dataLabelsConfig.offsetY; var dataLabelsX = x + rectWidth / 2 + offX; var dataLabelsY = y + rectHeight / 2 + parseInt(dataLabelsConfig.style.fontSize) / 3 + offY; var text = formatter(w.globals.series[i][j], { seriesIndex: i, dataPointIndex: j, w: w }); dataLabels.plotDataLabelsText({ x: dataLabelsX, y: dataLabelsY, text: text, i: i, j: j, parent: elDataLabelsWrap, dataLabelsConfig: dataLabelsConfig }); } return elDataLabelsWrap; } }, { key: "animateHeatMap", value: function animateHeatMap(el, x, y, width, height, speed) { var _this2 = this; var animations = new Animations(this.ctx); animations.animateRect(el, { x: x + width / 2, y: y + height / 2, width: 0, height: 0 }, { x: x, y: y, width: width, height: height }, speed, function () { _this2.w.globals.animationEnded = true; }); } }, { key: "animateHeatColor", value: function animateHeatColor(el, colorFrom, colorTo, speed) { el.attr({ fill: colorFrom }).animate(speed).attr({ fill: colorTo }); } }]); return HeatMap; }(); /** * ApexCharts Pie Class for drawing Pie / Donut Charts. * @module Pie **/ var Pie = /*#__PURE__*/ function () { function Pie(ctx) { _classCallCheck(this, Pie); this.ctx = ctx; this.w = ctx.w; this.chartType = this.w.config.chart.type; this.initialAnim = this.w.config.chart.animations.enabled; this.dynamicAnim = this.initialAnim && this.w.config.chart.animations.dynamicAnimation.enabled; this.animBeginArr = [0]; this.animDur = 0; this.donutDataLabels = this.w.config.plotOptions.pie.donut.labels; var w = this.w; this.lineColorArr = w.globals.stroke.colors !== undefined ? w.globals.stroke.colors : w.globals.colors; this.defaultSize = w.globals.svgHeight < w.globals.svgWidth ? w.globals.svgHeight - 35 : w.globals.gridWidth; this.centerY = this.defaultSize / 2; this.centerX = w.globals.gridWidth / 2; this.fullAngle = 360; this.size = 0; this.donutSize = 0; this.sliceLabels = []; this.prevSectorAngleArr = []; // for dynamic animations } _createClass(Pie, [{ key: "draw", value: function draw(series) { var self = this; var w = this.w; var graphics = new Graphics(this.ctx); var ret = graphics.group({ class: 'apexcharts-pie' }); var total = 0; for (var k = 0; k < series.length; k++) { // CALCULATE THE TOTAL total += Utils.negToZero(series[k]); } var sectorAngleArr = []; // el to which series will be drawn var elSeries = graphics.group(); // prevent division by zero error if there is no data if (total === 0) { total = 0.00001; } for (var i = 0; i < series.length; i++) { // CALCULATE THE ANGLES var angle = this.fullAngle * Utils.negToZero(series[i]) / total; sectorAngleArr.push(angle); } if (w.globals.dataChanged) { var prevTotal = 0; for (var _k = 0; _k < w.globals.previousPaths.length; _k++) { // CALCULATE THE PREV TOTAL prevTotal += Utils.negToZero(w.globals.previousPaths[_k]); } var previousAngle; for (var _i = 0; _i < w.globals.previousPaths.length; _i++) { // CALCULATE THE PREVIOUS ANGLES previousAngle = this.fullAngle * Utils.negToZero(w.globals.previousPaths[_i]) / prevTotal; this.prevSectorAngleArr.push(previousAngle); } } this.size = this.defaultSize / 2.05 - w.config.stroke.width - w.config.chart.dropShadow.blur; if (w.config.plotOptions.pie.size !== undefined) { this.size = w.config.plotOptions.pie.size; } this.donutSize = this.size * parseInt(w.config.plotOptions.pie.donut.size) / 100; var scaleSize = w.config.plotOptions.pie.customScale; var halfW = w.globals.gridWidth / 2; var halfH = w.globals.gridHeight / 2; var translateX = halfW - w.globals.gridWidth / 2 * scaleSize; var translateY = halfH - w.globals.gridHeight / 2 * scaleSize; if (this.donutDataLabels.show) { var dataLabels = this.renderInnerDataLabels(this.donutDataLabels, { hollowSize: this.donutSize, centerX: this.centerX, centerY: this.centerY, opacity: this.donutDataLabels.show, translateX: translateX, translateY: translateY }); ret.add(dataLabels); } if (w.config.chart.type === 'donut') { // draw the inner circle and add some text to it var circle = graphics.drawCircle(this.donutSize); circle.attr({ cx: this.centerX, cy: this.centerY, fill: w.config.plotOptions.pie.donut.background }); elSeries.add(circle); } var elG = self.drawArcs(sectorAngleArr, series); // add slice dataLabels at the end this.sliceLabels.forEach(function (s) { elG.add(s); }); elSeries.attr({ transform: "translate(".concat(translateX, ", ").concat(translateY - 5, ") scale(").concat(scaleSize, ")") }); ret.attr({ 'data:innerTranslateX': translateX, 'data:innerTranslateY': translateY - 25 }); elSeries.add(elG); ret.add(elSeries); return ret; } // core function for drawing pie arcs }, { key: "drawArcs", value: function drawArcs(sectorAngleArr, series) { var w = this.w; var filters = new Filters(this.ctx); var graphics = new Graphics(this.ctx); var fill = new Fill(this.ctx); var g = graphics.group(); var startAngle = 0; var prevStartAngle = 0; var endAngle = 0; var prevEndAngle = 0; this.strokeWidth = w.config.stroke.show ? w.config.stroke.width : 0; for (var i = 0; i < sectorAngleArr.length; i++) { // if(sectorAngleArr[i]>0) { var elPieArc = graphics.group({ class: "apexcharts-series apexcharts-pie-series ".concat(Utils.escapeString(w.globals.seriesNames[i])), id: 'apexcharts-series-' + i, rel: i + 1 }); g.add(elPieArc); startAngle = endAngle; prevStartAngle = prevEndAngle; endAngle = startAngle + sectorAngleArr[i]; prevEndAngle = prevStartAngle + this.prevSectorAngleArr[i]; var angle = endAngle - startAngle; var pathFill = fill.fillPath({ seriesNumber: i, size: this.size, value: series[i] }); // additionaly, pass size for gradient drawing in the fillPath function var path = this.getChangedPath(prevStartAngle, prevEndAngle); var elPath = graphics.drawPath({ d: path, stroke: this.lineColorArr instanceof Array ? this.lineColorArr[i] : this.lineColorArr, strokeWidth: this.strokeWidth, fill: pathFill, fillOpacity: w.config.fill.opacity, classes: 'apexcharts-pie-area' }); elPath.attr({ id: "apexcharts-".concat(w.config.chart.type, "-slice-").concat(i), index: 0, j: i }); if (w.config.chart.dropShadow.enabled) { var shadow = w.config.chart.dropShadow; filters.dropShadow(elPath, shadow, i); } this.addListeners(elPath, this.donutDataLabels); Graphics.setAttrs(elPath.node, { 'data:angle': angle, 'data:startAngle': startAngle, 'data:strokeWidth': this.strokeWidth, 'data:value': series[i] }); var labelPosition = { x: 0, y: 0 }; if (w.config.chart.type === 'pie') { labelPosition = Utils.polarToCartesian(this.centerX, this.centerY, this.size / 1.25 + w.config.plotOptions.pie.dataLabels.offset, startAngle + (endAngle - startAngle) / 2); } else if (w.config.chart.type === 'donut') { labelPosition = Utils.polarToCartesian(this.centerX, this.centerY, (this.size + this.donutSize) / 2 + w.config.plotOptions.pie.dataLabels.offset, startAngle + (endAngle - startAngle) / 2); } elPieArc.add(elPath); // Animation code starts var dur = 0; if (this.initialAnim && !w.globals.resized && !w.globals.dataChanged) { dur = (endAngle - startAngle) / this.fullAngle * w.config.chart.animations.speed; this.animDur = dur + this.animDur; this.animBeginArr.push(this.animDur); } else { this.animBeginArr.push(0); } if (this.dynamicAnim && w.globals.dataChanged) { this.animatePaths(elPath, { endAngle: endAngle, startAngle: startAngle, prevStartAngle: prevStartAngle, prevEndAngle: prevEndAngle, animateStartingPos: true, i: i, animBeginArr: this.animBeginArr, dur: w.config.chart.animations.dynamicAnimation.speed }); } else { this.animatePaths(elPath, { endAngle: endAngle, startAngle: startAngle, i: i, totalItems: sectorAngleArr.length - 1, animBeginArr: this.animBeginArr, dur: dur }); } // animation code ends if (w.config.plotOptions.pie.expandOnClick) { elPath.click(this.pieClicked.bind(this, i)); } if (w.config.dataLabels.enabled) { var xPos = labelPosition.x; var yPos = labelPosition.y; var text = 100 * (endAngle - startAngle) / 360 + '%'; if (angle !== 0 && w.config.plotOptions.pie.dataLabels.minAngleToShowLabel < sectorAngleArr[i]) { var formatter = w.config.dataLabels.formatter; if (formatter !== undefined) { text = formatter(w.globals.seriesPercent[i][0], { seriesIndex: i, w: w }); } var foreColor = w.globals.dataLabels.style.colors[i]; var elPieLabel = graphics.drawText({ x: xPos, y: yPos, text: text, textAnchor: 'middle', fontSize: w.config.dataLabels.style.fontSize, fontFamily: w.config.dataLabels.style.fontFamily, foreColor: foreColor }); if (w.config.dataLabels.dropShadow.enabled) { var textShadow = w.config.dataLabels.dropShadow; var _filters = new Filters(this.ctx); _filters.dropShadow(elPieLabel, textShadow); } elPieLabel.node.classList.add('apexcharts-pie-label'); if (w.config.chart.animations.animate && w.globals.resized === false) { elPieLabel.node.classList.add('apexcharts-pie-label-delay'); elPieLabel.node.style.animationDelay = w.config.chart.animations.speed / 940 + 's'; } this.sliceLabels.push(elPieLabel); } } // } } return g; } }, { key: "addListeners", value: function addListeners(elPath, dataLabels) { var graphics = new Graphics(this.ctx); // append filters on mouseenter and mouseleave elPath.node.addEventListener('mouseenter', graphics.pathMouseEnter.bind(this, elPath)); elPath.node.addEventListener('mouseenter', this.printDataLabelsInner.bind(this, elPath.node, dataLabels)); elPath.node.addEventListener('mouseleave', graphics.pathMouseLeave.bind(this, elPath)); elPath.node.addEventListener('mouseleave', this.revertDataLabelsInner.bind(this, elPath.node, dataLabels)); elPath.node.addEventListener('mousedown', graphics.pathMouseDown.bind(this, elPath)); elPath.node.addEventListener('mousedown', this.printDataLabelsInner.bind(this, elPath.node, dataLabels)); } // This function can be used for other circle charts too }, { key: "animatePaths", value: function animatePaths(el, opts) { var w = this.w; var me = this; var angle = opts.endAngle - opts.startAngle; var prevAngle = angle; var fromStartAngle = opts.startAngle; var toStartAngle = opts.startAngle; if (opts.prevStartAngle !== undefined && opts.prevEndAngle !== undefined) { fromStartAngle = opts.prevEndAngle; prevAngle = opts.prevEndAngle - opts.prevStartAngle; } if (opts.i === w.config.series.length - 1) { // some adjustments for the last overlapping paths if (angle + toStartAngle > this.fullAngle) { opts.endAngle = opts.endAngle - (angle + toStartAngle); } else if (angle + toStartAngle < this.fullAngle) { opts.endAngle = opts.endAngle + (this.fullAngle - (angle + toStartAngle)); } } if (angle === this.fullAngle) angle = this.fullAngle - 0.01; me.animateArc(el, fromStartAngle, toStartAngle, angle, prevAngle, opts); } }, { key: "animateArc", value: function animateArc(el, fromStartAngle, toStartAngle, angle, prevAngle, opts) { var me = this; var w = this.w; var size = me.size; if (!size) { size = opts.size; } var path; if (isNaN(fromStartAngle) || isNaN(prevAngle)) { fromStartAngle = toStartAngle; prevAngle = angle; opts.dur = 0; } var currAngle = angle; var startAngle = toStartAngle; var fromAngle = fromStartAngle - toStartAngle; if (w.globals.dataChanged && opts.shouldSetPrevPaths) { // to avoid flickering, set prev path first and then we will animate from there path = me.getPiePath({ me: me, startAngle: startAngle, angle: prevAngle, size: size }); el.attr({ d: path }); } if (opts.dur !== 0) { el.animate(opts.dur, w.globals.easing, opts.animBeginArr[opts.i]).afterAll(function () { if (w.config.chart.type === 'pie' || w.config.chart.type === 'donut') { this.animate(300).attr({ 'stroke-width': w.config.stroke.width }); } w.globals.animationEnded = true; }).during(function (pos) { currAngle = fromAngle + (angle - fromAngle) * pos; if (opts.animateStartingPos) { currAngle = prevAngle + (angle - prevAngle) * pos; startAngle = fromStartAngle - prevAngle + (toStartAngle - (fromStartAngle - prevAngle)) * pos; } path = me.getPiePath({ me: me, startAngle: startAngle, angle: currAngle, size: size }); el.node.setAttribute('data:pathOrig', path); el.attr({ d: path }); }); } else { path = me.getPiePath({ me: me, startAngle: startAngle, angle: angle, size: size }); if (!opts.isTrack) { w.globals.animationEnded = true; } el.node.setAttribute('data:pathOrig', path); el.attr({ d: path }); } } }, { key: "pieClicked", value: function pieClicked(i) { var w = this.w; var me = this; var path; var size = me.size + 4; var elPath = w.globals.dom.Paper.select("#apexcharts-".concat(w.config.chart.type.toLowerCase(), "-slice-").concat(i)).members[0]; var pathFrom = elPath.attr('d'); if (elPath.attr('data:pieClicked') === 'true') { elPath.attr({ 'data:pieClicked': 'false' }); this.revertDataLabelsInner(elPath.node, this.donutDataLabels); var origPath = elPath.attr('data:pathOrig'); elPath.attr({ d: origPath }); return; } else { // reset all elems var allEls = w.globals.dom.baseEl.querySelectorAll('.apexcharts-pie-area'); Array.prototype.forEach.call(allEls, function (pieSlice) { pieSlice.setAttribute('data:pieClicked', 'false'); var origPath = pieSlice.getAttribute('data:pathOrig'); pieSlice.setAttribute('d', origPath); }); elPath.attr('data:pieClicked', 'true'); } var startAngle = parseInt(elPath.attr('data:startAngle')); var angle = parseInt(elPath.attr('data:angle')); path = me.getPiePath({ me: me, startAngle: startAngle, angle: angle, size: size }); if (angle === 360) return; elPath.plot(path).animate(1).plot(pathFrom).animate(100).plot(path); } }, { key: "getChangedPath", value: function getChangedPath(prevStartAngle, prevEndAngle) { var path = ''; if (this.dynamicAnim && this.w.globals.dataChanged) { path = this.getPiePath({ me: this, startAngle: prevStartAngle, angle: prevEndAngle - prevStartAngle, size: this.size }); } return path; } }, { key: "getPiePath", value: function getPiePath(_ref) { var me = _ref.me, startAngle = _ref.startAngle, angle = _ref.angle, size = _ref.size; var w = this.w; var path; var startDeg = startAngle; var startRadians = Math.PI * (startDeg - 90) / 180; var endDeg = angle + startAngle; if (Math.ceil(endDeg) >= 360) endDeg = 359.99; var endRadians = Math.PI * (endDeg - 90) / 180; var x1 = me.centerX + size * Math.cos(startRadians); var y1 = me.centerY + size * Math.sin(startRadians); var x2 = me.centerX + size * Math.cos(endRadians); var y2 = me.centerY + size * Math.sin(endRadians); var startInner = Utils.polarToCartesian(me.centerX, me.centerY, me.donutSize, endDeg); var endInner = Utils.polarToCartesian(me.centerX, me.centerY, me.donutSize, startDeg); var largeArc = angle > 180 ? 1 : 0; if (w.config.chart.type === 'donut') { path = ['M', x1, y1, 'A', size, size, 0, largeArc, 1, x2, y2, 'L', startInner.x, startInner.y, 'A', me.donutSize, me.donutSize, 0, largeArc, 0, endInner.x, endInner.y, 'L', x1, y1, 'z'].join(' '); } else if (w.config.chart.type === 'pie') { path = ['M', x1, y1, 'A', size, size, 0, largeArc, 1, x2, y2, 'L', me.centerX, me.centerY, 'L', x1, y1].join(' '); } else { path = ['M', x1, y1, 'A', size, size, 0, largeArc, 1, x2, y2].join(' '); } return path; } }, { key: "renderInnerDataLabels", value: function renderInnerDataLabels(dataLabelsConfig, opts) { var w = this.w; var graphics = new Graphics(this.ctx); var g = graphics.group({ class: 'apexcharts-datalabels-group', transform: "translate(".concat(opts.translateX ? opts.translateX : 0, ", ").concat(opts.translateY ? opts.translateY : 0, ")") }); var showTotal = dataLabelsConfig.total.show; g.node.style.opacity = opts.opacity; var x = opts.centerX; var y = opts.centerY; var labelColor, valueColor; if (dataLabelsConfig.name.color === undefined) { labelColor = w.globals.colors[0]; } else { labelColor = dataLabelsConfig.name.color; } if (dataLabelsConfig.value.color === undefined) { valueColor = w.config.chart.foreColor; } else { valueColor = dataLabelsConfig.value.color; } var lbFormatter = dataLabelsConfig.value.formatter; var val = ''; var name = ''; if (showTotal) { labelColor = dataLabelsConfig.total.color; name = dataLabelsConfig.total.label; val = dataLabelsConfig.total.formatter(w); } else { if (w.globals.series.length === 1) { val = lbFormatter(w.globals.series[0], w); name = w.globals.seriesNames[0]; } } if (dataLabelsConfig.name.show) { var elLabel = graphics.drawText({ x: x, y: y + parseInt(dataLabelsConfig.name.offsetY), text: name, textAnchor: 'middle', foreColor: labelColor, fontSize: dataLabelsConfig.name.fontSize, fontFamily: dataLabelsConfig.name.fontFamily }); elLabel.node.classList.add('apexcharts-datalabel-label'); g.add(elLabel); } if (dataLabelsConfig.value.show) { var valOffset = dataLabelsConfig.name.show ? parseInt(dataLabelsConfig.value.offsetY) + 16 : dataLabelsConfig.value.offsetY; var elValue = graphics.drawText({ x: x, y: y + valOffset, text: val, textAnchor: 'middle', foreColor: valueColor, fontSize: dataLabelsConfig.value.fontSize, fontFamily: dataLabelsConfig.value.fontFamily }); elValue.node.classList.add('apexcharts-datalabel-value'); g.add(elValue); } // for a multi-series circle chart, we need to show total value instead of first series labels return g; } /** * * @param {string} name - The name of the series * @param {string} val - The value of that series * @param {object} el - Optional el (indicates which series was hovered/clicked). If this param is not present, means we need to show total */ }, { key: "printInnerLabels", value: function printInnerLabels(labelsConfig, name, val, el) { var w = this.w; var labelColor; if (el) { if (labelsConfig.name.color === undefined) { labelColor = w.globals.colors[parseInt(el.parentNode.getAttribute('rel')) - 1]; } else { labelColor = labelsConfig.name.color; } } else { if (w.globals.series.length > 1 && labelsConfig.total.show) { labelColor = labelsConfig.total.color; } } var elLabel = w.globals.dom.baseEl.querySelector('.apexcharts-datalabel-label'); var elValue = w.globals.dom.baseEl.querySelector('.apexcharts-datalabel-value'); var lbFormatter = labelsConfig.value.formatter; val = lbFormatter(val, w); // we need to show Total Val - so get the formatter of it if (!el && typeof labelsConfig.total.formatter === 'function') { val = labelsConfig.total.formatter(w); } if (elLabel !== null) { elLabel.textContent = name; } if (elValue !== null) { elValue.textContent = val; } if (elLabel !== null) { elLabel.style.fill = labelColor; } } }, { key: "printDataLabelsInner", value: function printDataLabelsInner(el, dataLabelsConfig) { var w = this.w; var val = el.getAttribute('data:value'); var name = w.globals.seriesNames[parseInt(el.parentNode.getAttribute('rel')) - 1]; if (w.globals.series.length > 1) { this.printInnerLabels(dataLabelsConfig, name, val, el); } var dataLabelsGroup = w.globals.dom.baseEl.querySelector('.apexcharts-datalabels-group'); if (dataLabelsGroup !== null) { dataLabelsGroup.style.opacity = 1; } } }, { key: "revertDataLabelsInner", value: function revertDataLabelsInner(el, dataLabelsConfig, event) { var _this = this; var w = this.w; var dataLabelsGroup = w.globals.dom.baseEl.querySelector('.apexcharts-datalabels-group'); if (dataLabelsConfig.total.show && w.globals.series.length > 1) { var pie = new Pie(this.ctx); pie.printInnerLabels(dataLabelsConfig, dataLabelsConfig.total.label, dataLabelsConfig.total.formatter(w)); } else { var slices = document.querySelectorAll(".apexcharts-pie-area"); var sliceOut = false; slices.forEach(function (s) { if (s.getAttribute('data:pieClicked') === 'true') { sliceOut = true; _this.printDataLabelsInner(s, dataLabelsConfig); } }); if (!sliceOut) { if (w.globals.selectedDataPoints.length && w.globals.series.length > 1) { if (w.globals.selectedDataPoints[0].length > 0) { var index = w.globals.selectedDataPoints[0]; var _el = w.globals.dom.baseEl.querySelector("#apexcharts-".concat(w.config.chart.type.toLowerCase(), "-slice-").concat(index)); this.printDataLabelsInner(_el, dataLabelsConfig); } else if (dataLabelsGroup && w.globals.selectedDataPoints.length && w.globals.selectedDataPoints[0].length === 0) { dataLabelsGroup.style.opacity = 0; } } else { if (dataLabelsGroup && w.globals.series.length > 1) { dataLabelsGroup.style.opacity = 0; } } } } } }]); return Pie; }(); /** * ApexCharts Radar Class for Spider/Radar Charts. * @module Radar **/ var Radar = /*#__PURE__*/ function () { function Radar(ctx) { _classCallCheck(this, Radar); this.ctx = ctx; this.w = ctx.w; this.chartType = this.w.config.chart.type; this.initialAnim = this.w.config.chart.animations.enabled; this.dynamicAnim = this.initialAnim && this.w.config.chart.animations.dynamicAnimation.enabled; this.animDur = 0; var w = this.w; this.graphics = new Graphics(this.ctx); this.lineColorArr = w.globals.stroke.colors !== undefined ? w.globals.stroke.colors : w.globals.colors; this.defaultSize = w.globals.svgHeight < w.globals.svgWidth ? w.globals.svgHeight - 35 : w.globals.gridWidth; this.maxValue = this.w.globals.maxY; this.polygons = w.config.plotOptions.radar.polygons; this.maxLabelWidth = 20; var longestLabel = w.globals.labels.slice().sort(function (a, b) { return b.length - a.length; })[0]; var labelWidth = this.graphics.getTextRects(longestLabel, w.config.dataLabels.style.fontSize); this.size = this.defaultSize / 2.1 - w.config.stroke.width - w.config.chart.dropShadow.blur - labelWidth.width / 1.75; if (w.config.plotOptions.radar.size !== undefined) { this.size = w.config.plotOptions.radar.size; } this.dataRadiusOfPercent = []; this.dataRadius = []; this.angleArr = []; this.yaxisLabelsTextsPos = []; } _createClass(Radar, [{ key: "draw", value: function draw(series) { var _this = this; var w = this.w; var fill = new Fill(this.ctx); var allSeries = []; this.dataPointsLen = series[w.globals.maxValsInArrayIndex].length; this.disAngle = Math.PI * 2 / this.dataPointsLen; var halfW = w.globals.gridWidth / 2; var halfH = w.globals.gridHeight / 2; var translateX = halfW; var translateY = halfH; var ret = this.graphics.group({ class: 'apexcharts-radar-series', 'data:innerTranslateX': translateX, 'data:innerTranslateY': translateY - 25, transform: "translate(".concat(translateX || 0, ", ").concat(translateY || 0, ")") }); var dataPointsPos = []; var elPointsMain = null; this.yaxisLabels = this.graphics.group({ class: 'apexcharts-yaxis' }); series.forEach(function (s, i) { // el to which series will be drawn var elSeries = _this.graphics.group().attr({ class: "apexcharts-series ".concat(Utils.escapeString(w.globals.seriesNames[i])), rel: i + 1, 'data:realIndex': i }); _this.dataRadiusOfPercent[i] = []; _this.dataRadius[i] = []; _this.angleArr[i] = []; s.forEach(function (dv, j) { _this.dataRadiusOfPercent[i][j] = dv / _this.maxValue; _this.dataRadius[i][j] = _this.dataRadiusOfPercent[i][j] * _this.size; _this.angleArr[i][j] = j * _this.disAngle; }); dataPointsPos = _this.getDataPointsPos(_this.dataRadius[i], _this.angleArr[i]); var paths = _this.createPaths(dataPointsPos, { x: 0, y: 0 }); // points elPointsMain = _this.graphics.group({ class: 'apexcharts-series-markers-wrap hidden' }); w.globals.delayedElements.push({ el: elPointsMain.node, index: i }); var defaultRenderedPathOptions = { i: i, realIndex: i, animationDelay: i, initialSpeed: w.config.chart.animations.speed, dataChangeSpeed: w.config.chart.animations.dynamicAnimation.speed, className: "apexcharts-radar", id: "apexcharts-radar", shouldClipToGrid: false, bindEventsOnPaths: false, stroke: w.globals.stroke.colors[i], strokeLineCap: w.config.stroke.lineCap }; var pathFrom = null; if (w.globals.previousPaths.length > 0) { pathFrom = _this.getPathFrom(i); } for (var p = 0; p < paths.linePathsTo.length; p++) { var renderedLinePath = _this.graphics.renderPaths(_objectSpread({}, defaultRenderedPathOptions, { pathFrom: pathFrom === null ? paths.linePathsFrom[p] : pathFrom, pathTo: paths.linePathsTo[p], strokeWidth: Array.isArray(w.config.stroke.width) ? w.config.stroke.width[i] : w.config.stroke.width, fill: 'none', drawShadow: false })); elSeries.add(renderedLinePath); var pathFill = fill.fillPath({ seriesNumber: i }); var renderedAreaPath = _this.graphics.renderPaths(_objectSpread({}, defaultRenderedPathOptions, { pathFrom: pathFrom === null ? paths.areaPathsFrom[p] : pathFrom, pathTo: paths.areaPathsTo[p], strokeWidth: 0, fill: pathFill, drawShadow: false })); if (w.config.chart.dropShadow.enabled) { var filters = new Filters(_this.ctx); var shadow = w.config.chart.dropShadow; filters.dropShadow(renderedAreaPath, Object.assign({}, shadow, { noUserSpaceOnUse: true }), i); } elSeries.add(renderedAreaPath); } s.forEach(function (sj, j) { var markers = new Markers(_this.ctx); var opts = markers.getMarkerConfig('apexcharts-marker', i); var point = _this.graphics.drawMarker(dataPointsPos[j].x, dataPointsPos[j].y, opts); point.attr('rel', j); point.attr('j', j); point.attr('index', i); point.node.setAttribute('default-marker-size', opts.pSize); var elPointsWrap = _this.graphics.group({ class: 'apexcharts-series-markers' }); if (elPointsWrap) { elPointsWrap.add(point); } elPointsMain.add(elPointsWrap); elSeries.add(elPointsMain); }); allSeries.push(elSeries); }); this.drawPolygons({ parent: ret }); if (w.config.dataLabels.enabled) { var dataLabels = this.drawLabels(); ret.add(dataLabels); } ret.add(this.yaxisLabels); allSeries.forEach(function (elS) { ret.add(elS); }); return ret; } }, { key: "drawPolygons", value: function drawPolygons(opts) { var _this2 = this; var w = this.w; var parent = opts.parent; var yaxisTexts = w.globals.yAxisScale[0].result.reverse(); var layers = yaxisTexts.length; var radiusSizes = []; var layerDis = this.size / (layers - 1); for (var i = 0; i < layers; i++) { radiusSizes[i] = layerDis * i; } radiusSizes.reverse(); var polygonStrings = []; var lines = []; radiusSizes.forEach(function (radiusSize, r) { var polygon = _this2.getPolygonPos(radiusSize); var string = ''; polygon.forEach(function (p, i) { if (r === 0) { var line = _this2.graphics.drawLine(p.x, p.y, 0, 0, Array.isArray(_this2.polygons.connectorColors) ? _this2.polygons.connectorColors[i] : _this2.polygons.connectorColors); lines.push(line); } if (i === 0) { _this2.yaxisLabelsTextsPos.push({ x: p.x, y: p.y }); } string += p.x + ',' + p.y + ' '; }); polygonStrings.push(string); }); polygonStrings.forEach(function (p, i) { var strokeColors = _this2.polygons.strokeColors; var polygon = _this2.graphics.drawPolygon(p, Array.isArray(strokeColors) ? strokeColors[i] : strokeColors, w.globals.radarPolygons.fill.colors[i]); parent.add(polygon); }); lines.forEach(function (l) { parent.add(l); }); if (w.config.yaxis[0].show) { this.yaxisLabelsTextsPos.forEach(function (p, i) { var yText = _this2.drawYAxisText(p.x, p.y, i, yaxisTexts[i]); _this2.yaxisLabels.add(yText); }); } } }, { key: "drawYAxisText", value: function drawYAxisText(x, y, i, text) { var w = this.w; var yaxisConfig = w.config.yaxis[0]; var formatter = w.globals.yLabelFormatters[0]; var yaxisLabel = this.graphics.drawText({ x: x + yaxisConfig.labels.offsetX, y: y + yaxisConfig.labels.offsetY, text: formatter(text, i), textAnchor: 'middle', fontSize: yaxisConfig.labels.style.fontSize, fontFamily: yaxisConfig.labels.style.fontFamily, foreColor: yaxisConfig.labels.style.color }); return yaxisLabel; } }, { key: "drawLabels", value: function drawLabels() { var _this3 = this; var w = this.w; var limit = 10; var textAnchor = 'middle'; var dataLabelsConfig = w.config.dataLabels; var elDataLabelsWrap = this.graphics.group({ class: 'apexcharts-datalabels' }); var polygonPos = this.getPolygonPos(this.size); var currPosX = 0; var currPosY = 0; w.globals.labels.forEach(function (label, i) { var formatter = dataLabelsConfig.formatter; var dataLabels = new DataLabels(_this3.ctx); if (polygonPos[i]) { currPosX = polygonPos[i].x; currPosY = polygonPos[i].y; if (Math.abs(polygonPos[i].x) >= limit) { if (polygonPos[i].x > 0) { textAnchor = 'start'; currPosX += 10; } else if (polygonPos[i].x < 0) { textAnchor = 'end'; currPosX -= 10; } } else { textAnchor = 'middle'; } if (Math.abs(polygonPos[i].y) >= _this3.size - limit) { if (polygonPos[i].y < 0) { currPosY -= 10; } else if (polygonPos[i].y > 0) { currPosY += 10; } } var text = formatter(label, { seriesIndex: -1, dataPointIndex: i, w: w }); dataLabels.plotDataLabelsText({ x: currPosX, y: currPosY, text: text, textAnchor: textAnchor, i: i, j: i, parent: elDataLabelsWrap, dataLabelsConfig: dataLabelsConfig, offsetCorrection: false }); } }); return elDataLabelsWrap; } }, { key: "createPaths", value: function createPaths(pos, origin) { var _this4 = this; var linePathsTo = []; var linePathsFrom = []; var areaPathsTo = []; var areaPathsFrom = []; if (pos.length) { linePathsFrom = [this.graphics.move(origin.x, origin.y)]; areaPathsFrom = [this.graphics.move(origin.x, origin.y)]; var linePathTo = this.graphics.move(pos[0].x, pos[0].y); var areaPathTo = this.graphics.move(pos[0].x, pos[0].y); pos.forEach(function (p, i) { linePathTo += _this4.graphics.line(p.x, p.y); areaPathTo += _this4.graphics.line(p.x, p.y); if (i === pos.length - 1) { linePathTo += 'Z'; areaPathTo += 'Z'; } }); linePathsTo.push(linePathTo); areaPathsTo.push(areaPathTo); } return { linePathsFrom: linePathsFrom, linePathsTo: linePathsTo, areaPathsFrom: areaPathsFrom, areaPathsTo: areaPathsTo }; } }, { key: "getPathFrom", value: function getPathFrom(realIndex) { var w = this.w; var pathFrom = null; for (var pp = 0; pp < w.globals.previousPaths.length; pp++) { var gpp = w.globals.previousPaths[pp]; if (gpp.paths.length > 0 && parseInt(gpp.realIndex) === parseInt(realIndex)) { if (typeof w.globals.previousPaths[pp].paths[0] !== 'undefined') { pathFrom = w.globals.previousPaths[pp].paths[0].d; } } } return pathFrom; } }, { key: "getDataPointsPos", value: function getDataPointsPos(dataRadiusArr, angleArr) { var dataPointsLen = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : this.dataPointsLen; dataRadiusArr = dataRadiusArr || []; angleArr = angleArr || []; var dataPointsPosArray = []; for (var j = 0; j < dataPointsLen; j++) { var curPointPos = {}; curPointPos.x = dataRadiusArr[j] * Math.sin(angleArr[j]); curPointPos.y = -dataRadiusArr[j] * Math.cos(angleArr[j]); dataPointsPosArray.push(curPointPos); } return dataPointsPosArray; } }, { key: "getPolygonPos", value: function getPolygonPos(size) { var dotsArray = []; var angle = Math.PI * 2 / this.dataPointsLen; for (var i = 0; i < this.dataPointsLen; i++) { var curPos = {}; curPos.x = size * Math.sin(i * angle); curPos.y = -size * Math.cos(i * angle); dotsArray.push(curPos); } return dotsArray; } }]); return Radar; }(); /** * ApexCharts Radial Class for drawing Circle / Semi Circle Charts. * @module Radial **/ var Radial = /*#__PURE__*/ function (_Pie) { _inherits(Radial, _Pie); function Radial(ctx) { var _this; _classCallCheck(this, Radial); _this = _possibleConstructorReturn(this, _getPrototypeOf(Radial).call(this, ctx)); _this.ctx = ctx; _this.w = ctx.w; _this.animBeginArr = [0]; _this.animDur = 0; var w = _this.w; _this.startAngle = w.config.plotOptions.radialBar.startAngle; _this.endAngle = w.config.plotOptions.radialBar.endAngle; _this.trackStartAngle = w.config.plotOptions.radialBar.track.startAngle; _this.trackEndAngle = w.config.plotOptions.radialBar.track.endAngle; _this.radialDataLabels = w.config.plotOptions.radialBar.dataLabels; if (!_this.trackStartAngle) _this.trackStartAngle = _this.startAngle; if (!_this.trackEndAngle) _this.trackEndAngle = _this.endAngle; if (_this.endAngle === 360) _this.endAngle = 359.99; _this.fullAngle = 360 - w.config.plotOptions.radialBar.endAngle - w.config.plotOptions.radialBar.startAngle; _this.margin = parseInt(w.config.plotOptions.radialBar.track.margin); return _this; } _createClass(Radial, [{ key: "draw", value: function draw(series) { var w = this.w; var graphics = new Graphics(this.ctx); var ret = graphics.group({ class: 'apexcharts-radialbar' }); var elSeries = graphics.group(); var centerY = this.defaultSize / 2; var centerX = w.globals.gridWidth / 2; var size = this.defaultSize / 2.05 - w.config.stroke.width - w.config.chart.dropShadow.blur; if (w.config.plotOptions.radialBar.size !== undefined) { size = w.config.plotOptions.radialBar.size; } var colorArr = w.globals.fill.colors; if (w.config.plotOptions.radialBar.track.show) { var elTracks = this.drawTracks({ size: size, centerX: centerX, centerY: centerY, colorArr: colorArr, series: series }); elSeries.add(elTracks); } var elG = this.drawArcs({ size: size, centerX: centerX, centerY: centerY, colorArr: colorArr, series: series }); elSeries.add(elG.g); if (w.config.plotOptions.radialBar.hollow.position === 'front') { elG.g.add(elG.elHollow); if (elG.dataLabels) { elG.g.add(elG.dataLabels); } } ret.add(elSeries); return ret; } }, { key: "drawTracks", value: function drawTracks(opts) { var w = this.w; var graphics = new Graphics(this.ctx); var g = graphics.group(); var filters = new Filters(this.ctx); var fill = new Fill(this.ctx); var strokeWidth = this.getStrokeWidth(opts); opts.size = opts.size - strokeWidth / 2; for (var i = 0; i < opts.series.length; i++) { var elRadialBarTrack = graphics.group({ class: 'apexcharts-radialbar-track apexcharts-track' }); g.add(elRadialBarTrack); elRadialBarTrack.attr({ id: 'apexcharts-track-' + i, rel: i + 1 }); opts.size = opts.size - strokeWidth - this.margin; var trackConfig = w.config.plotOptions.radialBar.track; var pathFill = fill.fillPath({ seriesNumber: 0, size: opts.size, fillColors: Array.isArray(trackConfig.background) ? trackConfig.background[i] : trackConfig.background, solid: true }); var startAngle = this.trackStartAngle; var endAngle = this.trackEndAngle; if (Math.abs(endAngle) + Math.abs(startAngle) >= 360) endAngle = 360 - Math.abs(this.startAngle) - 0.1; var elPath = graphics.drawPath({ d: '', stroke: pathFill, strokeWidth: strokeWidth * parseInt(trackConfig.strokeWidth) / 100, fill: 'none', strokeOpacity: trackConfig.opacity, classes: 'apexcharts-radialbar-area' }); if (trackConfig.dropShadow.enabled) { var shadow = trackConfig.dropShadow; filters.dropShadow(elPath, shadow); } elRadialBarTrack.add(elPath); elPath.attr('id', 'apexcharts-radialbarTrack-' + i); var pie = new Pie(this.ctx); pie.animatePaths(elPath, { centerX: opts.centerX, centerY: opts.centerY, endAngle: endAngle, startAngle: startAngle, size: opts.size, i: i, totalItems: 2, animBeginArr: 0, dur: 0, isTrack: true, easing: w.globals.easing }); } return g; } }, { key: "drawArcs", value: function drawArcs(opts) { var w = this.w; // size, donutSize, centerX, centerY, colorArr, lineColorArr, sectorAngleArr, series var graphics = new Graphics(this.ctx); var fill = new Fill(this.ctx); var filters = new Filters(this.ctx); var g = graphics.group(); var strokeWidth = this.getStrokeWidth(opts); opts.size = opts.size - strokeWidth / 2; var hollowFillID = w.config.plotOptions.radialBar.hollow.background; var hollowSize = opts.size - strokeWidth * opts.series.length - this.margin * opts.series.length - strokeWidth * parseInt(w.config.plotOptions.radialBar.track.strokeWidth) / 100 / 2; var hollowRadius = hollowSize - w.config.plotOptions.radialBar.hollow.margin; if (w.config.plotOptions.radialBar.hollow.image !== undefined) { hollowFillID = this.drawHollowImage(opts, g, hollowSize, hollowFillID); } var elHollow = this.drawHollow({ size: hollowRadius, centerX: opts.centerX, centerY: opts.centerY, fill: hollowFillID }); if (w.config.plotOptions.radialBar.hollow.dropShadow.enabled) { var shadow = w.config.plotOptions.radialBar.hollow.dropShadow; filters.dropShadow(elHollow, shadow); } var shown = 1; if (!this.radialDataLabels.total.show && w.globals.series.length > 1) { shown = 0; } var pie = new Pie(this.ctx); var dataLabels = null; if (this.radialDataLabels.show) { dataLabels = pie.renderInnerDataLabels(this.radialDataLabels, { hollowSize: hollowSize, centerX: opts.centerX, centerY: opts.centerY, opacity: shown }); } if (w.config.plotOptions.radialBar.hollow.position === 'back') { g.add(elHollow); if (dataLabels) { g.add(dataLabels); } } var reverseLoop = false; if (w.config.plotOptions.radialBar.inverseOrder) { reverseLoop = true; } for (var i = reverseLoop ? opts.series.length - 1 : 0; reverseLoop ? i >= 0 : i < opts.series.length; reverseLoop ? i-- : i++) { var elRadialBarArc = graphics.group({ class: "apexcharts-series apexcharts-radial-series ".concat(Utils.escapeString(w.globals.seriesNames[i])) }); g.add(elRadialBarArc); elRadialBarArc.attr({ id: 'apexcharts-series-' + i, rel: i + 1 }); this.ctx.series.addCollapsedClassToSeries(elRadialBarArc, i); opts.size = opts.size - strokeWidth - this.margin; var pathFill = fill.fillPath({ seriesNumber: i, size: opts.size, value: opts.series[i] }); var startAngle = this.startAngle; var prevStartAngle = void 0; var totalAngle = Math.abs(w.config.plotOptions.radialBar.endAngle - w.config.plotOptions.radialBar.startAngle); // if data exceeds 100, make it 100 var dataValue = Utils.negToZero(opts.series[i] > 100 ? 100 : opts.series[i]) / 100; var endAngle = Math.round(totalAngle * dataValue) + this.startAngle; var prevEndAngle = void 0; if (w.globals.dataChanged) { prevStartAngle = this.startAngle; prevEndAngle = Math.round(totalAngle * Utils.negToZero(w.globals.previousPaths[i]) / 100) + prevStartAngle; } var currFullAngle = Math.abs(endAngle) + Math.abs(startAngle); if (currFullAngle >= 360) { endAngle = endAngle - 0.01; } var prevFullAngle = Math.abs(prevEndAngle) + Math.abs(prevStartAngle); if (prevFullAngle >= 360) { prevEndAngle = prevEndAngle - 0.01; } var angle = endAngle - startAngle; var dashArray = Array.isArray(w.config.stroke.dashArray) ? w.config.stroke.dashArray[i] : w.config.stroke.dashArray; var elPath = graphics.drawPath({ d: '', stroke: pathFill, strokeWidth: strokeWidth, fill: 'none', fillOpacity: w.config.fill.opacity, classes: 'apexcharts-radialbar-area', strokeDashArray: dashArray }); Graphics.setAttrs(elPath.node, { 'data:angle': angle, 'data:value': opts.series[i] }); if (w.config.chart.dropShadow.enabled) { var _shadow = w.config.chart.dropShadow; filters.dropShadow(elPath, _shadow, i); } this.addListeners(elPath, this.radialDataLabels); var _pie = new Pie(this.ctx); elRadialBarArc.add(elPath); elPath.attr({ id: 'apexcharts-radialbar-slice-' + i, index: 0, j: i }); var dur = 0; if (_pie.initialAnim && !w.globals.resized && !w.globals.dataChanged) { dur = (endAngle - startAngle) / 360 * w.config.chart.animations.speed; this.animDur = dur / (opts.series.length * 1.2) + this.animDur; this.animBeginArr.push(this.animDur); } if (w.globals.dataChanged) { dur = (endAngle - startAngle) / 360 * w.config.chart.animations.dynamicAnimation.speed; this.animDur = dur / (opts.series.length * 1.2) + this.animDur; this.animBeginArr.push(this.animDur); } _pie.animatePaths(elPath, { centerX: opts.centerX, centerY: opts.centerY, endAngle: endAngle, startAngle: startAngle, prevEndAngle: prevEndAngle, prevStartAngle: prevStartAngle, size: opts.size, i: i, totalItems: 2, animBeginArr: this.animBeginArr, dur: dur, shouldSetPrevPaths: true, easing: w.globals.easing }); } return { g: g, elHollow: elHollow, dataLabels: dataLabels }; } }, { key: "drawHollow", value: function drawHollow(opts) { var graphics = new Graphics(this.ctx); var circle = graphics.drawCircle(opts.size * 2); circle.attr({ class: 'apexcharts-radialbar-hollow', cx: opts.centerX, cy: opts.centerY, r: opts.size, fill: opts.fill }); return circle; } }, { key: "drawHollowImage", value: function drawHollowImage(opts, g, hollowSize, hollowFillID) { var w = this.w; var fill = new Fill(this.ctx); var randID = (Math.random() + 1).toString(36).substring(4); var hollowFillImg = w.config.plotOptions.radialBar.hollow.image; if (w.config.plotOptions.radialBar.hollow.imageClipped) { fill.clippedImgArea({ width: hollowSize, height: hollowSize, image: hollowFillImg, patternID: "pattern".concat(w.globals.cuid).concat(randID) }); hollowFillID = "url(#pattern".concat(w.globals.cuid).concat(randID, ")"); } else { var imgWidth = w.config.plotOptions.radialBar.hollow.imageWidth; var imgHeight = w.config.plotOptions.radialBar.hollow.imageHeight; if (imgWidth === undefined && imgHeight === undefined) { var image = w.globals.dom.Paper.image(hollowFillImg).loaded(function (loader) { this.move(opts.centerX - loader.width / 2 + w.config.plotOptions.radialBar.hollow.imageOffsetX, opts.centerY - loader.height / 2 + w.config.plotOptions.radialBar.hollow.imageOffsetY); }); g.add(image); } else { var _image = w.globals.dom.Paper.image(hollowFillImg).loaded(function (loader) { this.move(opts.centerX - imgWidth / 2 + w.config.plotOptions.radialBar.hollow.imageOffsetX, opts.centerY - imgHeight / 2 + w.config.plotOptions.radialBar.hollow.imageOffsetY); this.size(imgWidth, imgHeight); }); g.add(_image); } } return hollowFillID; } }, { key: "getStrokeWidth", value: function getStrokeWidth(opts) { var w = this.w; return opts.size * (100 - parseInt(w.config.plotOptions.radialBar.hollow.size)) / 100 / (opts.series.length + 1) - this.margin; } }]); return Radial; }(Pie); /** * ApexCharts RangeBar Class responsible for drawing Range/Timeline Bars. * * @module RangeBar **/ var RangeBar = /*#__PURE__*/ function (_Bar) { _inherits(RangeBar, _Bar); function RangeBar() { _classCallCheck(this, RangeBar); return _possibleConstructorReturn(this, _getPrototypeOf(RangeBar).apply(this, arguments)); } _createClass(RangeBar, [{ key: "draw", value: function draw(series, seriesIndex) { var w = this.w; var graphics = new Graphics(this.ctx); var fill = new Fill(this.ctx); this.rangeBarOptions = this.w.config.plotOptions.rangeBar; this.series = series; this.seriesRangeStart = w.globals.seriesRangeStart; this.seriesRangeEnd = w.globals.seriesRangeEnd; this.initVariables(series); var ret = graphics.group({ class: 'apexcharts-rangebar-series apexcharts-plot-series' }); for (var i = 0, bc = 0; i < series.length; i++, bc++) { var pathTo = void 0, pathFrom = void 0; var x = void 0, y = void 0, xDivision = void 0, // xDivision is the GRIDWIDTH divided by number of datapoints (columns) yDivision = void 0, // yDivision is the GRIDHEIGHT divided by number of datapoints (bars) zeroH = void 0, // zeroH is the baseline where 0 meets y axis zeroW = void 0; // zeroW is the baseline where 0 meets x axis var yArrj = []; // hold y values of current iterating series var xArrj = []; // hold x values of current iterating series var realIndex = w.globals.comboCharts ? seriesIndex[i] : i; // el to which series will be drawn var elSeries = graphics.group({ class: "apexcharts-series ".concat(Utils.escapeString(w.globals.seriesNames[realIndex])), rel: i + 1, 'data:realIndex': realIndex }); if (series[i].length > 0) { this.visibleI = this.visibleI + 1; } var strokeWidth = 0; var barHeight = 0; var barWidth = 0; if (this.yRatio.length > 1) { this.yaxisIndex = realIndex; } var initPositions = this.initialPositions(); y = initPositions.y; yDivision = initPositions.yDivision; barHeight = initPositions.barHeight; zeroW = initPositions.zeroW; x = initPositions.x; barWidth = initPositions.barWidth; xDivision = initPositions.xDivision; zeroH = initPositions.zeroH; xArrj.push(x + barWidth / 2); // eldatalabels var elDataLabelsWrap = graphics.group({ class: 'apexcharts-datalabels' }); for (var j = 0, tj = w.globals.dataPoints; j < w.globals.dataPoints; j++, tj--) { if (typeof this.series[i][j] === 'undefined' || series[i][j] === null) { this.isNullValue = true; } else { this.isNullValue = false; } if (w.config.stroke.show) { if (this.isNullValue) { strokeWidth = 0; } else { strokeWidth = Array.isArray(this.strokeWidth) ? this.strokeWidth[realIndex] : this.strokeWidth; } } var paths = null; if (this.isHorizontal) { paths = this.drawRangeBarPaths({ indexes: { i: i, j: j, realIndex: realIndex, bc: bc }, barHeight: barHeight, strokeWidth: strokeWidth, pathTo: pathTo, pathFrom: pathFrom, zeroW: zeroW, x: x, y: y, yDivision: yDivision, elSeries: elSeries }); barWidth = paths.barWidth; } else { paths = this.drawRangeColumnPaths({ indexes: { i: i, j: j, realIndex: realIndex, bc: bc }, x: x, y: y, xDivision: xDivision, pathTo: pathTo, pathFrom: pathFrom, barWidth: barWidth, zeroH: zeroH, strokeWidth: strokeWidth, elSeries: elSeries }); barHeight = paths.barHeight; } pathTo = paths.pathTo; pathFrom = paths.pathFrom; y = paths.y; x = paths.x; // push current X if (j > 0) { xArrj.push(x + barWidth / 2); } yArrj.push(y); var pathFill = fill.fillPath({ seriesNumber: realIndex }); var lineFill = w.globals.stroke.colors[realIndex]; elSeries = this.renderSeries({ realIndex: realIndex, pathFill: pathFill, lineFill: lineFill, j: j, i: i, pathFrom: pathFrom, pathTo: pathTo, strokeWidth: strokeWidth, elSeries: elSeries, x: x, y: y, series: series, barHeight: barHeight, barWidth: barWidth, elDataLabelsWrap: elDataLabelsWrap, visibleSeries: this.visibleI, type: 'rangebar' }); } // push all x val arrays into main xArr w.globals.seriesXvalues[realIndex] = xArrj; w.globals.seriesYvalues[realIndex] = yArrj; ret.add(elSeries); } return ret; } }, { key: "drawRangeColumnPaths", value: function drawRangeColumnPaths(_ref) { var indexes = _ref.indexes, x = _ref.x, y = _ref.y, strokeWidth = _ref.strokeWidth, xDivision = _ref.xDivision, pathTo = _ref.pathTo, pathFrom = _ref.pathFrom, barWidth = _ref.barWidth, zeroH = _ref.zeroH; var w = this.w; var graphics = new Graphics(this.ctx); var i = indexes.i; var j = indexes.j; var yRatio = this.yRatio[this.yaxisIndex]; var realIndex = indexes.realIndex; var range = this.getRangeValue(realIndex, j); var y1 = Math.min(range.start, range.end); var y2 = Math.max(range.start, range.end); if (w.globals.isXNumeric) { x = (w.globals.seriesX[i][j] - w.globals.minX) / this.xRatio - barWidth / 2; } var barXPosition = x + barWidth * this.visibleI; if (typeof this.series[i][j] === 'undefined' || this.series[i][j] === null) { y1 = zeroH; } else { y1 = zeroH - y1 / yRatio; y2 = zeroH - y2 / yRatio; } var barHeight = Math.abs(y2 - y1); pathTo = graphics.move(barXPosition, zeroH); pathFrom = graphics.move(barXPosition, y1); if (w.globals.previousPaths.length > 0) { pathFrom = this.getPathFrom(realIndex, j, true); } pathTo = graphics.move(barXPosition, y2) + graphics.line(barXPosition + barWidth, y2) + graphics.line(barXPosition + barWidth, y1) + graphics.line(barXPosition, y1) + graphics.line(barXPosition, y2 - strokeWidth / 2); pathFrom = pathFrom + graphics.move(barXPosition, y1) + graphics.line(barXPosition + barWidth, y1) + graphics.line(barXPosition + barWidth, y1) + graphics.line(barXPosition, y1); if (!w.globals.isXNumeric) { x = x + xDivision; } return { pathTo: pathTo, pathFrom: pathFrom, barHeight: barHeight, x: x, y: y2, barXPosition: barXPosition }; } }, { key: "drawRangeBarPaths", value: function drawRangeBarPaths(_ref2) { var indexes = _ref2.indexes, x = _ref2.x, y = _ref2.y, yDivision = _ref2.yDivision, pathTo = _ref2.pathTo, pathFrom = _ref2.pathFrom, barHeight = _ref2.barHeight, zeroW = _ref2.zeroW; var w = this.w; var graphics = new Graphics(this.ctx); var i = indexes.i; var j = indexes.j; var realIndex = indexes.realIndex; var x1 = zeroW; var x2 = zeroW; if (w.globals.isXNumeric) { y = (w.globals.seriesX[i][j] - w.globals.minX) / this.invertedXRatio - barHeight; } var barYPosition = y + barHeight * this.visibleI; if (typeof this.series[i][j] !== 'undefined' && this.series[i][j] !== null) { x1 = zeroW + this.seriesRangeStart[i][j] / this.invertedYRatio; x2 = zeroW + this.seriesRangeEnd[i][j] / this.invertedYRatio; } pathTo = graphics.move(zeroW, barYPosition); pathFrom = graphics.move(zeroW, barYPosition); if (w.globals.previousPaths.length > 0) { pathFrom = this.getPathFrom(realIndex, j); } var barWidth = Math.abs(x2 - x1); pathTo = graphics.move(x1, barYPosition) + graphics.line(x2, barYPosition) + graphics.line(x2, barYPosition + barHeight) + graphics.line(x1, barYPosition + barHeight) + graphics.line(x1, barYPosition); pathFrom = pathFrom + graphics.line(x1, barYPosition) + graphics.line(x1, barYPosition + barHeight) + graphics.line(x1, barYPosition + barHeight) + graphics.line(x1, barYPosition); if (!w.globals.isXNumeric) { y = y + yDivision; } return { pathTo: pathTo, pathFrom: pathFrom, barWidth: barWidth, x: x2, y: y, barYPosition: barYPosition }; } }, { key: "getRangeValue", value: function getRangeValue(i, j) { var w = this.w; return { start: w.globals.seriesRangeStart[i][j], end: w.globals.seriesRangeEnd[i][j] }; } }]); return RangeBar; }(Bar); /** * ApexCharts Line Class responsible for drawing Line / Area Charts. * This class is also responsible for generating values for Bubble/Scatter charts, so need to rename it to Axis Charts to avoid confusions * @module Line **/ var Line = /*#__PURE__*/ function () { function Line(ctx, xyRatios, isPointsChart) { _classCallCheck(this, Line); this.ctx = ctx; this.w = ctx.w; this.xyRatios = xyRatios; this.pointsChart = !(this.w.config.chart.type !== 'bubble' && this.w.config.chart.type !== 'scatter') || isPointsChart; this.scatter = new Scatter(this.ctx); this.noNegatives = this.w.globals.minX === Number.MAX_VALUE; this.yaxisIndex = 0; } _createClass(Line, [{ key: "draw", value: function draw(series, ptype, seriesIndex) { var w = this.w; var graphics = new Graphics(this.ctx); var fill = new Fill(this.ctx); var type = w.globals.comboCharts ? ptype : w.config.chart.type; var ret = graphics.group({ class: "apexcharts-".concat(type, "-series apexcharts-plot-series") }); var coreUtils = new CoreUtils(this.ctx, w); series = coreUtils.getLogSeries(series); var yRatio = this.xyRatios.yRatio; yRatio = coreUtils.getLogYRatios(yRatio); var zRatio = this.xyRatios.zRatio; var xRatio = this.xyRatios.xRatio; var baseLineY = this.xyRatios.baseLineY; // push all series in an array, so we can draw in reverse order (for stacked charts) var allSeries = []; var prevSeriesY = []; var categoryAxisCorrection = 0; for (var i = 0; i < series.length; i++) { // width divided into equal parts if (type === 'line' && (w.config.fill.type === 'gradient' || w.config.fill.type[i] === 'gradient')) { // a small adjustment to allow gradient line to draw correctly for all same values /* #fix https://github.com/apexcharts/apexcharts.js/issues/358 */ if (coreUtils.seriesHaveSameValues(i)) { var gSeries = series[i].slice(); gSeries[gSeries.length - 1] = gSeries[gSeries.length - 1] + 0.000001; series[i] = gSeries; } } var xDivision = w.globals.gridWidth / w.globals.dataPoints; var realIndex = w.globals.comboCharts ? seriesIndex[i] : i; if (yRatio.length > 1) { this.yaxisIndex = realIndex; } this.isReversed = w.config.yaxis[this.yaxisIndex] && w.config.yaxis[this.yaxisIndex].reversed; var yArrj = []; // hold y values of current iterating series var xArrj = []; // hold x values of current iterating series // zeroY is the 0 value in y series which can be used in negative charts var zeroY = w.globals.gridHeight - baseLineY[this.yaxisIndex] - (this.isReversed ? w.globals.gridHeight : 0) + (this.isReversed ? baseLineY[this.yaxisIndex] * 2 : 0); var areaBottomY = zeroY; if (zeroY > w.globals.gridHeight) { areaBottomY = w.globals.gridHeight; } categoryAxisCorrection = xDivision / 2; var x = w.globals.padHorizontal + categoryAxisCorrection; var y = 1; if (w.globals.isXNumeric && w.globals.seriesX.length > 0) { x = (w.globals.seriesX[realIndex][0] - w.globals.minX) / xRatio; } xArrj.push(x); var linePath = void 0, areaPath = void 0, pathFromLine = void 0, pathFromArea = void 0; var linePaths = []; var areaPaths = []; // el to which series will be drawn var elSeries = graphics.group({ class: "apexcharts-series ".concat(Utils.escapeString(w.globals.seriesNames[realIndex])) }); // points var elPointsMain = graphics.group({ class: 'apexcharts-series-markers-wrap' }); // eldatalabels var elDataLabelsWrap = graphics.group({ class: 'apexcharts-datalabels' }); this.ctx.series.addCollapsedClassToSeries(elSeries, realIndex); var longestSeries = series[i].length === w.globals.dataPoints; elSeries.attr({ 'data:longestSeries': longestSeries, rel: i + 1, 'data:realIndex': realIndex }); this.appendPathFrom = true; var pX = x; var pY = void 0; var prevX = pX; var prevY = zeroY; // w.globals.svgHeight; var lineYPosition = 0; // the first value in the current series is not null or undefined var firstPrevY = this.determineFirstPrevY({ i: i, series: series, yRatio: yRatio[this.yaxisIndex], zeroY: zeroY, prevY: prevY, prevSeriesY: prevSeriesY, lineYPosition: lineYPosition }); prevY = firstPrevY.prevY; yArrj.push(prevY); pY = prevY; if (series[i][0] === null) { // when the first value itself is null, we need to move the pointer to a location where a null value is not found for (var s = 0; s < series[i].length; s++) { if (series[i][s] !== null) { prevX = xDivision * s; prevY = zeroY - series[i][s] / yRatio[this.yaxisIndex]; linePath = graphics.move(prevX, prevY); areaPath = graphics.move(prevX, areaBottomY); break; } } } else { linePath = graphics.move(prevX, prevY); areaPath = graphics.move(prevX, areaBottomY) + graphics.line(prevX, prevY); } pathFromLine = graphics.move(-1, zeroY) + graphics.line(-1, zeroY); pathFromArea = graphics.move(-1, zeroY) + graphics.line(-1, zeroY); if (w.globals.previousPaths.length > 0) { var pathFrom = this.checkPreviousPaths({ pathFromLine: pathFromLine, pathFromArea: pathFromArea, realIndex: realIndex }); pathFromLine = pathFrom.pathFromLine; pathFromArea = pathFrom.pathFromArea; } var iterations = w.globals.dataPoints > 1 ? w.globals.dataPoints - 1 : w.globals.dataPoints; for (var j = 0; j < iterations; j++) { if (w.globals.isXNumeric) { var sX = w.globals.seriesX[realIndex][j + 1]; if (typeof w.globals.seriesX[realIndex][j + 1] === 'undefined') { /* fix #374 */ sX = w.globals.seriesX[realIndex][iterations - 1]; } x = (sX - w.globals.minX) / xRatio; } else { x = x + xDivision; } var minY = Utils.isNumber(w.globals.minYArr[realIndex]) ? w.globals.minYArr[realIndex] : w.globals.minY; if (w.config.chart.stacked) { if (i > 0 && w.globals.collapsedSeries.length < w.config.series.length - 1) { lineYPosition = prevSeriesY[i - 1][j + 1]; } else { // the first series will not have prevY values lineYPosition = zeroY; } if (typeof series[i][j + 1] === 'undefined' || series[i][j + 1] === null) { y = lineYPosition - minY / yRatio[this.yaxisIndex] + (this.isReversed ? minY / yRatio[this.yaxisIndex] : 0) * 2; } else { y = lineYPosition - series[i][j + 1] / yRatio[this.yaxisIndex] + (this.isReversed ? series[i][j + 1] / yRatio[this.yaxisIndex] : 0) * 2; } } else { if (typeof series[i][j + 1] === 'undefined' || series[i][j + 1] === null) { y = zeroY - minY / yRatio[this.yaxisIndex] + (this.isReversed ? minY / yRatio[this.yaxisIndex] : 0) * 2; } else { y = zeroY - series[i][j + 1] / yRatio[this.yaxisIndex] + (this.isReversed ? series[i][j + 1] / yRatio[this.yaxisIndex] : 0) * 2; } } // push current X xArrj.push(x); // push current Y that will be used as next series's bottom position yArrj.push(y); var calculatedPaths = this.createPaths({ series: series, i: i, j: j, x: x, y: y, xDivision: xDivision, pX: pX, pY: pY, areaBottomY: areaBottomY, linePath: linePath, areaPath: areaPath, linePaths: linePaths, areaPaths: areaPaths, seriesIndex: seriesIndex }); areaPaths = calculatedPaths.areaPaths; linePaths = calculatedPaths.linePaths; pX = calculatedPaths.pX; pY = calculatedPaths.pY; areaPath = calculatedPaths.areaPath; linePath = calculatedPaths.linePath; if (this.appendPathFrom) { pathFromLine = pathFromLine + graphics.line(x, zeroY); pathFromArea = pathFromArea + graphics.line(x, zeroY); } var pointsPos = this.calculatePoints({ series: series, x: x, y: y, realIndex: realIndex, i: i, j: j, prevY: prevY, categoryAxisCorrection: categoryAxisCorrection, xRatio: xRatio }); if (!this.pointsChart) { var markers = new Markers(this.ctx); if (w.globals.dataPoints > 1) { elPointsMain.node.classList.add('hidden'); } var elPointsWrap = markers.plotChartMarkers(pointsPos, realIndex, j + 1); if (elPointsWrap !== null) { elPointsMain.add(elPointsWrap); } } else { // scatter / bubble chart points creation this.scatter.draw(elSeries, j, { realIndex: realIndex, pointsPos: pointsPos, zRatio: zRatio, elParent: elPointsMain }); } var dataLabelAlign = !series[i][j + 1] || series[i][j + 1] > series[i][j] ? 'top' : 'bottom'; var dataLabels = new DataLabels(this.ctx); var drawnLabels = dataLabels.drawDataLabel(pointsPos, realIndex, j + 1, null, dataLabelAlign); if (drawnLabels !== null) { elDataLabelsWrap.add(drawnLabels); } } // push all current y values array to main PrevY Array prevSeriesY.push(yArrj); // push all x val arrays into main xArr w.globals.seriesXvalues[realIndex] = xArrj; w.globals.seriesYvalues[realIndex] = yArrj; // these elements will be shown after area path animation completes if (!this.pointsChart) { w.globals.delayedElements.push({ el: elPointsMain.node, index: realIndex }); } var defaultRenderedPathOptions = { i: i, realIndex: realIndex, animationDelay: i, initialSpeed: w.config.chart.animations.speed, dataChangeSpeed: w.config.chart.animations.dynamicAnimation.speed, className: "apexcharts-".concat(type), id: "apexcharts-".concat(type) }; if (type === 'area') { var pathFill = fill.fillPath({ seriesNumber: realIndex }); for (var p = 0; p < areaPaths.length; p++) { var renderedPath = graphics.renderPaths(_objectSpread({}, defaultRenderedPathOptions, { pathFrom: pathFromArea, pathTo: areaPaths[p], stroke: 'none', strokeWidth: 0, strokeLineCap: null, fill: pathFill })); elSeries.add(renderedPath); } } if (w.config.stroke.show && !this.pointsChart) { var lineFill = null; if (type === 'line') { // fillable lines only for lineChart lineFill = fill.fillPath({ seriesNumber: realIndex, i: i }); } else { lineFill = w.globals.stroke.colors[realIndex]; } for (var _p = 0; _p < linePaths.length; _p++) { var _renderedPath = graphics.renderPaths(_objectSpread({}, defaultRenderedPathOptions, { pathFrom: pathFromLine, pathTo: linePaths[_p], stroke: lineFill, strokeWidth: Array.isArray(w.config.stroke.width) ? w.config.stroke.width[realIndex] : w.config.stroke.width, strokeLineCap: w.config.stroke.lineCap, fill: 'none' })); elSeries.add(_renderedPath); } } elSeries.add(elPointsMain); elSeries.add(elDataLabelsWrap); allSeries.push(elSeries); } for (var _s = allSeries.length; _s > 0; _s--) { ret.add(allSeries[_s - 1]); } return ret; } }, { key: "createPaths", value: function createPaths(_ref) { var series = _ref.series, i = _ref.i, j = _ref.j, x = _ref.x, y = _ref.y, pX = _ref.pX, pY = _ref.pY, xDivision = _ref.xDivision, areaBottomY = _ref.areaBottomY, linePath = _ref.linePath, areaPath = _ref.areaPath, linePaths = _ref.linePaths, areaPaths = _ref.areaPaths, seriesIndex = _ref.seriesIndex; var w = this.w; var graphics = new Graphics(this.ctx); var curve = w.config.stroke.curve; if (Array.isArray(w.config.stroke.curve)) { if (Array.isArray(seriesIndex)) { curve = w.config.stroke.curve[seriesIndex[i]]; } else { curve = w.config.stroke.curve[i]; } } // logic of smooth curve derived from chartist // CREDITS: https://gionkunz.github.io/chartist-js/ if (curve === 'smooth') { var length = (x - pX) * 0.35; if (w.globals.hasNullValues) { if (series[i][j] !== null) { if (series[i][j + 1] !== null) { linePath = graphics.move(pX, pY) + graphics.curve(pX + length, pY, x - length, y, x + 1, y); areaPath = graphics.move(pX + 1, pY) + graphics.curve(pX + length, pY, x - length, y, x + 1, y) + graphics.line(x, areaBottomY) + graphics.line(pX, areaBottomY) + 'z'; } else { linePath = graphics.move(pX, pY); areaPath = graphics.move(pX, pY) + 'z'; } } linePaths.push(linePath); areaPaths.push(areaPath); } else { linePath = linePath + graphics.curve(pX + length, pY, x - length, y, x, y); areaPath = areaPath + graphics.curve(pX + length, pY, x - length, y, x, y); } pX = x; pY = y; if (j === series[i].length - 2) { // last loop, close path areaPath = areaPath + graphics.curve(pX, pY, x, y, x, areaBottomY) + graphics.move(x, y) + 'z'; if (!w.globals.hasNullValues) { linePaths.push(linePath); areaPaths.push(areaPath); } } } else { if (series[i][j + 1] === null) { linePath = linePath + graphics.move(x, y); areaPath = areaPath + graphics.line(x - xDivision, areaBottomY) + graphics.move(x, y); } if (series[i][j] === null) { linePath = linePath + graphics.move(x, y); areaPath = areaPath + graphics.move(x, areaBottomY); } if (curve === 'stepline') { linePath = linePath + graphics.line(x, null, 'H') + graphics.line(null, y, 'V'); areaPath = areaPath + graphics.line(x, null, 'H') + graphics.line(null, y, 'V'); } else if (curve === 'straight') { linePath = linePath + graphics.line(x, y); areaPath = areaPath + graphics.line(x, y); } if (j === series[i].length - 2) { // last loop, close path areaPath = areaPath + graphics.line(x, areaBottomY) + graphics.move(x, y) + 'z'; linePaths.push(linePath); areaPaths.push(areaPath); } } return { linePaths: linePaths, areaPaths: areaPaths, pX: pX, pY: pY, linePath: linePath, areaPath: areaPath }; } }, { key: "calculatePoints", value: function calculatePoints(_ref2) { var series = _ref2.series, realIndex = _ref2.realIndex, x = _ref2.x, y = _ref2.y, i = _ref2.i, j = _ref2.j, prevY = _ref2.prevY, categoryAxisCorrection = _ref2.categoryAxisCorrection, xRatio = _ref2.xRatio; var w = this.w; var ptX = []; var ptY = []; if (j === 0) { var xPT1st = categoryAxisCorrection + w.config.markers.offsetX; // the first point for line series // we need to check whether it's not a time series, because a time series may // start from the middle of the x axis if (w.globals.isXNumeric) { xPT1st = (w.globals.seriesX[realIndex][0] - w.globals.minX) / xRatio + w.config.markers.offsetX; } // push 2 points for the first data values ptX.push(xPT1st); ptY.push(Utils.isNumber(series[i][0]) ? prevY + w.config.markers.offsetY : null); ptX.push(x + w.config.markers.offsetX); ptY.push(Utils.isNumber(series[i][j + 1]) ? y + w.config.markers.offsetY : null); } else { ptX.push(x + w.config.markers.offsetX); ptY.push(Utils.isNumber(series[i][j + 1]) ? y + w.config.markers.offsetY : null); } var pointsPos = { x: ptX, y: ptY }; return pointsPos; } }, { key: "checkPreviousPaths", value: function checkPreviousPaths(_ref3) { var pathFromLine = _ref3.pathFromLine, pathFromArea = _ref3.pathFromArea, realIndex = _ref3.realIndex; var w = this.w; for (var pp = 0; pp < w.globals.previousPaths.length; pp++) { var gpp = w.globals.previousPaths[pp]; if ((gpp.type === 'line' || gpp.type === 'area') && gpp.paths.length > 0 && parseInt(gpp.realIndex) === parseInt(realIndex)) { if (gpp.type === 'line') { this.appendPathFrom = false; pathFromLine = w.globals.previousPaths[pp].paths[0].d; } else if (gpp.type === 'area') { this.appendPathFrom = false; pathFromArea = w.globals.previousPaths[pp].paths[0].d; if (w.config.stroke.show) { pathFromLine = w.globals.previousPaths[pp].paths[1].d; } } } } return { pathFromLine: pathFromLine, pathFromArea: pathFromArea }; } }, { key: "determineFirstPrevY", value: function determineFirstPrevY(_ref4) { var i = _ref4.i, series = _ref4.series, yRatio = _ref4.yRatio, zeroY = _ref4.zeroY, prevY = _ref4.prevY, prevSeriesY = _ref4.prevSeriesY, lineYPosition = _ref4.lineYPosition; var w = this.w; if (typeof series[i][0] !== 'undefined') { if (w.config.chart.stacked) { if (i > 0) { // 1st y value of previous series lineYPosition = prevSeriesY[i - 1][0]; } else { // the first series will not have prevY values lineYPosition = zeroY; } prevY = lineYPosition - series[i][0] / yRatio + (this.isReversed ? series[i][0] / yRatio : 0) * 2; } else { prevY = zeroY - series[i][0] / yRatio + (this.isReversed ? series[i][0] / yRatio : 0) * 2; } } else { // the first value in the current series is null if (w.config.chart.stacked && i > 0 && typeof series[i][0] === 'undefined') { // check for undefined value (undefined value will occur when we clear the series while user clicks on legend to hide serieses) for (var s = i - 1; s >= 0; s--) { // for loop to get to 1st previous value until we get it if (series[s][0] !== null && typeof series[s][0] !== 'undefined') { lineYPosition = prevSeriesY[s][0]; prevY = lineYPosition; break; } } } } return { prevY: prevY, lineYPosition: lineYPosition }; } }]); return Line; }(); /** * ApexCharts Formatter Class for setting value formatters for axes as well as tooltips. * * @module Formatters **/ var Formatters = /*#__PURE__*/ function () { function Formatters(ctx) { _classCallCheck(this, Formatters); this.ctx = ctx; this.w = ctx.w; this.tooltipKeyFormat = 'dd MMM'; } _createClass(Formatters, [{ key: "xLabelFormat", value: function xLabelFormat(fn, val) { var w = this.w; if (w.config.xaxis.type === 'datetime') { // if user has not specified a custom formatter, use the default tooltip.x.format if (w.config.tooltip.x.formatter === undefined) { var datetimeObj = new DateTime(this.ctx); return datetimeObj.formatDate(new Date(val), w.config.tooltip.x.format, true, true); } } return fn(val); } }, { key: "setLabelFormatters", value: function setLabelFormatters() { var w = this.w; w.globals.xLabelFormatter = function (val) { return val; }; w.globals.xaxisTooltipFormatter = function (val) { return val; }; w.globals.ttKeyFormatter = function (val) { return val; }; w.globals.ttZFormatter = function (val) { return val; }; w.globals.legendFormatter = function (val) { return val; }; if (typeof w.config.tooltip.x.formatter === 'function') { w.globals.ttKeyFormatter = w.config.tooltip.x.formatter; } if (typeof w.config.xaxis.tooltip.formatter === 'function') { w.globals.xaxisTooltipFormatter = w.config.xaxis.tooltip.formatter; } if (Array.isArray(w.config.tooltip.y)) { w.globals.ttVal = w.config.tooltip.y; } else { if (w.config.tooltip.y.formatter !== undefined) { w.globals.ttVal = w.config.tooltip.y; } } if (w.config.tooltip.z.formatter !== undefined) { w.globals.ttZFormatter = w.config.tooltip.z.formatter; } // legend formatter - if user wants to append any global values of series to legend text if (w.config.legend.formatter !== undefined) { w.globals.legendFormatter = w.config.legend.formatter; } // formatter function will always overwrite format property if (w.config.xaxis.labels.formatter !== undefined) { w.globals.xLabelFormatter = w.config.xaxis.labels.formatter; } else { w.globals.xLabelFormatter = function (val) { if (Utils.isNumber(val)) { // numeric xaxis may have smaller range, so defaulting to 1 decimal if (w.config.xaxis.type === 'numeric' && w.globals.dataPoints < 50) { return val.toFixed(1); } return val.toFixed(0); } return val; }; } // formatter function will always overwrite format property w.config.yaxis.forEach(function (yaxe, i) { if (yaxe.labels.formatter !== undefined) { w.globals.yLabelFormatters[i] = yaxe.labels.formatter; } else { w.globals.yLabelFormatters[i] = function (val) { if (Utils.isNumber(val)) { if (w.globals.yValueDecimal !== 0 || w.globals.maxY - w.globals.minY < 4) { return val.toFixed(yaxe.decimalsInFloat !== undefined ? yaxe.decimalsInFloat : w.globals.yValueDecimal); } else { return val.toFixed(0); } } return val; }; } }); return w.globals; } }, { key: "heatmapLabelFormatters", value: function heatmapLabelFormatters() { var w = this.w; if (w.config.chart.type === 'heatmap') { w.globals.yAxisScale[0].result = w.globals.seriesNames.slice(); // get the longest string from the labels array and also apply label formatter to it var longest = w.globals.seriesNames.reduce(function (a, b) { return a.length > b.length ? a : b; }, 0); w.globals.yAxisScale[0].niceMax = longest; w.globals.yAxisScale[0].niceMin = longest; } } }]); return Formatters; }(); var AxesUtils = /*#__PURE__*/ function () { function AxesUtils(ctx) { _classCallCheck(this, AxesUtils); this.ctx = ctx; this.w = ctx.w; } // Based on the formatter function, get the label text and position _createClass(AxesUtils, [{ key: "getLabel", value: function getLabel(labels, timelineLabels, x, i) { var drawnLabels = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : []; var w = this.w; var rawLabel = typeof labels[i] === 'undefined' ? '' : labels[i]; var label; var xlbFormatter = w.globals.xLabelFormatter; var customFormatter = w.config.xaxis.labels.formatter; var xFormat = new Formatters(this.ctx); label = xFormat.xLabelFormat(xlbFormatter, rawLabel); if (customFormatter !== undefined) { label = customFormatter(rawLabel, labels[i], i); } if (timelineLabels.length > 0) { x = timelineLabels[i].position; label = timelineLabels[i].value; } else { if (w.config.xaxis.type === 'datetime' && customFormatter === undefined) { label = ''; } } if (typeof label === 'undefined') label = ''; label = label.toString(); if (label.indexOf('NaN') === 0 || label.toLowerCase().indexOf('invalid') === 0 || label.toLowerCase().indexOf('infinity') >= 0 || drawnLabels.indexOf(label) >= 0 && !w.config.xaxis.labels.showDuplicates) { label = ''; } return { x: x, text: label }; } }, { key: "drawYAxisTicks", value: function drawYAxisTicks(x, tickAmount, axisBorder, axisTicks, realIndex, labelsDivider, elYaxis) { var w = this.w; var graphics = new Graphics(this.ctx); // initial label position = 0; var t = w.globals.translateY; if (axisTicks.show) { if (w.config.yaxis[realIndex].opposite === true) x = x + axisTicks.width; for (var i = tickAmount; i >= 0; i--) { var tY = t + tickAmount / 10 + w.config.yaxis[realIndex].labels.offsetY - 1; if (w.globals.isBarHorizontal) { tY = labelsDivider * i; } var elTick = graphics.drawLine(x + axisBorder.offsetX - axisTicks.width + axisTicks.offsetX, tY + axisTicks.offsetY, x + axisBorder.offsetX + axisTicks.offsetX, tY + axisTicks.offsetY, axisBorder.color); elYaxis.add(elTick); t = t + labelsDivider; } } } }]); return AxesUtils; }(); /** * ApexCharts XAxis Class for drawing X-Axis. * * @module XAxis **/ var XAxis = /*#__PURE__*/ function () { function XAxis(ctx) { _classCallCheck(this, XAxis); this.ctx = ctx; this.w = ctx.w; var w = this.w; this.xaxisLabels = w.globals.labels.slice(); if (w.globals.timelineLabels.length > 0) { // timeline labels are there this.xaxisLabels = w.globals.timelineLabels.slice(); } this.drawnLabels = []; if (w.config.xaxis.position === 'top') { this.offY = 0; } else { this.offY = w.globals.gridHeight + 1; } this.offY = this.offY + w.config.xaxis.axisBorder.offsetY; this.xaxisFontSize = w.config.xaxis.labels.style.fontSize; this.xaxisFontFamily = w.config.xaxis.labels.style.fontFamily; this.xaxisForeColors = w.config.xaxis.labels.style.colors; this.xaxisBorderWidth = w.config.xaxis.axisBorder.width; if (this.xaxisBorderWidth.indexOf('%') > -1) { this.xaxisBorderWidth = w.globals.gridWidth * parseInt(this.xaxisBorderWidth) / 100; } else { this.xaxisBorderWidth = parseInt(this.xaxisBorderWidth); } this.xaxisBorderHeight = w.config.xaxis.axisBorder.height; // For bars, we will only consider single y xais, // as we are not providing multiple yaxis for bar charts this.yaxis = w.config.yaxis[0]; this.axesUtils = new AxesUtils(ctx); } _createClass(XAxis, [{ key: "drawXaxis", value: function drawXaxis() { var w = this.w; var graphics = new Graphics(this.ctx); var elXaxis = graphics.group({ class: 'apexcharts-xaxis', transform: "translate(".concat(w.config.xaxis.offsetX, ", ").concat(w.config.xaxis.offsetY, ")") }); var elXaxisTexts = graphics.group({ class: 'apexcharts-xaxis-texts-g', transform: "translate(".concat(w.globals.translateXAxisX, ", ").concat(w.globals.translateXAxisY, ")") }); elXaxis.add(elXaxisTexts); var colWidth; // initial x Position (keep adding column width in the loop) var xPos = w.globals.padHorizontal; var labels = []; for (var i = 0; i < this.xaxisLabels.length; i++) { labels.push(this.xaxisLabels[i]); } if (w.globals.isXNumeric) { colWidth = w.globals.gridWidth / (labels.length - 1); xPos = xPos + colWidth / 2 + w.config.xaxis.labels.offsetX; } else { colWidth = w.globals.gridWidth / labels.length; xPos = xPos + colWidth + w.config.xaxis.labels.offsetX; } var labelsLen = labels.length; if (w.config.xaxis.labels.show) { for (var _i = 0; _i <= labelsLen - 1; _i++) { var x = xPos - colWidth / 2 + w.config.xaxis.labels.offsetX; var label = this.axesUtils.getLabel(labels, w.globals.timelineLabels, x, _i, this.drawnLabels); this.drawnLabels.push(label.text); var offsetYCorrection = 28; if (w.globals.rotateXLabels) { offsetYCorrection = 22; } var elTick = graphics.drawText({ x: label.x, y: this.offY + w.config.xaxis.labels.offsetY + offsetYCorrection, text: '', textAnchor: 'middle', fontSize: this.xaxisFontSize, fontFamily: this.xaxisFontFamily, foreColor: Array.isArray(this.xaxisForeColors) ? this.xaxisForeColors[_i] : this.xaxisForeColors, cssClass: 'apexcharts-xaxis-label ' + w.config.xaxis.labels.style.cssClass }); if (_i === labelsLen - 1) { if (w.globals.skipLastTimelinelabel) { label.text = ''; } } elXaxisTexts.add(elTick); graphics.addTspan(elTick, label.text, this.xaxisFontFamily); var elTooltipTitle = document.createElementNS(w.globals.SVGNS, 'title'); elTooltipTitle.textContent = label.text; elTick.node.appendChild(elTooltipTitle); xPos = xPos + colWidth; } } if (w.config.xaxis.title.text !== undefined) { var elXaxisTitle = graphics.group({ class: 'apexcharts-xaxis-title' }); var elXAxisTitleText = graphics.drawText({ x: w.globals.gridWidth / 2 + w.config.xaxis.title.offsetX, y: this.offY - parseInt(this.xaxisFontSize) + w.globals.xAxisLabelsHeight + w.config.xaxis.title.offsetY, text: w.config.xaxis.title.text, textAnchor: 'middle', fontSize: w.config.xaxis.title.style.fontSize, fontFamily: w.config.xaxis.title.style.fontFamily, foreColor: w.config.xaxis.title.style.color, cssClass: 'apexcharts-xaxis-title-text ' + w.config.xaxis.title.style.cssClass }); elXaxisTitle.add(elXAxisTitleText); elXaxis.add(elXaxisTitle); } if (w.config.xaxis.axisBorder.show) { var lineCorrection = 0; if (w.config.chart.type === 'bar' && w.globals.isXNumeric) { lineCorrection = lineCorrection - 15; } var elHorzLine = graphics.drawLine(w.globals.padHorizontal + lineCorrection + w.config.xaxis.axisBorder.offsetX, this.offY, this.xaxisBorderWidth, this.offY, w.config.xaxis.axisBorder.color, 0, this.xaxisBorderHeight); elXaxis.add(elHorzLine); } return elXaxis; } // this actually becomes the vertical axis (for bar charts) }, { key: "drawXaxisInversed", value: function drawXaxisInversed(realIndex) { var w = this.w; var graphics = new Graphics(this.ctx); var translateYAxisX = w.config.yaxis[0].opposite ? w.globals.translateYAxisX[realIndex] : 0; var elYaxis = graphics.group({ class: 'apexcharts-yaxis apexcharts-xaxis-inversed', rel: realIndex }); var elYaxisTexts = graphics.group({ class: 'apexcharts-yaxis-texts-g apexcharts-xaxis-inversed-texts-g', transform: 'translate(' + translateYAxisX + ', 0)' }); elYaxis.add(elYaxisTexts); var colHeight; // initial x Position (keep adding column width in the loop) var yPos; var labels = []; for (var i = 0; i < this.xaxisLabels.length; i++) { labels.push(this.xaxisLabels[i]); } colHeight = w.globals.gridHeight / labels.length; yPos = -(colHeight / 2.2); var lbFormatter = w.globals.yLabelFormatters[0]; var ylabels = w.config.yaxis[0].labels; if (ylabels.show) { for (var _i2 = 0; _i2 <= labels.length - 1; _i2++) { var label = typeof labels[_i2] === 'undefined' ? '' : labels[_i2]; label = lbFormatter(label); var elLabel = graphics.drawText({ x: ylabels.offsetX - 15, y: yPos + colHeight + ylabels.offsetY, text: label, textAnchor: this.yaxis.opposite ? 'start' : 'end', foreColor: ylabels.style.color ? ylabels.style.color : ylabels.style.colors[_i2], fontSize: ylabels.style.fontSize, fontFamily: ylabels.style.fontFamily, cssClass: 'apexcharts-yaxis-label ' + ylabels.style.cssClass }); elYaxisTexts.add(elLabel); if (w.config.yaxis[realIndex].labels.rotate !== 0) { var labelRotatingCenter = graphics.rotateAroundCenter(elLabel.node); elLabel.node.setAttribute('transform', "rotate(".concat(w.config.yaxis[realIndex].labels.rotate, " ").concat(labelRotatingCenter.x, " ").concat(labelRotatingCenter.y, ")")); } yPos = yPos + colHeight; } } if (w.config.yaxis[0].title.text !== undefined) { var elXaxisTitle = graphics.group({ class: 'apexcharts-yaxis-title apexcharts-xaxis-title-inversed', transform: 'translate(' + translateYAxisX + ', 0)' }); var elXAxisTitleText = graphics.drawText({ x: 0, y: w.globals.gridHeight / 2, text: w.config.yaxis[0].title.text, textAnchor: 'middle', foreColor: w.config.yaxis[0].title.style.color, fontSize: w.config.yaxis[0].title.style.fontSize, fontFamily: w.config.yaxis[0].title.style.fontFamily, cssClass: 'apexcharts-yaxis-title-text ' + w.config.yaxis[0].title.style.cssClass }); elXaxisTitle.add(elXAxisTitleText); elYaxis.add(elXaxisTitle); } if (w.config.xaxis.axisBorder.show) { var elHorzLine = graphics.drawLine(w.globals.padHorizontal + w.config.xaxis.axisBorder.offsetX, this.offY, this.xaxisBorderWidth, this.offY, this.yaxis.axisBorder.color, 0, this.xaxisBorderHeight); elYaxis.add(elHorzLine); this.axesUtils.drawYAxisTicks(0, labels.length, w.config.yaxis[0].axisBorder, w.config.yaxis[0].axisTicks, 0, colHeight, elYaxis); } return elYaxis; } }, { key: "drawXaxisTicks", value: function drawXaxisTicks(x1, appendToElement) { var w = this.w; var x2 = x1; if (x1 < 0 || x1 > w.globals.gridWidth) return; var y1 = this.offY + w.config.xaxis.axisTicks.offsetY; var y2 = y1 + w.config.xaxis.axisTicks.height; if (w.config.xaxis.axisTicks.show) { var graphics = new Graphics(this.ctx); var line = graphics.drawLine(x1 + w.config.xaxis.axisTicks.offsetX, y1 + w.config.xaxis.offsetY, x2 + w.config.xaxis.axisTicks.offsetX, y2 + w.config.xaxis.offsetY, w.config.xaxis.axisTicks.color); // we are not returning anything, but appending directly to the element pased in param appendToElement.add(line); line.node.classList.add('apexcharts-xaxis-tick'); } } }, { key: "getXAxisTicksPositions", value: function getXAxisTicksPositions() { var w = this.w; var xAxisTicksPositions = []; var xCount = this.xaxisLabels.length; var x1 = w.globals.padHorizontal; if (w.globals.timelineLabels.length > 0) { for (var i = 0; i < xCount; i++) { x1 = this.xaxisLabels[i].position; xAxisTicksPositions.push(x1); } } else { var xCountForCategoryCharts = xCount; for (var _i3 = 0; _i3 < xCountForCategoryCharts; _i3++) { var x1Count = xCountForCategoryCharts; if (w.globals.isXNumeric && w.config.chart.type !== 'bar') { x1Count -= 1; } x1 = x1 + w.globals.gridWidth / x1Count; xAxisTicksPositions.push(x1); } } return xAxisTicksPositions; } // to rotate x-axis labels or to put ... for longer text in xaxis }, { key: "xAxisLabelCorrections", value: function xAxisLabelCorrections() { var w = this.w; var graphics = new Graphics(this.ctx); var xAxis = w.globals.dom.baseEl.querySelector('.apexcharts-xaxis-texts-g'); var xAxisTexts = w.globals.dom.baseEl.querySelectorAll('.apexcharts-xaxis-texts-g text'); var yAxisTextsInversed = w.globals.dom.baseEl.querySelectorAll('.apexcharts-yaxis-inversed text'); var xAxisTextsInversed = w.globals.dom.baseEl.querySelectorAll('.apexcharts-xaxis-inversed-texts-g text'); if (w.globals.rotateXLabels || w.config.xaxis.labels.rotateAlways) { for (var xat = 0; xat < xAxisTexts.length; xat++) { var textRotatingCenter = graphics.rotateAroundCenter(xAxisTexts[xat]); textRotatingCenter.y = textRotatingCenter.y - 1; // + tickWidth/4; textRotatingCenter.x = textRotatingCenter.x + 1; xAxisTexts[xat].setAttribute('transform', "rotate(".concat(w.config.xaxis.labels.rotate, " ").concat(textRotatingCenter.x, " ").concat(textRotatingCenter.y, ")")); xAxisTexts[xat].setAttribute('text-anchor', "end"); var offsetHeight = 10; xAxis.setAttribute('transform', "translate(0, ".concat(-offsetHeight, ")")); var tSpan = xAxisTexts[xat].childNodes; if (w.config.xaxis.labels.trim) { graphics.placeTextWithEllipsis(tSpan[0], tSpan[0].textContent, w.config.xaxis.labels.maxHeight - 40); } } } else { var width = w.globals.gridWidth / w.globals.labels.length; for (var _xat = 0; _xat < xAxisTexts.length; _xat++) { var _tSpan = xAxisTexts[_xat].childNodes; if (w.config.xaxis.labels.trim && w.config.xaxis.type !== 'datetime') { graphics.placeTextWithEllipsis(_tSpan[0], _tSpan[0].textContent, width); } } } if (yAxisTextsInversed.length > 0) { // truncate rotated y axis in bar chart (x axis) var firstLabelPosX = yAxisTextsInversed[yAxisTextsInversed.length - 1].getBBox(); var lastLabelPosX = yAxisTextsInversed[0].getBBox(); if (firstLabelPosX.x < -20) { yAxisTextsInversed[yAxisTextsInversed.length - 1].parentNode.removeChild(yAxisTextsInversed[yAxisTextsInversed.length - 1]); } if (lastLabelPosX.x + lastLabelPosX.width > w.globals.gridWidth) { yAxisTextsInversed[0].parentNode.removeChild(yAxisTextsInversed[0]); } // truncate rotated x axis in bar chart (y axis) for (var _xat2 = 0; _xat2 < xAxisTextsInversed.length; _xat2++) { graphics.placeTextWithEllipsis(xAxisTextsInversed[_xat2], xAxisTextsInversed[_xat2].textContent, w.config.yaxis[0].labels.maxWidth - parseInt(w.config.yaxis[0].title.style.fontSize) * 2 - 20); } } } // renderXAxisBands() { // let w = this.w; // let plotBand = document.createElementNS(w.globals.SVGNS, 'rect') // w.globals.dom.elGraphical.add(plotBand) // } }]); return XAxis; }(); /** * ApexCharts YAxis Class for drawing Y-Axis. * * @module YAxis **/ var YAxis = /*#__PURE__*/ function () { function YAxis(ctx) { _classCallCheck(this, YAxis); this.ctx = ctx; this.w = ctx.w; var w = this.w; this.xaxisFontSize = w.config.xaxis.labels.style.fontSize; this.axisFontFamily = w.config.xaxis.labels.style.fontFamily; this.xaxisForeColors = w.config.xaxis.labels.style.colors; this.xAxisoffX = 0; if (w.config.xaxis.position === 'bottom') { this.xAxisoffX = w.globals.gridHeight; } this.drawnLabels = []; this.axesUtils = new AxesUtils(ctx); } _createClass(YAxis, [{ key: "drawYaxis", value: function drawYaxis(realIndex) { var w = this.w; var graphics = new Graphics(this.ctx); var yaxisFontSize = w.config.yaxis[realIndex].labels.style.fontSize; var yaxisFontFamily = w.config.yaxis[realIndex].labels.style.fontFamily; var elYaxis = graphics.group({ class: 'apexcharts-yaxis', rel: realIndex, transform: 'translate(' + w.globals.translateYAxisX[realIndex] + ', 0)' }); if (!w.config.yaxis[realIndex].show) { return elYaxis; } var elYaxisTexts = graphics.group({ class: 'apexcharts-yaxis-texts-g' }); elYaxis.add(elYaxisTexts); var tickAmount = w.globals.yAxisScale[realIndex].result.length - 1; // labelsDivider is simply svg height/number of ticks var labelsDivider = w.globals.gridHeight / tickAmount + 0.1; // initial label position = 0; var l = w.globals.translateY; var lbFormatter = w.globals.yLabelFormatters[realIndex]; var labels = w.globals.yAxisScale[realIndex].result.slice(); if (w.config.yaxis[realIndex] && w.config.yaxis[realIndex].reversed) { labels.reverse(); } if (w.config.yaxis[realIndex].labels.show) { for (var i = tickAmount; i >= 0; i--) { var val = labels[i]; val = lbFormatter(val, i); var xPad = w.config.yaxis[realIndex].labels.padding; if (w.config.yaxis[realIndex].opposite && w.config.yaxis.length !== 0) { xPad = xPad * -1; } var label = graphics.drawText({ x: xPad, y: l + tickAmount / 10 + w.config.yaxis[realIndex].labels.offsetY + 1, text: val, textAnchor: w.config.yaxis[realIndex].opposite ? 'start' : 'end', fontSize: yaxisFontSize, fontFamily: yaxisFontFamily, foreColor: w.config.yaxis[realIndex].labels.style.color, cssClass: 'apexcharts-yaxis-label ' + w.config.yaxis[realIndex].labels.style.cssClass }); elYaxisTexts.add(label); var labelRotatingCenter = graphics.rotateAroundCenter(label.node); if (w.config.yaxis[realIndex].labels.rotate !== 0) { label.node.setAttribute('transform', "rotate(".concat(w.config.yaxis[realIndex].labels.rotate, " ").concat(labelRotatingCenter.x, " ").concat(labelRotatingCenter.y, ")")); } l = l + labelsDivider; } } if (w.config.yaxis[realIndex].title.text !== undefined) { var elYaxisTitle = graphics.group({ class: 'apexcharts-yaxis-title' }); var x = 0; if (w.config.yaxis[realIndex].opposite) { x = w.globals.translateYAxisX[realIndex]; } var elYAxisTitleText = graphics.drawText({ x: x, y: w.globals.gridHeight / 2 + w.globals.translateY, text: w.config.yaxis[realIndex].title.text, textAnchor: 'end', foreColor: w.config.yaxis[realIndex].title.style.color, fontSize: w.config.yaxis[realIndex].title.style.fontSize, fontFamily: w.config.yaxis[realIndex].title.style.fontFamily, cssClass: 'apexcharts-yaxis-title-text ' + w.config.yaxis[realIndex].title.style.cssClass }); elYaxisTitle.add(elYAxisTitleText); elYaxis.add(elYaxisTitle); } var axisBorder = w.config.yaxis[realIndex].axisBorder; if (axisBorder.show) { var _x = 31 + axisBorder.offsetX; if (w.config.yaxis[realIndex].opposite) { _x = -31 - axisBorder.offsetX; } var elVerticalLine = graphics.drawLine(_x, w.globals.translateY + axisBorder.offsetY - 2, _x, w.globals.gridHeight + w.globals.translateY + axisBorder.offsetY + 2, axisBorder.color); elYaxis.add(elVerticalLine); this.axesUtils.drawYAxisTicks(_x, tickAmount, axisBorder, w.config.yaxis[realIndex].axisTicks, realIndex, labelsDivider, elYaxis); } return elYaxis; } // This actually becomes horizonal axis (for bar charts) }, { key: "drawYaxisInversed", value: function drawYaxisInversed(realIndex) { var w = this.w; var graphics = new Graphics(this.ctx); var elXaxis = graphics.group({ class: 'apexcharts-xaxis apexcharts-yaxis-inversed' }); var elXaxisTexts = graphics.group({ class: 'apexcharts-xaxis-texts-g', transform: "translate(".concat(w.globals.translateXAxisX, ", ").concat(w.globals.translateXAxisY, ")") }); elXaxis.add(elXaxisTexts); var tickAmount = w.globals.yAxisScale[realIndex].result.length - 1; // labelsDivider is simply svg width/number of ticks var labelsDivider = w.globals.gridWidth / tickAmount + 0.1; // initial label position; var l = labelsDivider + w.config.xaxis.labels.offsetX; var lbFormatter = w.globals.xLabelFormatter; var labels = w.globals.yAxisScale[realIndex].result.slice(); var timelineLabels = w.globals.invertedTimelineLabels; if (timelineLabels.length > 0) { this.xaxisLabels = timelineLabels.slice(); labels = timelineLabels.slice(); tickAmount = labels.length; } if (w.config.yaxis[realIndex] && w.config.yaxis[realIndex].reversed) { labels.reverse(); } var tl = timelineLabels.length; if (w.config.xaxis.labels.show) { for (var i = tl ? 0 : tickAmount; tl ? i < tl - 1 : i >= 0; tl ? i++ : i--) { var val = labels[i]; val = lbFormatter(val, i); var x = w.globals.gridWidth + w.globals.padHorizontal - (l - labelsDivider + w.config.xaxis.labels.offsetX); if (timelineLabels.length) { var label = this.axesUtils.getLabel(labels, timelineLabels, x, i, this.drawnLabels); x = label.x; val = label.text; this.drawnLabels.push(label.text); } var elTick = graphics.drawText({ x: x, y: this.xAxisoffX + w.config.xaxis.labels.offsetY + 30, text: '', textAnchor: 'middle', foreColor: Array.isArray(this.xaxisForeColors) ? this.xaxisForeColors[realIndex] : this.xaxisForeColors, fontSize: this.xaxisFontSize, fontFamily: this.xaxisFontFamily, cssClass: 'apexcharts-xaxis-label ' + w.config.xaxis.labels.style.cssClass }); elXaxisTexts.add(elTick); elTick.tspan(val); var elTooltipTitle = document.createElementNS(w.globals.SVGNS, 'title'); elTooltipTitle.textContent = val; elTick.node.appendChild(elTooltipTitle); l = l + labelsDivider; } } if (w.config.xaxis.title.text !== undefined) { var elYaxisTitle = graphics.group({ class: 'apexcharts-xaxis-title apexcharts-yaxis-title-inversed' }); var elYAxisTitleText = graphics.drawText({ x: w.globals.gridWidth / 2, y: this.xAxisoffX + parseInt(this.xaxisFontSize) + parseInt(w.config.xaxis.title.style.fontSize) + 20, text: w.config.xaxis.title.text, textAnchor: 'middle', fontSize: w.config.xaxis.title.style.fontSize, fontFamily: w.config.xaxis.title.style.fontFamily, cssClass: 'apexcharts-xaxis-title-text ' + w.config.xaxis.title.style.cssClass }); elYaxisTitle.add(elYAxisTitleText); elXaxis.add(elYaxisTitle); } var axisBorder = w.config.yaxis[realIndex].axisBorder; if (axisBorder.show) { var elVerticalLine = graphics.drawLine(w.globals.padHorizontal + axisBorder.offsetX, 1 + axisBorder.offsetY, w.globals.padHorizontal + axisBorder.offsetX, w.globals.gridHeight + axisBorder.offsetY, axisBorder.color); elXaxis.add(elVerticalLine); } return elXaxis; } }, { key: "yAxisTitleRotate", value: function yAxisTitleRotate(realIndex, yAxisOpposite) { var w = this.w; var graphics = new Graphics(this.ctx); var yAxisLabelsCoord = { width: 0, height: 0 }; var yAxisTitleCoord = { width: 0, height: 0 }; var elYAxisLabelsWrap = w.globals.dom.baseEl.querySelector(" .apexcharts-yaxis[rel='".concat(realIndex, "'] .apexcharts-yaxis-texts-g")); if (elYAxisLabelsWrap !== null) { yAxisLabelsCoord = elYAxisLabelsWrap.getBoundingClientRect(); } var yAxisTitle = w.globals.dom.baseEl.querySelector(".apexcharts-yaxis[rel='".concat(realIndex, "'] .apexcharts-yaxis-title text")); if (yAxisTitle !== null) { yAxisTitleCoord = yAxisTitle.getBoundingClientRect(); } if (yAxisTitle !== null) { var x = this.xPaddingForYAxisTitle(realIndex, yAxisLabelsCoord, yAxisTitleCoord, yAxisOpposite); yAxisTitle.setAttribute('x', x.xPos - (yAxisOpposite ? 10 : 0)); } if (yAxisTitle !== null) { var titleRotatingCenter = graphics.rotateAroundCenter(yAxisTitle); if (!yAxisOpposite) { yAxisTitle.setAttribute('transform', "rotate(-".concat(w.config.yaxis[realIndex].title.rotate, " ").concat(titleRotatingCenter.x, " ").concat(titleRotatingCenter.y, ")")); } else { yAxisTitle.setAttribute('transform', "rotate(".concat(w.config.yaxis[realIndex].title.rotate, " ").concat(titleRotatingCenter.x, " ").concat(titleRotatingCenter.y, ")")); } } } }, { key: "xPaddingForYAxisTitle", value: function xPaddingForYAxisTitle(realIndex, yAxisLabelsCoord, yAxisTitleCoord, yAxisOpposite) { var w = this.w; var oppositeAxisCount = 0; var x = 0; var padd = 10; if (w.config.yaxis[realIndex].title.text === undefined || realIndex < 0) { return { xPos: x, padd: 0 }; } if (yAxisOpposite) { x = yAxisLabelsCoord.width + w.config.yaxis[realIndex].title.offsetX + yAxisTitleCoord.width / 2 + padd / 2; oppositeAxisCount += 1; if (oppositeAxisCount === 0) { x = x - padd / 2; } } else { x = yAxisLabelsCoord.width * -1 + w.config.yaxis[realIndex].title.offsetX + padd / 2 + yAxisTitleCoord.width / 2; if (w.globals.isBarHorizontal) { padd = 25; x = yAxisLabelsCoord.width * -1 - w.config.yaxis[realIndex].title.offsetX - padd; } } return { xPos: x, padd: padd }; } // sets the x position of the y-axis by counting the labels width, title width and any offset }, { key: "setYAxisXPosition", value: function setYAxisXPosition(yaxisLabelCoords, yTitleCoords) { var w = this.w; var xLeft = 0; var xRight = 0; var leftOffsetX = 21; var rightOffsetX = 1; if (w.config.yaxis.length > 1) { this.multipleYs = true; } w.config.yaxis.map(function (yaxe, index) { var shouldNotDrawAxis = w.globals.ignoreYAxisIndexes.indexOf(index) > -1 || !yaxe.show || yaxe.floating || yaxisLabelCoords[index].width === 0; var axisWidth = yaxisLabelCoords[index].width + yTitleCoords[index].width; if (!yaxe.opposite) { xLeft = w.globals.translateX - leftOffsetX; if (!shouldNotDrawAxis) { leftOffsetX = leftOffsetX + axisWidth + 20; } w.globals.translateYAxisX[index] = xLeft + yaxe.labels.offsetX; } else { if (w.globals.isBarHorizontal) { xRight = w.globals.gridWidth + w.globals.translateX - 1; w.globals.translateYAxisX[index] = xRight - yaxe.labels.offsetX; } else { xRight = w.globals.gridWidth + w.globals.translateX + rightOffsetX; if (!shouldNotDrawAxis) { rightOffsetX = rightOffsetX + axisWidth + 20; } w.globals.translateYAxisX[index] = xRight - yaxe.labels.offsetX + 20; } } }); } }, { key: "setYAxisTextAlignments", value: function setYAxisTextAlignments() { var w = this.w; var yaxis = w.globals.dom.baseEl.querySelectorAll(".apexcharts-yaxis"); yaxis = Utils.listToArray(yaxis); yaxis.forEach(function (y, index) { var yaxe = w.config.yaxis[index]; // proceed only if user has specified alignment if (yaxe.labels.align !== undefined) { var yAxisInner = w.globals.dom.baseEl.querySelector(".apexcharts-yaxis[rel='".concat(index, "'] .apexcharts-yaxis-texts-g")); var yAxisTexts = w.globals.dom.baseEl.querySelectorAll(".apexcharts-yaxis[rel='".concat(index, "'] .apexcharts-yaxis-label")); yAxisTexts = Utils.listToArray(yAxisTexts); var rect = yAxisInner.getBoundingClientRect(); if (yaxe.labels.align === 'left') { yAxisTexts.forEach(function (label, lI) { label.setAttribute('text-anchor', 'start'); }); if (!yaxe.opposite) { yAxisInner.setAttribute('transform', "translate(-".concat(rect.width, ", 0)")); } } else if (yaxe.labels.align === 'center') { yAxisTexts.forEach(function (label, lI) { label.setAttribute('text-anchor', 'middle'); }); yAxisInner.setAttribute('transform', "translate(".concat(rect.width / 2 * (!yaxe.opposite ? -1 : 1), ", 0)")); } else if (yaxe.labels.align === 'right') { yAxisTexts.forEach(function (label, lI) { label.setAttribute('text-anchor', 'end'); }); if (yaxe.opposite) { yAxisInner.setAttribute('transform', "translate(".concat(rect.width, ", 0)")); } } } }); } }]); return YAxis; }(); var Range = /*#__PURE__*/ function () { function Range(ctx) { _classCallCheck(this, Range); this.ctx = ctx; this.w = ctx.w; } // http://stackoverflow.com/questions/326679/choosing-an-attractive-linear-scale-for-a-graphs-y-axiss // This routine creates the Y axis values for a graph. _createClass(Range, [{ key: "niceScale", value: function niceScale(yMin, yMax) { var index = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var ticks = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 10; var w = this.w; var NO_MIN_MAX_PROVIDED = this.w.config.yaxis[index].max === undefined && this.w.config.yaxis[index].min === undefined || this.w.config.yaxis[index].forceNiceScale; if (yMin === Number.MIN_VALUE && yMax === 0 || !Utils.isNumber(yMin) && !Utils.isNumber(yMax) || yMin === Number.MIN_VALUE && yMax === -Number.MAX_VALUE) { // when all values are 0 yMin = 0; yMax = ticks; var linearScale = this.linearScale(yMin, yMax, ticks); return linearScale; } if (yMin > yMax) { // if somehow due to some wrong config, user sent max less than min, // adjust the min/max again console.warn('yaxis.min cannot be greater than yaxis.max'); yMax = yMin + 0.1; } else if (yMin === yMax) { // If yMin and yMax are identical, then // adjust the yMin and yMax values to actually // make a graph. Also avoids division by zero errors. yMin = yMin === 0 ? 0 : yMin - 0.5; // some small value yMax = yMax === 0 ? 2 : yMax + 0.5; // some small value } // Calculate Min amd Max graphical labels and graph // increments. The number of ticks defaults to // 10 which is the SUGGESTED value. Any tick value // entered is used as a suggested value which is // adjusted to be a 'pretty' value. // // Output will be an array of the Y axis values that // encompass the Y values. var result = []; // Determine Range var range = yMax - yMin; if (range < 1 && NO_MIN_MAX_PROVIDED && (w.config.chart.type === 'candlestick' || w.config.series[index].type === 'candlestick' || w.globals.isRangeData)) { /* fix https://github.com/apexcharts/apexcharts.js/issues/430 */ yMax = yMax * 1.01; } // for extremely small values - #fix #553 if (range < 0.00001 && NO_MIN_MAX_PROVIDED) { yMax = yMax * 1.05; } var tiks = ticks + 1; // Adjust ticks if needed if (tiks < 2) { tiks = 2; } else if (tiks > 2) { tiks -= 2; } // Get raw step value var tempStep = range / tiks; // Calculate pretty step value var mag = Math.floor(Utils.log10(tempStep)); var magPow = Math.pow(10, mag); var magMsd = parseInt(tempStep / magPow); var stepSize = magMsd * magPow; // build Y label array. // Lower and upper bounds calculations var lb = stepSize * Math.floor(yMin / stepSize); var ub = stepSize * Math.ceil(yMax / stepSize); // Build array var val = lb; while (1) { result.push(val); val += stepSize; if (val > ub) { break; } } if (NO_MIN_MAX_PROVIDED) { return { result: result, niceMin: result[0], niceMax: result[result.length - 1] }; } else { result = []; var v = yMin; result.push(v); var valuesDivider = Math.abs(yMax - yMin) / ticks; for (var i = 0; i <= ticks - 1; i++) { v = v + valuesDivider; result.push(v); } return { result: result, niceMin: result[0], niceMax: result[result.length - 1] }; } } }, { key: "linearScale", value: function linearScale(yMin, yMax) { var ticks = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 10; var range = Math.abs(yMax - yMin); var step = range / ticks; if (ticks === Number.MAX_VALUE) { ticks = 10; step = 1; } var result = []; var v = yMin; while (ticks >= 0) { result.push(v); v = v + step; ticks -= 1; } return { result: result, niceMin: result[0], niceMax: result[result.length - 1] }; } }, { key: "logarithmicScale", value: function logarithmicScale(index, yMin, yMax, ticks) { if (yMin < 0 || yMin === Number.MIN_VALUE) yMin = 0.01; var base = 10; var min = Math.log(yMin) / Math.log(base); var max = Math.log(yMax) / Math.log(base); var range = Math.abs(yMax - yMin); var step = range / ticks; var result = []; var v = yMin; while (ticks >= 0) { result.push(v); v = v + step; ticks -= 1; } var logs = result.map(function (niceNumber, i) { if (niceNumber <= 0) { niceNumber = 0.01; } // calculate adjustment factor var scale = (max - min) / (yMax - yMin); var logVal = Math.pow(base, min + scale * (niceNumber - min)); return Math.round(logVal / Utils.roundToBase(logVal, base)) * Utils.roundToBase(logVal, base); }); // Math.floor may have rounded the value to 0, revert back to 1 if (logs[0] === 0) logs[0] = 1; return { result: logs, niceMin: logs[0], niceMax: logs[logs.length - 1] }; } }, { key: "setYScaleForIndex", value: function setYScaleForIndex(index, minY, maxY) { var gl = this.w.globals; var cnf = this.w.config; var y = gl.isBarHorizontal ? cnf.xaxis : cnf.yaxis[index]; if (typeof gl.yAxisScale[index] === 'undefined') { gl.yAxisScale[index] = []; } if (y.logarithmic) { gl.allSeriesCollapsed = false; gl.yAxisScale[index] = this.logarithmicScale(index, minY, maxY, y.tickAmount ? y.tickAmount : Math.floor(Math.log10(maxY))); } else { if (maxY === -Number.MAX_VALUE || !Utils.isNumber(maxY)) { // no data in the chart. Either all series collapsed or user passed a blank array gl.yAxisScale[index] = this.linearScale(0, 5, 5); } else { // there is some data. Turn off the allSeriesCollapsed flag gl.allSeriesCollapsed = false; if ((y.min !== undefined || y.max !== undefined) && !y.forceNiceScale) { // fix https://github.com/apexcharts/apexcharts.js/issues/492 gl.yAxisScale[index] = this.linearScale(minY, maxY, y.tickAmount); } else { gl.yAxisScale[index] = this.niceScale(minY, maxY, index, // fix https://github.com/apexcharts/apexcharts.js/issues/397 y.tickAmount ? y.tickAmount : maxY < 5 && maxY > 1 ? maxY + 1 : 5); } } } } }, { key: "setMultipleYScales", value: function setMultipleYScales() { var _this = this; var gl = this.w.globals; var cnf = this.w.config; var minYArr = gl.minYArr.concat([]); var maxYArr = gl.maxYArr.concat([]); var scalesIndices = []; // here, we loop through the yaxis array and find the item which has "seriesName" property cnf.yaxis.forEach(function (yaxe, i) { var index = i; cnf.series.forEach(function (s, si) { // if seriesName matches and that series is not collapsed, we use that scale if (s.name === yaxe.seriesName && gl.collapsedSeriesIndices.indexOf(si) === -1) { index = si; if (i !== si) { scalesIndices.push({ index: si, similarIndex: i, alreadyExists: true }); } else { scalesIndices.push({ index: si }); } } }); var minY = minYArr[index]; var maxY = maxYArr[index]; _this.setYScaleForIndex(i, minY, maxY); }); this.sameScaleInMultipleAxes(minYArr, maxYArr, scalesIndices); } }, { key: "sameScaleInMultipleAxes", value: function sameScaleInMultipleAxes(minYArr, maxYArr, scalesIndices) { var _this2 = this; var cnf = this.w.config; var gl = this.w.globals; // we got the scalesIndices array in the above code, but we need to filter out the items which doesn't have same scales var similarIndices = []; scalesIndices.forEach(function (scale) { if (scale.alreadyExists) { if (typeof similarIndices[scale.index] === 'undefined') { similarIndices[scale.index] = []; } similarIndices[scale.index].push(scale.index); similarIndices[scale.index].push(scale.similarIndex); } }); function intersect(a, b) { return a.filter(function (value) { return b.indexOf(value) !== -1; }); } similarIndices.forEach(function (si, i) { similarIndices.forEach(function (sj, j) { if (i !== j) { if (intersect(si, sj).length > 0) { similarIndices[i] = similarIndices[i].concat(similarIndices[j]); } } }); }); // then, we remove duplicates from the similarScale array var uniqueSimilarIndices = similarIndices.map(function (item) { return item.filter(function (i, pos) { return item.indexOf(i) === pos; }); }); // sort further to remove whole duplicate arrays later var sortedIndices = uniqueSimilarIndices.map(function (s) { return s.sort(); }); // remove undefined items similarIndices = similarIndices.filter(function (s) { return !!s; }); var indices = sortedIndices.slice(); var stringIndices = indices.map(function (ind) { return JSON.stringify(ind); }); indices = indices.filter(function (ind, p) { return stringIndices.indexOf(JSON.stringify(ind)) === p; }); var sameScaleMinYArr = []; var sameScaleMaxYArr = []; minYArr.forEach(function (minYValue, yi) { indices.forEach(function (scale, i) { // we compare only the yIndex which exists in the indices array if (scale.indexOf(yi) > -1) { if (typeof sameScaleMinYArr[i] === 'undefined') { sameScaleMinYArr[i] = []; sameScaleMaxYArr[i] = []; } sameScaleMinYArr[i].push({ key: yi, value: minYValue }); sameScaleMaxYArr[i].push({ key: yi, value: maxYArr[yi] }); } }); }); var sameScaleMin = Array.apply(null, Array(indices.length)).map(Number.prototype.valueOf, Number.MIN_VALUE); var sameScaleMax = Array.apply(null, Array(indices.length)).map(Number.prototype.valueOf, -Number.MAX_VALUE); sameScaleMinYArr.forEach(function (s, i) { s.forEach(function (sc, j) { sameScaleMin[i] = Math.min(sc.value, sameScaleMin[i]); }); }); sameScaleMaxYArr.forEach(function (s, i) { s.forEach(function (sc, j) { sameScaleMax[i] = Math.max(sc.value, sameScaleMax[i]); }); }); minYArr.forEach(function (min, i) { sameScaleMaxYArr.forEach(function (s, si) { var minY = sameScaleMin[si]; var maxY = sameScaleMax[si]; s.forEach(function (ind, k) { if (s[k].key === i) { if (cnf.yaxis[i].min !== undefined) { if (typeof cnf.yaxis[i].min === 'function') { minY = cnf.yaxis[i].min(gl.minY); } else { minY = cnf.yaxis[i].min; } } if (cnf.yaxis[i].max !== undefined) { if (typeof cnf.yaxis[i].max === 'function') { maxY = cnf.yaxis[i].max(gl.maxY); } else { maxY = cnf.yaxis[i].max; } } _this2.setYScaleForIndex(i, minY, maxY); } }); }); }); } }, { key: "autoScaleY", value: function autoScaleY(ctx, e) { if (!ctx) { ctx = this; } var ret = []; ctx.w.config.series.forEach(function (serie) { var min, max; var first = serie.data.find(function (x) { return x[0] >= e.xaxis.min; }); var firstValue = first[1]; max = min = firstValue; serie.data.forEach(function (data) { if (data[0] <= e.xaxis.max && data[0] >= e.xaxis.min) { if (data[1] > max && data[1] !== null) max = data[1]; if (data[1] < min && data[1] !== null) min = data[1]; } }); min *= 0.95; max *= 1.05; ret.push({ min: min, max: max }); }); return ret; } }]); return Range; }(); /** * Range is used to generates values between min and max. * * @module Range **/ var Range$1 = /*#__PURE__*/ function () { function Range$$1(ctx) { _classCallCheck(this, Range$$1); this.ctx = ctx; this.w = ctx.w; this.scales = new Range(ctx); } _createClass(Range$$1, [{ key: "init", value: function init() { this.setYRange(); this.setXRange(); this.setZRange(); } }, { key: "getMinYMaxY", value: function getMinYMaxY(startingIndex) { var lowestY = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : Number.MAX_VALUE; var highestY = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : -Number.MAX_VALUE; var len = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var gl = this.w.globals; var maxY = -Number.MAX_VALUE; var minY = Number.MIN_VALUE; if (len === null) { len = startingIndex + 1; } var series = gl.series; var seriesMin = series; var seriesMax = series; if (this.w.config.chart.type === 'candlestick') { seriesMin = gl.seriesCandleL; seriesMax = gl.seriesCandleH; } else if (gl.isRangeData) { seriesMin = gl.seriesRangeStart; seriesMax = gl.seriesRangeEnd; } for (var i = startingIndex; i < len; i++) { gl.dataPoints = Math.max(gl.dataPoints, series[i].length); for (var j = 0; j < gl.series[i].length; j++) { var val = series[i][j]; if (val !== null && Utils.isNumber(val)) { maxY = Math.max(maxY, seriesMax[i][j]); lowestY = Math.min(lowestY, seriesMin[i][j]); highestY = Math.max(highestY, seriesMin[i][j]); if (this.w.config.chart.type === 'candlestick') { maxY = Math.max(maxY, gl.seriesCandleO[i][j]); maxY = Math.max(maxY, gl.seriesCandleH[i][j]); maxY = Math.max(maxY, gl.seriesCandleL[i][j]); maxY = Math.max(maxY, gl.seriesCandleC[i][j]); highestY = maxY; } if (Utils.isFloat(val)) { val = Utils.noExponents(val); gl.yValueDecimal = Math.max(gl.yValueDecimal, val.toString().split('.')[1].length); } if (minY > seriesMin[i][j] && seriesMin[i][j] < 0) { minY = seriesMin[i][j]; } } else { gl.hasNullValues = true; } } } return { minY: minY, maxY: maxY, lowestY: lowestY, highestY: highestY }; } }, { key: "setYRange", value: function setYRange() { var gl = this.w.globals; var cnf = this.w.config; gl.maxY = -Number.MAX_VALUE; gl.minY = Number.MIN_VALUE; var lowestYInAllSeries = Number.MAX_VALUE; if (gl.isMultipleYAxis) { // we need to get minY and maxY for multiple y axis for (var i = 0; i < gl.series.length; i++) { var minYMaxYArr = this.getMinYMaxY(i, lowestYInAllSeries, null, i + 1); gl.minYArr.push(minYMaxYArr.minY); gl.maxYArr.push(minYMaxYArr.maxY); lowestYInAllSeries = minYMaxYArr.lowestY; } } // and then, get the minY and maxY from all series var minYMaxY = this.getMinYMaxY(0, lowestYInAllSeries, null, gl.series.length); gl.minY = minYMaxY.minY; gl.maxY = minYMaxY.maxY; lowestYInAllSeries = minYMaxY.lowestY; if (cnf.chart.stacked) { // for stacked charts, we calculate each series's parallel values. i.e, series[0][j] + series[1][j] .... [series[i.length][j]] and get the max out of it var stackedPoss = []; var stackedNegs = []; for (var j = 0; j < gl.series[gl.maxValsInArrayIndex].length; j++) { var poss = 0; var negs = 0; for (var _i = 0; _i < gl.series.length; _i++) { if (gl.series[_i][j] !== null && Utils.isNumber(gl.series[_i][j])) { if (gl.series[_i][j] > 0) { // 0.0001 fixes #185 when values are very small poss = poss + parseFloat(gl.series[_i][j]) + 0.0001; } else { negs = negs + parseFloat(gl.series[_i][j]); } } if (_i === gl.series.length - 1) { // push all the totals to the array for future use stackedPoss.push(poss); stackedNegs.push(negs); } } } // get the max/min out of the added parallel values for (var z = 0; z < stackedPoss.length; z++) { gl.maxY = Math.max(gl.maxY, stackedPoss[z]); gl.minY = Math.min(gl.minY, stackedNegs[z]); } } // if the numbers are too big, reduce the range // for eg, if number is between 100000-110000, putting 0 as the lowest value is not so good idea. So change the gl.minY for line/area/candlesticks if (cnf.chart.type === 'line' || cnf.chart.type === 'area' || cnf.chart.type === 'candlestick') { if (gl.minY === Number.MIN_VALUE && lowestYInAllSeries !== -Number.MAX_VALUE && lowestYInAllSeries !== gl.maxY // single value possibility ) { var diff = gl.maxY - lowestYInAllSeries; if (lowestYInAllSeries >= 0 && lowestYInAllSeries <= 10) { // if minY is already 0/low value, we don't want to go negatives here - so this check is essential. diff = 0; } gl.minY = lowestYInAllSeries - diff * 5 / 100; /* fix https://github.com/apexcharts/apexcharts.js/issues/426 */ gl.maxY = gl.maxY + diff * 5 / 100; } } cnf.yaxis.map(function (yaxe, index) { // override all min/max values by user defined values (y axis) if (yaxe.max !== undefined) { if (typeof yaxe.max === 'number') { gl.maxYArr[index] = yaxe.max; } else if (typeof yaxe.max === 'function') { gl.maxYArr[index] = yaxe.max(gl.maxY); } // gl.maxY is for single y-axis chart, it will be ignored in multi-yaxis gl.maxY = gl.maxYArr[index]; } if (yaxe.min !== undefined) { if (typeof yaxe.min === 'number') { gl.minYArr[index] = yaxe.min; } else if (typeof yaxe.min === 'function') { gl.minYArr[index] = yaxe.min(gl.minY); } // gl.minY is for single y-axis chart, it will be ignored in multi-yaxis gl.minY = gl.minYArr[index]; } }); // for horizontal bar charts, we need to check xaxis min/max as user may have specified there if (gl.isBarHorizontal) { if (cnf.xaxis.min !== undefined && typeof cnf.xaxis.min === 'number') { gl.minY = cnf.xaxis.min; } if (cnf.xaxis.max !== undefined && typeof cnf.xaxis.max === 'number') { gl.maxY = cnf.xaxis.max; } } // for multi y-axis we need different scales for each if (gl.isMultipleYAxis) { this.scales.setMultipleYScales(); gl.minY = lowestYInAllSeries; gl.yAxisScale.forEach(function (scale, i) { gl.minYArr[i] = scale.niceMin; gl.maxYArr[i] = scale.niceMax; }); } else { this.scales.setYScaleForIndex(0, gl.minY, gl.maxY); gl.minY = gl.yAxisScale[0].niceMin; gl.maxY = gl.yAxisScale[0].niceMax; gl.minYArr[0] = gl.yAxisScale[0].niceMin; gl.maxYArr[0] = gl.yAxisScale[0].niceMax; } return { minY: gl.minY, maxY: gl.maxY, minYArr: gl.minYArr, maxYArr: gl.maxYArr }; } }, { key: "setXRange", value: function setXRange() { var gl = this.w.globals; var cnf = this.w.config; var isXNumeric = cnf.xaxis.type === 'numeric' || cnf.xaxis.type === 'datetime' || cnf.xaxis.type === 'category' && !gl.noLabelsProvided || gl.noLabelsProvided || gl.isXNumeric; // minX maxX starts here if (gl.isXNumeric) { for (var i = 0; i < gl.series.length; i++) { if (gl.labels[i]) { for (var j = 0; j < gl.labels[i].length; j++) { if (gl.labels[i][j] !== null && Utils.isNumber(gl.labels[i][j])) { gl.maxX = Math.max(gl.maxX, gl.labels[i][j]); gl.initialmaxX = Math.max(gl.maxX, gl.labels[i][j]); gl.minX = Math.min(gl.minX, gl.labels[i][j]); gl.initialminX = Math.min(gl.minX, gl.labels[i][j]); } } } } } if (gl.noLabelsProvided) { if (cnf.xaxis.categories.length === 0) { gl.maxX = gl.labels[gl.labels.length - 1]; gl.initialmaxX = gl.labels[gl.labels.length - 1]; gl.minX = 1; gl.initialminX = 1; } } // for numeric xaxis, we need to adjust some padding left and right for bar charts if (gl.comboChartsHasBars || cnf.chart.type === 'candlestick' || cnf.chart.type === 'bar' && cnf.xaxis.type !== 'category') { if (cnf.xaxis.type !== 'category') { var minX = gl.minX - gl.svgWidth / gl.dataPoints * (Math.abs(gl.maxX - gl.minX) / gl.svgWidth) / 2; gl.minX = minX; gl.initialminX = minX; var maxX = gl.maxX + gl.svgWidth / gl.dataPoints * (Math.abs(gl.maxX - gl.minX) / gl.svgWidth) / 2; gl.maxX = maxX; gl.initialmaxX = maxX; } } if ((gl.isXNumeric || gl.noLabelsProvided) && (!cnf.xaxis.convertedCatToNumeric || gl.dataFormatXNumeric)) { var ticks; if (cnf.xaxis.tickAmount === undefined) { ticks = Math.round(gl.svgWidth / 150); // no labels provided and total number of dataPoints is less than 20 if (cnf.xaxis.type === 'numeric' && gl.dataPoints < 20) { ticks = gl.dataPoints - 1; } // this check is for when ticks exceeds total datapoints and that would result in duplicate labels if (ticks > gl.dataPoints && gl.dataPoints !== 0) { ticks = gl.dataPoints - 1; } } else if (cnf.xaxis.tickAmount === 'dataPoints') { ticks = gl.series[gl.maxValsInArrayIndex].length - 1; } else { ticks = cnf.xaxis.tickAmount; } // override all min/max values by user defined values (x axis) if (cnf.xaxis.max !== undefined && typeof cnf.xaxis.max === 'number') { gl.maxX = cnf.xaxis.max; } if (cnf.xaxis.min !== undefined && typeof cnf.xaxis.min === 'number') { gl.minX = cnf.xaxis.min; } // if range is provided, adjust the new minX if (cnf.xaxis.range !== undefined) { gl.minX = gl.maxX - cnf.xaxis.range; } if (gl.minX !== Number.MAX_VALUE && gl.maxX !== -Number.MAX_VALUE) { gl.xAxisScale = this.scales.linearScale(gl.minX, gl.maxX, ticks); } else { gl.xAxisScale = this.scales.linearScale(1, ticks, ticks); if (gl.noLabelsProvided && gl.labels.length > 0) { gl.xAxisScale = this.scales.linearScale(1, gl.labels.length, ticks - 1); // this is the only place seriesX is again mutated gl.seriesX = gl.labels.slice(); } } // we will still store these labels as the count for this will be different (to draw grid and labels placement) if (isXNumeric) { gl.labels = gl.xAxisScale.result.slice(); } } if (gl.minX === gl.maxX) { // single dataPoint if (cnf.xaxis.type === 'datetime') { var newMinX = new Date(gl.minX); newMinX.setDate(newMinX.getDate() - 2); gl.minX = new Date(newMinX).getTime(); var newMaxX = new Date(gl.maxX); newMaxX.setDate(newMaxX.getDate() + 2); gl.maxX = new Date(newMaxX).getTime(); } else if (cnf.xaxis.type === 'numeric' || cnf.xaxis.type === 'category' && !gl.noLabelsProvided) { gl.minX = gl.minX - 2; gl.maxX = gl.maxX + 2; } } if (gl.isXNumeric) { // get the least x diff if numeric x axis is present gl.seriesX.forEach(function (sX, i) { sX.forEach(function (s, j) { if (j > 0) { var xDiff = s - gl.seriesX[i][j - 1]; gl.minXDiff = Math.min(xDiff, gl.minXDiff); } }); }); this.calcMinXDiffForTinySeries(); } return { minX: gl.minX, maxX: gl.maxX }; } }, { key: "calcMinXDiffForTinySeries", value: function calcMinXDiffForTinySeries() { var w = this.w; var len = w.globals.labels.length; if (w.globals.labels.length === 1) { w.globals.minXDiff = (w.globals.maxX - w.globals.minX) / len / 3; } else { if (w.globals.minXDiff === Number.MAX_VALUE) { // possibly a single dataPoint (fixes react-apexcharts/issue#34) if (w.globals.timelineLabels.length > 0) { len = w.globals.timelineLabels.length; } if (len < 3) { len = 3; } w.globals.minXDiff = (w.globals.maxX - w.globals.minX) / len; } } return w.globals.minXDiff; } }, { key: "setZRange", value: function setZRange() { var gl = this.w.globals; // minZ, maxZ starts here if (gl.isDataXYZ) { for (var i = 0; i < gl.series.length; i++) { if (typeof gl.seriesZ[i] !== 'undefined') { for (var j = 0; j < gl.seriesZ[i].length; j++) { if (gl.seriesZ[i][j] !== null && Utils.isNumber(gl.seriesZ[i][j])) { gl.maxZ = Math.max(gl.maxZ, gl.seriesZ[i][j]); gl.minZ = Math.min(gl.minZ, gl.seriesZ[i][j]); } } } } } } }]); return Range$$1; }(); /** * ApexCharts Series Class for interation with the Series of the chart. * * @module Series **/ var Series = /*#__PURE__*/ function () { function Series(ctx) { _classCallCheck(this, Series); this.ctx = ctx; this.w = ctx.w; } _createClass(Series, [{ key: "getAllSeriesEls", value: function getAllSeriesEls() { return this.w.globals.dom.baseEl.querySelectorAll(".apexcharts-series"); } }, { key: "getSeriesByName", value: function getSeriesByName(seriesName) { return this.w.globals.dom.baseEl.querySelector(".apexcharts-series.".concat(Utils.escapeString(seriesName))); } }, { key: "addCollapsedClassToSeries", value: function addCollapsedClassToSeries(elSeries, index) { var w = this.w; for (var cs = 0; cs < w.globals.collapsedSeries.length; cs++) { if (w.globals.collapsedSeries[cs].index === index) { elSeries.node.classList.add('apexcharts-series-collapsed'); } } } }, { key: "toggleSeriesOnHover", value: function toggleSeriesOnHover(e, targetElement) { var w = this.w; var allSeriesEls = w.globals.dom.baseEl.querySelectorAll(".apexcharts-series"); if (e.type === 'mousemove') { var seriesCnt = parseInt(targetElement.getAttribute('rel')) - 1; var seriesEl = null; if (w.globals.axisCharts || w.config.chart.type === 'radialBar') { if (w.globals.axisCharts) { seriesEl = w.globals.dom.baseEl.querySelector(".apexcharts-series[data\\:realIndex='".concat(seriesCnt, "']")); } else { seriesEl = w.globals.dom.baseEl.querySelector(".apexcharts-series[rel='".concat(seriesCnt + 1, "']")); } } else { seriesEl = w.globals.dom.baseEl.querySelector(".apexcharts-series[rel='".concat(seriesCnt + 1, "'] path")); } for (var se = 0; se < allSeriesEls.length; se++) { allSeriesEls[se].classList.add('legend-mouseover-inactive'); } if (seriesEl !== null) { if (!w.globals.axisCharts) { seriesEl.parentNode.classList.remove('legend-mouseover-inactive'); } seriesEl.classList.remove('legend-mouseover-inactive'); } } else if (e.type === 'mouseout') { for (var _se = 0; _se < allSeriesEls.length; _se++) { allSeriesEls[_se].classList.remove('legend-mouseover-inactive'); } } } }, { key: "highlightRangeInSeries", value: function highlightRangeInSeries(e, targetElement) { var w = this.w; var allHeatMapElements = w.globals.dom.baseEl.querySelectorAll('.apexcharts-heatmap-rect'); var allActive = function allActive() { for (var i = 0; i < allHeatMapElements.length; i++) { allHeatMapElements[i].classList.remove('legend-mouseover-inactive'); } }; var allInactive = function allInactive() { for (var i = 0; i < allHeatMapElements.length; i++) { allHeatMapElements[i].classList.add('legend-mouseover-inactive'); } }; var selectedActive = function selectedActive(range) { for (var i = 0; i < allHeatMapElements.length; i++) { var val = parseInt(allHeatMapElements[i].getAttribute('val')); if (val >= range.from && val <= range.to) { allHeatMapElements[i].classList.remove('legend-mouseover-inactive'); } } }; if (e.type === 'mousemove') { var seriesCnt = parseInt(targetElement.getAttribute('rel')) - 1; allActive(); allInactive(); var range = w.config.plotOptions.heatmap.colorScale.ranges[seriesCnt]; selectedActive(range); } else if (e.type === 'mouseout') { allActive(); } } }, { key: "getActiveSeriesIndex", value: function getActiveSeriesIndex() { var w = this.w; var activeIndex = 0; if (w.globals.series.length > 1) { // active series flag is required to know if user has not deactivated via legend click var firstActiveSeriesIndex = w.globals.series.map(function (series, index) { if (series.length > 0 && w.config.series[index].type !== 'bar' && w.config.series[index].type !== 'column') { return index; } else { return -1; } }); for (var a = 0; a < firstActiveSeriesIndex.length; a++) { if (firstActiveSeriesIndex[a] !== -1) { activeIndex = firstActiveSeriesIndex[a]; break; } } } return activeIndex; } }, { key: "getActiveConfigSeriesIndex", value: function getActiveConfigSeriesIndex() { var w = this.w; var activeIndex = 0; if (w.config.series.length > 1) { // active series flag is required to know if user has not deactivated via legend click var firstActiveSeriesIndex = w.config.series.map(function (series, index) { if (series.data && series.data.length > 0) { return index; } else { return -1; } }); for (var a = 0; a < firstActiveSeriesIndex.length; a++) { if (firstActiveSeriesIndex[a] !== -1) { activeIndex = firstActiveSeriesIndex[a]; break; } } } return activeIndex; } }, { key: "getPreviousPaths", value: function getPreviousPaths() { var w = this.w; w.globals.previousPaths = []; function pushPaths(seriesEls, i, type) { var paths = seriesEls[i].childNodes; var dArr = { type: type, paths: [], realIndex: seriesEls[i].getAttribute('data:realIndex') }; for (var j = 0; j < paths.length; j++) { if (paths[j].hasAttribute('pathTo')) { var d = paths[j].getAttribute('pathTo'); dArr.paths.push({ d: d }); } } w.globals.previousPaths.push(dArr); } var linePaths = w.globals.dom.baseEl.querySelectorAll('.apexcharts-line-series .apexcharts-series'); if (linePaths.length > 0) { for (var p = linePaths.length - 1; p >= 0; p--) { pushPaths(linePaths, p, 'line'); } } var areapaths = w.globals.dom.baseEl.querySelectorAll('.apexcharts-area-series .apexcharts-series'); if (areapaths.length > 0) { for (var i = areapaths.length - 1; i >= 0; i--) { pushPaths(areapaths, i, 'area'); } } var barPaths = w.globals.dom.baseEl.querySelectorAll('.apexcharts-bar-series .apexcharts-series'); if (barPaths.length > 0) { for (var _p = 0; _p < barPaths.length; _p++) { pushPaths(barPaths, _p, 'bar'); } } var candlestickPaths = w.globals.dom.baseEl.querySelectorAll('.apexcharts-candlestick-series .apexcharts-series'); if (candlestickPaths.length > 0) { for (var _p2 = 0; _p2 < candlestickPaths.length; _p2++) { pushPaths(candlestickPaths, _p2, 'candlestick'); } } var radarPaths = w.globals.dom.baseEl.querySelectorAll('.apexcharts-radar-series .apexcharts-series'); if (radarPaths.length > 0) { for (var _p3 = 0; _p3 < radarPaths.length; _p3++) { pushPaths(radarPaths, _p3, 'radar'); } } var bubblepaths = w.globals.dom.baseEl.querySelectorAll('.apexcharts-bubble-series .apexcharts-series'); if (bubblepaths.length > 0) { for (var s = 0; s < bubblepaths.length; s++) { var seriesEls = w.globals.dom.baseEl.querySelectorAll(".apexcharts-bubble-series .apexcharts-series[data\\:realIndex='".concat(s, "'] circle")); var dArr = []; for (var _i = 0; _i < seriesEls.length; _i++) { dArr.push({ x: seriesEls[_i].getAttribute('cx'), y: seriesEls[_i].getAttribute('cy'), r: seriesEls[_i].getAttribute('r') }); } w.globals.previousPaths.push(dArr); } } var scatterpaths = w.globals.dom.baseEl.querySelectorAll('.apexcharts-scatter-series .apexcharts-series'); if (scatterpaths.length > 0) { for (var _s = 0; _s < scatterpaths.length; _s++) { var _seriesEls = w.globals.dom.baseEl.querySelectorAll(".apexcharts-scatter-series .apexcharts-series[data\\:realIndex='".concat(_s, "'] circle")); var _dArr = []; for (var _i2 = 0; _i2 < _seriesEls.length; _i2++) { _dArr.push({ x: _seriesEls[_i2].getAttribute('cx'), y: _seriesEls[_i2].getAttribute('cy'), r: _seriesEls[_i2].getAttribute('r') }); } w.globals.previousPaths.push(_dArr); } } var heatmapColors = w.globals.dom.baseEl.querySelectorAll('.apexcharts-heatmap .apexcharts-series'); if (heatmapColors.length > 0) { for (var h = 0; h < heatmapColors.length; h++) { var _seriesEls2 = w.globals.dom.baseEl.querySelectorAll(".apexcharts-heatmap .apexcharts-series[data\\:realIndex='".concat(h, "'] rect")); var _dArr2 = []; for (var _i3 = 0; _i3 < _seriesEls2.length; _i3++) { _dArr2.push({ color: _seriesEls2[_i3].getAttribute('color') }); } w.globals.previousPaths.push(_dArr2); } } if (!w.globals.axisCharts) { // for non-axis charts (i.e., circular charts, pathFrom is not usable. We need whole series) w.globals.previousPaths = w.globals.series; } } }, { key: "handleNoData", value: function handleNoData() { var w = this.w; var me = this; var noDataOpts = w.config.noData; var graphics = new Graphics(me.ctx); var x = w.globals.svgWidth / 2; var y = w.globals.svgHeight / 2; var textAnchor = 'middle'; w.globals.noData = true; w.globals.animationEnded = true; if (noDataOpts.align === 'left') { x = 10; textAnchor = 'start'; } else if (noDataOpts.align === 'right') { x = w.globals.svgWidth - 10; textAnchor = 'end'; } if (noDataOpts.verticalAlign === 'top') { y = 50; } else if (noDataOpts.verticalAlign === 'bottom') { y = w.globals.svgHeight - 50; } x = x + noDataOpts.offsetX; y = y + parseInt(noDataOpts.style.fontSize) + 2; if (noDataOpts.text !== undefined && noDataOpts.text !== '') { var titleText = graphics.drawText({ x: x, y: y, text: noDataOpts.text, textAnchor: textAnchor, fontSize: noDataOpts.style.fontSize, fontFamily: noDataOpts.style.fontFamily, foreColor: noDataOpts.style.color, opacity: 1, class: 'apexcharts-text-nodata' }); titleText.node.setAttribute('class', 'apexcharts-title-text'); w.globals.dom.Paper.add(titleText); } } // When user clicks on legends, the collapsed series is filled with [0,0,0,...,0] // This is because we don't want to alter the series' length as it is used at many places }, { key: "setNullSeriesToZeroValues", value: function setNullSeriesToZeroValues(series) { var w = this.w; for (var sl = 0; sl < series.length; sl++) { if (series[sl].length === 0) { for (var j = 0; j < series[w.globals.maxValsInArrayIndex].length; j++) { series[sl].push(0); } } } return series; } }, { key: "hasAllSeriesEqualX", value: function hasAllSeriesEqualX() { var equalLen = true; var w = this.w; var filteredSerX = this.filteredSeriesX(); for (var i = 0; i < filteredSerX.length - 1; i++) { if (filteredSerX[i][0] !== filteredSerX[i + 1][0]) { equalLen = false; break; } } w.globals.allSeriesHasEqualX = equalLen; return equalLen; } }, { key: "filteredSeriesX", value: function filteredSeriesX() { var w = this.w; var filteredSeriesX = w.globals.seriesX.map(function (ser, index) { if (ser.length > 0) { return ser; } else { return []; } }); return filteredSeriesX; } }]); return Series; }(); /** * ApexCharts Dimensions Class for calculating rects of all elements that are drawn and will be drawn. * * @module Dimensions **/ var Dimensions = /*#__PURE__*/ function () { function Dimensions(ctx) { _classCallCheck(this, Dimensions); this.ctx = ctx; this.w = ctx.w; this.lgRect = {}; this.yAxisWidth = 0; this.xAxisHeight = 0; this.isSparkline = this.w.config.chart.sparkline.enabled; this.xPadRight = 0; this.xPadLeft = 0; } /** * @memberof Dimensions * @param {object} w - chart context **/ _createClass(Dimensions, [{ key: "plotCoords", value: function plotCoords() { var w = this.w; var gl = w.globals; var lgRect = this.getLegendsRect(); if (gl.axisCharts) { // for line / area / scatter / column this.setGridCoordsForAxisCharts(lgRect); } else { // for pie / donuts / circle this.setGridCoordsForNonAxisCharts(lgRect); } this.titleSubtitleOffset(); // after calculating everything, apply padding set by user gl.gridHeight = gl.gridHeight - w.config.grid.padding.top - w.config.grid.padding.bottom; gl.gridWidth = gl.gridWidth - w.config.grid.padding.left - w.config.grid.padding.right - this.xPadRight - this.xPadLeft; gl.translateX = gl.translateX + w.config.grid.padding.left + this.xPadLeft; gl.translateY = gl.translateY + w.config.grid.padding.top; } }, { key: "conditionalChecksForAxisCoords", value: function conditionalChecksForAxisCoords(xaxisLabelCoords, xtitleCoords) { var w = this.w; this.xAxisHeight = (xaxisLabelCoords.height + xtitleCoords.height) * w.globals.LINE_HEIGHT_RATIO + 15; this.xAxisWidth = xaxisLabelCoords.width; if (this.xAxisHeight - xtitleCoords.height > w.config.xaxis.labels.maxHeight) { this.xAxisHeight = w.config.xaxis.labels.maxHeight; } if (w.config.xaxis.labels.minHeight && this.xAxisHeight < w.config.xaxis.labels.minHeight) { this.xAxisHeight = w.config.xaxis.labels.minHeight; } if (w.config.xaxis.floating) { this.xAxisHeight = 0; } if (!w.globals.isBarHorizontal) { this.yAxisWidth = this.getTotalYAxisWidth(); } else { this.yAxisWidth = w.globals.yLabelsCoords[0].width + w.globals.yTitleCoords[0].width + 15; } var minYAxisWidth = 0; var maxYAxisWidth = 0; w.config.yaxis.forEach(function (y) { minYAxisWidth += y.labels.minWidth; maxYAxisWidth += y.labels.maxWidth; }); if (this.yAxisWidth < minYAxisWidth) { this.yAxisWidth = minYAxisWidth; } if (this.yAxisWidth > maxYAxisWidth) { this.yAxisWidth = maxYAxisWidth; } } }, { key: "setGridCoordsForAxisCharts", value: function setGridCoordsForAxisCharts(lgRect) { var w = this.w; var gl = w.globals; var yaxisLabelCoords = this.getyAxisLabelsCoords(); var xaxisLabelCoords = this.getxAxisLabelsCoords(); var yTitleCoords = this.getyAxisTitleCoords(); var xtitleCoords = this.getxAxisTitleCoords(); w.globals.yLabelsCoords = []; w.globals.yTitleCoords = []; w.config.yaxis.map(function (yaxe, index) { // store the labels and titles coords in global vars w.globals.yLabelsCoords.push({ width: yaxisLabelCoords[index].width, index: index }); w.globals.yTitleCoords.push({ width: yTitleCoords[index].width, index: index }); }); this.conditionalChecksForAxisCoords(xaxisLabelCoords, xtitleCoords); gl.translateXAxisY = w.globals.rotateXLabels ? this.xAxisHeight / 8 : -4; gl.translateXAxisX = w.globals.rotateXLabels && w.globals.isXNumeric && w.config.xaxis.labels.rotate <= -45 ? -this.xAxisWidth / 4 : 0; if (w.globals.isBarHorizontal) { gl.rotateXLabels = false; gl.translateXAxisY = -1 * (parseInt(w.config.xaxis.labels.style.fontSize) / 1.5); } gl.translateXAxisY = gl.translateXAxisY + w.config.xaxis.labels.offsetY; gl.translateXAxisX = gl.translateXAxisX + w.config.xaxis.labels.offsetX; var yAxisWidth = this.yAxisWidth; var xAxisHeight = this.xAxisHeight; gl.xAxisLabelsHeight = this.xAxisHeight; gl.xAxisHeight = this.xAxisHeight; var translateY = 10; if (!w.config.grid.show || w.config.chart.type === 'radar') { yAxisWidth = 0; xAxisHeight = 35; } if (this.isSparkline) { lgRect = { height: 0, width: 0 }; xAxisHeight = 0; yAxisWidth = 0; translateY = 0; } this.additionalPaddingXLabels(xaxisLabelCoords); switch (w.config.legend.position) { case 'bottom': gl.translateY = translateY; gl.translateX = yAxisWidth; gl.gridHeight = gl.svgHeight - lgRect.height - xAxisHeight - (!this.isSparkline ? w.globals.rotateXLabels ? 10 : 15 : 0); gl.gridWidth = gl.svgWidth - yAxisWidth; break; case 'top': gl.translateY = lgRect.height + translateY; gl.translateX = yAxisWidth; gl.gridHeight = gl.svgHeight - lgRect.height - xAxisHeight - (!this.isSparkline ? w.globals.rotateXLabels ? 10 : 15 : 0); gl.gridWidth = gl.svgWidth - yAxisWidth; break; case 'left': gl.translateY = translateY; gl.translateX = lgRect.width + yAxisWidth; gl.gridHeight = gl.svgHeight - xAxisHeight - 12; gl.gridWidth = gl.svgWidth - lgRect.width - yAxisWidth; break; case 'right': gl.translateY = translateY; gl.translateX = yAxisWidth; gl.gridHeight = gl.svgHeight - xAxisHeight - 12; gl.gridWidth = gl.svgWidth - lgRect.width - yAxisWidth - 5; break; default: throw new Error('Legend position not supported'); } this.setGridXPosForDualYAxis(yTitleCoords, yaxisLabelCoords); // after drawing everything, set the Y axis positions var objyAxis = new YAxis(this.ctx); objyAxis.setYAxisXPosition(yaxisLabelCoords, yTitleCoords); } }, { key: "setGridCoordsForNonAxisCharts", value: function setGridCoordsForNonAxisCharts(lgRect) { var w = this.w; var gl = w.globals; var xPad = 0; if (w.config.legend.show && !w.config.legend.floating) { xPad = 20; } var offY = 10; var offX = 0; if (w.config.chart.type === 'pie' || w.config.chart.type === 'donut') { offY = offY + w.config.plotOptions.pie.offsetY; offX = offX + w.config.plotOptions.pie.offsetX; } else if (w.config.chart.type === 'radialBar') { offY = offY + w.config.plotOptions.radialBar.offsetY; offX = offX + w.config.plotOptions.radialBar.offsetX; } if (!w.config.legend.show) { gl.gridHeight = gl.svgHeight - 35; gl.gridWidth = gl.gridHeight; gl.translateY = offY - 10; gl.translateX = offX + (gl.svgWidth - gl.gridWidth) / 2; return; } switch (w.config.legend.position) { case 'bottom': gl.gridHeight = gl.svgHeight - lgRect.height - 35; gl.gridWidth = gl.gridHeight; gl.translateY = offY - 20; gl.translateX = offX + (gl.svgWidth - gl.gridWidth) / 2; break; case 'top': gl.gridHeight = gl.svgHeight - lgRect.height - 35; gl.gridWidth = gl.gridHeight; gl.translateY = lgRect.height + offY; gl.translateX = offX + (gl.svgWidth - gl.gridWidth) / 2; break; case 'left': gl.gridWidth = gl.svgWidth - lgRect.width - xPad; gl.gridHeight = gl.gridWidth; gl.translateY = offY; gl.translateX = offX + lgRect.width + xPad; break; case 'right': gl.gridWidth = gl.svgWidth - lgRect.width - xPad - 5; gl.gridHeight = gl.gridWidth; gl.translateY = offY; gl.translateX = offX + 10; break; default: throw new Error('Legend position not supported'); } } }, { key: "setGridXPosForDualYAxis", value: function setGridXPosForDualYAxis(yTitleCoords, yaxisLabelCoords) { var w = this.w; w.config.yaxis.map(function (yaxe, index) { if (w.globals.ignoreYAxisIndexes.indexOf(index) === -1 && !w.config.yaxis[index].floating && w.config.yaxis[index].show) { if (yaxe.opposite) { w.globals.translateX = w.globals.translateX - (yaxisLabelCoords[index].width + yTitleCoords[index].width) - parseInt(w.config.yaxis[index].labels.style.fontSize) / 1.2 - 12; } } }); } // Sometimes, the last labels gets cropped in category/numeric xaxis. // Hence, we add some additional padding based on the label length to avoid the last label being cropped. // NOTE: datetime x-axis won't have any effect with this as we don't know the label length there due to many constraints. }, { key: "additionalPaddingXLabels", value: function additionalPaddingXLabels(xaxisLabelCoords) { var _this = this; var w = this.w; if (w.config.xaxis.type === 'category' && w.globals.isBarHorizontal || w.config.xaxis.type === 'numeric' || w.config.xaxis.type === 'datetime') { var rightPad = function rightPad(labels) { if (_this.timescaleLabels) { // for timeline labels, we take the last label and check if it exceeds gridWidth var lastTimescaleLabel = _this.timescaleLabels[_this.timescaleLabels.length - 1]; var labelPosition = lastTimescaleLabel.position + labels.width; if (labelPosition > w.globals.gridWidth) { w.globals.skipLastTimelinelabel = true; } else { // we have to make it false again in case of zooming/panning w.globals.skipLastTimelinelabel = false; } } else if (w.config.xaxis.type !== 'datetime') { if (w.config.grid.padding.right < labels.width) { _this.xPadRight = labels.width / 2 + 1; } } }; var leftPad = function leftPad(labels) { if (w.config.grid.padding.left < labels.width) { _this.xPadLeft = labels.width / 2 + 1; } }; var isXNumeric = w.globals.isXNumeric; w.config.yaxis.forEach(function (yaxe, i) { var shouldPad = !yaxe.show || yaxe.floating || w.globals.collapsedSeriesIndices.indexOf(i) !== -1 || isXNumeric || yaxe.opposite && w.globals.isBarHorizontal; if (shouldPad) { if (isXNumeric && w.globals.isMultipleYAxis && w.globals.collapsedSeriesIndices.indexOf(i) !== -1 || w.globals.isBarHorizontal && yaxe.opposite) { leftPad(xaxisLabelCoords); } if (!w.globals.isBarHorizontal && yaxe.opposite && w.globals.collapsedSeriesIndices.indexOf(i) !== -1 || isXNumeric && !w.globals.isMultipleYAxis) { rightPad(xaxisLabelCoords); } } }); } } }, { key: "titleSubtitleOffset", value: function titleSubtitleOffset() { var w = this.w; var gl = w.globals; var gridShrinkOffset = this.isSparkline || !w.globals.axisCharts ? 0 : 10; if (w.config.title.text !== undefined) { gridShrinkOffset += w.config.title.margin; } else { gridShrinkOffset += this.isSparkline || !w.globals.axisCharts ? 0 : 5; } if (w.config.subtitle.text !== undefined) { gridShrinkOffset += w.config.subtitle.margin; } else { gridShrinkOffset += this.isSparkline || !w.globals.axisCharts ? 0 : 5; } if (w.config.legend.show && w.config.legend.position === 'bottom' && !w.config.legend.floating && w.config.series.length > 1) { gridShrinkOffset += 10; } var titleCoords = this.getTitleSubtitleCoords('title'); var subtitleCoords = this.getTitleSubtitleCoords('subtitle'); gl.gridHeight = gl.gridHeight - titleCoords.height - subtitleCoords.height - gridShrinkOffset; gl.translateY = gl.translateY + titleCoords.height + subtitleCoords.height + gridShrinkOffset; } }, { key: "getTotalYAxisWidth", value: function getTotalYAxisWidth() { var w = this.w; var yAxisWidth = 0; var padding = 10; var isHiddenYAxis = function isHiddenYAxis(index) { return w.globals.ignoreYAxisIndexes.indexOf(index) > -1; }; w.globals.yLabelsCoords.map(function (yLabelCoord, index) { var floating = w.config.yaxis[index].floating; if (yLabelCoord.width > 0 && !floating) { yAxisWidth = yAxisWidth + yLabelCoord.width + padding; if (isHiddenYAxis(index)) { yAxisWidth = yAxisWidth - yLabelCoord.width - padding; } } else { yAxisWidth = yAxisWidth + (floating || !w.config.yaxis[index].show ? 0 : 5); } }); w.globals.yTitleCoords.map(function (yTitleCoord, index) { var floating = w.config.yaxis[index].floating; padding = parseInt(w.config.yaxis[index].title.style.fontSize); if (yTitleCoord.width > 0 && !floating) { yAxisWidth = yAxisWidth + yTitleCoord.width + padding; if (isHiddenYAxis(index)) { yAxisWidth = yAxisWidth - yTitleCoord.width - padding; } } else { yAxisWidth = yAxisWidth + (floating || !w.config.yaxis[index].show ? 0 : 5); } }); return yAxisWidth; } }, { key: "getxAxisTimeScaleLabelsCoords", value: function getxAxisTimeScaleLabelsCoords() { var w = this.w; var rect; this.timescaleLabels = w.globals.timelineLabels.slice(); if (w.globals.isBarHorizontal && w.config.xaxis.type === 'datetime') { this.timescaleLabels = w.globals.invertedTimelineLabels.slice(); } var labels = this.timescaleLabels.map(function (label) { return label.value; }); // get the longest string from the labels array and also apply label formatter to it var val = labels.reduce(function (a, b) { // if undefined, maybe user didn't pass the datetime(x) values if (typeof a === 'undefined') { console.error('You have possibly supplied invalid Date format. Please supply a valid JavaScript Date'); return 0; } else { return a.length > b.length ? a : b; } }, 0); var graphics = new Graphics(this.ctx); rect = graphics.getTextRects(val, w.config.xaxis.labels.style.fontSize); var totalWidthRotated = rect.width * 1.05 * labels.length; if (totalWidthRotated > w.globals.gridWidth && w.config.xaxis.labels.rotate !== 0) { w.globals.overlappingXLabels = true; } return rect; } /** * Get X Axis Dimensions * @memberof Dimensions * @return {{width, height}} **/ }, { key: "getxAxisLabelsCoords", value: function getxAxisLabelsCoords() { var w = this.w; var xaxisLabels = w.globals.labels.slice(); var rect; if (w.globals.timelineLabels.length > 0) { var coords = this.getxAxisTimeScaleLabelsCoords(); rect = { width: coords.width, height: coords.height }; } else { var lgWidthForSideLegends = w.config.legend.position === 'left' && w.config.legend.position === 'right' && !w.config.legend.floating ? this.lgRect.width : 0; // get the longest string from the labels array and also apply label formatter var xlbFormatter = w.globals.xLabelFormatter; // prevent changing xaxisLabels to avoid issues in multi-yaxies - fix #522 var val = xaxisLabels.reduce(function (a, b) { return a.length > b.length ? a : b; }, 0); // the labels gets changed for bar charts if (w.globals.isBarHorizontal) { val = w.globals.yAxisScale[0].result.reduce(function (a, b) { return a.length > b.length ? a : b; }, 0); } var xFormat = new Formatters(this.ctx); val = xFormat.xLabelFormat(xlbFormatter, val); var graphics = new Graphics(this.ctx); var xLabelrect = graphics.getTextRects(val, w.config.xaxis.labels.style.fontSize); rect = { width: xLabelrect.width, height: xLabelrect.height }; if (rect.width * xaxisLabels.length > w.globals.svgWidth - lgWidthForSideLegends - this.yAxisWidth && w.config.xaxis.labels.rotate !== 0) { if (!w.globals.isBarHorizontal) { w.globals.rotateXLabels = true; xLabelrect = graphics.getTextRects(val, w.config.xaxis.labels.style.fontSize, w.config.xaxis.labels.style.fontFamily, "rotate(".concat(w.config.xaxis.labels.rotate, " 0 0)"), false); rect.height = xLabelrect.height / 1.66; } } else { w.globals.rotateXLabels = false; } } if (!w.config.xaxis.labels.show) { rect = { width: 0, height: 0 }; } return { width: rect.width, height: rect.height }; } /** * Get Y Axis Dimensions * @memberof Dimensions * @return {{width, height}} **/ }, { key: "getyAxisLabelsCoords", value: function getyAxisLabelsCoords() { var _this2 = this; var w = this.w; var width = 0; var height = 0; var ret = []; var labelPad = 10; w.config.yaxis.map(function (yaxe, index) { if (yaxe.show && yaxe.labels.show && w.globals.yAxisScale[index].result.length) { var lbFormatter = w.globals.yLabelFormatters[index]; // the second parameter -1 is the index of tick which user can use in the formatter var val = lbFormatter(w.globals.yAxisScale[index].niceMax, -1); // if user has specified a custom formatter, and the result is null or empty, we need to discard the formatter and take the value as it is. if (typeof val === 'undefined' || val.length === 0) { val = w.globals.yAxisScale[index].niceMax; } if (w.globals.isBarHorizontal) { labelPad = 0; var barYaxisLabels = w.globals.labels.slice(); // get the longest string from the labels array and also apply label formatter to it val = barYaxisLabels.reduce(function (a, b) { return a.length > b.length ? a : b; }, 0); val = lbFormatter(val, -1); } var graphics = new Graphics(_this2.ctx); var rect = graphics.getTextRects(val, yaxe.labels.style.fontSize); ret.push({ width: rect.width + labelPad, height: rect.height }); } else { ret.push({ width: width, height: height }); } }); return ret; } /** * Get X Axis Title Dimensions * @memberof Dimensions * @return {{width, height}} **/ }, { key: "getxAxisTitleCoords", value: function getxAxisTitleCoords() { var w = this.w; var width = 0; var height = 0; if (w.config.xaxis.title.text !== undefined) { var graphics = new Graphics(this.ctx); var rect = graphics.getTextRects(w.config.xaxis.title.text, w.config.xaxis.title.style.fontSize); width = rect.width; height = rect.height; } return { width: width, height: height }; } /** * Get Y Axis Dimensions * @memberof Dimensions * @return {{width, height}} **/ }, { key: "getyAxisTitleCoords", value: function getyAxisTitleCoords() { var _this3 = this; var w = this.w; var ret = []; w.config.yaxis.map(function (yaxe, index) { if (yaxe.show && yaxe.title.text !== undefined) { var graphics = new Graphics(_this3.ctx); var rect = graphics.getTextRects(yaxe.title.text, yaxe.title.style.fontSize, yaxe.title.style.fontFamily, 'rotate(-90 0 0)', false); ret.push({ width: rect.width, height: rect.height }); } else { ret.push({ width: 0, height: 0 }); } }); return ret; } /** * Get Chart Title/Subtitle Dimensions * @memberof Dimensions * @return {{width, height}} **/ }, { key: "getTitleSubtitleCoords", value: function getTitleSubtitleCoords(type) { var w = this.w; var width = 0; var height = 0; var floating = type === 'title' ? w.config.title.floating : w.config.subtitle.floating; var el = w.globals.dom.baseEl.querySelector(".apexcharts-".concat(type, "-text")); if (el !== null && !floating) { var coord = el.getBoundingClientRect(); width = coord.width; height = w.globals.axisCharts ? coord.height + 5 : coord.height; } return { width: width, height: height }; } }, { key: "getLegendsRect", value: function getLegendsRect() { var w = this.w; var elLegendWrap = w.globals.dom.baseEl.querySelector('.apexcharts-legend'); var lgRect = Object.assign({}, Utils.getBoundingClientRect(elLegendWrap)); if (elLegendWrap !== null && !w.config.legend.floating && w.config.legend.show) { this.lgRect = { x: lgRect.x, y: lgRect.y, height: lgRect.height, width: lgRect.height === 0 ? 0 : lgRect.width }; } else { this.lgRect = { x: 0, y: 0, height: 0, width: 0 }; } return this.lgRect; } }]); return Dimensions; }(); /** * ApexCharts TimeScale Class for generating time ticks for x-axis. * * @module TimeScale **/ var TimeScale = /*#__PURE__*/ function () { function TimeScale(ctx) { _classCallCheck(this, TimeScale); this.ctx = ctx; this.w = ctx.w; this.timeScaleArray = []; } _createClass(TimeScale, [{ key: "calculateTimeScaleTicks", value: function calculateTimeScaleTicks(minX, maxX) { var _this = this; var w = this.w; // null check when no series to show if (w.globals.allSeriesCollapsed) { w.globals.labels = []; w.globals.timelineLabels = []; return []; } var dt = new DateTime(this.ctx); var daysDiff = (maxX - minX) / (1000 * 60 * 60 * 24); this.determineInterval(daysDiff); w.globals.disableZoomIn = false; w.globals.disableZoomOut = false; if (daysDiff < 0.005) { w.globals.disableZoomIn = true; } else if (daysDiff > 50000) { w.globals.disableZoomOut = true; } var timeIntervals = dt.getTimeUnitsfromTimestamp(minX, maxX); var daysWidthOnXAxis = w.globals.gridWidth / daysDiff; var hoursWidthOnXAxis = daysWidthOnXAxis / 24; var minutesWidthOnXAxis = hoursWidthOnXAxis / 60; var numberOfHours = Math.floor(daysDiff * 24); var numberOfMinutes = Math.floor(daysDiff * 24 * 60); var numberOfDays = Math.floor(daysDiff); var numberOfMonths = Math.floor(daysDiff / 30); var numberOfYears = Math.floor(daysDiff / 365); var firstVal = { minMinute: timeIntervals.minMinute, minHour: timeIntervals.minHour, minDate: timeIntervals.minDate, minMonth: timeIntervals.minMonth, minYear: timeIntervals.minYear }; var currentMinute = firstVal.minMinute; var currentHour = firstVal.minHour; var currentMonthDate = firstVal.minDate; var currentDate = firstVal.minDate; var currentMonth = firstVal.minMonth; var currentYear = firstVal.minYear; var params = { firstVal: firstVal, currentMinute: currentMinute, currentHour: currentHour, currentMonthDate: currentMonthDate, currentDate: currentDate, currentMonth: currentMonth, currentYear: currentYear, daysWidthOnXAxis: daysWidthOnXAxis, hoursWidthOnXAxis: hoursWidthOnXAxis, minutesWidthOnXAxis: minutesWidthOnXAxis, numberOfMinutes: numberOfMinutes, numberOfHours: numberOfHours, numberOfDays: numberOfDays, numberOfMonths: numberOfMonths, numberOfYears: numberOfYears }; switch (this.tickInterval) { case 'years': { this.generateYearScale(params); break; } case 'months': case 'half_year': { this.generateMonthScale(params); break; } case 'months_days': case 'months_fortnight': case 'days': case 'week_days': { this.generateDayScale(params); break; } case 'hours': { this.generateHourScale(params); break; } case 'minutes': this.generateMinuteScale(params); break; } // first, we will adjust the month values index // as in the upper function, it is starting from 0 // we will start them from 1 var adjustedMonthInTimeScaleArray = this.timeScaleArray.map(function (ts) { var defaultReturn = { position: ts.position, unit: ts.unit, year: ts.year, day: ts.day ? ts.day : 1, hour: ts.hour ? ts.hour : 0, month: ts.month + 1 }; if (ts.unit === 'month') { return _objectSpread({}, defaultReturn, { value: ts.value + 1 }); } else if (ts.unit === 'day' || ts.unit === 'hour') { return _objectSpread({}, defaultReturn, { value: ts.value }); } else if (ts.unit === 'minute') { return _objectSpread({}, defaultReturn, { value: ts.value, minute: ts.value }); } return ts; }); var filteredTimeScale = adjustedMonthInTimeScaleArray.filter(function (ts) { var modulo = 1; var ticks = Math.ceil(w.globals.gridWidth / 120); var value = ts.value; if (w.config.xaxis.tickAmount !== undefined) { ticks = w.config.xaxis.tickAmount; } if (adjustedMonthInTimeScaleArray.length > ticks) { modulo = Math.floor(adjustedMonthInTimeScaleArray.length / ticks); } var shouldNotSkipUnit = false; // there is a big change in unit i.e days to months var shouldNotPrint = false; // should skip these values switch (_this.tickInterval) { case 'half_year': modulo = 7; if (ts.unit === 'year') { shouldNotSkipUnit = true; } break; case 'months': modulo = 1; if (ts.unit === 'year') { shouldNotSkipUnit = true; } break; case 'months_fortnight': modulo = 15; if (ts.unit === 'year' || ts.unit === 'month') { shouldNotSkipUnit = true; } if (value === 30) { shouldNotPrint = true; } break; case 'months_days': modulo = 10; if (ts.unit === 'month') { shouldNotSkipUnit = true; } if (value === 30) { shouldNotPrint = true; } break; case 'week_days': modulo = 8; if (ts.unit === 'month') { shouldNotSkipUnit = true; } break; case 'days': modulo = 1; if (ts.unit === 'month') { shouldNotSkipUnit = true; } break; case 'hours': if (ts.unit === 'day') { shouldNotSkipUnit = true; } break; case 'minutes': if (value % 5 !== 0) { shouldNotPrint = true; } break; } if (_this.tickInterval === 'minutes' || _this.tickInterval === 'hours') { if (!shouldNotPrint) { return true; } } else { if ((value % modulo === 0 || shouldNotSkipUnit) && !shouldNotPrint) { return true; } } }); return filteredTimeScale; } }, { key: "recalcDimensionsBasedOnFormat", value: function recalcDimensionsBasedOnFormat(filteredTimeScale, inverted) { var w = this.w; var reformattedTimescaleArray = this.formatDates(filteredTimeScale); var removedOverlappingTS = this.removeOverlappingTS(reformattedTimescaleArray); if (!inverted) { w.globals.timelineLabels = removedOverlappingTS.slice(); } else { w.globals.invertedTimelineLabels = removedOverlappingTS.slice(); } // at this stage, we need to re-calculate coords of the grid as timeline labels may have altered the xaxis labels coords // The reason we can't do this prior to this stage is because timeline labels depends on gridWidth, and as the ticks are calculated based on available gridWidth, there can be unknown number of ticks generated for different minX and maxX // Dependency on Dimensions(), need to refactor correctly // TODO - find an alternate way to avoid calling this Heavy method twice var dimensions = new Dimensions(this.ctx); dimensions.plotCoords(); } }, { key: "determineInterval", value: function determineInterval(daysDiff) { switch (true) { case daysDiff > 1825: // difference is more than 5 years this.tickInterval = 'years'; break; case daysDiff > 800 && daysDiff <= 1825: this.tickInterval = 'half_year'; break; case daysDiff > 180 && daysDiff <= 800: this.tickInterval = 'months'; break; case daysDiff > 90 && daysDiff <= 180: this.tickInterval = 'months_fortnight'; break; case daysDiff > 60 && daysDiff <= 90: this.tickInterval = 'months_days'; break; case daysDiff > 30 && daysDiff <= 60: this.tickInterval = 'week_days'; break; case daysDiff > 2 && daysDiff <= 30: this.tickInterval = 'days'; break; case daysDiff > 0.1 && daysDiff <= 2: // less than 2 days this.tickInterval = 'hours'; break; case daysDiff < 0.1: this.tickInterval = 'minutes'; break; default: this.tickInterval = 'days'; break; } } }, { key: "generateYearScale", value: function generateYearScale(params) { var firstVal = params.firstVal, currentMonth = params.currentMonth, currentYear = params.currentYear, daysWidthOnXAxis = params.daysWidthOnXAxis, numberOfYears = params.numberOfYears; var firstTickValue = firstVal.minYear; var firstTickPosition = 0; var dt = new DateTime(this.ctx); var unit = 'year'; if (firstVal.minDate > 1 && firstVal.minMonth > 0) { var remainingDays = dt.determineRemainingDaysOfYear(firstVal.minYear, firstVal.minMonth, firstVal.minDate); // remainingDaysofFirstMonth is used to reacht the 2nd tick position var remainingDaysOfFirstYear = dt.determineDaysOfYear(firstVal.minYear) - remainingDays + 1; // calculate the first tick position firstTickPosition = remainingDaysOfFirstYear * daysWidthOnXAxis; firstTickValue = firstVal.minYear + 1; // push the first tick in the array this.timeScaleArray.push({ position: firstTickPosition, value: firstTickValue, unit: unit, year: firstTickValue, month: Utils.monthMod(currentMonth + 1) }); } else if (firstVal.minDate === 1 && firstVal.minMonth === 0) { // push the first tick in the array this.timeScaleArray.push({ position: firstTickPosition, value: firstTickValue, unit: unit, year: currentYear, month: Utils.monthMod(currentMonth + 1) }); } var year = firstTickValue; var pos = firstTickPosition; // keep drawing rest of the ticks for (var i = 0; i < numberOfYears; i++) { year++; pos = dt.determineDaysOfYear(year - 1) * daysWidthOnXAxis + pos; this.timeScaleArray.push({ position: pos, value: year, unit: unit, year: year, month: 1 }); } } }, { key: "generateMonthScale", value: function generateMonthScale(params) { var firstVal = params.firstVal, currentMonthDate = params.currentMonthDate, currentMonth = params.currentMonth, currentYear = params.currentYear, daysWidthOnXAxis = params.daysWidthOnXAxis, numberOfMonths = params.numberOfMonths; var firstTickValue = currentMonth; var firstTickPosition = 0; var dt = new DateTime(this.ctx); var unit = 'month'; var yrCounter = 0; if (firstVal.minDate > 1) { // remainingDaysofFirstMonth is used to reacht the 2nd tick position var remainingDaysOfFirstMonth = dt.determineDaysOfMonths(currentMonth + 1, firstVal.minYear) - currentMonthDate + 1; // calculate the first tick position firstTickPosition = remainingDaysOfFirstMonth * daysWidthOnXAxis; firstTickValue = Utils.monthMod(currentMonth + 1); var year = currentYear + yrCounter; var _month = Utils.monthMod(firstTickValue); var value = firstTickValue; // it's Jan, so update the year if (firstTickValue === 0) { unit = 'year'; value = year; _month = 1; yrCounter += 1; year = year + yrCounter; } // push the first tick in the array this.timeScaleArray.push({ position: firstTickPosition, value: value, unit: unit, year: year, month: _month }); } else { // push the first tick in the array this.timeScaleArray.push({ position: firstTickPosition, value: firstTickValue, unit: unit, year: currentYear, month: Utils.monthMod(currentMonth) }); } var month = firstTickValue + 1; var pos = firstTickPosition; // keep drawing rest of the ticks for (var i = 0, j = 1; i < numberOfMonths; i++, j++) { month = Utils.monthMod(month); if (month === 0) { unit = 'year'; yrCounter += 1; } else { unit = 'month'; } var _year = currentYear + Math.floor(month / 12) + yrCounter; pos = dt.determineDaysOfMonths(month, _year) * daysWidthOnXAxis + pos; var monthVal = month === 0 ? _year : month; this.timeScaleArray.push({ position: pos, value: monthVal, unit: unit, year: _year, month: month === 0 ? 1 : month }); month++; } } }, { key: "generateDayScale", value: function generateDayScale(params) { var firstVal = params.firstVal, currentMonth = params.currentMonth, currentYear = params.currentYear, hoursWidthOnXAxis = params.hoursWidthOnXAxis, numberOfDays = params.numberOfDays; var dt = new DateTime(this.ctx); var unit = 'day'; var remainingHours = 24 - firstVal.minHour; var yrCounter = 0; // calculate the first tick position var firstTickPosition = remainingHours * hoursWidthOnXAxis; var firstTickValue = firstVal.minDate + 1; var val = firstTickValue; var changeMonth = function changeMonth(dateVal, month, year) { var monthdays = dt.determineDaysOfMonths(month + 1, year); if (dateVal > monthdays) { month = month + 1; date = 1; unit = 'month'; val = month; return month; } return month; }; var date = firstTickValue; var month = changeMonth(date, currentMonth, currentYear); // push the first tick in the array this.timeScaleArray.push({ position: firstTickPosition, value: val, unit: unit, year: currentYear, month: Utils.monthMod(month), day: date }); var pos = firstTickPosition; // keep drawing rest of the ticks for (var i = 0; i < numberOfDays; i++) { date += 1; unit = 'day'; month = changeMonth(date, month, currentYear + Math.floor(month / 12) + yrCounter); var year = currentYear + Math.floor(month / 12) + yrCounter; pos = 24 * hoursWidthOnXAxis + pos; var _val = date === 1 ? Utils.monthMod(month) : date; this.timeScaleArray.push({ position: pos, value: _val, unit: unit, year: year, month: Utils.monthMod(month), day: _val }); } } }, { key: "generateHourScale", value: function generateHourScale(params) { var firstVal = params.firstVal, currentDate = params.currentDate, currentMonth = params.currentMonth, currentYear = params.currentYear, minutesWidthOnXAxis = params.minutesWidthOnXAxis, numberOfHours = params.numberOfHours; var dt = new DateTime(this.ctx); var yrCounter = 0; var unit = 'hour'; var changeDate = function changeDate(dateVal, month) { var monthdays = dt.determineDaysOfMonths(month + 1, currentYear); if (dateVal > monthdays) { date = 1; month = month + 1; } return { month: month, date: date }; }; var changeMonth = function changeMonth(dateVal, month) { var monthdays = dt.determineDaysOfMonths(month + 1, currentYear); if (dateVal > monthdays) { month = month + 1; return month; } return month; }; var remainingMins = 60 - firstVal.minMinute; var firstTickPosition = remainingMins * minutesWidthOnXAxis; var firstTickValue = firstVal.minHour + 1; var hour = firstTickValue + 1; if (remainingMins === 60) { firstTickPosition = 0; firstTickValue = firstVal.minHour; hour = firstTickValue + 1; } var date = currentDate; var month = changeMonth(date, currentMonth); // push the first tick in the array this.timeScaleArray.push({ position: firstTickPosition, value: firstTickValue, unit: unit, day: date, hour: hour, year: currentYear, month: Utils.monthMod(month) }); var pos = firstTickPosition; // keep drawing rest of the ticks for (var i = 0; i < numberOfHours; i++) { unit = 'hour'; if (hour >= 24) { hour = 0; date += 1; unit = 'day'; var checkNextMonth = changeDate(date, month); month = checkNextMonth.month; month = changeMonth(date, month); } var year = currentYear + Math.floor(month / 12) + yrCounter; pos = hour === 0 && i === 0 ? remainingMins * minutesWidthOnXAxis : 60 * minutesWidthOnXAxis + pos; var val = hour === 0 ? date : hour; this.timeScaleArray.push({ position: pos, value: val, unit: unit, hour: hour, day: date, year: year, month: Utils.monthMod(month) }); hour++; } } }, { key: "generateMinuteScale", value: function generateMinuteScale(params) { var firstVal = params.firstVal, currentMinute = params.currentMinute, currentHour = params.currentHour, currentDate = params.currentDate, currentMonth = params.currentMonth, currentYear = params.currentYear, minutesWidthOnXAxis = params.minutesWidthOnXAxis, numberOfMinutes = params.numberOfMinutes; var yrCounter = 0; var unit = 'minute'; var remainingMins = currentMinute - firstVal.minMinute; var firstTickPosition = minutesWidthOnXAxis - remainingMins; var firstTickValue = firstVal.minMinute + 1; var minute = firstTickValue + 1; var date = currentDate; var month = currentMonth; var year = currentYear; var hour = currentHour; // push the first tick in the array this.timeScaleArray.push({ position: firstTickPosition, value: firstTickValue, unit: unit, day: date, hour: hour, minute: minute, year: year, month: Utils.monthMod(month) }); var pos = firstTickPosition; // keep drawing rest of the ticks for (var i = 0; i < numberOfMinutes; i++) { if (minute >= 60) { minute = 0; hour += 1; if (hour === 24) { hour = 0; } } var _year2 = currentYear + Math.floor(month / 12) + yrCounter; pos = minutesWidthOnXAxis + pos; var val = minute; this.timeScaleArray.push({ position: pos, value: val, unit: unit, hour: hour, minute: minute, day: date, year: _year2, month: Utils.monthMod(month) }); minute++; } } }, { key: "createRawDateString", value: function createRawDateString(ts, value) { var raw = ts.year; raw += '-' + ('0' + ts.month.toString()).slice(-2); // unit is day if (ts.unit === 'day') { raw += ts.unit === 'day' ? '-' + ('0' + value).slice(-2) : '-01'; } else { raw += '-' + ('0' + (ts.day ? ts.day : '1')).slice(-2); } // unit is hour if (ts.unit === 'hour') { raw += ts.unit === 'hour' ? 'T' + ('0' + value).slice(-2) : 'T00'; } else { raw += 'T' + ('0' + (ts.hour ? ts.hour : '0')).slice(-2); } // unit is minute raw += ts.unit === 'minute' ? ':' + ('0' + value).slice(-2) + ':00.000Z' : ':00:00.000Z'; return raw; } }, { key: "formatDates", value: function formatDates(filteredTimeScale) { var _this2 = this; var w = this.w; var reformattedTimescaleArray = filteredTimeScale.map(function (ts) { var value = ts.value.toString(); var dt = new DateTime(_this2.ctx); var raw = _this2.createRawDateString(ts, value); // parse the whole ISO datestring var dateString = new Date(Date.parse(raw)); if (w.config.xaxis.labels.format === undefined) { var customFormat = 'dd MMM'; var dtFormatter = w.config.xaxis.labels.datetimeFormatter; if (ts.unit === 'year') customFormat = dtFormatter.year; if (ts.unit === 'month') customFormat = dtFormatter.month; if (ts.unit === 'day') customFormat = dtFormatter.day; if (ts.unit === 'hour') customFormat = dtFormatter.hour; if (ts.unit === 'minute') customFormat = dtFormatter.minute; value = dt.formatDate(dateString, customFormat, true, false); } else { value = dt.formatDate(dateString, w.config.xaxis.labels.format); } return { dateString: raw, position: ts.position, value: value, unit: ts.unit, year: ts.year, month: ts.month }; }); return reformattedTimescaleArray; } }, { key: "removeOverlappingTS", value: function removeOverlappingTS(arr) { var _this3 = this; var graphics = new Graphics(this.ctx); var lastDrawnIndex = 0; var filteredArray = arr.map(function (item, index) { if (index > 0 && _this3.w.config.xaxis.labels.hideOverlappingLabels) { var prevLabelWidth = graphics.getTextRects(arr[lastDrawnIndex].value).width; var prevPos = arr[lastDrawnIndex].position; var pos = item.position; if (pos > prevPos + prevLabelWidth + 10) { lastDrawnIndex = index; return item; } else { return null; } } else { return item; } }); filteredArray = filteredArray.filter(function (f) { return f !== null; }); return filteredArray; } }]); return TimeScale; }(); /** * ApexCharts Core Class responsible for major calculations and creating elements. * * @module Core **/ var Core = /*#__PURE__*/ function () { function Core(el, ctx) { _classCallCheck(this, Core); this.ctx = ctx; this.w = ctx.w; this.el = el; this.coreUtils = new CoreUtils(this.ctx); this.twoDSeries = []; this.threeDSeries = []; this.twoDSeriesX = []; } // get data and store into appropriate vars _createClass(Core, [{ key: "setupElements", value: function setupElements() { var gl = this.w.globals; var cnf = this.w.config; // const graphics = new Graphics(this.ctx) var ct = cnf.chart.type; var axisChartsArrTypes = ['line', 'area', 'bar', 'rangeBar', // 'rangeArea', 'candlestick', 'radar', 'scatter', 'bubble', 'heatmap']; var xyChartsArrTypes = ['line', 'area', 'bar', 'rangeBar', // 'rangeArea', 'candlestick', 'scatter', 'bubble']; gl.axisCharts = axisChartsArrTypes.indexOf(ct) > -1; gl.xyCharts = xyChartsArrTypes.indexOf(ct) > -1; gl.isBarHorizontal = (cnf.chart.type === 'bar' || cnf.chart.type === 'rangeBar') && cnf.plotOptions.bar.horizontal; gl.chartClass = '.apexcharts' + gl.cuid; gl.dom.baseEl = this.el; gl.dom.elWrap = document.createElement('div'); Graphics.setAttrs(gl.dom.elWrap, { id: gl.chartClass.substring(1), class: 'apexcharts-canvas ' + gl.chartClass.substring(1) }); this.el.appendChild(gl.dom.elWrap); gl.dom.Paper = new window.SVG.Doc(gl.dom.elWrap); gl.dom.Paper.attr({ class: 'apexcharts-svg', 'xmlns:data': 'ApexChartsNS', transform: "translate(".concat(cnf.chart.offsetX, ", ").concat(cnf.chart.offsetY, ")") }); gl.dom.Paper.node.style.background = cnf.chart.background; this.setSVGDimensions(); gl.dom.elGraphical = gl.dom.Paper.group().attr({ class: 'apexcharts-inner apexcharts-graphical' }); gl.dom.elDefs = gl.dom.Paper.defs(); gl.dom.elLegendWrap = document.createElement('div'); gl.dom.elLegendWrap.classList.add('apexcharts-legend'); gl.dom.elWrap.appendChild(gl.dom.elLegendWrap); // gl.dom.Paper.add(gl.dom.elLegendWrap) gl.dom.Paper.add(gl.dom.elGraphical); gl.dom.elGraphical.add(gl.dom.elDefs); } }, { key: "plotChartType", value: function plotChartType(ser, xyRatios) { var w = this.w; var cnf = w.config; var gl = w.globals; var lineSeries = { series: [], i: [] }; var areaSeries = { series: [], i: [] }; var scatterSeries = { series: [], i: [] }; var columnSeries = { series: [], i: [] }; var candlestickSeries = { series: [], i: [] }; gl.series.map(function (series, st) { // if user has specified a particular type for particular series if (typeof ser[st].type !== 'undefined') { if (ser[st].type === 'column' || ser[st].type === 'bar') { w.config.plotOptions.bar.horizontal = false; // horizontal bars not supported in mixed charts, hence forcefully set to false columnSeries.series.push(series); columnSeries.i.push(st); } else if (ser[st].type === 'area') { areaSeries.series.push(series); areaSeries.i.push(st); } else if (ser[st].type === 'line') { lineSeries.series.push(series); lineSeries.i.push(st); } else if (ser[st].type === 'scatter') { scatterSeries.series.push(series); scatterSeries.i.push(st); } else if (ser[st].type === 'bubble') ; else if (ser[st].type === 'candlestick') { candlestickSeries.series.push(series); candlestickSeries.i.push(st); } else { // user has specified type, but it is not valid (other than line/area/column) console.warn('You have specified an unrecognized chart type. Available types for this propery are line/area/column/bar/scatter/bubble'); } gl.comboCharts = true; } else { lineSeries.series.push(series); lineSeries.i.push(st); } }); var line = new Line(this.ctx, xyRatios); var candlestick = new CandleStick(this.ctx, xyRatios); var pie = new Pie(this.ctx); var radialBar = new Radial(this.ctx); var rangeBar = new RangeBar(this.ctx, xyRatios); var radar = new Radar(this.ctx); var elGraph = []; if (gl.comboCharts) { if (areaSeries.series.length > 0) { elGraph.push(line.draw(areaSeries.series, 'area', areaSeries.i)); } if (columnSeries.series.length > 0) { if (w.config.chart.stacked) { var barStacked = new BarStacked(this.ctx, xyRatios); elGraph.push(barStacked.draw(columnSeries.series, columnSeries.i)); } else { var bar = new Bar(this.ctx, xyRatios); elGraph.push(bar.draw(columnSeries.series, columnSeries.i)); } } if (lineSeries.series.length > 0) { elGraph.push(line.draw(lineSeries.series, 'line', lineSeries.i)); } if (candlestickSeries.series.length > 0) { elGraph.push(candlestick.draw(candlestickSeries.series, candlestickSeries.i)); } if (scatterSeries.series.length > 0) { var scatterLine = new Line(this.ctx, xyRatios, true); elGraph.push(scatterLine.draw(scatterSeries.series, 'scatter', scatterSeries.i)); } // TODO: allow bubble series in a combo chart // if (bubbleSeries.series.length > 0) { // const bubbleLine = new Line(this.ctx, xyRatios, true) // elGraph.push( // bubbleLine.draw(bubbleSeries.series, 'bubble', bubbleSeries.i) // ) // } } else { switch (cnf.chart.type) { case 'line': elGraph = line.draw(gl.series, 'line'); break; case 'area': elGraph = line.draw(gl.series, 'area'); break; case 'bar': if (cnf.chart.stacked) { var _barStacked = new BarStacked(this.ctx, xyRatios); elGraph = _barStacked.draw(gl.series); } else { var _bar = new Bar(this.ctx, xyRatios); elGraph = _bar.draw(gl.series); } break; case 'candlestick': var candleStick = new CandleStick(this.ctx, xyRatios); elGraph = candleStick.draw(gl.series); break; case 'rangeBar': elGraph = rangeBar.draw(gl.series); break; case 'heatmap': var heatmap = new HeatMap(this.ctx, xyRatios); elGraph = heatmap.draw(gl.series); break; case 'pie': case 'donut': elGraph = pie.draw(gl.series); break; case 'radialBar': elGraph = radialBar.draw(gl.series); break; case 'radar': elGraph = radar.draw(gl.series); break; default: elGraph = line.draw(gl.series); } } return elGraph; } }, { key: "setSVGDimensions", value: function setSVGDimensions() { var gl = this.w.globals; var cnf = this.w.config; gl.svgWidth = cnf.chart.width; gl.svgHeight = cnf.chart.height; var elDim = Utils.getDimensions(this.el); var widthUnit = cnf.chart.width.toString().split(/[0-9]+/g).pop(); if (widthUnit === '%') { if (Utils.isNumber(elDim[0])) { if (elDim[0].width === 0) { elDim = Utils.getDimensions(this.el.parentNode); } gl.svgWidth = elDim[0] * parseInt(cnf.chart.width) / 100; } } else if (widthUnit === 'px' || widthUnit === '') { gl.svgWidth = parseInt(cnf.chart.width); } if (gl.svgHeight !== 'auto' && gl.svgHeight !== '') { var heightUnit = cnf.chart.height.toString().split(/[0-9]+/g).pop(); if (heightUnit === '%') { var elParentDim = Utils.getDimensions(this.el.parentNode); gl.svgHeight = elParentDim[1] * parseInt(cnf.chart.height) / 100; } else { gl.svgHeight = parseInt(cnf.chart.height); } } else { if (gl.axisCharts) { gl.svgHeight = gl.svgWidth / 1.61; } else { gl.svgHeight = gl.svgWidth; } } Graphics.setAttrs(gl.dom.Paper.node, { width: gl.svgWidth, height: gl.svgHeight }); // gl.dom.Paper.node.parentNode.parentNode.style.minWidth = gl.svgWidth + "px"; var offsetY = cnf.chart.sparkline.enabled ? 0 : gl.axisCharts ? cnf.chart.parentHeightOffset : 0; gl.dom.Paper.node.parentNode.parentNode.style.minHeight = gl.svgHeight + offsetY + 'px'; gl.dom.elWrap.style.width = gl.svgWidth + 'px'; gl.dom.elWrap.style.height = gl.svgHeight + 'px'; } }, { key: "shiftGraphPosition", value: function shiftGraphPosition() { var gl = this.w.globals; var tY = gl.translateY; var tX = gl.translateX; var scalingAttrs = { transform: 'translate(' + tX + ', ' + tY + ')' }; Graphics.setAttrs(gl.dom.elGraphical.node, scalingAttrs); } /* ** All the calculations for setting range in charts will be done here */ }, { key: "coreCalculations", value: function coreCalculations() { var range = new Range$1(this.ctx); range.init(); } }, { key: "resetGlobals", value: function resetGlobals() { var _this = this; var gl = this.w.globals; gl.series = []; gl.seriesCandleO = []; gl.seriesCandleH = []; gl.seriesCandleL = []; gl.seriesCandleC = []; gl.seriesRangeStart = []; gl.seriesRangeEnd = []; gl.seriesPercent = []; gl.seriesX = []; gl.seriesZ = []; gl.seriesNames = []; gl.seriesTotals = []; gl.stackedSeriesTotals = []; gl.labels = []; gl.timelineLabels = []; gl.noLabelsProvided = false; gl.timescaleTicks = []; gl.resizeTimer = null; gl.selectionResizeTimer = null; gl.seriesXvalues = function () { return _this.w.config.series.map(function (s) { return []; }); }(); gl.seriesYvalues = function () { return _this.w.config.series.map(function (s) { return []; }); }(); gl.delayedElements = []; gl.pointsArray = []; gl.dataLabelsRects = []; gl.isXNumeric = false; gl.isDataXYZ = false; gl.maxY = -Number.MAX_VALUE; gl.minY = Number.MIN_VALUE; gl.minYArr = []; gl.maxYArr = []; gl.maxX = -Number.MAX_VALUE; gl.minX = Number.MAX_VALUE; gl.initialmaxX = -Number.MAX_VALUE; gl.initialminX = Number.MAX_VALUE; gl.maxDate = 0; gl.minDate = Number.MAX_VALUE; gl.minZ = Number.MAX_VALUE; gl.maxZ = -Number.MAX_VALUE; gl.minXDiff = Number.MAX_VALUE; gl.yAxisScale = []; gl.xAxisScale = null; gl.xAxisTicksPositions = []; gl.yLabelsCoords = []; gl.yTitleCoords = []; gl.xRange = 0; gl.yRange = []; gl.zRange = 0; gl.dataPoints = 0; } }, { key: "isMultipleY", value: function isMultipleY() { // user has supplied an array in yaxis property. So, turn on multipleYAxis flag if (this.w.config.yaxis.constructor === Array && this.w.config.yaxis.length > 1) { // first, turn off stacking if multiple y axis this.w.config.chart.stacked = false; this.w.globals.isMultipleYAxis = true; return true; } } }, { key: "excludeCollapsedSeriesInYAxis", value: function excludeCollapsedSeriesInYAxis() { var _this2 = this; var w = this.w; w.globals.ignoreYAxisIndexes = w.globals.collapsedSeries.map(function (collapsed, i) { if (_this2.w.globals.isMultipleYAxis) { return collapsed.index; } }); } }, { key: "isMultiFormat", value: function isMultiFormat() { return this.isFormatXY() || this.isFormat2DArray(); } // given format is [{x, y}, {x, y}] }, { key: "isFormatXY", value: function isFormatXY() { var series = this.w.config.series.slice(); var sr = new Series(this.ctx); this.activeSeriesIndex = sr.getActiveConfigSeriesIndex(); if (typeof series[this.activeSeriesIndex].data !== 'undefined' && series[this.activeSeriesIndex].data.length > 0 && series[this.activeSeriesIndex].data[0] !== null && typeof series[this.activeSeriesIndex].data[0].x !== 'undefined' && series[this.activeSeriesIndex].data[0] !== null) { return true; } } // given format is [[x, y], [x, y]] }, { key: "isFormat2DArray", value: function isFormat2DArray() { var series = this.w.config.series.slice(); var sr = new Series(this.ctx); this.activeSeriesIndex = sr.getActiveConfigSeriesIndex(); if (typeof series[this.activeSeriesIndex].data !== 'undefined' && series[this.activeSeriesIndex].data.length > 0 && typeof series[this.activeSeriesIndex].data[0] !== 'undefined' && series[this.activeSeriesIndex].data[0] !== null && series[this.activeSeriesIndex].data[0].constructor === Array) { return true; } } }, { key: "handleFormat2DArray", value: function handleFormat2DArray(ser, i) { var cnf = this.w.config; var gl = this.w.globals; for (var j = 0; j < ser[i].data.length; j++) { if (typeof ser[i].data[j][1] !== 'undefined') { if (Array.isArray(ser[i].data[j][1]) && ser[i].data[j][1].length === 4) { this.twoDSeries.push(Utils.parseNumber(ser[i].data[j][1][3])); } else { this.twoDSeries.push(Utils.parseNumber(ser[i].data[j][1])); } gl.dataFormatXNumeric = true; } if (cnf.xaxis.type === 'datetime') { // if timestamps are provided and xaxis type is datettime, var ts = new Date(ser[i].data[j][0]); ts = new Date(ts).getTime(); this.twoDSeriesX.push(ts); } else { this.twoDSeriesX.push(ser[i].data[j][0]); } } for (var _j = 0; _j < ser[i].data.length; _j++) { if (typeof ser[i].data[_j][2] !== 'undefined') { this.threeDSeries.push(ser[i].data[_j][2]); gl.isDataXYZ = true; } } } }, { key: "handleFormatXY", value: function handleFormatXY(ser, i) { var cnf = this.w.config; var gl = this.w.globals; var dt = new DateTime(this.ctx); var activeI = i; if (gl.collapsedSeriesIndices.indexOf(i) > -1) { // fix #368 activeI = this.activeSeriesIndex; } // get series for (var j = 0; j < ser[i].data.length; j++) { if (typeof ser[i].data[j].y !== 'undefined') { if (Array.isArray(ser[i].data[j].y)) { this.twoDSeries.push(Utils.parseNumber(ser[i].data[j].y[ser[i].data[j].y.length - 1])); } else { this.twoDSeries.push(Utils.parseNumber(ser[i].data[j].y)); } } } // get seriesX for (var _j2 = 0; _j2 < ser[activeI].data.length; _j2++) { var isXString = typeof ser[activeI].data[_j2].x === 'string'; var isXDate = !!dt.isValidDate(ser[activeI].data[_j2].x.toString()); if (isXString || isXDate) { // user supplied '01/01/2017' or a date string (a JS date object is not supported) if (isXString) { if (cnf.xaxis.type === 'datetime' && !gl.isRangeData) { this.twoDSeriesX.push(dt.parseDate(ser[activeI].data[_j2].x)); } else { // a category and not a numeric x value this.fallbackToCategory = true; this.twoDSeriesX.push(ser[activeI].data[_j2].x); } } else { if (cnf.xaxis.type === 'datetime') { this.twoDSeriesX.push(dt.parseDate(ser[activeI].data[_j2].x.toString())); } else { gl.dataFormatXNumeric = true; gl.isXNumeric = true; this.twoDSeriesX.push(parseFloat(ser[activeI].data[_j2].x)); } } } else { // a numeric value in x property gl.isXNumeric = true; gl.dataFormatXNumeric = true; this.twoDSeriesX.push(ser[activeI].data[_j2].x); } } if (ser[i].data[0] && typeof ser[i].data[0].z !== 'undefined') { for (var t = 0; t < ser[i].data.length; t++) { this.threeDSeries.push(ser[i].data[t].z); } gl.isDataXYZ = true; } } }, { key: "handleRangeData", value: function handleRangeData(ser, i) { var gl = this.w.globals; var range = {}; if (this.isFormat2DArray()) { range = this.handleRangeDataFormat('array', ser, i); } else if (this.isFormatXY()) { range = this.handleRangeDataFormat('xy', ser, i); } gl.seriesRangeStart.push(range.start); gl.seriesRangeEnd.push(range.end); return range; } }, { key: "handleCandleStickData", value: function handleCandleStickData(ser, i) { var gl = this.w.globals; var ohlc = {}; if (this.isFormat2DArray()) { ohlc = this.handleCandleStickDataFormat('array', ser, i); } else if (this.isFormatXY()) { ohlc = this.handleCandleStickDataFormat('xy', ser, i); } gl.seriesCandleO.push(ohlc.o); gl.seriesCandleH.push(ohlc.h); gl.seriesCandleL.push(ohlc.l); gl.seriesCandleC.push(ohlc.c); return ohlc; } }, { key: "handleRangeDataFormat", value: function handleRangeDataFormat(format, ser, i) { var rangeStart = []; var rangeEnd = []; var err = 'Please provide [Start, End] values in valid format. Read more https://apexcharts.com/docs/series/#rangecharts'; var serObj = new Series(this.ctx); var activeIndex = serObj.getActiveConfigSeriesIndex(); if (format === 'array') { if (ser[activeIndex].data[0][1].length !== 2) { throw new Error(err); } for (var j = 0; j < ser[i].data.length; j++) { rangeStart.push(ser[i].data[j][1][0]); rangeEnd.push(ser[i].data[j][1][1]); } } else if (format === 'xy') { if (ser[activeIndex].data[0].y.length !== 2) { throw new Error(err); } for (var _j3 = 0; _j3 < ser[i].data.length; _j3++) { rangeStart.push(ser[i].data[_j3].y[0]); rangeEnd.push(ser[i].data[_j3].y[1]); } } return { start: rangeStart, end: rangeEnd }; } }, { key: "handleCandleStickDataFormat", value: function handleCandleStickDataFormat(format, ser, i) { var serO = []; var serH = []; var serL = []; var serC = []; var err = 'Please provide [Open, High, Low and Close] values in valid format. Read more https://apexcharts.com/docs/series/#candlestick'; if (format === 'array') { if (ser[i].data[0][1].length !== 4) { throw new Error(err); } for (var j = 0; j < ser[i].data.length; j++) { serO.push(ser[i].data[j][1][0]); serH.push(ser[i].data[j][1][1]); serL.push(ser[i].data[j][1][2]); serC.push(ser[i].data[j][1][3]); } } else if (format === 'xy') { if (ser[i].data[0].y.length !== 4) { throw new Error(err); } for (var _j4 = 0; _j4 < ser[i].data.length; _j4++) { serO.push(ser[i].data[_j4].y[0]); serH.push(ser[i].data[_j4].y[1]); serL.push(ser[i].data[_j4].y[2]); serC.push(ser[i].data[_j4].y[3]); } } return { o: serO, h: serH, l: serL, c: serC }; } }, { key: "parseDataAxisCharts", value: function parseDataAxisCharts(ser) { var ctx = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : this.ctx; var cnf = this.w.config; var gl = this.w.globals; var dt = new DateTime(ctx); for (var i = 0; i < ser.length; i++) { this.twoDSeries = []; this.twoDSeriesX = []; this.threeDSeries = []; if (typeof ser[i].data === 'undefined') { console.error("It is a possibility that you may have not included 'data' property in series."); return; } if (cnf.chart.type === 'rangeBar' || cnf.chart.type === 'rangeArea' || ser[i].type === 'rangeBar' || ser[i].type === 'rangeArea') { gl.isRangeData = true; this.handleRangeData(ser, i); } if (this.isMultiFormat()) { if (this.isFormat2DArray()) { this.handleFormat2DArray(ser, i); } else if (this.isFormatXY()) { this.handleFormatXY(ser, i); } if (cnf.chart.type === 'candlestick' || ser[i].type === 'candlestick') { this.handleCandleStickData(ser, i); } gl.series.push(this.twoDSeries); gl.labels.push(this.twoDSeriesX); gl.seriesX.push(this.twoDSeriesX); if (!this.fallbackToCategory) { gl.isXNumeric = true; } } else { if (cnf.xaxis.type === 'datetime') { // user didn't supplied [{x,y}] or [[x,y]], but single array in data. // Also labels/categories were supplied differently gl.isXNumeric = true; var dates = cnf.labels.length > 0 ? cnf.labels.slice() : cnf.xaxis.categories.slice(); for (var j = 0; j < dates.length; j++) { if (typeof dates[j] === 'string') { var isDate = dt.isValidDate(dates[j]); if (isDate) { this.twoDSeriesX.push(dt.parseDate(dates[j])); } else { throw new Error('You have provided invalid Date format. Please provide a valid JavaScript Date'); } } } gl.seriesX.push(this.twoDSeriesX); } else if (cnf.xaxis.type === 'numeric') { gl.isXNumeric = true; var x = cnf.labels.length > 0 ? cnf.labels.slice() : cnf.xaxis.categories.slice(); if (x.length > 0) { this.twoDSeriesX = x; gl.seriesX.push(this.twoDSeriesX); } } gl.labels.push(this.twoDSeriesX); var singleArray = ser[i].data.map(function (d) { return Utils.parseNumber(d); }); gl.series.push(singleArray); } gl.seriesZ.push(this.threeDSeries); if (ser[i].name !== undefined) { gl.seriesNames.push(ser[i].name); } else { gl.seriesNames.push('series-' + parseInt(i + 1)); } } return this.w; } }, { key: "parseDataNonAxisCharts", value: function parseDataNonAxisCharts(ser) { var gl = this.w.globals; var cnf = this.w.config; gl.series = ser.slice(); gl.seriesNames = cnf.labels.slice(); for (var i = 0; i < gl.series.length; i++) { if (gl.seriesNames[i] === undefined) { gl.seriesNames.push('series-' + (i + 1)); } } return this.w; } /** User possibly set string categories in xaxis.categories or labels prop * Or didn't set xaxis labels at all - in which case we manually do it. * If user passed series data as [[3, 2], [4, 5]] or [{ x: 3, y: 55 }], * this shouldn't be called * @param {array} ser - the series which user passed to the config */ }, { key: "handleExternalLabelsData", value: function handleExternalLabelsData(ser) { var cnf = this.w.config; var gl = this.w.globals; if (cnf.xaxis.categories.length > 0) { // user provided labels in xaxis.category prop gl.labels = cnf.xaxis.categories; } else if (cnf.labels.length > 0) { // user provided labels in labels props gl.labels = cnf.labels.slice(); } else if (this.fallbackToCategory) { // user provided labels in x prop in [{ x: 3, y: 55 }] data, and those labels are already stored in gl.labels[0], so just re-arrange the gl.labels array gl.labels = gl.labels[0]; } else { // user didn't provided any labels, fallback to 1-2-3-4-5 var labelArr = []; if (gl.axisCharts) { // for axis charts, we get the longest series and create labels from it for (var i = 0; i < gl.series[gl.maxValsInArrayIndex].length; i++) { labelArr.push(i + 1); } // create gl.seriesX as it will be used in calculations of x positions for (var _i = 0; _i < ser.length; _i++) { gl.seriesX.push(labelArr); } // turn on the isXNumeric flag to allow minX and maxX to function properly gl.isXNumeric = true; } // no series to pull labels from, put a 0-10 series // possibly, user collapsed all series. Hence we can't work with above calc if (labelArr.length === 0) { labelArr = [0, 10]; for (var _i2 = 0; _i2 < ser.length; _i2++) { gl.seriesX.push(labelArr); } } // Finally, pass the labelArr in gl.labels which will be printed on x-axis gl.labels = labelArr; // Turn on this global flag to indicate no labels were provided by user gl.noLabelsProvided = true; } } // Segregate user provided data into appropriate vars }, { key: "parseData", value: function parseData(ser) { var w = this.w; var cnf = w.config; var gl = w.globals; this.excludeCollapsedSeriesInYAxis(); // If we detected string in X prop of series, we fallback to category x-axis this.fallbackToCategory = false; this.resetGlobals(); this.isMultipleY(); if (gl.axisCharts) { // axisCharts includes line / area / column / scatter this.parseDataAxisCharts(ser); } else { // non-axis charts are pie / donut this.parseDataNonAxisCharts(ser); } this.coreUtils.getLargestSeries(); // set Null values to 0 in all series when user hides/shows some series if (cnf.chart.type === 'bar' && cnf.chart.stacked) { var series = new Series(this.ctx); gl.series = series.setNullSeriesToZeroValues(gl.series); } this.coreUtils.getSeriesTotals(); if (gl.axisCharts) { this.coreUtils.getStackedSeriesTotals(); } this.coreUtils.getPercentSeries(); if (!gl.dataFormatXNumeric && (!gl.isXNumeric || cnf.xaxis.type === 'numeric' && cnf.labels.length === 0 && cnf.xaxis.categories.length === 0)) { // x-axis labels couldn't be detected; hence try searching every option in config this.handleExternalLabelsData(ser); } } }, { key: "xySettings", value: function xySettings() { var xyRatios = null; var w = this.w; if (w.globals.axisCharts) { if (w.config.xaxis.crosshairs.position === 'back') { var crosshairs = new Crosshairs(this.ctx); crosshairs.drawXCrosshairs(); } if (w.config.yaxis[0].crosshairs.position === 'back') { var _crosshairs = new Crosshairs(this.ctx); _crosshairs.drawYCrosshairs(); } xyRatios = this.coreUtils.getCalculatedRatios(); if (w.config.xaxis.type === 'datetime' && w.config.xaxis.labels.formatter === undefined) { var ts = new TimeScale(this.ctx); var formattedTimeScale; if (isFinite(w.globals.minX) && isFinite(w.globals.maxX) && !w.globals.isBarHorizontal) { formattedTimeScale = ts.calculateTimeScaleTicks(w.globals.minX, w.globals.maxX); ts.recalcDimensionsBasedOnFormat(formattedTimeScale, false); } else if (w.globals.isBarHorizontal) { formattedTimeScale = ts.calculateTimeScaleTicks(w.globals.minY, w.globals.maxY); ts.recalcDimensionsBasedOnFormat(formattedTimeScale, true); } } } return xyRatios; } }, { key: "drawAxis", value: function drawAxis(type, xyRatios) { var gl = this.w.globals; var cnf = this.w.config; var xAxis = new XAxis(this.ctx); var yAxis = new YAxis(this.ctx); if (gl.axisCharts && type !== 'radar') { var elXaxis, elYaxis; if (gl.isBarHorizontal) { elYaxis = yAxis.drawYaxisInversed(0); elXaxis = xAxis.drawXaxisInversed(0); gl.dom.elGraphical.add(elXaxis); gl.dom.elGraphical.add(elYaxis); } else { elXaxis = xAxis.drawXaxis(); gl.dom.elGraphical.add(elXaxis); cnf.yaxis.map(function (yaxe, index) { if (gl.ignoreYAxisIndexes.indexOf(index) === -1) { elYaxis = yAxis.drawYaxis(index); gl.dom.Paper.add(elYaxis); } }); } } cnf.yaxis.map(function (yaxe, index) { if (gl.ignoreYAxisIndexes.indexOf(index) === -1) { yAxis.yAxisTitleRotate(index, yaxe.opposite); } }); } }, { key: "setupBrushHandler", value: function setupBrushHandler() { var _this3 = this; var w = this.w; // only for brush charts if (!w.config.chart.brush.enabled) { return; } // if user has not defined a custom function for selection - we handle the brush chart // otherwise we leave it to the user to define the functionality for selection if (typeof w.config.chart.events.selection !== 'function') { var targets = w.config.chart.brush.targets || [w.config.chart.brush.target]; // retro compatibility with single target option targets.forEach(function (target) { var targetChart = ApexCharts.getChartByID(target); targetChart.w.globals.brushSource = _this3.ctx; var updateSourceChart = function updateSourceChart() { _this3.ctx._updateOptions({ chart: { selection: { xaxis: { min: targetChart.w.globals.minX, max: targetChart.w.globals.maxX } } } }, false, false); }; if (typeof targetChart.w.config.chart.events.zoomed !== 'function') { targetChart.w.config.chart.events.zoomed = function () { updateSourceChart(); }; } if (typeof targetChart.w.config.chart.events.scrolled !== 'function') { targetChart.w.config.chart.events.scrolled = function () { updateSourceChart(); }; } w.config.chart.events.selection = function (chart, e) { var yaxis = Utils.clone(w.config.yaxis); if (w.config.chart.brush.autoScaleYaxis) { var scale = new Range(targetChart); yaxis = scale.autoScaleY(targetChart, e); } targetChart._updateOptions({ xaxis: { min: e.xaxis.min, max: e.xaxis.max }, yaxis: yaxis }, false, false, false); }; }); } } }]); return Core; }(); /** * @this {Promise} */ function finallyConstructor(callback) { var constructor = this.constructor; return this.then( function(value) { return constructor.resolve(callback()).then(function() { return value; }); }, function(reason) { return constructor.resolve(callback()).then(function() { return constructor.reject(reason); }); } ); } // Store setTimeout reference so promise-polyfill will be unaffected by // other code modifying setTimeout (like sinon.useFakeTimers()) var setTimeoutFunc = setTimeout; function noop() {} // Polyfill for Function.prototype.bind function bind(fn, thisArg) { return function() { fn.apply(thisArg, arguments); }; } /** * @constructor * @param {Function} fn */ function Promise$1(fn) { if (!(this instanceof Promise$1)) throw new TypeError('Promises must be constructed via new'); if (typeof fn !== 'function') throw new TypeError('not a function'); /** @type {!number} */ this._state = 0; /** @type {!boolean} */ this._handled = false; /** @type {Promise|undefined} */ this._value = undefined; /** @type {!Array<!Function>} */ this._deferreds = []; doResolve(fn, this); } function handle(self, deferred) { while (self._state === 3) { self = self._value; } if (self._state === 0) { self._deferreds.push(deferred); return; } self._handled = true; Promise$1._immediateFn(function() { var cb = self._state === 1 ? deferred.onFulfilled : deferred.onRejected; if (cb === null) { (self._state === 1 ? resolve : reject)(deferred.promise, self._value); return; } var ret; try { ret = cb(self._value); } catch (e) { reject(deferred.promise, e); return; } resolve(deferred.promise, ret); }); } function resolve(self, newValue) { try { // Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.'); if ( newValue && (typeof newValue === 'object' || typeof newValue === 'function') ) { var then = newValue.then; if (newValue instanceof Promise$1) { self._state = 3; self._value = newValue; finale(self); return; } else if (typeof then === 'function') { doResolve(bind(then, newValue), self); return; } } self._state = 1; self._value = newValue; finale(self); } catch (e) { reject(self, e); } } function reject(self, newValue) { self._state = 2; self._value = newValue; finale(self); } function finale(self) { if (self._state === 2 && self._deferreds.length === 0) { Promise$1._immediateFn(function() { if (!self._handled) { Promise$1._unhandledRejectionFn(self._value); } }); } for (var i = 0, len = self._deferreds.length; i < len; i++) { handle(self, self._deferreds[i]); } self._deferreds = null; } /** * @constructor */ function Handler(onFulfilled, onRejected, promise) { this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null; this.onRejected = typeof onRejected === 'function' ? onRejected : null; this.promise = promise; } /** * Take a potentially misbehaving resolver function and make sure * onFulfilled and onRejected are only called once. * * Makes no guarantees about asynchrony. */ function doResolve(fn, self) { var done = false; try { fn( function(value) { if (done) return; done = true; resolve(self, value); }, function(reason) { if (done) return; done = true; reject(self, reason); } ); } catch (ex) { if (done) return; done = true; reject(self, ex); } } Promise$1.prototype['catch'] = function(onRejected) { return this.then(null, onRejected); }; Promise$1.prototype.then = function(onFulfilled, onRejected) { // @ts-ignore var prom = new this.constructor(noop); handle(this, new Handler(onFulfilled, onRejected, prom)); return prom; }; Promise$1.prototype['finally'] = finallyConstructor; Promise$1.all = function(arr) { return new Promise$1(function(resolve, reject) { if (!arr || typeof arr.length === 'undefined') throw new TypeError('Promise.all accepts an array'); var args = Array.prototype.slice.call(arr); if (args.length === 0) return resolve([]); var remaining = args.length; function res(i, val) { try { if (val && (typeof val === 'object' || typeof val === 'function')) { var then = val.then; if (typeof then === 'function') { then.call( val, function(val) { res(i, val); }, reject ); return; } } args[i] = val; if (--remaining === 0) { resolve(args); } } catch (ex) { reject(ex); } } for (var i = 0; i < args.length; i++) { res(i, args[i]); } }); }; Promise$1.resolve = function(value) { if (value && typeof value === 'object' && value.constructor === Promise$1) { return value; } return new Promise$1(function(resolve) { resolve(value); }); }; Promise$1.reject = function(value) { return new Promise$1(function(resolve, reject) { reject(value); }); }; Promise$1.race = function(values) { return new Promise$1(function(resolve, reject) { for (var i = 0, len = values.length; i < len; i++) { values[i].then(resolve, reject); } }); }; // Use polyfill for setImmediate for performance gains Promise$1._immediateFn = (typeof setImmediate === 'function' && function(fn) { setImmediate(fn); }) || function(fn) { setTimeoutFunc(fn, 0); }; Promise$1._unhandledRejectionFn = function _unhandledRejectionFn(err) { if (typeof console !== 'undefined' && console) { console.warn('Possible Unhandled Promise Rejection:', err); // eslint-disable-line no-console } }; var Exports = /*#__PURE__*/ function () { function Exports(ctx) { _classCallCheck(this, Exports); this.ctx = ctx; this.w = ctx.w; } _createClass(Exports, [{ key: "getSvgString", value: function getSvgString() { return this.w.globals.dom.Paper.svg(); } }, { key: "cleanup", value: function cleanup() { var w = this.w; // hide some elements to avoid printing them on exported svg var xcrosshairs = w.globals.dom.baseEl.querySelector('.apexcharts-xcrosshairs'); var ycrosshairs = w.globals.dom.baseEl.querySelector('.apexcharts-ycrosshairs'); if (xcrosshairs) { xcrosshairs.setAttribute('x', -500); } if (ycrosshairs) { ycrosshairs.setAttribute('y1', -100); ycrosshairs.setAttribute('y2', -100); } } }, { key: "svgUrl", value: function svgUrl() { this.cleanup(); var svgData = this.getSvgString(); var svgBlob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' }); return URL.createObjectURL(svgBlob); } }, { key: "dataURI", value: function dataURI() { var _this = this; return new Promise$1(function (resolve) { var w = _this.w; _this.cleanup(); var canvas = document.createElement('canvas'); canvas.width = w.globals.svgWidth; canvas.height = w.globals.svgHeight; var canvasBg = w.config.chart.background === 'transparent' ? '#fff' : w.config.chart.background; var ctx = canvas.getContext('2d'); ctx.fillStyle = canvasBg; ctx.fillRect(0, 0, canvas.width, canvas.height); var DOMURL = window.URL || window.webkitURL || window; var img = new Image(); img.crossOrigin = 'anonymous'; var svgData = _this.getSvgString(); var svgUrl = 'data:image/svg+xml,' + encodeURIComponent(svgData); img.onload = function () { ctx.drawImage(img, 0, 0); DOMURL.revokeObjectURL(svgUrl); var imgURI = canvas.toDataURL('image/png'); resolve(imgURI); }; img.src = svgUrl; }); } }, { key: "exportToSVG", value: function exportToSVG() { this.triggerDownload(this.svgUrl(), '.svg'); } }, { key: "exportToPng", value: function exportToPng() { var _this2 = this; this.dataURI().then(function (imgURI) { _this2.triggerDownload(imgURI, '.png'); }); } }, { key: "triggerDownload", value: function triggerDownload(href, ext) { var downloadLink = document.createElement('a'); downloadLink.href = href; downloadLink.download = this.w.globals.chartID + ext; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } }]); return Exports; }(); /** * ApexCharts Grid Class for drawing Cartesian Grid. * * @module Grid **/ var Grid = /*#__PURE__*/ function () { function Grid(ctx) { _classCallCheck(this, Grid); this.ctx = ctx; this.w = ctx.w; var w = this.w; this.anim = new Animations(this.ctx); this.xaxisLabels = w.globals.labels.slice(); this.animX = w.config.grid.xaxis.lines.animate && w.config.chart.animations.enabled; this.animY = w.config.grid.yaxis.lines.animate && w.config.chart.animations.enabled; if (w.globals.timelineLabels.length > 0) { // timeline labels are there this.xaxisLabels = w.globals.timelineLabels.slice(); } } // .when using sparklines or when showing no grid, we need to have a grid area which is reused at many places for other calculations as well _createClass(Grid, [{ key: "drawGridArea", value: function drawGridArea() { var elGrid = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var w = this.w; var graphics = new Graphics(this.ctx); if (elGrid === null) { elGrid = graphics.group({ class: 'apexcharts-grid' }); } var elVerticalLine = graphics.drawLine(w.globals.padHorizontal, 1, w.globals.padHorizontal, w.globals.gridHeight, 'transparent'); var elHorzLine = graphics.drawLine(w.globals.padHorizontal, w.globals.gridHeight, w.globals.gridWidth, w.globals.gridHeight, 'transparent'); elGrid.add(elHorzLine); elGrid.add(elVerticalLine); return elGrid; } }, { key: "drawGrid", value: function drawGrid() { var w = this.w; var xAxis = new XAxis(this.ctx); var yaxis = new YAxis(this.ctx); var gl = this.w.globals; var elgrid = null; if (gl.axisCharts) { if (w.config.grid.show) { // grid is drawn after xaxis and yaxis are drawn elgrid = this.renderGrid(); gl.dom.elGraphical.add(elgrid.el); this.drawGridArea(elgrid.el); } else { var elgridArea = this.drawGridArea(); gl.dom.elGraphical.add(elgridArea); } if (elgrid !== null) { xAxis.xAxisLabelCorrections(elgrid.xAxisTickWidth); } yaxis.setYAxisTextAlignments(); } } // This mask will clip off overflowing graphics from the drawable area }, { key: "createGridMask", value: function createGridMask() { var w = this.w; var gl = w.globals; var graphics = new Graphics(this.ctx); var strokeSize = Array.isArray(w.config.stroke.width) ? 0 : w.config.stroke.width; if (Array.isArray(w.config.stroke.width)) { var strokeMaxSize = 0; w.config.stroke.width.forEach(function (m) { strokeMaxSize = Math.max(strokeMaxSize, m); }); strokeSize = strokeMaxSize; } gl.dom.elGridRectMask = document.createElementNS(gl.SVGNS, 'clipPath'); gl.dom.elGridRectMask.setAttribute('id', "gridRectMask".concat(gl.cuid)); gl.dom.elGridRectMarkerMask = document.createElementNS(gl.SVGNS, 'clipPath'); gl.dom.elGridRectMarkerMask.setAttribute('id', "gridRectMarkerMask".concat(gl.cuid)); gl.dom.elGridRect = graphics.drawRect(-strokeSize / 2, -strokeSize / 2, gl.gridWidth + strokeSize, gl.gridHeight + strokeSize, 0, '#fff'); var coreUtils = new CoreUtils(this); coreUtils.getLargestMarkerSize(); var markerSize = w.globals.markers.largestSize + w.config.markers.hover.sizeOffset + 1; if (markerSize < 10) markerSize = 10; gl.dom.elGridRectMarker = graphics.drawRect(-markerSize * 2, -markerSize * 2, gl.gridWidth + markerSize * 4, gl.gridHeight + markerSize * 4, 0, '#fff'); gl.dom.elGridRectMask.appendChild(gl.dom.elGridRect.node); gl.dom.elGridRectMarkerMask.appendChild(gl.dom.elGridRectMarker.node); var defs = gl.dom.baseEl.querySelector('defs'); defs.appendChild(gl.dom.elGridRectMask); defs.appendChild(gl.dom.elGridRectMarkerMask); } // actual grid rendering }, { key: "renderGrid", value: function renderGrid() { var w = this.w; var graphics = new Graphics(this.ctx); var strokeDashArray = w.config.grid.strokeDashArray; var elg = graphics.group({ class: 'apexcharts-grid' }); var elgridLinesH = graphics.group({ class: 'apexcharts-gridlines-horizontal' }); var elgridLinesV = graphics.group({ class: 'apexcharts-gridlines-vertical' }); elg.add(elgridLinesH); elg.add(elgridLinesV); var tickAmount = 8; for (var i = 0; i < w.globals.series.length; i++) { if (typeof w.globals.yAxisScale[i] !== 'undefined') { tickAmount = w.globals.yAxisScale[i].result.length - 1; } if (tickAmount > 2) break; } var xCount; if (!w.globals.isBarHorizontal) { xCount = this.xaxisLabels.length; // draw vertical lines if (w.config.grid.xaxis.lines.show || w.config.xaxis.axisTicks.show) { var x1 = w.globals.padHorizontal; var y1 = 0; var x2; var y2 = w.globals.gridHeight; if (w.globals.timelineLabels.length > 0) { for (var _i = 0; _i < xCount; _i++) { x1 = this.xaxisLabels[_i].position; x2 = this.xaxisLabels[_i].position; if (w.config.grid.xaxis.lines.show && x1 > 0 && x1 < w.globals.gridWidth) { var line = graphics.drawLine(x1, y1, x2, y2, w.config.grid.borderColor, strokeDashArray); line.node.classList.add('apexcharts-gridline'); elgridLinesV.add(line); if (this.animX) { this.animateLine(line, { x1: 0, x2: 0 }, { x1: x1, x2: x2 }); } } var xAxis = new XAxis(this.ctx); if (_i === xCount - 1) { if (!w.globals.skipLastTimelinelabel) { // skip drawing last label here xAxis.drawXaxisTicks(x1, elg); } } else { xAxis.drawXaxisTicks(x1, elg); } } } else { var xCountForCategoryCharts = xCount; for (var _i2 = 0; _i2 < xCountForCategoryCharts; _i2++) { var x1Count = xCountForCategoryCharts; if (w.globals.isXNumeric && w.config.chart.type !== 'bar') { x1Count -= 1; } x1 = x1 + w.globals.gridWidth / x1Count; x2 = x1; // skip the last line if (_i2 === x1Count - 1) break; if (w.config.grid.xaxis.lines.show) { var _line = graphics.drawLine(x1, y1, x2, y2, w.config.grid.borderColor, strokeDashArray); _line.node.classList.add('apexcharts-gridline'); elgridLinesV.add(_line); if (this.animX) { this.animateLine(_line, { x1: 0, x2: 0 }, { x1: x1, x2: x2 }); } } var _xAxis = new XAxis(this.ctx); _xAxis.drawXaxisTicks(x1, elg); } } } // draw horizontal lines if (w.config.grid.yaxis.lines.show) { var _x = 0; var _y = 0; var _y2 = 0; var _x2 = w.globals.gridWidth; for (var _i3 = 0; _i3 < tickAmount + 1; _i3++) { var _line2 = graphics.drawLine(_x, _y, _x2, _y2, w.config.grid.borderColor, strokeDashArray); elgridLinesH.add(_line2); _line2.node.classList.add('apexcharts-gridline'); if (this.animY) { this.animateLine(_line2, { y1: _y + 20, y2: _y2 + 20 }, { y1: _y, y2: _y2 }); } _y = _y + w.globals.gridHeight / tickAmount; _y2 = _y; } } } else { xCount = tickAmount; // draw vertical lines if (w.config.grid.xaxis.lines.show || w.config.xaxis.axisTicks.show) { var _x3 = w.globals.padHorizontal; var _y3 = 0; var _x4; var _y4 = w.globals.gridHeight; for (var _i4 = 0; _i4 < xCount + 1; _i4++) { _x3 = _x3 + w.globals.gridWidth / xCount + 0.3; _x4 = _x3; // skip the last vertical line if (_i4 === xCount - 1) break; if (w.config.grid.xaxis.lines.show) { var _line3 = graphics.drawLine(_x3, _y3, _x4, _y4, w.config.grid.borderColor, strokeDashArray); _line3.node.classList.add('apexcharts-gridline'); elgridLinesV.add(_line3); if (this.animX) { this.animateLine(_line3, { x1: 0, x2: 0 }, { x1: _x3, x2: _x4 }); } } // skip the first vertical line var _xAxis2 = new XAxis(this.ctx); _xAxis2.drawXaxisTicks(_x3, elg); } } // draw horizontal lines if (w.config.grid.yaxis.lines.show) { var _x5 = 0; var _y5 = 0; var _y6 = 0; var _x6 = w.globals.gridWidth; for (var _i5 = 0; _i5 < w.globals.dataPoints + 1; _i5++) { var _line4 = graphics.drawLine(_x5, _y5, _x6, _y6, w.config.grid.borderColor, strokeDashArray); elgridLinesH.add(_line4); _line4.node.classList.add('apexcharts-gridline'); if (this.animY) { this.animateLine(_line4, { y1: _y5 + 20, y2: _y6 + 20 }, { y1: _y5, y2: _y6 }); } _y5 = _y5 + w.globals.gridHeight / w.globals.dataPoints; _y6 = _y5; } } } this.drawGridBands(elg, xCount, tickAmount); return { el: elg, xAxisTickWidth: w.globals.gridWidth / xCount }; } }, { key: "drawGridBands", value: function drawGridBands(elg, xCount, tickAmount) { var w = this.w; var graphics = new Graphics(this.ctx); // rows background bands if (w.config.grid.row.colors !== undefined && w.config.grid.row.colors.length > 0) { var x1 = 0; var y1 = 0; var y2 = w.globals.gridHeight / tickAmount; var x2 = w.globals.gridWidth; for (var i = 0, c = 0; i < tickAmount; i++, c++) { if (c >= w.config.grid.row.colors.length) { c = 0; } var color = w.config.grid.row.colors[c]; var rect = graphics.drawRect(x1, y1, x2, y2, 0, color, w.config.grid.row.opacity); elg.add(rect); rect.node.classList.add('apexcharts-gridRow'); y1 = y1 + w.globals.gridHeight / tickAmount; } } // columns background bands if (w.config.grid.column.colors !== undefined && w.config.grid.column.colors.length > 0) { var _x7 = w.globals.padHorizontal; var _y7 = 0; var _x8 = w.globals.padHorizontal + w.globals.gridWidth / xCount; var _y8 = w.globals.gridHeight; for (var _i6 = 0, _c = 0; _i6 < xCount; _i6++, _c++) { if (_c >= w.config.grid.column.colors.length) { _c = 0; } var _color = w.config.grid.column.colors[_c]; var _rect = graphics.drawRect(_x7, _y7, _x8, _y8, 0, _color, w.config.grid.column.opacity); _rect.node.classList.add('apexcharts-gridColumn'); elg.add(_rect); _x7 = _x7 + w.globals.gridWidth / xCount; } } } }, { key: "animateLine", value: function animateLine(line, from, to) { var w = this.w; var initialAnim = w.config.chart.animations; if (initialAnim && !w.globals.resized && !w.globals.dataChanged) { var speed = initialAnim.speed; this.anim.animateLine(line, from, to, speed); } } }]); return Grid; }(); /** * ApexCharts Legend Class to draw legend. * * @module Legend **/ var Legend = /*#__PURE__*/ function () { function Legend(ctx, opts) { _classCallCheck(this, Legend); this.ctx = ctx; this.w = ctx.w; this.onLegendClick = this.onLegendClick.bind(this); this.onLegendHovered = this.onLegendHovered.bind(this); } _createClass(Legend, [{ key: "init", value: function init() { var w = this.w; var gl = w.globals; var cnf = w.config; var showLegendAlways = cnf.legend.showForSingleSeries && gl.series.length === 1 || gl.series.length > 1; if ((showLegendAlways || !gl.axisCharts) && cnf.legend.show) { while (gl.dom.elLegendWrap.firstChild) { gl.dom.elLegendWrap.removeChild(gl.dom.elLegendWrap.firstChild); } this.drawLegends(); if (!Utils.isIE11()) { this.appendToForeignObject(); } else { // IE11 doesn't supports foreignObject, hence append it to <head> document.getElementsByTagName('head')[0].appendChild(this.getLegendStyles()); } if (cnf.legend.position === 'bottom' || cnf.legend.position === 'top') { this.legendAlignHorizontal(); } else if (cnf.legend.position === 'right' || cnf.legend.position === 'left') { this.legendAlignVertical(); } } } }, { key: "appendToForeignObject", value: function appendToForeignObject() { var gl = this.w.globals; var elForeign = document.createElementNS(gl.SVGNS, 'foreignObject'); elForeign.setAttribute('x', 0); elForeign.setAttribute('y', 0); elForeign.setAttribute('width', gl.svgWidth); elForeign.setAttribute('height', gl.svgHeight); gl.dom.elLegendWrap.setAttribute('xmlns', 'http://www.w3.org/1999/xhtml'); elForeign.appendChild(gl.dom.elLegendWrap); elForeign.appendChild(this.getLegendStyles()); gl.dom.Paper.node.insertBefore(elForeign, gl.dom.elGraphical.node); } }, { key: "drawLegends", value: function drawLegends() { var self = this; var w = this.w; var fontFamily = w.config.legend.fontFamily; var legendNames = w.globals.seriesNames; var fillcolor = w.globals.colors.slice(); if (w.config.chart.type === 'heatmap') { var ranges = w.config.plotOptions.heatmap.colorScale.ranges; legendNames = ranges.map(function (colorScale) { return colorScale.name ? colorScale.name : colorScale.from + ' - ' + colorScale.to; }); fillcolor = ranges.map(function (color) { return color.color; }); } var legendFormatter = w.globals.legendFormatter; for (var i = 0; i <= legendNames.length - 1; i++) { var text = legendFormatter(legendNames[i], { seriesIndex: i, w: w }); var collapsedSeries = false; var ancillaryCollapsedSeries = false; if (w.globals.collapsedSeries.length > 0) { for (var c = 0; c < w.globals.collapsedSeries.length; c++) { if (w.globals.collapsedSeries[c].index === i) { collapsedSeries = true; } } } if (w.globals.ancillaryCollapsedSeriesIndices.length > 0) { for (var _c = 0; _c < w.globals.ancillaryCollapsedSeriesIndices.length; _c++) { if (w.globals.ancillaryCollapsedSeriesIndices[_c] === i) { ancillaryCollapsedSeries = true; } } } var elMarker = document.createElement('span'); elMarker.classList.add('apexcharts-legend-marker'); var mOffsetX = w.config.legend.markers.offsetX; var mOffsetY = w.config.legend.markers.offsetY; var mHeight = w.config.legend.markers.height; var mWidth = w.config.legend.markers.width; var mBorderWidth = w.config.legend.markers.strokeWidth; var mBorderColor = w.config.legend.markers.strokeColor; var mBorderRadius = w.config.legend.markers.radius; var mStyle = elMarker.style; mStyle.background = fillcolor[i]; mStyle.color = fillcolor[i]; mStyle.height = Array.isArray(mHeight) ? parseFloat(mHeight[i]) + 'px' : parseFloat(mHeight) + 'px'; mStyle.width = Array.isArray(mWidth) ? parseFloat(mWidth[i]) + 'px' : parseFloat(mWidth) + 'px'; mStyle.left = Array.isArray(mOffsetX) ? mOffsetX[i] : mOffsetX; mStyle.top = Array.isArray(mOffsetY) ? mOffsetY[i] : mOffsetY; mStyle.borderWidth = Array.isArray(mBorderWidth) ? mBorderWidth[i] : mBorderWidth; mStyle.borderColor = Array.isArray(mBorderColor) ? mBorderColor[i] : mBorderColor; mStyle.borderRadius = Array.isArray(mBorderRadius) ? parseFloat(mBorderRadius[i]) + 'px' : parseFloat(mBorderRadius) + 'px'; if (w.config.legend.markers.customHTML) { if (Array.isArray(w.config.legend.markers.customHTML)) { elMarker.innerHTML = w.config.legend.markers.customHTML[i](); } else { elMarker.innerHTML = w.config.legend.markers.customHTML(); } } Graphics.setAttrs(elMarker, { rel: i + 1, 'data:collapsed': collapsedSeries || ancillaryCollapsedSeries }); if (collapsedSeries || ancillaryCollapsedSeries) { elMarker.classList.add('inactive-legend'); } var elLegend = document.createElement('div'); var elLegendText = document.createElement('span'); elLegendText.classList.add('apexcharts-legend-text'); elLegendText.innerHTML = text; var textColor = w.config.legend.labels.useSeriesColors ? w.globals.colors[i] : w.config.legend.labels.colors; if (!textColor) { textColor = w.config.chart.foreColor; } elLegendText.style.color = textColor; elLegendText.style.fontSize = parseFloat(w.config.legend.fontSize) + 'px'; elLegendText.style.fontFamily = fontFamily || w.config.chart.fontFamily; Graphics.setAttrs(elLegendText, { rel: i + 1, 'data:collapsed': collapsedSeries || ancillaryCollapsedSeries }); elLegend.appendChild(elMarker); elLegend.appendChild(elLegendText); var coreUtils = new CoreUtils(this.ctx); if (!w.config.legend.showForZeroSeries) { var total = coreUtils.getSeriesTotalByIndex(i); if (total === 0 && coreUtils.seriesHaveSameValues(i) && !coreUtils.isSeriesNull(i) && w.globals.collapsedSeriesIndices.indexOf(i) === -1 && w.globals.ancillaryCollapsedSeriesIndices.indexOf(i) === -1) { elLegend.classList.add('apexcharts-hidden-zero-series'); } } if (!w.config.legend.showForNullSeries) { if (coreUtils.isSeriesNull(i) && w.globals.collapsedSeriesIndices.indexOf(i) === -1 && w.globals.ancillaryCollapsedSeriesIndices.indexOf(i) === -1) { elLegend.classList.add('apexcharts-hidden-null-series'); } } w.globals.dom.elLegendWrap.appendChild(elLegend); w.globals.dom.elLegendWrap.classList.add(w.config.legend.horizontalAlign); // w.globals.dom.elLegendWrap.classList.add(w.config.legend.verticalAlign) w.globals.dom.elLegendWrap.classList.add('position-' + w.config.legend.position); elLegend.classList.add('apexcharts-legend-series'); elLegend.style.margin = "".concat(w.config.legend.itemMargin.horizontal, "px ").concat(w.config.legend.itemMargin.vertical, "px"); w.globals.dom.elLegendWrap.style.width = w.config.legend.width ? w.config.legend.width + 'px' : ''; w.globals.dom.elLegendWrap.style.height = w.config.legend.height ? w.config.legend.height + 'px' : ''; Graphics.setAttrs(elLegend, { rel: i + 1, 'data:collapsed': collapsedSeries || ancillaryCollapsedSeries }); if (collapsedSeries || ancillaryCollapsedSeries) { elLegend.classList.add('inactive-legend'); } if (!w.config.legend.onItemClick.toggleDataSeries) { elLegend.classList.add('no-click'); } } // for now - just prevent click on heatmap legend - and allow hover only var clickAllowed = w.config.chart.type !== 'heatmap'; if (clickAllowed && w.config.legend.onItemClick.toggleDataSeries) { w.globals.dom.elWrap.addEventListener('click', self.onLegendClick, true); } if (w.config.legend.onItemHover.highlightDataSeries) { w.globals.dom.elWrap.addEventListener('mousemove', self.onLegendHovered, true); w.globals.dom.elWrap.addEventListener('mouseout', self.onLegendHovered, true); } } }, { key: "getLegendBBox", value: function getLegendBBox() { var w = this.w; var currLegendsWrap = w.globals.dom.baseEl.querySelector('.apexcharts-legend'); var currLegendsWrapRect = currLegendsWrap.getBoundingClientRect(); var currLegendsWrapWidth = currLegendsWrapRect.width; var currLegendsWrapHeight = currLegendsWrapRect.height; return { clwh: currLegendsWrapHeight, clww: currLegendsWrapWidth }; } }, { key: "setLegendWrapXY", value: function setLegendWrapXY(offsetX, offsetY) { var w = this.w; var elLegendWrap = w.globals.dom.baseEl.querySelector('.apexcharts-legend'); var legendRect = elLegendWrap.getBoundingClientRect(); var x = 0; var y = 0; if (w.config.legend.position === 'bottom') { y = y + (w.globals.svgHeight - legendRect.height / 2); } else if (w.config.legend.position === 'top') { var dim = new Dimensions(this.ctx); var titleH = dim.getTitleSubtitleCoords('title').height; var subtitleH = dim.getTitleSubtitleCoords('subtitle').height; y = y + (titleH > 0 ? titleH - 10 : 0) + (subtitleH > 0 ? subtitleH - 10 : 0); } elLegendWrap.style.position = 'absolute'; x = x + offsetX + w.config.legend.offsetX; y = y + offsetY + w.config.legend.offsetY; elLegendWrap.style.left = x + 'px'; elLegendWrap.style.top = y + 'px'; if (w.config.legend.position === 'bottom') { elLegendWrap.style.top = 'auto'; elLegendWrap.style.bottom = 10 + w.config.legend.offsetY + 'px'; } else if (w.config.legend.position === 'right') { elLegendWrap.style.left = 'auto'; elLegendWrap.style.right = 25 + w.config.legend.offsetX + 'px'; } if (elLegendWrap.style.width) { elLegendWrap.style.width = parseInt(w.config.legend.width) + 'px'; } if (elLegendWrap.style.height) { elLegendWrap.style.height = parseInt(w.config.legend.height) + 'px'; } } }, { key: "legendAlignHorizontal", value: function legendAlignHorizontal() { var w = this.w; var elLegendWrap = w.globals.dom.baseEl.querySelector('.apexcharts-legend'); elLegendWrap.style.right = 0; var lRect = this.getLegendBBox(); var dimensions = new Dimensions(this.ctx); var titleRect = dimensions.getTitleSubtitleCoords('title'); var subtitleRect = dimensions.getTitleSubtitleCoords('subtitle'); var offsetX = 20; var offsetY = 0; // the whole legend box is set to bottom if (w.config.legend.position === 'bottom') { offsetY = -lRect.clwh / 1.8; } else if (w.config.legend.position === 'top') { offsetY = titleRect.height + subtitleRect.height + w.config.title.margin + w.config.subtitle.margin - 15; } this.setLegendWrapXY(offsetX, offsetY); } }, { key: "legendAlignVertical", value: function legendAlignVertical() { var w = this.w; var lRect = this.getLegendBBox(); var offsetY = 20; var offsetX = 0; if (w.config.legend.position === 'left') { offsetX = 20; } if (w.config.legend.position === 'right') { offsetX = w.globals.svgWidth - lRect.clww - 10; } this.setLegendWrapXY(offsetX, offsetY); } }, { key: "onLegendHovered", value: function onLegendHovered(e) { var w = this.w; var hoverOverLegend = e.target.classList.contains('apexcharts-legend-text') || e.target.classList.contains('apexcharts-legend-marker'); if (w.config.chart.type !== 'heatmap') { if (!e.target.classList.contains('inactive-legend') && hoverOverLegend) { var series = new Series(this.ctx); series.toggleSeriesOnHover(e, e.target); } } else { // for heatmap handling if (hoverOverLegend) { var seriesCnt = parseInt(e.target.getAttribute('rel')) - 1; this.ctx.fireEvent('legendHover', [this.ctx, seriesCnt, this.w]); var _series = new Series(this.ctx); _series.highlightRangeInSeries(e, e.target); } } } }, { key: "onLegendClick", value: function onLegendClick(e) { if (e.target.classList.contains('apexcharts-legend-text') || e.target.classList.contains('apexcharts-legend-marker')) { var seriesCnt = parseInt(e.target.getAttribute('rel')) - 1; var isHidden = e.target.getAttribute('data:collapsed') === 'true'; var legendClick = this.w.config.chart.events.legendClick; if (typeof legendClick === 'function') { legendClick(this.ctx, seriesCnt, this.w); } this.ctx.fireEvent('legendClick', [this.ctx, seriesCnt, this.w]); var markerClick = this.w.config.legend.markers.onClick; if (typeof markerClick === 'function' && e.target.classList.contains('apexcharts-legend-marker')) { markerClick(this.ctx, seriesCnt, this.w); this.ctx.fireEvent('legendMarkerClick', [this.ctx, seriesCnt, this.w]); } this.toggleDataSeries(seriesCnt, isHidden); } } }, { key: "getLegendStyles", value: function getLegendStyles() { var stylesheet = document.createElement('style'); stylesheet.setAttribute('type', 'text/css'); var text = "\n \n .apexcharts-legend {\n display: flex;\n overflow: auto;\n padding: 0 10px;\n }\n\n .apexcharts-legend.position-bottom, .apexcharts-legend.position-top {\n flex-wrap: wrap\n }\n .apexcharts-legend.position-right, .apexcharts-legend.position-left {\n flex-direction: column;\n bottom: 0;\n }\n\n .apexcharts-legend.position-bottom.left, .apexcharts-legend.position-top.left, .apexcharts-legend.position-right, .apexcharts-legend.position-left {\n justify-content: flex-start;\n }\n\n .apexcharts-legend.position-bottom.center, .apexcharts-legend.position-top.center {\n justify-content: center; \n }\n\n .apexcharts-legend.position-bottom.right, .apexcharts-legend.position-top.right {\n justify-content: flex-end;\n }\n\n .apexcharts-legend-series {\n cursor: pointer;\n line-height: normal;\n }\n\n .apexcharts-legend.position-bottom .apexcharts-legend-series, .apexcharts-legend.position-top .apexcharts-legend-series{\n display: flex;\n align-items: center;\n }\n\n .apexcharts-legend-text {\n position: relative;\n font-size: 14px;\n }\n\n .apexcharts-legend-text *, .apexcharts-legend-marker * {\n pointer-events: none;\n }\n\n .apexcharts-legend-marker {\n position: relative;\n display: inline-block;\n cursor: pointer;\n margin-right: 3px;\n }\n \n .apexcharts-legend.right .apexcharts-legend-series, .apexcharts-legend.left .apexcharts-legend-series{\n display: inline-block;\n }\n\n .apexcharts-legend-series.no-click {\n cursor: auto;\n }\n\n .apexcharts-legend .apexcharts-hidden-zero-series, .apexcharts-legend .apexcharts-hidden-null-series {\n display: none !important;\n }\n\n .inactive-legend {\n opacity: 0.45;\n }"; var rules = document.createTextNode(text); stylesheet.appendChild(rules); return stylesheet; } }, { key: "resetToggleDataSeries", value: function resetToggleDataSeries() { var w = this.w; var seriesEls = null; var realIndexes = []; if (w.globals.axisCharts) { seriesEls = w.globals.dom.baseEl.querySelectorAll(".apexcharts-series[data\\:realIndex]"); seriesEls = Utils.listToArray(seriesEls); seriesEls.forEach(function (v) { realIndexes.push(parseInt(v.getAttribute('data:realIndex'))); }); } else { seriesEls = w.globals.dom.baseEl.querySelectorAll(".apexcharts-series[rel]"); seriesEls = Utils.listToArray(seriesEls); seriesEls.forEach(function (v) { realIndexes.push(parseInt(v.getAttribute('rel')) - 1); }); } realIndexes.sort(); if (w.globals.collapsedSeries.length > 0) { var risingSeries = w.globals.risingSeries.slice(); var series = w.config.series.slice(); for (var c = 0; c < w.globals.collapsedSeries.length; c++) { var index = realIndexes.indexOf(w.globals.collapsedSeries[c].index); if (index !== -1) { if (w.globals.axisCharts) { series[index].data = w.globals.collapsedSeries.slice()[c].data.slice(); } else { series[index] = w.globals.collapsedSeries.slice()[c].data; } risingSeries.push(index); } } w.globals.collapsedSeries = []; w.globals.ancillaryCollapsedSeries = []; w.globals.collapsedSeriesIndices = []; w.globals.ancillaryCollapsedSeriesIndices = []; w.globals.risingSeries = risingSeries; w.config.series = series; this.ctx._updateSeries(w.config.series, w.config.chart.animations.dynamicAnimation.enabled); } } }, { key: "toggleDataSeries", value: function toggleDataSeries(seriesCnt, isHidden) { var w = this.w; if (w.globals.axisCharts || w.config.chart.type === 'radialBar') { w.globals.resized = true; // we don't want initial animations again var seriesEl = null; var realIndex = null; // yes, make it null. 1 series will rise at a time w.globals.risingSeries = []; if (w.globals.axisCharts) { seriesEl = w.globals.dom.baseEl.querySelector(".apexcharts-series[data\\:realIndex='".concat(seriesCnt, "']")); realIndex = parseInt(seriesEl.getAttribute('data:realIndex')); } else { seriesEl = w.globals.dom.baseEl.querySelector(".apexcharts-series[rel='".concat(seriesCnt + 1, "']")); realIndex = parseInt(seriesEl.getAttribute('rel')) - 1; } if (isHidden) { this.riseCollapsedSeries(w.globals.collapsedSeries, w.globals.collapsedSeriesIndices, realIndex); this.riseCollapsedSeries(w.globals.ancillaryCollapsedSeries, w.globals.ancillaryCollapsedSeriesIndices, realIndex); } else { if (w.globals.axisCharts) { var shouldNotHideYAxis = false; if (w.config.yaxis[realIndex] && w.config.yaxis[realIndex].show && w.config.yaxis[realIndex].showAlways) { shouldNotHideYAxis = true; if (w.globals.ancillaryCollapsedSeriesIndices.indexOf(realIndex) < 0) { w.globals.ancillaryCollapsedSeries.push({ index: realIndex, data: w.config.series[realIndex].data.slice(), type: seriesEl.parentNode.className.baseVal.split('-')[1] }); w.globals.ancillaryCollapsedSeriesIndices.push(realIndex); } } if (!shouldNotHideYAxis) { w.globals.collapsedSeries.push({ index: realIndex, data: w.config.series[realIndex].data.slice(), type: seriesEl.parentNode.className.baseVal.split('-')[1] }); w.globals.collapsedSeriesIndices.push(realIndex); var removeIndexOfRising = w.globals.risingSeries.indexOf(realIndex); w.globals.risingSeries.splice(removeIndexOfRising, 1); } // TODO: AVOID mutating the user's config object below w.config.series[realIndex].data = []; } else { w.globals.collapsedSeries.push({ index: realIndex, data: w.config.series[realIndex] }); w.globals.collapsedSeriesIndices.push(realIndex); w.config.series[realIndex] = 0; } var seriesChildren = seriesEl.childNodes; for (var sc = 0; sc < seriesChildren.length; sc++) { if (seriesChildren[sc].classList.contains('apexcharts-series-markers-wrap')) { if (seriesChildren[sc].classList.contains('apexcharts-hide')) { seriesChildren[sc].classList.remove('apexcharts-hide'); } else { seriesChildren[sc].classList.add('apexcharts-hide'); } } } w.globals.allSeriesCollapsed = w.globals.collapsedSeries.length === w.globals.series.length; this.ctx._updateSeries(w.config.series, w.config.chart.animations.dynamicAnimation.enabled); } } else { // for non-axis charts i.e pie / donuts var _seriesEl = w.globals.dom.Paper.select(" .apexcharts-series[rel='".concat(seriesCnt + 1, "'] path")); var type = w.config.chart.type; if (type === 'pie' || type === 'donut') { var dataLabels = w.config.plotOptions.pie.donut.labels; var graphics = new Graphics(this.ctx); var pie = new Pie(this.ctx); graphics.pathMouseDown(_seriesEl.members[0], null); pie.printDataLabelsInner(_seriesEl.members[0].node, dataLabels); } _seriesEl.fire('click'); } } }, { key: "riseCollapsedSeries", value: function riseCollapsedSeries(series, seriesIndices, realIndex) { var w = this.w; if (series.length > 0) { for (var c = 0; c < series.length; c++) { if (series[c].index === realIndex) { if (w.globals.axisCharts) { w.config.series[realIndex].data = series[c].data.slice(); series.splice(c, 1); seriesIndices.splice(c, 1); w.globals.risingSeries.push(realIndex); } else { w.config.series[realIndex] = series[c].data; series.splice(c, 1); seriesIndices.splice(c, 1); w.globals.risingSeries.push(realIndex); } this.ctx._updateSeries(w.config.series, w.config.chart.animations.dynamicAnimation.enabled); } } } } }]); return Legend; }(); /** * ApexCharts Responsive Class to override options for different screen sizes. * * @module Responsive **/ var Responsive = /*#__PURE__*/ function () { function Responsive(ctx) { _classCallCheck(this, Responsive); this.ctx = ctx; this.w = ctx.w; } // the opts parameter if not null has to be set overriding everything // as the opts is set by user externally _createClass(Responsive, [{ key: "checkResponsiveConfig", value: function checkResponsiveConfig(opts) { var _this = this; var w = this.w; var cnf = w.config; // check if responsive config exists if (cnf.responsive.length === 0) return; var res = cnf.responsive.slice(); res.sort(function (a, b) { return a.breakpoint > b.breakpoint ? 1 : b.breakpoint > a.breakpoint ? -1 : 0; }).reverse(); var config = new Config({}); var iterateResponsiveOptions = function iterateResponsiveOptions() { var newOptions = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var largestBreakpoint = res[0].breakpoint; var width = window.innerWidth > 0 ? window.innerWidth : screen.width; if (width > largestBreakpoint) { var options = CoreUtils.extendArrayProps(config, w.globals.initialConfig); newOptions = Utils.extend(options, newOptions); newOptions = Utils.extend(w.config, newOptions); _this.overrideResponsiveOptions(newOptions); } else { for (var i = 0; i < res.length; i++) { if (width < res[i].breakpoint) { newOptions = CoreUtils.extendArrayProps(config, res[i].options); newOptions = Utils.extend(w.config, newOptions); _this.overrideResponsiveOptions(newOptions); } } } }; if (opts) { var options = CoreUtils.extendArrayProps(config, opts); options = Utils.extend(w.config, options); options = Utils.extend(options, opts); iterateResponsiveOptions(options); } else { iterateResponsiveOptions({}); } } }, { key: "overrideResponsiveOptions", value: function overrideResponsiveOptions(newOptions) { var newConfig = new Config(newOptions).init(); this.w.config = newConfig; } }]); return Responsive; }(); /** * ApexCharts Theme Class for setting the colors and palettes. * * @module Theme **/ var Theme = /*#__PURE__*/ function () { function Theme(ctx) { _classCallCheck(this, Theme); this.ctx = ctx; this.w = ctx.w; this.colors = []; } _createClass(Theme, [{ key: "init", value: function init() { this.setDefaultColors(); } }, { key: "setDefaultColors", value: function setDefaultColors() { var w = this.w; var utils = new Utils(); w.globals.dom.elWrap.classList.add(w.config.theme.mode); if (w.config.colors === undefined) { w.globals.colors = this.predefined(); } else { w.globals.colors = w.config.colors; } if (w.config.theme.monochrome.enabled) { var monoArr = []; var glsCnt = w.globals.series.length; if (w.config.plotOptions.bar.distributed && w.config.chart.type === 'bar') { glsCnt = w.globals.series[0].length * w.globals.series.length; } var mainColor = w.config.theme.monochrome.color; var part = 1 / (glsCnt / w.config.theme.monochrome.shadeIntensity); var shade = w.config.theme.monochrome.shadeTo; var percent = 0; for (var gsl = 0; gsl < glsCnt; gsl++) { var newColor = void 0; if (shade === 'dark') { newColor = utils.shadeColor(percent * -1, mainColor); percent = percent + part; } else { newColor = utils.shadeColor(percent, mainColor); percent = percent + part; } monoArr.push(newColor); } w.globals.colors = monoArr.slice(); } var defaultColors = w.globals.colors.slice(); // if user specfied less colors than no. of series, push the same colors again this.pushExtraColors(w.globals.colors); // The Border colors if (w.config.stroke.colors === undefined) { w.globals.stroke.colors = defaultColors; } else { w.globals.stroke.colors = w.config.stroke.colors; } this.pushExtraColors(w.globals.stroke.colors); // The FILL colors if (w.config.fill.colors === undefined) { w.globals.fill.colors = defaultColors; } else { w.globals.fill.colors = w.config.fill.colors; } this.pushExtraColors(w.globals.fill.colors); if (w.config.dataLabels.style.colors === undefined) { w.globals.dataLabels.style.colors = defaultColors; } else { w.globals.dataLabels.style.colors = w.config.dataLabels.style.colors; } this.pushExtraColors(w.globals.dataLabels.style.colors, 50); if (w.config.plotOptions.radar.polygons.fill.colors === undefined) { w.globals.radarPolygons.fill.colors = [w.config.theme.mode === 'dark' ? '#202D48' : '#fff']; } else { w.globals.radarPolygons.fill.colors = w.config.plotOptions.radar.polygons.fill.colors; } this.pushExtraColors(w.globals.radarPolygons.fill.colors, 20); // The point colors if (w.config.markers.colors === undefined) { w.globals.markers.colors = defaultColors; } else { w.globals.markers.colors = w.config.markers.colors; } this.pushExtraColors(w.globals.markers.colors); } // When the number of colors provided is less than the number of series, this method // will push same colors to the list // params: // distributed is only valid for distributed column/bar charts }, { key: "pushExtraColors", value: function pushExtraColors(colorSeries, length) { var distributed = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var w = this.w; var len = length || w.globals.series.length; if (distributed === null) { distributed = w.config.chart.type === 'bar' && w.config.plotOptions.bar.distributed || w.config.chart.type === 'heatmap' && w.config.plotOptions.heatmap.colorScale.inverse; } if (distributed) { len = w.globals.series[0].length * w.globals.series.length; } if (colorSeries.length < len) { var diff = len - colorSeries.length; for (var i = 0; i < diff; i++) { colorSeries.push(colorSeries[i]); } } } }, { key: "updateThemeOptions", value: function updateThemeOptions(options) { options.chart = options.chart || {}; options.tooltip = options.tooltip || {}; var mode = options.theme.mode || 'light'; var palette = options.theme.palette ? options.theme.palette : mode === 'dark' ? 'palette4' : 'palette1'; var foreColor = options.chart.foreColor ? options.chart.foreColor : mode === 'dark' ? '#f6f7f8' : '#373d3f'; options.tooltip.theme = mode; options.chart.foreColor = foreColor; options.theme.palette = palette; return options; } }, { key: "predefined", value: function predefined() { var palette = this.w.config.theme.palette; // D6E3F8, FCEFEF, DCE0D9, A5978B, EDDDD4, D6E3F8, FEF5EF switch (palette) { case 'palette1': this.colors = ['#008FFB', '#00E396', '#FEB019', '#FF4560', '#775DD0']; break; case 'palette2': this.colors = ['#3f51b5', '#03a9f4', '#4caf50', '#f9ce1d', '#FF9800']; break; case 'palette3': this.colors = ['#33b2df', '#546E7A', '#d4526e', '#13d8aa', '#A5978B']; break; case 'palette4': this.colors = ['#4ecdc4', '#c7f464', '#81D4FA', '#fd6a6a', '#546E7A']; break; case 'palette5': this.colors = ['#2b908f', '#f9a3a4', '#90ee7e', '#fa4443', '#69d2e7']; break; case 'palette6': this.colors = ['#449DD1', '#F86624', '#EA3546', '#662E9B', '#C5D86D']; break; case 'palette7': this.colors = ['#D7263D', '#1B998B', '#2E294E', '#F46036', '#E2C044']; break; case 'palette8': this.colors = ['#662E9B', '#F86624', '#F9C80E', '#EA3546', '#43BCCD']; break; case 'palette9': this.colors = ['#5C4742', '#A5978B', '#8D5B4C', '#5A2A27', '#C4BBAF']; break; case 'palette10': this.colors = ['#A300D6', '#7D02EB', '#5653FE', '#2983FF', '#00B1F2']; break; default: this.colors = ['#008FFB', '#00E396', '#FEB019', '#FF4560', '#775DD0']; break; } return this.colors; } }]); return Theme; }(); var Utils$1 = /*#__PURE__*/ function () { function Utils(tooltipContext) { _classCallCheck(this, Utils); this.w = tooltipContext.w; this.ttCtx = tooltipContext; this.ctx = tooltipContext.ctx; } /** ** When hovering over series, you need to capture which series is being hovered on. ** This function will return both capturedseries index as well as inner index of that series * @memberof Utils * @param {object} * - hoverArea = the rect on which user hovers * - elGrid = dimensions of the hover rect (it can be different than hoverarea) */ _createClass(Utils, [{ key: "getNearestValues", value: function getNearestValues(_ref) { var hoverArea = _ref.hoverArea, elGrid = _ref.elGrid, clientX = _ref.clientX, clientY = _ref.clientY, hasBars = _ref.hasBars; var w = this.w; var hoverWidth = w.globals.gridWidth; var xDivisor = hoverWidth / (w.globals.dataPoints - 1); var seriesBound = elGrid.getBoundingClientRect(); if (hasBars && w.globals.comboCharts || hasBars) { xDivisor = hoverWidth / w.globals.dataPoints; } var hoverX = clientX - seriesBound.left; var hoverY = clientY - seriesBound.top; var inRect = hoverX < 0 || hoverY < 0 || hoverX > w.globals.gridWidth || hoverY > w.globals.gridHeight; if (inRect) { hoverArea.classList.remove('hovering-zoom'); hoverArea.classList.remove('hovering-pan'); } else { if (w.globals.zoomEnabled) { hoverArea.classList.remove('hovering-pan'); hoverArea.classList.add('hovering-zoom'); } else if (w.globals.panEnabled) { hoverArea.classList.remove('hovering-zoom'); hoverArea.classList.add('hovering-pan'); } } var j = Math.round(hoverX / xDivisor); if (hasBars) { j = Math.ceil(hoverX / xDivisor); j = j - 1; } var capturedSeries = null; var closest = null; var seriesXValArr = []; var seriesYValArr = []; for (var s = 0; s < w.globals.seriesXvalues.length; s++) { seriesXValArr.push([w.globals.seriesXvalues[s][0] - 0.000001].concat(w.globals.seriesXvalues[s])); } seriesXValArr = seriesXValArr.map(function (seriesXVal) { return seriesXVal.filter(function (s) { return s; }); }); seriesYValArr = w.globals.seriesYvalues.map(function (seriesYVal) { return seriesYVal.filter(function (s) { return s; }); }); // if X axis type is not category and tooltip is not shared, then we need to find the cursor position and get the nearest value if (w.globals.isXNumeric) { closest = this.closestInMultiArray(hoverX, hoverY, seriesXValArr, seriesYValArr); capturedSeries = closest.index; j = closest.j; if (capturedSeries !== null) { // initial push, it should be a little smaller than the 1st val seriesXValArr = w.globals.seriesXvalues[capturedSeries]; closest = this.closestInArray(hoverX, seriesXValArr); j = closest.index; } } if (!j || j < 1) j = 0; return { capturedSeries: capturedSeries, j: j, hoverX: hoverX, hoverY: hoverY }; } }, { key: "closestInMultiArray", value: function closestInMultiArray(hoverX, hoverY, Xarrays, Yarrays) { var w = this.w; var activeIndex = 0; var currIndex = null; var j = -1; if (w.globals.series.length > 1) { activeIndex = this.getFirstActiveXArray(Xarrays); } else { currIndex = 0; } var currY = Yarrays[activeIndex][0]; var currX = Xarrays[activeIndex][0]; var diffX = Math.abs(hoverX - currX); var diffY = Math.abs(hoverY - currY); var diff = diffY + diffX; Yarrays.map(function (arrY, arrIndex) { arrY.map(function (y, innerKey) { var newdiffY = Math.abs(hoverY - Yarrays[arrIndex][innerKey]); var newdiffX = Math.abs(hoverX - Xarrays[arrIndex][innerKey]); var newdiff = newdiffX + newdiffY; if (newdiff < diff) { diff = newdiff; diffX = newdiffX; diffY = newdiffY; currIndex = arrIndex; j = innerKey; } }); }); return { index: currIndex, j: j }; } }, { key: "getFirstActiveXArray", value: function getFirstActiveXArray(Xarrays) { var activeIndex = 0; var coreUtils = new CoreUtils(this.ctx); var firstActiveSeriesIndex = Xarrays.map(function (xarr, index) { if (xarr.length > 0) { return index; } else { return -1; } }); for (var a = 0; a < firstActiveSeriesIndex.length; a++) { var total = coreUtils.getSeriesTotalByIndex(a); if (firstActiveSeriesIndex[a] !== -1 && total !== 0 && !coreUtils.seriesHaveSameValues(a)) { activeIndex = firstActiveSeriesIndex[a]; break; } } return activeIndex; } }, { key: "closestInArray", value: function closestInArray(val, arr) { var curr = arr[0]; var currIndex = null; var diff = Math.abs(val - curr); for (var i = 0; i < arr.length; i++) { var newdiff = Math.abs(val - arr[i]); if (newdiff < diff) { diff = newdiff; curr = arr[i]; currIndex = i; } } return { index: currIndex }; } /** * When there are multiple series, it is possible to have different x values for each series. * But it may be possible in those multiple series, that there is same x value for 2 or more * series. * @memberof Utils * @param {int} * - j = is the inner index of series -> (series[i][j]) * @return {bool} */ }, { key: "isXoverlap", value: function isXoverlap(j) { var w = this.w; var xSameForAllSeriesJArr = []; var seriesX = w.globals.seriesX.filter(function (s) { return typeof s[0] !== 'undefined'; }); if (seriesX.length > 0) { for (var i = 0; i < seriesX.length - 1; i++) { if (typeof seriesX[i][j] !== 'undefined' && typeof seriesX[i + 1][j] !== 'undefined') { if (seriesX[i][j] !== seriesX[i + 1][j]) { xSameForAllSeriesJArr.push('unEqual'); } } } } if (xSameForAllSeriesJArr.length === 0) { return true; } return false; } }, { key: "isinitialSeriesSameLen", value: function isinitialSeriesSameLen() { var sameLen = true; var initialSeries = this.w.globals.initialSeries; for (var i = 0; i < initialSeries.length - 1; i++) { if (initialSeries[i].data.length !== initialSeries[i + 1].data.length) { sameLen = false; break; } } return sameLen; } }, { key: "getBarsHeight", value: function getBarsHeight(allbars) { var bars = _toConsumableArray(allbars); var totalHeight = bars.reduce(function (acc, bar) { return acc + bar.getBBox().height; }, 0); return totalHeight; } }, { key: "toggleAllTooltipSeriesGroups", value: function toggleAllTooltipSeriesGroups(state) { var w = this.w; var ttCtx = this.ttCtx; if (ttCtx.allTooltipSeriesGroups.length === 0) { ttCtx.allTooltipSeriesGroups = w.globals.dom.baseEl.querySelectorAll('.apexcharts-tooltip-series-group'); } var allTooltipSeriesGroups = ttCtx.allTooltipSeriesGroups; for (var i = 0; i < allTooltipSeriesGroups.length; i++) { if (state === 'enable') { allTooltipSeriesGroups[i].classList.add('active'); allTooltipSeriesGroups[i].style.display = w.config.tooltip.items.display; } else { allTooltipSeriesGroups[i].classList.remove('active'); allTooltipSeriesGroups[i].style.display = 'none'; } } } }]); return Utils; }(); /** * ApexCharts Tooltip.Labels Class to draw texts on the tooltip. * * @module Tooltip.Labels **/ var Labels = /*#__PURE__*/ function () { function Labels(tooltipContext) { _classCallCheck(this, Labels); this.w = tooltipContext.w; this.ctx = tooltipContext.ctx; this.ttCtx = tooltipContext; this.tooltipUtil = new Utils$1(tooltipContext); } _createClass(Labels, [{ key: "drawSeriesTexts", value: function drawSeriesTexts(_ref) { var _ref$shared = _ref.shared, shared = _ref$shared === void 0 ? true : _ref$shared, ttItems = _ref.ttItems, _ref$i = _ref.i, i = _ref$i === void 0 ? 0 : _ref$i, _ref$j = _ref.j, j = _ref$j === void 0 ? null : _ref$j; var w = this.w; if (w.config.tooltip.custom !== undefined) { this.handleCustomTooltip({ i: i, j: j }); } else { this.toggleActiveInactiveSeries(shared); } var values = this.getValuesToPrint({ i: i, j: j }); this.printLabels({ i: i, j: j, values: values, ttItems: ttItems, shared: shared }); // Re-calculate tooltip dimensions now that we have drawn the text var tooltipEl = this.ttCtx.getElTooltip(); this.ttCtx.tooltipRect.ttWidth = tooltipEl.getBoundingClientRect().width; this.ttCtx.tooltipRect.ttHeight = tooltipEl.getBoundingClientRect().height; } }, { key: "printLabels", value: function printLabels(_ref2) { var i = _ref2.i, j = _ref2.j, values = _ref2.values, ttItems = _ref2.ttItems, shared = _ref2.shared; var w = this.w; var val; var xVal = values.xVal, zVal = values.zVal, xAxisTTVal = values.xAxisTTVal; var seriesName = ''; var pColor = w.globals.colors[i]; if (j !== null && w.config.plotOptions.bar.distributed) { pColor = w.globals.colors[j]; } for (var t = 0, inverset = w.globals.series.length - 1; t < w.globals.series.length; t++, inverset--) { var f = this.getFormatters(i); seriesName = this.getSeriesName({ fn: f.yLbTitleFormatter, index: i, seriesIndex: i, j: j }); if (shared) { var tIndex = w.config.tooltip.inverseOrder ? inverset : t; f = this.getFormatters(tIndex); seriesName = this.getSeriesName({ fn: f.yLbTitleFormatter, index: tIndex, seriesIndex: i, j: j }); pColor = w.globals.colors[tIndex]; // for plot charts, not for pie/donuts val = f.yLbFormatter(w.globals.series[tIndex][j], { series: w.globals.series, seriesIndex: tIndex, dataPointIndex: j, w: w }); // discard 0 values in BARS if (this.ttCtx.hasBars() && w.config.chart.stacked && w.globals.series[tIndex][j] === 0 || typeof w.globals.series[tIndex][j] === 'undefined') { val = undefined; } } else { val = f.yLbFormatter(w.globals.series[i][j], { series: w.globals.series, seriesIndex: i, dataPointIndex: j, w: w }); } // for pie / donuts if (j === null) { val = f.yLbFormatter(w.globals.series[i], w); } this.DOMHandling({ t: t, ttItems: ttItems, values: { val: val, xVal: xVal, xAxisTTVal: xAxisTTVal, zVal: zVal }, seriesName: seriesName, shared: shared, pColor: pColor }); } } }, { key: "getFormatters", value: function getFormatters(i) { var w = this.w; var yLbFormatter = w.globals.yLabelFormatters[i]; var yLbTitleFormatter; if (w.globals.ttVal !== undefined) { if (Array.isArray(w.globals.ttVal)) { yLbFormatter = w.globals.ttVal[i] && w.globals.ttVal[i].formatter; yLbTitleFormatter = w.globals.ttVal[i] && w.globals.ttVal[i].title && w.globals.ttVal[i].title.formatter; } else { yLbFormatter = w.globals.ttVal.formatter; if (typeof w.globals.ttVal.title.formatter === 'function') { yLbTitleFormatter = w.globals.ttVal.title.formatter; } } } else { yLbTitleFormatter = w.config.tooltip.y.title.formatter; } if (typeof yLbFormatter !== 'function') { if (w.globals.yLabelFormatters[0]) { yLbFormatter = w.globals.yLabelFormatters[0]; } else { yLbFormatter = function yLbFormatter(label) { return label; }; } } if (typeof yLbTitleFormatter !== 'function') { yLbTitleFormatter = function yLbTitleFormatter(label) { return label; }; } return { yLbFormatter: yLbFormatter, yLbTitleFormatter: yLbTitleFormatter }; } }, { key: "getSeriesName", value: function getSeriesName(_ref3) { var fn = _ref3.fn, index = _ref3.index, seriesIndex = _ref3.seriesIndex, j = _ref3.j; var w = this.w; return fn(String(w.globals.seriesNames[index]), { series: w.globals.series, seriesIndex: seriesIndex, dataPointIndex: j, w: w }); } }, { key: "DOMHandling", value: function DOMHandling(_ref4) { var t = _ref4.t, ttItems = _ref4.ttItems, values = _ref4.values, seriesName = _ref4.seriesName, shared = _ref4.shared, pColor = _ref4.pColor; var w = this.w; var ttCtx = this.ttCtx; var val = values.val, xVal = values.xVal, xAxisTTVal = values.xAxisTTVal, zVal = values.zVal; var ttItemsChildren = null; ttItemsChildren = ttItems[t].children; if (w.config.tooltip.fillSeriesColor) { // elTooltip.style.backgroundColor = pColor ttItems[t].style.backgroundColor = pColor; ttItemsChildren[0].style.display = 'none'; } if (ttCtx.showTooltipTitle) { if (ttCtx.tooltipTitle === null) { // get it once if null, and store it in class property ttCtx.tooltipTitle = w.globals.dom.baseEl.querySelector('.apexcharts-tooltip-title'); } ttCtx.tooltipTitle.innerHTML = xVal; } // if xaxis tooltip is constructed, we need to replace the innerHTML if (ttCtx.blxaxisTooltip) { ttCtx.xaxisTooltipText.innerHTML = xAxisTTVal !== '' ? xAxisTTVal : xVal; } var ttYLabel = ttItems[t].querySelector('.apexcharts-tooltip-text-label'); if (ttYLabel) { ttYLabel.innerHTML = seriesName ? seriesName + ': ' : ''; } var ttYVal = ttItems[t].querySelector('.apexcharts-tooltip-text-value'); if (ttYVal) { ttYVal.innerHTML = val; } if (ttItemsChildren[0] && ttItemsChildren[0].classList.contains('apexcharts-tooltip-marker')) { ttItemsChildren[0].style.backgroundColor = pColor; } if (!w.config.tooltip.marker.show) { ttItemsChildren[0].style.display = 'none'; } if (zVal !== null) { var ttZLabel = ttItems[t].querySelector('.apexcharts-tooltip-text-z-label'); ttZLabel.innerHTML = w.config.tooltip.z.title; var ttZVal = ttItems[t].querySelector('.apexcharts-tooltip-text-z-value'); ttZVal.innerHTML = zVal; } if (shared && ttItemsChildren[0]) { // hide when no Val or series collapsed if (typeof val === 'undefined' || val === null || w.globals.collapsedSeriesIndices.indexOf(t) > -1) { ttItemsChildren[0].parentNode.style.display = 'none'; } else { ttItemsChildren[0].parentNode.style.display = w.config.tooltip.items.display; } } } }, { key: "toggleActiveInactiveSeries", value: function toggleActiveInactiveSeries(shared) { var w = this.w; if (shared) { // make all tooltips active this.tooltipUtil.toggleAllTooltipSeriesGroups('enable'); } else { // disable all tooltip text groups this.tooltipUtil.toggleAllTooltipSeriesGroups('disable'); // enable the first tooltip text group var firstTooltipSeriesGroup = w.globals.dom.baseEl.querySelector('.apexcharts-tooltip-series-group'); if (firstTooltipSeriesGroup) { firstTooltipSeriesGroup.classList.add('active'); firstTooltipSeriesGroup.style.display = w.config.tooltip.items.display; } } } }, { key: "getValuesToPrint", value: function getValuesToPrint(_ref5) { var i = _ref5.i, j = _ref5.j; var w = this.w; var filteredSeriesX = this.ctx.series.filteredSeriesX(); var xVal = ''; var xAxisTTVal = ''; var zVal = null; var val = null; var customFormatterOpts = { series: w.globals.series, seriesIndex: i, dataPointIndex: j, w: w }; var zFormatter = w.globals.ttZFormatter; if (j === null) { val = w.globals.series[i]; } else { if (w.globals.isXNumeric) { xVal = filteredSeriesX[i][j]; if (filteredSeriesX[i].length === 0) { // a series (possibly the first one) might be collapsed, so get the next active index var firstActiveSeriesIndex = this.tooltipUtil.getFirstActiveXArray(filteredSeriesX); xVal = filteredSeriesX[firstActiveSeriesIndex][j]; } } else { xVal = typeof w.globals.labels[j] !== 'undefined' ? w.globals.labels[j] : ''; } } var bufferXVal = xVal; if (w.globals.isXNumeric && w.config.xaxis.type === 'datetime') { var xFormat = new Formatters(this.ctx); xVal = xFormat.xLabelFormat(w.globals.ttKeyFormatter, bufferXVal); } else { xVal = w.globals.xLabelFormatter(bufferXVal, customFormatterOpts); } // override default x-axis formatter with tooltip formatter if (w.config.tooltip.x.formatter !== undefined) { xVal = w.globals.ttKeyFormatter(bufferXVal, customFormatterOpts); } if (w.globals.seriesZ.length > 0 && w.globals.seriesZ[0].length > 0) { zVal = zFormatter(w.globals.seriesZ[i][j], w); } if (typeof w.config.xaxis.tooltip.formatter === 'function') { xAxisTTVal = w.globals.xaxisTooltipFormatter(bufferXVal, customFormatterOpts); } else { xAxisTTVal = xVal; } return { val: val, xVal: xVal, xAxisTTVal: xAxisTTVal, zVal: zVal }; } }, { key: "handleCustomTooltip", value: function handleCustomTooltip(_ref6) { var i = _ref6.i, j = _ref6.j; var w = this.w; var tooltipEl = this.ttCtx.getElTooltip(); // override everything with a custom html tooltip and replace it tooltipEl.innerHTML = w.config.tooltip.custom({ ctx: this.ctx, series: w.globals.series, seriesIndex: i, dataPointIndex: j, w: w }); } }]); return Labels; }(); /** * ApexCharts Tooltip.Position Class to move the tooltip based on x and y position. * * @module Tooltip.Position **/ var Position = /*#__PURE__*/ function () { function Position(tooltipContext) { _classCallCheck(this, Position); this.ttCtx = tooltipContext; this.ctx = tooltipContext.ctx; this.w = tooltipContext.w; } /** * This will move the crosshair (the vertical/horz line that moves along with mouse) * Along with this, this function also calls the xaxisMove function * @memberof Position * @param {int} - cx = point's x position, wherever point's x is, you need to move crosshair */ _createClass(Position, [{ key: "moveXCrosshairs", value: function moveXCrosshairs(cx) { var j = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var ttCtx = this.ttCtx; var w = this.w; var xcrosshairs = ttCtx.getElXCrosshairs(); var x = cx - ttCtx.xcrosshairsWidth / 2; var tickAmount = w.globals.labels.slice().length; if (j !== null) { x = w.globals.gridWidth / tickAmount * j; } if (w.config.xaxis.crosshairs.width === 'tickWidth' || w.config.xaxis.crosshairs.width === 'barWidth') { if (x + ttCtx.xcrosshairsWidth > w.globals.gridWidth) { x = w.globals.gridWidth - ttCtx.xcrosshairsWidth; } } else { if (j !== null) { x = x + w.globals.gridWidth / tickAmount / 2; } } if (x < 0) { x = 0; } if (x > w.globals.gridWidth) { x = w.globals.gridWidth; } if (xcrosshairs !== null) { xcrosshairs.setAttribute('x', x); xcrosshairs.setAttribute('x1', x); xcrosshairs.setAttribute('x2', x); xcrosshairs.setAttribute('y2', w.globals.gridHeight); xcrosshairs.classList.add('active'); } if (ttCtx.blxaxisTooltip) { var tx = x; if (w.config.xaxis.crosshairs.width === 'tickWidth' || w.config.xaxis.crosshairs.width === 'barWidth') { tx = x + ttCtx.xcrosshairsWidth / 2; } this.moveXAxisTooltip(tx); } } /** * This will move the crosshair (the vertical/horz line that moves along with mouse) * Along with this, this function also calls the xaxisMove function * @memberof Position * @param {int} - cx = point's x position, wherever point's x is, you need to move crosshair */ }, { key: "moveYCrosshairs", value: function moveYCrosshairs(cy) { var ttCtx = this.ttCtx; if (ttCtx.ycrosshairs !== null) { Graphics.setAttrs(ttCtx.ycrosshairs, { y1: cy, y2: cy }); Graphics.setAttrs(ttCtx.ycrosshairsHidden, { y1: cy, y2: cy }); } } /** ** AxisTooltip is the small rectangle which appears on x axis with x value, when user moves * @memberof Position * @param {int} - cx = point's x position, wherever point's x is, you need to move */ }, { key: "moveXAxisTooltip", value: function moveXAxisTooltip(cx) { var w = this.w; var ttCtx = this.ttCtx; if (ttCtx.xaxisTooltip !== null) { ttCtx.xaxisTooltip.classList.add('active'); var cy = ttCtx.xaxisOffY + w.config.xaxis.tooltip.offsetY + w.globals.translateY + 1 + w.config.xaxis.offsetY; var xaxisTTText = ttCtx.xaxisTooltip.getBoundingClientRect(); var xaxisTTTextWidth = xaxisTTText.width; cx = cx - xaxisTTTextWidth / 2; if (!isNaN(cx)) { cx = cx + w.globals.translateX; var textRect = 0; var graphics = new Graphics(this.ctx); textRect = graphics.getTextRects(ttCtx.xaxisTooltipText.innerHTML); ttCtx.xaxisTooltipText.style.minWidth = textRect.width + 'px'; ttCtx.xaxisTooltip.style.left = cx + 'px'; ttCtx.xaxisTooltip.style.top = cy + 'px'; } } } }, { key: "moveYAxisTooltip", value: function moveYAxisTooltip(index) { var w = this.w; var ttCtx = this.ttCtx; if (ttCtx.yaxisTTEls === null) { ttCtx.yaxisTTEls = w.globals.dom.baseEl.querySelectorAll('.apexcharts-yaxistooltip'); } var ycrosshairsHiddenRectY1 = parseInt(ttCtx.ycrosshairsHidden.getAttribute('y1')); var cy = w.globals.translateY + ycrosshairsHiddenRectY1; var yAxisTTRect = ttCtx.yaxisTTEls[index].getBoundingClientRect(); var yAxisTTHeight = yAxisTTRect.height; var cx = w.globals.translateYAxisX[index] - 2; if (w.config.yaxis[index].opposite) { cx = cx - 26; } cy = cy - yAxisTTHeight / 2; if (w.globals.ignoreYAxisIndexes.indexOf(index) === -1) { ttCtx.yaxisTTEls[index].classList.add('active'); ttCtx.yaxisTTEls[index].style.top = cy + 'px'; ttCtx.yaxisTTEls[index].style.left = cx + w.config.yaxis[index].tooltip.offsetX + 'px'; } else { ttCtx.yaxisTTEls[index].classList.remove('active'); } } /** ** moves the whole tooltip by changing x, y attrs * @memberof Position * @param {int} - cx = point's x position, wherever point's x is, you need to move tooltip * @param {int} - cy = point's y position, wherever point's y is, you need to move tooltip * @param {int} - r = point's radius */ }, { key: "moveTooltip", value: function moveTooltip(cx, cy) { var r = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var w = this.w; var ttCtx = this.ttCtx; var tooltipEl = ttCtx.getElTooltip(); var tooltipRect = ttCtx.tooltipRect; var pointR = r !== null ? parseInt(r) : 1; var x = parseInt(cx) + pointR + 5; var y = parseInt(cy) + pointR / 2; // - tooltipRect.ttHeight / 2 if (x > w.globals.gridWidth / 2) { x = x - tooltipRect.ttWidth - pointR - 15; } if (x > w.globals.gridWidth - tooltipRect.ttWidth - 10) { x = w.globals.gridWidth - tooltipRect.ttWidth; } if (x < -20) { x = -20; } if (w.config.tooltip.followCursor) { var elGrid = ttCtx.getElGrid(); var seriesBound = elGrid.getBoundingClientRect(); y = ttCtx.e.clientY + w.globals.translateY - seriesBound.top - tooltipRect.ttHeight / 2; } var newPositions = this.positionChecks(tooltipRect, x, y); x = newPositions.x; y = newPositions.y; if (!isNaN(x)) { x = x + w.globals.translateX; tooltipEl.style.left = x + 'px'; tooltipEl.style.top = y + 'px'; } } }, { key: "positionChecks", value: function positionChecks(tooltipRect, x, y) { var w = this.w; if (tooltipRect.ttHeight + y > w.globals.gridHeight) { y = w.globals.gridHeight - tooltipRect.ttHeight + w.globals.translateY; } if (y < 0) { y = 0; } return { x: x, y: y }; } }, { key: "moveMarkers", value: function moveMarkers(i, j) { var w = this.w; var ttCtx = this.ttCtx; if (w.globals.markers.size[i] > 0) { var allPoints = w.globals.dom.baseEl.querySelectorAll(" .apexcharts-series[data\\:realIndex='".concat(i, "'] .apexcharts-marker")); for (var p = 0; p < allPoints.length; p++) { if (parseInt(allPoints[p].getAttribute('rel')) === j) { ttCtx.marker.resetPointsSize(); ttCtx.marker.enlargeCurrentPoint(j, allPoints[p]); } } } else { ttCtx.marker.resetPointsSize(); this.moveDynamicPointOnHover(j, i); } } // This function is used when you need to show markers/points only on hover - // DIFFERENT X VALUES in multiple series }, { key: "moveDynamicPointOnHover", value: function moveDynamicPointOnHover(j, capturedSeries) { var w = this.w; var ttCtx = this.ttCtx; var cx = 0; var cy = 0; var pointsArr = w.globals.pointsArray; var hoverSize = w.config.markers.hover.size; if (hoverSize === undefined) { hoverSize = w.globals.markers.size[capturedSeries] + w.config.markers.hover.sizeOffset; } cx = pointsArr[capturedSeries][j][0]; cy = pointsArr[capturedSeries][j][1] ? pointsArr[capturedSeries][j][1] : 0; var point = w.globals.dom.baseEl.querySelector(".apexcharts-series[data\\:realIndex='".concat(capturedSeries, "'] .apexcharts-series-markers circle")); if (point) { point.setAttribute('r', hoverSize); point.setAttribute('cx', cx); point.setAttribute('cy', cy); } // point.style.opacity = w.config.markers.hover.opacity this.moveXCrosshairs(cx); if (!ttCtx.fixedTooltip) { this.moveTooltip(cx, cy, hoverSize); } } // This function is used when you need to show markers/points only on hover - // SAME X VALUES in multiple series }, { key: "moveDynamicPointsOnHover", value: function moveDynamicPointsOnHover(j) { var ttCtx = this.ttCtx; var w = ttCtx.w; var cx = 0; var cy = 0; var activeSeries = 0; var pointsArr = w.globals.pointsArray; var series = new Series(this.ctx); activeSeries = series.getActiveSeriesIndex(); var hoverSize = w.config.markers.hover.size; if (hoverSize === undefined) { hoverSize = w.globals.markers.size[activeSeries] + w.config.markers.hover.sizeOffset; } if (pointsArr[activeSeries]) { cx = pointsArr[activeSeries][j][0]; cy = pointsArr[activeSeries][j][1]; } var points = null; var allPoints = ttCtx.getAllMarkers(); if (allPoints !== null) { points = allPoints; } else { points = w.globals.dom.baseEl.querySelectorAll('.apexcharts-series-markers circle'); } if (points !== null) { for (var p = 0; p < points.length; p++) { var pointArr = pointsArr[p]; if (pointArr && pointArr.length) { var pcy = pointsArr[p][j][1]; points[p].setAttribute('cx', cx); var realIndex = parseInt(points[p].parentNode.parentNode.parentNode.getAttribute('data:realIndex')); if (pcy !== null) { points[realIndex] && points[realIndex].setAttribute('r', hoverSize); points[realIndex] && points[realIndex].setAttribute('cy', pcy); } else { points[realIndex] && points[realIndex].setAttribute('r', 0); } } } } this.moveXCrosshairs(cx); if (!ttCtx.fixedTooltip) { var tcy = cy || w.globals.gridHeight; this.moveTooltip(cx, tcy, hoverSize); } } }, { key: "moveStickyTooltipOverBars", value: function moveStickyTooltipOverBars(j) { var w = this.w; var ttCtx = this.ttCtx; var jBar = w.globals.dom.baseEl.querySelector(".apexcharts-bar-series .apexcharts-series[rel='1'] path[j='".concat(j, "'], .apexcharts-candlestick-series .apexcharts-series[rel='1'] path[j='").concat(j, "'], .apexcharts-rangebar-series .apexcharts-series[rel='1'] path[j='").concat(j, "']")); var bcx = jBar ? parseFloat(jBar.getAttribute('cx')) : 0; var bcy = 0; var bw = jBar ? parseFloat(jBar.getAttribute('barWidth')) : 0; if (w.globals.isXNumeric) { bcx = bcx - bw / 2; } else { bcx = ttCtx.xAxisTicksPositions[j - 1] + ttCtx.dataPointsDividedWidth / 2; if (isNaN(bcx)) { bcx = ttCtx.xAxisTicksPositions[j] - ttCtx.dataPointsDividedWidth / 2; } } // tooltip will move vertically along with mouse as it is a shared tooltip var elGrid = ttCtx.getElGrid(); var seriesBound = elGrid.getBoundingClientRect(); bcy = ttCtx.e.clientY - seriesBound.top - ttCtx.tooltipRect.ttHeight / 2; this.moveXCrosshairs(bcx); if (!ttCtx.fixedTooltip) { var tcy = bcy || w.globals.gridHeight; this.moveTooltip(bcx, tcy); } } }]); return Position; }(); /** * ApexCharts Tooltip.Marker Class to draw texts on the tooltip. * * @module Tooltip.Marker **/ var Marker = /*#__PURE__*/ function () { function Marker(tooltipContext) { _classCallCheck(this, Marker); this.w = tooltipContext.w; this.ttCtx = tooltipContext; this.ctx = tooltipContext.ctx; this.tooltipPosition = new Position(tooltipContext); } _createClass(Marker, [{ key: "drawDynamicPoints", value: function drawDynamicPoints() { var w = this.w; var graphics = new Graphics(this.ctx); var marker = new Markers(this.ctx); var elsSeries = w.globals.dom.baseEl.querySelectorAll('.apexcharts-series'); for (var i = 0; i < elsSeries.length; i++) { var seriesIndex = parseInt(elsSeries[i].getAttribute('data:realIndex')); var pointsMain = w.globals.dom.baseEl.querySelector(".apexcharts-series[data\\:realIndex='".concat(seriesIndex, "'] .apexcharts-series-markers-wrap")); if (pointsMain !== null) { // it can be null as we have tooltips in donut/bar charts var point = void 0; var PointClasses = "apexcharts-marker w".concat((Math.random() + 1).toString(36).substring(4)); if ((w.config.chart.type === 'line' || w.config.chart.type === 'area') && !w.globals.comboCharts && !w.config.tooltip.intersect) { PointClasses += ' no-pointer-events'; } var elPointOptions = marker.getMarkerConfig(PointClasses, seriesIndex); point = graphics.drawMarker(0, 0, elPointOptions); point.node.setAttribute('default-marker-size', 0); var elPointsG = document.createElementNS(w.globals.SVGNS, 'g'); elPointsG.classList.add('apexcharts-series-markers'); elPointsG.appendChild(point.node); pointsMain.appendChild(elPointsG); } } } }, { key: "enlargeCurrentPoint", value: function enlargeCurrentPoint(rel, point) { var x = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var y = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var w = this.w; if (w.config.chart.type !== 'bubble') { this.newPointSize(rel, point); } var cx = point.getAttribute('cx'); var cy = point.getAttribute('cy'); if (x !== null && y !== null) { cx = x; cy = y; } this.tooltipPosition.moveXCrosshairs(cx); if (!this.fixedTooltip) { if (w.config.chart.type === 'radar') { var elGrid = this.ttCtx.getElGrid(); var seriesBound = elGrid.getBoundingClientRect(); cx = this.ttCtx.e.clientX - seriesBound.left; } this.tooltipPosition.moveTooltip(cx, cy, w.config.markers.hover.size); } } }, { key: "enlargePoints", value: function enlargePoints(j) { var w = this.w; var me = this; var ttCtx = this.ttCtx; var col = j; var points = w.globals.dom.baseEl.querySelectorAll('.apexcharts-series:not(.apexcharts-series-collapsed) .apexcharts-marker'); var newSize = w.config.markers.hover.size; for (var p = 0; p < points.length; p++) { var rel = points[p].getAttribute('rel'); var index = points[p].getAttribute('index'); if (newSize === undefined) { newSize = w.globals.markers.size[index] + w.config.markers.hover.sizeOffset; } if (col === parseInt(rel)) { me.newPointSize(col, points[p]); var cx = points[p].getAttribute('cx'); var cy = points[p].getAttribute('cy'); me.tooltipPosition.moveXCrosshairs(cx); if (!ttCtx.fixedTooltip) { me.tooltipPosition.moveTooltip(cx, cy, newSize); } } else { me.oldPointSize(points[p]); } } } }, { key: "newPointSize", value: function newPointSize(rel, point) { var w = this.w; var newSize = w.config.markers.hover.size; var elPoint = null; if (rel === 0) { elPoint = point.parentNode.firstChild; } else { elPoint = point.parentNode.lastChild; } var index = parseInt(elPoint.getAttribute('index')); if (newSize === undefined) { newSize = w.globals.markers.size[index] + w.config.markers.hover.sizeOffset; } elPoint.setAttribute('r', newSize); } }, { key: "oldPointSize", value: function oldPointSize(point) { var size = parseInt(point.getAttribute('default-marker-size')); point.setAttribute('r', size); } }, { key: "resetPointsSize", value: function resetPointsSize() { var w = this.w; var points = w.globals.dom.baseEl.querySelectorAll('.apexcharts-series:not(.apexcharts-series-collapsed) .apexcharts-marker'); for (var p = 0; p < points.length; p++) { var size = parseInt(points[p].getAttribute('default-marker-size')); if (Utils.isNumber(size)) { points[p].setAttribute('r', size); } else { points[p].setAttribute('r', 0); } } } }]); return Marker; }(); /** * ApexCharts Tooltip.Intersect Class. * * @module Tooltip.Intersect **/ var Intersect = /*#__PURE__*/ function () { function Intersect(tooltipContext) { _classCallCheck(this, Intersect); this.w = tooltipContext.w; this.ttCtx = tooltipContext; } _createClass(Intersect, [{ key: "getAttr", value: function getAttr(e, attr) { return parseFloat(e.target.getAttribute(attr)); } }, { key: "handleHeatTooltip", value: function handleHeatTooltip(_ref) { var e = _ref.e, opt = _ref.opt, x = _ref.x, y = _ref.y; var ttCtx = this.ttCtx; var w = this.w; if (e.target.classList.contains('apexcharts-heatmap-rect')) { var i = this.getAttr(e, 'i'); var j = this.getAttr(e, 'j'); var cx = this.getAttr(e, 'cx'); var cy = this.getAttr(e, 'cy'); var width = this.getAttr(e, 'width'); var height = this.getAttr(e, 'height'); ttCtx.tooltipLabels.drawSeriesTexts({ ttItems: opt.ttItems, i: i, j: j, shared: false }); x = cx + ttCtx.tooltipRect.ttWidth / 2 + width; y = cy + ttCtx.tooltipRect.ttHeight / 2 - height / 2; ttCtx.tooltipPosition.moveXCrosshairs(cx + width / 2); if (x > w.globals.gridWidth / 2) { x = cx - ttCtx.tooltipRect.ttWidth / 2 + width; } if (ttCtx.w.config.tooltip.followCursor) { var elGrid = ttCtx.getElGrid(); var seriesBound = elGrid.getBoundingClientRect(); // x = ttCtx.e.clientX - seriesBound.left y = ttCtx.e.clientY - seriesBound.top + w.globals.translateY / 2 - 10; } } return { x: x, y: y }; } }, { key: "handleMarkerTooltip", value: function handleMarkerTooltip(_ref2) { var e = _ref2.e, opt = _ref2.opt, x = _ref2.x, y = _ref2.y; var w = this.w; var ttCtx = this.ttCtx; var i; var j; if (e.target.classList.contains('apexcharts-marker')) { var cx = parseInt(opt.paths.getAttribute('cx')); var cy = parseInt(opt.paths.getAttribute('cy')); var val = parseFloat(opt.paths.getAttribute('val')); j = parseInt(opt.paths.getAttribute('rel')); i = parseInt(opt.paths.parentNode.parentNode.parentNode.getAttribute('rel')) - 1; if (ttCtx.intersect) { var el = Utils.findAncestor(opt.paths, 'apexcharts-series'); if (el) { i = parseInt(el.getAttribute('data:realIndex')); } } ttCtx.tooltipLabels.drawSeriesTexts({ ttItems: opt.ttItems, i: i, j: j, shared: ttCtx.showOnIntersect ? false : w.config.tooltip.shared }); if (e.type === 'mouseup') { ttCtx.markerClick(e, i, j); } x = cx; y = cy + w.globals.translateY - ttCtx.tooltipRect.ttHeight * 1.4; if (ttCtx.w.config.tooltip.followCursor) { var elGrid = ttCtx.getElGrid(); var seriesBound = elGrid.getBoundingClientRect(); y = ttCtx.e.clientY + w.globals.translateY - seriesBound.top; } if (val < 0) { y = cy; } ttCtx.marker.enlargeCurrentPoint(j, opt.paths, x, y); } return { x: x, y: y }; } }, { key: "handleBarTooltip", value: function handleBarTooltip(_ref3) { var e = _ref3.e, opt = _ref3.opt; var w = this.w; var ttCtx = this.ttCtx; var tooltipEl = ttCtx.getElTooltip(); var bx = 0; var x = 0; var y = 0; // let bW = 0 var i = 0; var strokeWidth; var barXY = this.getBarTooltipXY({ e: e, opt: opt }); i = barXY.i; var barHeight = barXY.barHeight; var j = barXY.j; if (w.globals.isBarHorizontal && ttCtx.hasBars() || !w.config.tooltip.shared) { x = barXY.x; y = barXY.y; strokeWidth = Array.isArray(w.config.stroke.width) ? w.config.stroke.width[i] : w.config.stroke.width; // bW = barXY.barWidth bx = x; } else { if (!w.globals.comboCharts && !w.config.tooltip.shared) { bx = bx / 2; } } // y is NaN, make it touch the bottom of grid area if (isNaN(y)) { y = w.globals.svgHeight - ttCtx.tooltipRect.ttHeight; } // x exceeds gridWidth if (x + ttCtx.tooltipRect.ttWidth > w.globals.gridWidth) { x = x - ttCtx.tooltipRect.ttWidth; } else if (x < 0) { x = x + ttCtx.tooltipRect.ttWidth; } if (ttCtx.w.config.tooltip.followCursor) { var elGrid = ttCtx.getElGrid(); var seriesBound = elGrid.getBoundingClientRect(); y = ttCtx.e.clientY - seriesBound.top; } // if tooltip is still null, querySelector if (ttCtx.tooltip === null) { ttCtx.tooltip = w.globals.dom.baseEl.querySelector('.apexcharts-tooltip'); } if (!w.config.tooltip.shared) { if (w.globals.comboChartsHasBars) { ttCtx.tooltipPosition.moveXCrosshairs(bx + strokeWidth / 2); } else { ttCtx.tooltipPosition.moveXCrosshairs(bx); } } // move tooltip here if (!ttCtx.fixedTooltip && (!w.config.tooltip.shared || w.globals.isBarHorizontal && ttCtx.hasBars())) { if (isReversed) { x = w.globals.gridWidth - x; } tooltipEl.style.left = x + w.globals.translateX + 'px'; var seriesIndex = parseInt(opt.paths.parentNode.getAttribute('data:realIndex')); var isReversed = w.globals.isMultipleYAxis ? w.config.yaxis[seriesIndex] && w.config.yaxis[seriesIndex].reversed : w.config.yaxis[0].reversed; if (isReversed && !(w.globals.isBarHorizontal && ttCtx.hasBars())) { y = y + barHeight - (w.globals.series[i][j] < 0 ? barHeight : 0) * 2; } if (ttCtx.tooltipRect.ttHeight + y > w.globals.gridHeight) { y = w.globals.gridHeight - ttCtx.tooltipRect.ttHeight + w.globals.translateY; tooltipEl.style.top = y + 'px'; } else { tooltipEl.style.top = y + w.globals.translateY - ttCtx.tooltipRect.ttHeight / 2 + 'px'; } } } }, { key: "getBarTooltipXY", value: function getBarTooltipXY(_ref4) { var e = _ref4.e, opt = _ref4.opt; var w = this.w; var j = null; var ttCtx = this.ttCtx; var i = 0; var x = 0; var y = 0; var barWidth = 0; var barHeight = 0; var cl = e.target.classList; if (cl.contains('apexcharts-bar-area') || cl.contains('apexcharts-candlestick-area') || cl.contains('apexcharts-rangebar-area')) { var bar = e.target; var barRect = bar.getBoundingClientRect(); var seriesBound = opt.elGrid.getBoundingClientRect(); var bh = barRect.height; barHeight = barRect.height; var bw = barRect.width; var cx = parseInt(bar.getAttribute('cx')); var cy = parseInt(bar.getAttribute('cy')); barWidth = parseFloat(bar.getAttribute('barWidth')); var clientX = e.type === 'touchmove' ? e.touches[0].clientX : e.clientX; j = parseInt(bar.getAttribute('j')); i = parseInt(bar.parentNode.getAttribute('rel')) - 1; if (w.globals.comboCharts) { i = parseInt(bar.parentNode.getAttribute('data:realIndex')); } // if (w.config.tooltip.shared) { // this check not needed at the moment // const yDivisor = w.globals.gridHeight / (w.globals.series.length) // const hoverY = ttCtx.clientY - ttCtx.seriesBound.top // j = Math.ceil(hoverY / yDivisor) // } ttCtx.tooltipLabels.drawSeriesTexts({ ttItems: opt.ttItems, i: i, j: j, shared: ttCtx.showOnIntersect ? false : w.config.tooltip.shared }); if (w.config.tooltip.followCursor) { if (w.globals.isBarHorizontal) { x = clientX - seriesBound.left + 15; y = cy - ttCtx.dataPointsDividedHeight + bh / 2 - ttCtx.tooltipRect.ttHeight / 2; } else { if (w.globals.isXNumeric) { x = cx - bw / 2; } else { x = cx - ttCtx.dataPointsDividedWidth + bw / 2; } y = e.clientY - seriesBound.top - ttCtx.tooltipRect.ttHeight / 2 - 15; } } else { if (w.globals.isBarHorizontal) { x = cx; if (x < ttCtx.xyRatios.baseLineInvertedY) { x = cx - ttCtx.tooltipRect.ttWidth; } y = cy - ttCtx.dataPointsDividedHeight + bh / 2 - ttCtx.tooltipRect.ttHeight / 2; } else { // if columns if (w.globals.isXNumeric) { x = cx - bw / 2; } else { x = cx - ttCtx.dataPointsDividedWidth + bw / 2; } y = cy; // - ttCtx.tooltipRect.ttHeight / 2 + 10 } } } return { x: x, y: y, barHeight: barHeight, barWidth: barWidth, i: i, j: j }; } }]); return Intersect; }(); /** * ApexCharts Tooltip.AxesTooltip Class. * * @module Tooltip.AxesTooltip **/ var AxesTooltip = /*#__PURE__*/ function () { function AxesTooltip(tooltipContext) { _classCallCheck(this, AxesTooltip); this.w = tooltipContext.w; this.ttCtx = tooltipContext; } /** * This method adds the secondary tooltip which appears below x axis * @memberof Tooltip **/ _createClass(AxesTooltip, [{ key: "drawXaxisTooltip", value: function drawXaxisTooltip() { var w = this.w; var ttCtx = this.ttCtx; var isBottom = w.config.xaxis.position === 'bottom'; ttCtx.xaxisOffY = isBottom ? w.globals.gridHeight + 1 : 1; var tooltipCssClass = isBottom ? 'apexcharts-xaxistooltip apexcharts-xaxistooltip-bottom' : 'apexcharts-xaxistooltip apexcharts-xaxistooltip-top'; var renderTo = w.globals.dom.elWrap; if (ttCtx.blxaxisTooltip) { var xaxisTooltip = w.globals.dom.baseEl.querySelector('.apexcharts-xaxistooltip'); if (xaxisTooltip === null) { ttCtx.xaxisTooltip = document.createElement('div'); ttCtx.xaxisTooltip.setAttribute('class', tooltipCssClass + ' ' + w.config.tooltip.theme); renderTo.appendChild(ttCtx.xaxisTooltip); ttCtx.xaxisTooltipText = document.createElement('div'); ttCtx.xaxisTooltipText.classList.add('apexcharts-xaxistooltip-text'); ttCtx.xaxisTooltipText.style.fontFamily = w.config.xaxis.tooltip.style.fontFamily || w.config.chart.fontFamily; ttCtx.xaxisTooltipText.style.fontSize = w.config.xaxis.tooltip.style.fontSize; ttCtx.xaxisTooltip.appendChild(ttCtx.xaxisTooltipText); } } } /** * This method adds the secondary tooltip which appears below x axis * @memberof Tooltip **/ }, { key: "drawYaxisTooltip", value: function drawYaxisTooltip() { var w = this.w; var ttCtx = this.ttCtx; for (var i = 0; i < w.config.yaxis.length; i++) { var isRight = w.config.yaxis[i].opposite || w.config.yaxis[i].crosshairs.opposite; ttCtx.yaxisOffX = isRight ? w.globals.gridWidth + 1 : 1; var tooltipCssClass = isRight ? "apexcharts-yaxistooltip apexcharts-yaxistooltip-".concat(i, " apexcharts-yaxistooltip-right") : "apexcharts-yaxistooltip apexcharts-yaxistooltip-".concat(i, " apexcharts-yaxistooltip-left"); var renderTo = w.globals.dom.elWrap; if (ttCtx.blyaxisTooltip) { var yaxisTooltip = w.globals.dom.baseEl.querySelector(".apexcharts-yaxistooltip apexcharts-yaxistooltip-".concat(i)); if (yaxisTooltip === null) { ttCtx.yaxisTooltip = document.createElement('div'); ttCtx.yaxisTooltip.setAttribute('class', tooltipCssClass + ' ' + w.config.tooltip.theme); renderTo.appendChild(ttCtx.yaxisTooltip); if (i === 0) ttCtx.yaxisTooltipText = []; ttCtx.yaxisTooltipText.push(document.createElement('div')); ttCtx.yaxisTooltipText[i].classList.add('apexcharts-yaxistooltip-text'); ttCtx.yaxisTooltip.appendChild(ttCtx.yaxisTooltipText[i]); } } } } /** * @memberof Tooltip **/ }, { key: "setXCrosshairWidth", value: function setXCrosshairWidth() { var w = this.w; var ttCtx = this.ttCtx; // set xcrosshairs width var xcrosshairs = ttCtx.getElXCrosshairs(); ttCtx.xcrosshairsWidth = parseInt(w.config.xaxis.crosshairs.width); if (!w.globals.comboCharts) { if (w.config.xaxis.crosshairs.width === 'tickWidth') { var count = w.globals.labels.length; ttCtx.xcrosshairsWidth = w.globals.gridWidth / count; } else if (w.config.xaxis.crosshairs.width === 'barWidth') { var bar = w.globals.dom.baseEl.querySelector('.apexcharts-bar-area'); if (bar !== null) { var barWidth = parseFloat(bar.getAttribute('barWidth')); ttCtx.xcrosshairsWidth = barWidth; } else { ttCtx.xcrosshairsWidth = 1; } } } else { var _bar = w.globals.dom.baseEl.querySelector('.apexcharts-bar-area'); if (_bar !== null && w.config.xaxis.crosshairs.width === 'barWidth') { var _barWidth = parseFloat(_bar.getAttribute('barWidth')); ttCtx.xcrosshairsWidth = _barWidth; } else { if (w.config.xaxis.crosshairs.width === 'tickWidth') { var _count = w.globals.labels.length; ttCtx.xcrosshairsWidth = w.globals.gridWidth / _count; } } } if (w.globals.isBarHorizontal) { ttCtx.xcrosshairsWidth = 0; } if (xcrosshairs !== null && ttCtx.xcrosshairsWidth > 0) { xcrosshairs.setAttribute('width', ttCtx.xcrosshairsWidth); } } }, { key: "handleYCrosshair", value: function handleYCrosshair() { var w = this.w; var ttCtx = this.ttCtx; // set ycrosshairs height ttCtx.ycrosshairs = w.globals.dom.baseEl.querySelector('.apexcharts-ycrosshairs'); ttCtx.ycrosshairsHidden = w.globals.dom.baseEl.querySelector('.apexcharts-ycrosshairs-hidden'); } }, { key: "drawYaxisTooltipText", value: function drawYaxisTooltipText(index, clientY, xyRatios) { var ttCtx = this.ttCtx; var w = this.w; var lbFormatter = w.globals.yLabelFormatters[index]; if (ttCtx.blyaxisTooltip) { var elGrid = ttCtx.getElGrid(); var seriesBound = elGrid.getBoundingClientRect(); var hoverY = (clientY - seriesBound.top) * xyRatios.yRatio[index]; var height = w.globals.maxYArr[index] - w.globals.minYArr[index]; var val = w.globals.minYArr[index] + (height - hoverY); ttCtx.tooltipPosition.moveYCrosshairs(clientY - seriesBound.top); ttCtx.yaxisTooltipText[index].innerHTML = lbFormatter(val); ttCtx.tooltipPosition.moveYAxisTooltip(index); } } }]); return AxesTooltip; }(); /** * ApexCharts Core Tooltip Class to handle the tooltip generation. * * @module Tooltip **/ var Tooltip = /*#__PURE__*/ function () { function Tooltip(ctx) { _classCallCheck(this, Tooltip); this.ctx = ctx; this.w = ctx.w; var w = this.w; this.tooltipUtil = new Utils$1(this); this.tooltipLabels = new Labels(this); this.tooltipPosition = new Position(this); this.marker = new Marker(this); this.intersect = new Intersect(this); this.axesTooltip = new AxesTooltip(this); this.showOnIntersect = w.config.tooltip.intersect; this.showTooltipTitle = w.config.tooltip.x.show; this.fixedTooltip = w.config.tooltip.fixed.enabled; this.xaxisTooltip = null; this.yaxisTTEls = null; this.isBarShared = !w.globals.isBarHorizontal && w.config.tooltip.shared; } _createClass(Tooltip, [{ key: "getElTooltip", value: function getElTooltip(ctx) { if (!ctx) ctx = this; return ctx.w.globals.dom.baseEl.querySelector('.apexcharts-tooltip'); } }, { key: "getElXCrosshairs", value: function getElXCrosshairs() { return this.w.globals.dom.baseEl.querySelector('.apexcharts-xcrosshairs'); } }, { key: "getElGrid", value: function getElGrid() { return this.w.globals.dom.baseEl.querySelector('.apexcharts-grid'); } }, { key: "drawTooltip", value: function drawTooltip(xyRatios) { var w = this.w; this.xyRatios = xyRatios; this.blxaxisTooltip = w.config.xaxis.tooltip.enabled && w.globals.axisCharts; this.blyaxisTooltip = w.config.yaxis[0].tooltip.enabled && w.globals.axisCharts; this.allTooltipSeriesGroups = []; if (!w.globals.axisCharts) { this.showTooltipTitle = false; } var tooltipEl = document.createElement('div'); tooltipEl.classList.add('apexcharts-tooltip'); tooltipEl.classList.add(w.config.tooltip.theme); w.globals.dom.elWrap.appendChild(tooltipEl); if (w.globals.axisCharts) { this.axesTooltip.drawXaxisTooltip(); this.axesTooltip.drawYaxisTooltip(); this.axesTooltip.setXCrosshairWidth(); this.axesTooltip.handleYCrosshair(); var xAxis = new XAxis(this.ctx); this.xAxisTicksPositions = xAxis.getXAxisTicksPositions(); } // we forcefully set intersect true for these conditions if (w.globals.comboCharts && !w.config.tooltip.shared || w.config.tooltip.intersect && !w.config.tooltip.shared || (w.config.chart.type === 'bar' || w.config.chart.type === 'rangeBar') && !w.config.tooltip.shared) { this.showOnIntersect = true; } if (w.config.markers.size === 0 || w.globals.markers.largestSize === 0) { // when user don't want to show points all the time, but only on when hovering on series this.marker.drawDynamicPoints(this); } // no visible series, exit if (w.globals.collapsedSeries.length === w.globals.series.length) return; this.dataPointsDividedHeight = w.globals.gridHeight / w.globals.dataPoints; this.dataPointsDividedWidth = w.globals.gridWidth / w.globals.dataPoints; if (this.showTooltipTitle) { this.tooltipTitle = document.createElement('div'); this.tooltipTitle.classList.add('apexcharts-tooltip-title'); this.tooltipTitle.style.fontFamily = w.config.tooltip.style.fontFamily || w.config.chart.fontFamily; this.tooltipTitle.style.fontSize = w.config.tooltip.style.fontSize; tooltipEl.appendChild(this.tooltipTitle); } var ttItemsCnt = w.globals.series.length; // whether shared or not, default is shared if ((w.globals.xyCharts || w.globals.comboCharts) && w.config.tooltip.shared) { if (!this.showOnIntersect) { ttItemsCnt = w.globals.series.length; } else { ttItemsCnt = 1; } } this.ttItems = this.createTTElements(ttItemsCnt); this.addSVGEvents(); } }, { key: "createTTElements", value: function createTTElements(ttItemsCnt) { var w = this.w; var ttItems = []; var tooltipEl = this.getElTooltip(); for (var i = 0; i < ttItemsCnt; i++) { var gTxt = document.createElement('div'); gTxt.classList.add('apexcharts-tooltip-series-group'); var point = document.createElement('span'); point.classList.add('apexcharts-tooltip-marker'); point.style.backgroundColor = w.globals.colors[i]; gTxt.appendChild(point); var gYZ = document.createElement('div'); gYZ.classList.add('apexcharts-tooltip-text'); gYZ.style.fontFamily = w.config.tooltip.style.fontFamily || w.config.chart.fontFamily; gYZ.style.fontSize = w.config.tooltip.style.fontSize; // y values group var gYValText = document.createElement('div'); gYValText.classList.add('apexcharts-tooltip-y-group'); var txtLabel = document.createElement('span'); txtLabel.classList.add('apexcharts-tooltip-text-label'); gYValText.appendChild(txtLabel); var txtValue = document.createElement('span'); txtValue.classList.add('apexcharts-tooltip-text-value'); gYValText.appendChild(txtValue); // z values group var gZValText = document.createElement('div'); gZValText.classList.add('apexcharts-tooltip-z-group'); var txtZLabel = document.createElement('span'); txtZLabel.classList.add('apexcharts-tooltip-text-z-label'); gZValText.appendChild(txtZLabel); var txtZValue = document.createElement('span'); txtZValue.classList.add('apexcharts-tooltip-text-z-value'); gZValText.appendChild(txtZValue); gYZ.appendChild(gYValText); gYZ.appendChild(gZValText); gTxt.appendChild(gYZ); tooltipEl.appendChild(gTxt); ttItems.push(gTxt); } return ttItems; } }, { key: "addSVGEvents", value: function addSVGEvents() { var w = this.w; var type = w.config.chart.type; var tooltipEl = this.getElTooltip(); var commonBar = !!(type === 'bar' || type === 'candlestick' || type === 'rangeBar'); var hoverArea = w.globals.dom.Paper.node; var elGrid = this.getElGrid(); if (elGrid) { this.seriesBound = elGrid.getBoundingClientRect(); } var tooltipY = []; var tooltipX = []; var seriesHoverParams = { hoverArea: hoverArea, elGrid: elGrid, tooltipEl: tooltipEl, tooltipY: tooltipY, tooltipX: tooltipX, ttItems: this.ttItems }; var points; if (w.globals.axisCharts) { if (type === 'area' || type === 'line' || type === 'scatter' || type === 'bubble') { points = w.globals.dom.baseEl.querySelectorAll(".apexcharts-series[data\\:longestSeries='true'] .apexcharts-marker"); } else if (commonBar) { points = w.globals.dom.baseEl.querySelectorAll('.apexcharts-series .apexcharts-bar-area, .apexcharts-series .apexcharts-candlestick-area, .apexcharts-series .apexcharts-rangebar-area'); } else if (type === 'heatmap') { points = w.globals.dom.baseEl.querySelectorAll('.apexcharts-series .apexcharts-heatmap'); } else if (type === 'radar') { points = w.globals.dom.baseEl.querySelectorAll('.apexcharts-series .apexcharts-marker'); } if (points && points.length) { for (var p = 0; p < points.length; p++) { tooltipY.push(points[p].getAttribute('cy')); tooltipX.push(points[p].getAttribute('cx')); } } } var validSharedChartTypes = w.globals.xyCharts && !this.showOnIntersect || w.globals.comboCharts && !this.showOnIntersect || commonBar && this.hasBars() && w.config.tooltip.shared; if (validSharedChartTypes) { this.addPathsEventListeners([hoverArea], seriesHoverParams); } else if (commonBar && !w.globals.comboCharts) { this.addBarsEventListeners(seriesHoverParams); } else if (type === 'bubble' || type === 'scatter' || type === 'radar' || this.showOnIntersect && (type === 'area' || type === 'line')) { this.addPointsEventsListeners(seriesHoverParams); } else if (!w.globals.axisCharts || type === 'heatmap') { var seriesAll = w.globals.dom.baseEl.querySelectorAll('.apexcharts-series'); this.addPathsEventListeners(seriesAll, seriesHoverParams); } if (this.showOnIntersect) { var linePoints = w.globals.dom.baseEl.querySelectorAll('.apexcharts-line-series .apexcharts-marker'); if (linePoints.length > 0) { // if we find any lineSeries, addEventListeners for them this.addPathsEventListeners(linePoints, seriesHoverParams); } var areaPoints = w.globals.dom.baseEl.querySelectorAll('.apexcharts-area-series .apexcharts-marker'); if (areaPoints.length > 0) { // if we find any areaSeries, addEventListeners for them this.addPathsEventListeners(areaPoints, seriesHoverParams); } // combo charts may have bars, so add event listeners here too if (this.hasBars() && !w.config.tooltip.shared) { this.addBarsEventListeners(seriesHoverParams); } } } }, { key: "drawFixedTooltipRect", value: function drawFixedTooltipRect() { var w = this.w; var tooltipEl = this.getElTooltip(); var tooltipRect = tooltipEl.getBoundingClientRect(); var ttWidth = tooltipRect.width + 10; var ttHeight = tooltipRect.height + 10; var x = w.config.tooltip.fixed.offsetX; var y = w.config.tooltip.fixed.offsetY; if (w.config.tooltip.fixed.position.toLowerCase().indexOf('right') > -1) { x = x + w.globals.svgWidth - ttWidth + 10; } if (w.config.tooltip.fixed.position.toLowerCase().indexOf('bottom') > -1) { y = y + w.globals.svgHeight - ttHeight - 10; } tooltipEl.style.left = x + 'px'; tooltipEl.style.top = y + 'px'; return { x: x, y: y, ttWidth: ttWidth, ttHeight: ttHeight }; } }, { key: "addPointsEventsListeners", value: function addPointsEventsListeners(seriesHoverParams) { var w = this.w; var points = w.globals.dom.baseEl.querySelectorAll('.apexcharts-series-markers .apexcharts-marker'); this.addPathsEventListeners(points, seriesHoverParams); } }, { key: "addBarsEventListeners", value: function addBarsEventListeners(seriesHoverParams) { var w = this.w; var bars = w.globals.dom.baseEl.querySelectorAll('.apexcharts-bar-area, .apexcharts-candlestick-area, .apexcharts-rangebar-area'); this.addPathsEventListeners(bars, seriesHoverParams); } }, { key: "addPathsEventListeners", value: function addPathsEventListeners(paths, opts) { var _this = this; var self = this; var _loop = function _loop(p) { var extendedOpts = { paths: paths[p], tooltipEl: opts.tooltipEl, tooltipY: opts.tooltipY, tooltipX: opts.tooltipX, elGrid: opts.elGrid, hoverArea: opts.hoverArea, ttItems: opts.ttItems }; _this.w.globals.tooltipOpts = extendedOpts; var events = ['mousemove', 'mouseup', 'touchmove', 'mouseout', 'touchend']; events.map(function (ev) { return paths[p].addEventListener(ev, self.seriesHover.bind(self, extendedOpts), { capture: false, passive: true }); }); }; for (var p = 0; p < paths.length; p++) { _loop(p); } } /* ** The actual series hover function */ }, { key: "seriesHover", value: function seriesHover(opt, e) { var _this2 = this; var chartGroups = []; var w = this.w; // if user has more than one charts in group, we need to sync if (w.config.chart.group) { chartGroups = this.ctx.getGroupedCharts(); } if (w.globals.axisCharts && (w.globals.minX === -Infinity && w.globals.maxX === Infinity || w.globals.dataPoints === 0)) { return; } if (chartGroups.length) { chartGroups.forEach(function (ch) { var tooltipEl = _this2.getElTooltip(ch); var newOpts = { paths: opt.paths, tooltipEl: tooltipEl, tooltipY: opt.tooltipY, tooltipX: opt.tooltipX, elGrid: opt.elGrid, hoverArea: opt.hoverArea, ttItems: ch.w.globals.tooltip.ttItems // all the charts should have the same minX and maxX (same xaxis) for multiple tooltips to work correctly }; if (ch.w.globals.minX === _this2.w.globals.minX && ch.w.globals.maxX === _this2.w.globals.maxX) { ch.w.globals.tooltip.seriesHoverByContext({ chartCtx: ch, ttCtx: ch.w.globals.tooltip, opt: newOpts, e: e }); } }); } else { this.seriesHoverByContext({ chartCtx: this.ctx, ttCtx: this.w.globals.tooltip, opt: opt, e: e }); } } }, { key: "seriesHoverByContext", value: function seriesHoverByContext(_ref) { var chartCtx = _ref.chartCtx, ttCtx = _ref.ttCtx, opt = _ref.opt, e = _ref.e; var w = chartCtx.w; var tooltipEl = this.getElTooltip(); // tooltipRect is calculated on every mousemove, because the text is dynamic ttCtx.tooltipRect = { x: 0, y: 0, ttWidth: tooltipEl.getBoundingClientRect().width, ttHeight: tooltipEl.getBoundingClientRect().height }; ttCtx.e = e; // highlight the current hovered bars if (ttCtx.hasBars() && !w.globals.comboCharts && !ttCtx.isBarShared) { if (w.config.tooltip.onDatasetHover.highlightDataSeries) { var series = new Series(chartCtx); series.toggleSeriesOnHover(e, e.target.parentNode); } } if (ttCtx.fixedTooltip) { ttCtx.drawFixedTooltipRect(); } if (w.globals.axisCharts) { ttCtx.axisChartsTooltips({ e: e, opt: opt, tooltipRect: ttCtx.tooltipRect }); } else { // non-plot charts i.e pie/donut/circle ttCtx.nonAxisChartsTooltips({ e: e, opt: opt, tooltipRect: ttCtx.tooltipRect }); } } // tooltip handling for line/area/bar/columns/scatter }, { key: "axisChartsTooltips", value: function axisChartsTooltips(_ref2) { var e = _ref2.e, opt = _ref2.opt; var w = this.w; var j, x, y; var self = this; var capj = null; var seriesBound = opt.elGrid.getBoundingClientRect(); var clientX = e.type === 'touchmove' ? e.touches[0].clientX : e.clientX; var clientY = e.type === 'touchmove' ? e.touches[0].clientY : e.clientY; this.clientY = clientY; this.clientX = clientX; if (clientY < seriesBound.top || clientY > seriesBound.top + seriesBound.height) { self.handleMouseOut(opt); return; } var tooltipEl = this.getElTooltip(); var xcrosshairs = this.getElXCrosshairs(); var isStickyTooltip = w.globals.xyCharts || w.config.chart.type === 'bar' && !w.globals.isBarHorizontal && this.hasBars() && w.config.tooltip.shared || w.globals.comboCharts && this.hasBars; if (w.globals.isBarHorizontal && this.hasBars()) { isStickyTooltip = false; } if (e.type === 'mousemove' || e.type === 'touchmove' || e.type === 'mouseup') { if (xcrosshairs !== null) { xcrosshairs.classList.add('active'); } if (self.ycrosshairs !== null && self.blyaxisTooltip) { self.ycrosshairs.classList.add('active'); } if (isStickyTooltip && !self.showOnIntersect) { capj = self.tooltipUtil.getNearestValues({ context: self, hoverArea: opt.hoverArea, elGrid: opt.elGrid, clientX: clientX, clientY: clientY, hasBars: self.hasBars }); j = capj.j; var capturedSeries = capj.capturedSeries; if (capj.hoverX < 0 || capj.hoverX > w.globals.gridWidth) { self.handleMouseOut(opt); return; } if (capturedSeries !== null) { var ignoreNull = w.globals.series[capturedSeries][j] === null; if (ignoreNull) { opt.tooltipEl.classList.remove('active'); return; } if (typeof w.globals.series[capturedSeries][j] !== 'undefined') { if (w.config.tooltip.shared && this.tooltipUtil.isXoverlap(j) && this.tooltipUtil.isinitialSeriesSameLen()) { this.create(e, self, capturedSeries, j, opt.ttItems); } else { this.create(e, self, capturedSeries, j, opt.ttItems, false); } } else { if (this.tooltipUtil.isXoverlap(j)) { self.create(e, self, 0, j, opt.ttItems); } } } else { // couldn't capture any series. check if shared X is same, // if yes, draw a grouped tooltip if (this.tooltipUtil.isXoverlap(j)) { self.create(e, self, 0, j, opt.ttItems); } } } else { if (w.config.chart.type === 'heatmap') { var markerXY = this.intersect.handleHeatTooltip({ e: e, opt: opt, x: x, y: y }); x = markerXY.x; y = markerXY.y; tooltipEl.style.left = x + 'px'; tooltipEl.style.top = y + 'px'; } else { if (this.hasBars) { this.intersect.handleBarTooltip({ e: e, opt: opt }); } if (this.hasMarkers) { // intersect - line/area/scatter/bubble this.intersect.handleMarkerTooltip({ e: e, opt: opt, x: x, y: y }); } } } if (this.blyaxisTooltip) { for (var yt = 0; yt < w.config.yaxis.length; yt++) { self.axesTooltip.drawYaxisTooltipText(yt, clientY, self.xyRatios); } } opt.tooltipEl.classList.add('active'); } else if (e.type === 'mouseout' || e.type === 'touchend') { this.handleMouseOut(opt); } } // tooltip handling for pie/donuts }, { key: "nonAxisChartsTooltips", value: function nonAxisChartsTooltips(_ref3) { var e = _ref3.e, opt = _ref3.opt, tooltipRect = _ref3.tooltipRect; var w = this.w; var rel = opt.paths.getAttribute('rel'); var tooltipEl = this.getElTooltip(); var seriesBound = w.globals.dom.elWrap.getBoundingClientRect(); if (e.type === 'mousemove' || e.type === 'touchmove') { tooltipEl.classList.add('active'); this.tooltipLabels.drawSeriesTexts({ ttItems: opt.ttItems, i: parseInt(rel) - 1, shared: false }); var x = w.globals.clientX - seriesBound.left - tooltipRect.ttWidth / 2; var y = w.globals.clientY - seriesBound.top - tooltipRect.ttHeight - 10; tooltipEl.style.left = x + 'px'; tooltipEl.style.top = y + 'px'; } else if (e.type === 'mouseout' || e.type === 'touchend') { tooltipEl.classList.remove('active'); } } }, { key: "deactivateHoverFilter", value: function deactivateHoverFilter() { var w = this.w; var graphics = new Graphics(this.ctx); var allPaths = w.globals.dom.Paper.select(".apexcharts-bar-area"); for (var b = 0; b < allPaths.length; b++) { graphics.pathMouseLeave(allPaths[b]); } } }, { key: "handleMouseOut", value: function handleMouseOut(opt) { var w = this.w; var xcrosshairs = this.getElXCrosshairs(); opt.tooltipEl.classList.remove('active'); this.deactivateHoverFilter(); if (w.config.chart.type !== 'bubble') { this.marker.resetPointsSize(); } if (xcrosshairs !== null) { xcrosshairs.classList.remove('active'); } if (this.ycrosshairs !== null) { this.ycrosshairs.classList.remove('active'); } if (this.blxaxisTooltip) { this.xaxisTooltip.classList.remove('active'); } if (this.blyaxisTooltip) { if (this.yaxisTTEls === null) { this.yaxisTTEls = w.globals.dom.baseEl.querySelectorAll('.apexcharts-yaxistooltip'); } for (var i = 0; i < this.yaxisTTEls.length; i++) { this.yaxisTTEls[i].classList.remove('active'); } } } }, { key: "getElMarkers", value: function getElMarkers() { return this.w.globals.dom.baseEl.querySelectorAll(' .apexcharts-series-markers'); } }, { key: "getAllMarkers", value: function getAllMarkers() { return this.w.globals.dom.baseEl.querySelectorAll('.apexcharts-series-markers .apexcharts-marker'); } }, { key: "hasMarkers", value: function hasMarkers() { var markers = this.getElMarkers(); return markers.length > 0; } }, { key: "getElBars", value: function getElBars() { return this.w.globals.dom.baseEl.querySelectorAll('.apexcharts-bar-series, .apexcharts-candlestick-series, .apexcharts-rangebar-series'); } }, { key: "hasBars", value: function hasBars() { var bars = this.getElBars(); return bars.length > 0; } }, { key: "markerClick", value: function markerClick(e, seriesIndex, dataPointIndex) { var w = this.w; if (typeof w.config.chart.events.markerClick === 'function') { w.config.chart.events.markerClick(e, this.ctx, { seriesIndex: seriesIndex, dataPointIndex: dataPointIndex, w: w }); } this.ctx.fireEvent('markerClick', [e, this.ctx, { seriesIndex: seriesIndex, dataPointIndex: dataPointIndex, w: w }]); } }, { key: "create", value: function create(e, context, capturedSeries, j, ttItems) { var shared = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; var w = this.w; var ttCtx = context; if (e.type === 'mouseup') { this.markerClick(e, capturedSeries, j); } if (shared === null) shared = w.config.tooltip.shared; var hasMarkers = this.hasMarkers(); var bars = this.getElBars(); if (shared) { ttCtx.tooltipLabels.drawSeriesTexts({ ttItems: ttItems, i: capturedSeries, j: j, shared: this.showOnIntersect ? false : w.config.tooltip.shared }); if (hasMarkers) { if (w.globals.markers.largestSize > 0) { ttCtx.marker.enlargePoints(j); } else { ttCtx.tooltipPosition.moveDynamicPointsOnHover(j); } } if (this.hasBars()) { this.barSeriesHeight = this.tooltipUtil.getBarsHeight(bars); if (this.barSeriesHeight > 0) { // hover state, activate snap filter var graphics = new Graphics(this.ctx); var paths = w.globals.dom.Paper.select(".apexcharts-bar-area[j='".concat(j, "']")); // de-activate first this.deactivateHoverFilter(); this.tooltipPosition.moveStickyTooltipOverBars(j); for (var b = 0; b < paths.length; b++) { graphics.pathMouseEnter(paths[b]); } } } } else { ttCtx.tooltipLabels.drawSeriesTexts({ shared: false, ttItems: ttItems, i: capturedSeries, j: j }); if (this.hasBars()) { ttCtx.tooltipPosition.moveStickyTooltipOverBars(j); } if (hasMarkers) { ttCtx.tooltipPosition.moveMarkers(capturedSeries, j); } } } }]); return Tooltip; }(); var icoPan = "<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" fill=\"#000000\" height=\"24\" viewBox=\"0 0 24 24\" width=\"24\">\n <defs>\n <path d=\"M0 0h24v24H0z\" id=\"a\"/>\n </defs>\n <clipPath id=\"b\">\n <use overflow=\"visible\" xlink:href=\"#a\"/>\n </clipPath>\n <path clip-path=\"url(#b)\" d=\"M23 5.5V20c0 2.2-1.8 4-4 4h-7.3c-1.08 0-2.1-.43-2.85-1.19L1 14.83s1.26-1.23 1.3-1.25c.22-.19.49-.29.79-.29.22 0 .42.06.6.16.04.01 4.31 2.46 4.31 2.46V4c0-.83.67-1.5 1.5-1.5S11 3.17 11 4v7h1V1.5c0-.83.67-1.5 1.5-1.5S15 .67 15 1.5V11h1V2.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5V11h1V5.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5z\"/>\n</svg>"; var icoZoom = "<svg xmlns=\"http://www.w3.org/2000/svg\" fill=\"#000000\" height=\"24\" viewBox=\"0 0 24 24\" width=\"24\">\n <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 14z\"/>\n <path d=\"M0 0h24v24H0V0z\" fill=\"none\"/>\n <path d=\"M12 10h-2v2H9v-2H7V9h2V7h1v2h2v1z\"/>\n</svg>"; var icoReset = "<svg fill=\"#000000\" height=\"24\" viewBox=\"0 0 24 24\" width=\"24\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z\"/>\n <path d=\"M0 0h24v24H0z\" fill=\"none\"/>\n</svg>"; var icoZoomIn = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\">\n <path d=\"M0 0h24v24H0z\" fill=\"none\"/>\n <path d=\"M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4V7zm-1-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z\"/>\n</svg>\n"; var icoZoomOut = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\">\n <path d=\"M0 0h24v24H0z\" fill=\"none\"/>\n <path d=\"M7 11v2h10v-2H7zm5-9C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z\"/>\n</svg>\n"; var icoSelect = "<svg fill=\"#6E8192\" height=\"24\" viewBox=\"0 0 24 24\" width=\"24\" xmlns=\"http://www.w3.org/2000/svg\">\n <path d=\"M0 0h24v24H0z\" fill=\"none\"/>\n <path d=\"M3 5h2V3c-1.1 0-2 .9-2 2zm0 8h2v-2H3v2zm4 8h2v-2H7v2zM3 9h2V7H3v2zm10-6h-2v2h2V3zm6 0v2h2c0-1.1-.9-2-2-2zM5 21v-2H3c0 1.1.9 2 2 2zm-2-4h2v-2H3v2zM9 3H7v2h2V3zm2 18h2v-2h-2v2zm8-8h2v-2h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2zm0-12h2V7h-2v2zm0 8h2v-2h-2v2zm-4 4h2v-2h-2v2zm0-16h2V3h-2v2z\"/>\n</svg>"; var icoMenu = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"24\" height=\"24\" viewBox=\"0 0 24 24\"><path fill=\"none\" d=\"M0 0h24v24H0V0z\"/><path d=\"M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z\"/></svg>"; /** * ApexCharts Toolbar Class for creating toolbar in axis based charts. * * @module Toolbar **/ var Toolbar = /*#__PURE__*/ function () { function Toolbar(ctx) { _classCallCheck(this, Toolbar); this.ctx = ctx; this.w = ctx.w; this.ev = this.w.config.chart.events; this.localeValues = this.w.globals.locale.toolbar; } _createClass(Toolbar, [{ key: "createToolbar", value: function createToolbar() { var w = this.w; var elToolbarWrap = document.createElement('div'); elToolbarWrap.setAttribute('class', 'apexcharts-toolbar'); w.globals.dom.elWrap.appendChild(elToolbarWrap); this.elZoom = document.createElement('div'); this.elZoomIn = document.createElement('div'); this.elZoomOut = document.createElement('div'); this.elPan = document.createElement('div'); this.elSelection = document.createElement('div'); this.elZoomReset = document.createElement('div'); this.elMenuIcon = document.createElement('div'); this.elMenu = document.createElement('div'); this.elCustomIcons = []; this.t = w.config.chart.toolbar.tools; if (Array.isArray(this.t.customIcons)) { for (var i = 0; i < this.t.customIcons.length; i++) { this.elCustomIcons.push(document.createElement('div')); } } this.elMenuItems = []; var toolbarControls = []; if (this.t.zoomin && w.config.chart.zoom.enabled) { toolbarControls.push({ el: this.elZoomIn, icon: typeof this.t.zoomin === 'string' ? this.t.zoomin : icoZoomIn, title: this.localeValues.zoomIn, class: 'apexcharts-zoom-in-icon' }); } if (this.t.zoomout && w.config.chart.zoom.enabled) { toolbarControls.push({ el: this.elZoomOut, icon: typeof this.t.zoomout === 'string' ? this.t.zoomout : icoZoomOut, title: this.localeValues.zoomOut, class: 'apexcharts-zoom-out-icon' }); } if (this.t.zoom && w.config.chart.zoom.enabled) { toolbarControls.push({ el: this.elZoom, icon: typeof this.t.zoom === 'string' ? this.t.zoom : icoZoom, title: this.localeValues.selectionZoom, class: w.globals.isTouchDevice ? 'hidden' : 'apexcharts-zoom-icon' }); } if (this.t.selection && w.config.chart.selection.enabled) { toolbarControls.push({ el: this.elSelection, icon: typeof this.t.selection === 'string' ? this.t.selection : icoSelect, title: this.localeValues.selection, class: w.globals.isTouchDevice ? 'hidden' : 'apexcharts-selection-icon' }); } if (this.t.pan && w.config.chart.zoom.enabled) { toolbarControls.push({ el: this.elPan, icon: typeof this.t.pan === 'string' ? this.t.pan : icoPan, title: this.localeValues.pan, class: w.globals.isTouchDevice ? 'hidden' : 'apexcharts-pan-icon' }); } if (this.t.reset && w.config.chart.zoom.enabled) { toolbarControls.push({ el: this.elZoomReset, icon: typeof this.t.reset === 'string' ? this.t.reset : icoReset, title: this.localeValues.reset, class: 'apexcharts-reset-zoom-icon' }); } if (this.t.download) { toolbarControls.push({ el: this.elMenuIcon, icon: typeof this.t.download === 'string' ? this.t.download : icoMenu, title: this.localeValues.menu, class: 'apexcharts-menu-icon' }); } for (var _i = 0; _i < this.elCustomIcons.length; _i++) { toolbarControls.push({ el: this.elCustomIcons[_i], icon: this.t.customIcons[_i].icon, title: this.t.customIcons[_i].title, index: this.t.customIcons[_i].index, class: 'apexcharts-toolbar-custom-icon ' + this.t.customIcons[_i].class }); } toolbarControls.forEach(function (t, index) { if (t.index) { Utils.moveIndexInArray(toolbarControls, index, t.index); } }); for (var _i2 = 0; _i2 < toolbarControls.length; _i2++) { Graphics.setAttrs(toolbarControls[_i2].el, { class: toolbarControls[_i2].class, title: toolbarControls[_i2].title }); toolbarControls[_i2].el.innerHTML = toolbarControls[_i2].icon; elToolbarWrap.appendChild(toolbarControls[_i2].el); } elToolbarWrap.appendChild(this.elMenu); Graphics.setAttrs(this.elMenu, { class: 'apexcharts-menu' }); var menuItems = [{ name: 'exportSVG', title: this.localeValues.exportToSVG }, { name: 'exportPNG', title: this.localeValues.exportToPNG }]; for (var _i3 = 0; _i3 < menuItems.length; _i3++) { this.elMenuItems.push(document.createElement('div')); this.elMenuItems[_i3].innerHTML = menuItems[_i3].title; Graphics.setAttrs(this.elMenuItems[_i3], { class: "apexcharts-menu-item ".concat(menuItems[_i3].name), title: menuItems[_i3].title }); this.elMenu.appendChild(this.elMenuItems[_i3]); } if (w.globals.zoomEnabled) { this.elZoom.classList.add('selected'); } else if (w.globals.panEnabled) { this.elPan.classList.add('selected'); } else if (w.globals.selectionEnabled) { this.elSelection.classList.add('selected'); } this.addToolbarEventListeners(); } }, { key: "addToolbarEventListeners", value: function addToolbarEventListeners() { var _this = this; this.elZoomReset.addEventListener('click', this.handleZoomReset.bind(this)); this.elSelection.addEventListener('click', this.toggleSelection.bind(this)); this.elZoom.addEventListener('click', this.toggleZooming.bind(this)); this.elZoomIn.addEventListener('click', this.handleZoomIn.bind(this)); this.elZoomOut.addEventListener('click', this.handleZoomOut.bind(this)); this.elPan.addEventListener('click', this.togglePanning.bind(this)); this.elMenuIcon.addEventListener('click', this.toggleMenu.bind(this)); this.elMenuItems.forEach(function (m) { if (m.classList.contains('exportSVG')) { m.addEventListener('click', _this.downloadSVG.bind(_this)); } else if (m.classList.contains('exportPNG')) { m.addEventListener('click', _this.downloadPNG.bind(_this)); } }); for (var i = 0; i < this.t.customIcons.length; i++) { this.elCustomIcons[i].addEventListener('click', this.t.customIcons[i].click); } } }, { key: "toggleSelection", value: function toggleSelection() { this.toggleOtherControls(); this.w.globals.selectionEnabled = !this.w.globals.selectionEnabled; if (!this.elSelection.classList.contains('selected')) { this.elSelection.classList.add('selected'); } else { this.elSelection.classList.remove('selected'); } } }, { key: "toggleZooming", value: function toggleZooming() { this.toggleOtherControls(); this.w.globals.zoomEnabled = !this.w.globals.zoomEnabled; if (!this.elZoom.classList.contains('selected')) { this.elZoom.classList.add('selected'); } else { this.elZoom.classList.remove('selected'); } } }, { key: "getToolbarIconsReference", value: function getToolbarIconsReference() { var w = this.w; if (!this.elZoom) { this.elZoom = w.globals.dom.baseEl.querySelector('.apexcharts-zoom-icon'); } if (!this.elPan) { this.elPan = w.globals.dom.baseEl.querySelector('.apexcharts-pan-icon'); } if (!this.elSelection) { this.elSelection = w.globals.dom.baseEl.querySelector('.apexcharts-selection-icon'); } } }, { key: "enableZooming", value: function enableZooming() { this.toggleOtherControls(); this.w.globals.zoomEnabled = true; if (this.elZoom) { this.elZoom.classList.add('selected'); } if (this.elPan) { this.elPan.classList.remove('selected'); } } }, { key: "enablePanning", value: function enablePanning() { this.toggleOtherControls(); this.w.globals.panEnabled = true; if (this.elPan) { this.elPan.classList.add('selected'); } if (this.elZoom) { this.elZoom.classList.remove('selected'); } } }, { key: "togglePanning", value: function togglePanning() { this.toggleOtherControls(); this.w.globals.panEnabled = !this.w.globals.panEnabled; if (!this.elPan.classList.contains('selected')) { this.elPan.classList.add('selected'); } else { this.elPan.classList.remove('selected'); } } }, { key: "toggleOtherControls", value: function toggleOtherControls() { var w = this.w; w.globals.panEnabled = false; w.globals.zoomEnabled = false; w.globals.selectionEnabled = false; this.getToolbarIconsReference(); if (this.elPan) { this.elPan.classList.remove('selected'); } if (this.elSelection) { this.elSelection.classList.remove('selected'); } if (this.elZoom) { this.elZoom.classList.remove('selected'); } } }, { key: "handleZoomIn", value: function handleZoomIn() { var w = this.w; var centerX = (w.globals.minX + w.globals.maxX) / 2; var newMinX = (w.globals.minX + centerX) / 2; var newMaxX = (w.globals.maxX + centerX) / 2; if (!w.globals.disableZoomIn) { this.zoomUpdateOptions(newMinX, newMaxX); } } }, { key: "handleZoomOut", value: function handleZoomOut() { var w = this.w; // avoid zooming out beyond 1000 which may result in NaN values being printed on x-axis if (w.config.xaxis.type === 'datetime' && new Date(w.globals.minX).getUTCFullYear() < 1000) { return; } var centerX = (w.globals.minX + w.globals.maxX) / 2; var newMinX = w.globals.minX - (centerX - w.globals.minX); var newMaxX = w.globals.maxX - (centerX - w.globals.maxX); if (!w.globals.disableZoomOut) { this.zoomUpdateOptions(newMinX, newMaxX); } } }, { key: "zoomUpdateOptions", value: function zoomUpdateOptions(newMinX, newMaxX) { var xaxis = { min: newMinX, max: newMaxX }; var beforeZoomRange = this.getBeforeZoomRange(xaxis); if (beforeZoomRange) { xaxis = beforeZoomRange.xaxis; } this.w.globals.zoomed = true; this.ctx._updateOptions({ xaxis: xaxis }, false, this.w.config.chart.animations.dynamicAnimation.enabled); this.zoomCallback(xaxis); } }, { key: "zoomCallback", value: function zoomCallback(xaxis, yaxis) { if (typeof this.ev.zoomed === 'function') { this.ev.zoomed(this.ctx, { xaxis: xaxis, yaxis: yaxis }); } } }, { key: "getBeforeZoomRange", value: function getBeforeZoomRange(xaxis, yaxis) { var newRange = null; if (typeof this.ev.beforeZoom === 'function') { newRange = this.ev.beforeZoom(this, { xaxis: xaxis, yaxis: yaxis }); } return newRange; } }, { key: "toggleMenu", value: function toggleMenu() { if (this.elMenu.classList.contains('open')) { this.elMenu.classList.remove('open'); } else { this.elMenu.classList.add('open'); } } }, { key: "downloadPNG", value: function downloadPNG() { var downloadPNG = new Exports(this.ctx); downloadPNG.exportToPng(this.ctx); this.toggleMenu(); } }, { key: "downloadSVG", value: function downloadSVG() { var downloadSVG = new Exports(this.ctx); downloadSVG.exportToSVG(); this.toggleMenu(); } }, { key: "handleZoomReset", value: function handleZoomReset(e) { var _this2 = this; var charts = this.ctx.getSyncedCharts(); charts.forEach(function (ch) { var w = ch.w; if (w.globals.minX !== w.globals.initialminX && w.globals.maxX !== w.globals.initialmaxX) { ch.revertDefaultAxisMinMax(); if (typeof w.config.chart.events.zoomed === 'function') { _this2.zoomCallback({ min: w.config.xaxis.min, max: w.config.xaxis.max }); } w.globals.zoomed = false; ch._updateSeries(w.globals.initialSeries, w.config.chart.animations.dynamicAnimation.enabled); } }); } }, { key: "destroy", value: function destroy() { if (this.elZoomReset) { this.elZoomReset.removeEventListener('click', this.handleZoomReset.bind(this)); this.elSelection.removeEventListener('click', this.toggleSelection.bind(this)); this.elZoom.removeEventListener('click', this.toggleZooming.bind(this)); this.elZoomIn.removeEventListener('click', this.handleZoomIn.bind(this)); this.elZoomOut.removeEventListener('click', this.handleZoomOut.bind(this)); this.elPan.removeEventListener('click', this.togglePanning.bind(this)); this.elMenuIcon.removeEventListener('click', this.toggleMenu.bind(this)); } this.elZoom = null; this.elZoomIn = null; this.elZoomOut = null; this.elPan = null; this.elSelection = null; this.elZoomReset = null; this.elMenuIcon = null; } }]); return Toolbar; }(); /** * ApexCharts Zoom Class for handling zooming and panning on axes based charts. * * @module ZoomPanSelection **/ var ZoomPanSelection = /*#__PURE__*/ function (_Toolbar) { _inherits(ZoomPanSelection, _Toolbar); function ZoomPanSelection(ctx) { var _this; _classCallCheck(this, ZoomPanSelection); _this = _possibleConstructorReturn(this, _getPrototypeOf(ZoomPanSelection).call(this, ctx)); _this.ctx = ctx; _this.w = ctx.w; _this.dragged = false; _this.graphics = new Graphics(_this.ctx); _this.eventList = ['mousedown', 'mousemove', 'touchstart', 'touchmove', 'mouseup', 'touchend']; _this.clientX = 0; _this.clientY = 0; _this.startX = 0; _this.endX = 0; _this.dragX = 0; _this.startY = 0; _this.endY = 0; _this.dragY = 0; return _this; } _createClass(ZoomPanSelection, [{ key: "init", value: function init(_ref) { var _this2 = this; var xyRatios = _ref.xyRatios; var w = this.w; var me = this; this.xyRatios = xyRatios; this.zoomRect = this.graphics.drawRect(0, 0, 0, 0); this.selectionRect = this.graphics.drawRect(0, 0, 0, 0); this.gridRect = w.globals.dom.baseEl.querySelector('.apexcharts-grid'); this.zoomRect.node.classList.add('apexcharts-zoom-rect'); this.selectionRect.node.classList.add('apexcharts-selection-rect'); w.globals.dom.elGraphical.add(this.zoomRect); w.globals.dom.elGraphical.add(this.selectionRect); if (w.config.chart.selection.type === 'x') { this.slDraggableRect = this.selectionRect.draggable({ minX: 0, minY: 0, maxX: w.globals.gridWidth, maxY: w.globals.gridHeight }).on('dragmove', this.selectionDragging.bind(this, 'dragging')); } else if (w.config.chart.selection.type === 'y') { this.slDraggableRect = this.selectionRect.draggable({ minX: 0, maxX: w.globals.gridWidth }).on('dragmove', this.selectionDragging.bind(this, 'dragging')); } else { this.slDraggableRect = this.selectionRect.draggable().on('dragmove', this.selectionDragging.bind(this, 'dragging')); } this.preselectedSelection(); this.hoverArea = w.globals.dom.baseEl.querySelector(w.globals.chartClass); this.hoverArea.classList.add('zoomable'); this.eventList.forEach(function (event) { _this2.hoverArea.addEventListener(event, me.svgMouseEvents.bind(me, xyRatios), { capture: false, passive: true }); }); } // remove the event listeners which were previously added on hover area }, { key: "destroy", value: function destroy() { var _this3 = this; var me = this; this.eventList.forEach(function (event) { if (_this3.hoverArea) { _this3.hoverArea.removeEventListener(event, me.svgMouseEvents.bind(me, me.xyRatios), { capture: false, passive: true }); } }); if (this.slDraggableRect) { this.slDraggableRect.draggable(false); this.slDraggableRect.off(); this.selectionRect.off(); } this.selectionRect = null; this.zoomRect = null; this.gridRect = null; } }, { key: "svgMouseEvents", value: function svgMouseEvents(xyRatios, e) { var w = this.w; var me = this; var toolbar = this.ctx.toolbar; var zoomtype = w.globals.zoomEnabled ? w.config.chart.zoom.type : w.config.chart.selection.type; if (e.shiftKey) { this.shiftWasPressed = true; toolbar.enablePanning(); } else { if (this.shiftWasPressed) { toolbar.enableZooming(); this.shiftWasPressed = false; } } var falsePositives = e.target.classList.contains('apexcharts-selection-rect') || e.target.parentNode.classList.contains('apexcharts-toolbar'); if (falsePositives) return; me.clientX = e.type === 'touchmove' || e.type === 'touchstart' ? e.touches[0].clientX : e.type === 'touchend' ? e.changedTouches[0].clientX : e.clientX; me.clientY = e.type === 'touchmove' || e.type === 'touchstart' ? e.touches[0].clientY : e.type === 'touchend' ? e.changedTouches[0].clientY : e.clientY; if (e.type === 'mousedown' && e.which === 1) { var gridRectDim = me.gridRect.getBoundingClientRect(); me.startX = me.clientX - gridRectDim.left; me.startY = me.clientY - gridRectDim.top; me.dragged = false; me.w.globals.mousedown = true; } if (e.type === 'mousemove' && e.which === 1 || e.type === 'touchmove') { me.dragged = true; if (w.globals.panEnabled) { w.globals.selection = null; if (me.w.globals.mousedown) { me.panDragging({ context: me, zoomtype: zoomtype, xyRatios: xyRatios }); } } else { if (me.w.globals.mousedown && w.globals.zoomEnabled || me.w.globals.mousedown && w.globals.selectionEnabled) { me.selection = me.selectionDrawing({ context: me, zoomtype: zoomtype }); } } } if (e.type === 'mouseup' || e.type === 'touchend') { // we will be calling getBoundingClientRect on each mousedown/mousemove/mouseup var _gridRectDim = me.gridRect.getBoundingClientRect(); if (me.w.globals.mousedown) { // user released the drag, now do all the calculations me.endX = me.clientX - _gridRectDim.left; me.endY = me.clientY - _gridRectDim.top; me.dragX = Math.abs(me.endX - me.startX); me.dragY = Math.abs(me.endY - me.startY); if (w.globals.zoomEnabled || w.globals.selectionEnabled) { me.selectionDrawn({ context: me, zoomtype: zoomtype }); } } if (w.globals.zoomEnabled) { me.hideSelectionRect(this.selectionRect); } me.dragged = false; me.w.globals.mousedown = false; } this.makeSelectionRectDraggable(); } }, { key: "makeSelectionRectDraggable", value: function makeSelectionRectDraggable() { var w = this.w; if (!this.selectionRect) return; var rectDim = this.selectionRect.node.getBoundingClientRect(); if (rectDim.width > 0 && rectDim.height > 0) { this.slDraggableRect.selectize().resize({ constraint: { minX: 0, minY: 0, maxX: w.globals.gridWidth, maxY: w.globals.gridHeight } }).on('resizing', this.selectionDragging.bind(this, 'resizing')); } } }, { key: "preselectedSelection", value: function preselectedSelection() { var w = this.w; var xyRatios = this.xyRatios; if (!w.globals.zoomEnabled) { if (typeof w.globals.selection !== 'undefined' && w.globals.selection !== null) { this.drawSelectionRect(w.globals.selection); } else { if (w.config.chart.selection.xaxis.min !== undefined && w.config.chart.selection.xaxis.max !== undefined) { var x = (w.config.chart.selection.xaxis.min - w.globals.minX) / xyRatios.xRatio; var width = w.globals.gridWidth - (w.globals.maxX - w.config.chart.selection.xaxis.max) / xyRatios.xRatio - x; var selectionRect = { x: x, y: 0, width: width, height: w.globals.gridHeight, translateX: 0, translateY: 0, selectionEnabled: true }; this.drawSelectionRect(selectionRect); this.makeSelectionRectDraggable(); if (typeof w.config.chart.events.selection === 'function') { w.config.chart.events.selection(this.ctx, { xaxis: { min: w.config.chart.selection.xaxis.min, max: w.config.chart.selection.xaxis.max }, yaxis: {} }); } } } } } }, { key: "drawSelectionRect", value: function drawSelectionRect(_ref2) { var x = _ref2.x, y = _ref2.y, width = _ref2.width, height = _ref2.height, translateX = _ref2.translateX, translateY = _ref2.translateY; var w = this.w; var zoomRect = this.zoomRect; var selectionRect = this.selectionRect; if (this.dragged || w.globals.selection !== null) { var scalingAttrs = { transform: 'translate(' + translateX + ', ' + translateY + ')' // change styles based on zoom or selection // zoom is Enabled and user has dragged, so draw blue rect }; if (w.globals.zoomEnabled && this.dragged) { zoomRect.attr({ x: x, y: y, width: width, height: height, fill: w.config.chart.zoom.zoomedArea.fill.color, 'fill-opacity': w.config.chart.zoom.zoomedArea.fill.opacity, stroke: w.config.chart.zoom.zoomedArea.stroke.color, 'stroke-width': w.config.chart.zoom.zoomedArea.stroke.width, 'stroke-opacity': w.config.chart.zoom.zoomedArea.stroke.opacity }); Graphics.setAttrs(zoomRect.node, scalingAttrs); } // selection is enabled if (w.globals.selectionEnabled) { selectionRect.attr({ x: x, y: y, width: width > 0 ? width : 0, height: height > 0 ? height : 0, fill: w.config.chart.selection.fill.color, 'fill-opacity': w.config.chart.selection.fill.opacity, stroke: w.config.chart.selection.stroke.color, 'stroke-width': w.config.chart.selection.stroke.width, 'stroke-dasharray': w.config.chart.selection.stroke.dashArray, 'stroke-opacity': w.config.chart.selection.stroke.opacity }); Graphics.setAttrs(selectionRect.node, scalingAttrs); } } } }, { key: "hideSelectionRect", value: function hideSelectionRect(rect) { if (rect) { rect.attr({ x: 0, y: 0, width: 0, height: 0 }); } } }, { key: "selectionDrawing", value: function selectionDrawing(_ref3) { var context = _ref3.context, zoomtype = _ref3.zoomtype; var w = this.w; var me = context; var gridRectDim = this.gridRect.getBoundingClientRect(); var startX = me.startX - 1; var startY = me.startY; var selectionWidth = me.clientX - gridRectDim.left - startX; var selectionHeight = me.clientY - gridRectDim.top - startY; var translateX = 0; var translateY = 0; var selectionRect = {}; if (Math.abs(selectionWidth + startX) > w.globals.gridWidth || me.clientX - gridRectDim.left < 0) { // user dragged the mouse outside drawing area // TODO: test the selectionRect and make sure it doesn't crosses drawing area me.hideSelectionRect(this.zoomRect); me.dragged = false; me.w.globals.mousedown = false; } // inverse selection X if (startX > me.clientX - gridRectDim.left) { selectionWidth = Math.abs(selectionWidth); translateX = -selectionWidth; } // inverse selection Y if (startY > me.clientY - gridRectDim.top) { selectionHeight = Math.abs(selectionHeight); translateY = -selectionHeight; } if (zoomtype === 'x') { selectionRect = { x: startX, y: 0, width: selectionWidth, height: w.globals.gridHeight, translateX: translateX, translateY: 0 }; } else if (zoomtype === 'y') { selectionRect = { x: 0, y: startY, width: w.globals.gridWidth, height: selectionHeight, translateX: 0, translateY: translateY }; } else { selectionRect = { x: startX, y: startY, width: selectionWidth, height: selectionHeight, translateX: translateX, translateY: translateY }; } me.drawSelectionRect(selectionRect); me.selectionDragging('resizing'); return selectionRect; } }, { key: "selectionDragging", value: function selectionDragging(type, e) { var _this4 = this; var w = this.w; var xyRatios = this.xyRatios; var selRect = this.selectionRect; var timerInterval = 0; if (type === 'resizing') { timerInterval = 30; } if (typeof w.config.chart.events.selection === 'function' && w.globals.selectionEnabled) { // a small debouncer is required when resizing to avoid freezing the chart clearTimeout(this.w.globals.selectionResizeTimer); this.w.globals.selectionResizeTimer = window.setTimeout(function () { var gridRectDim = _this4.gridRect.getBoundingClientRect(); var selectionRect = selRect.node.getBoundingClientRect(); var minX = w.globals.xAxisScale.niceMin + (selectionRect.left - gridRectDim.left) * xyRatios.xRatio; var maxX = w.globals.xAxisScale.niceMin + (selectionRect.right - gridRectDim.left) * xyRatios.xRatio; var minY = w.globals.yAxisScale[0].niceMin + (gridRectDim.bottom - selectionRect.bottom) * xyRatios.yRatio[0]; var maxY = w.globals.yAxisScale[0].niceMax - (selectionRect.top - gridRectDim.top) * xyRatios.yRatio[0]; w.config.chart.events.selection(_this4.ctx, { xaxis: { min: minX, max: maxX }, yaxis: { min: minY, max: maxY } }); }, timerInterval); } } }, { key: "selectionDrawn", value: function selectionDrawn(_ref4) { var context = _ref4.context, zoomtype = _ref4.zoomtype; var w = this.w; var me = context; var xyRatios = this.xyRatios; var toolbar = this.ctx.toolbar; if (me.startX > me.endX) { var tempX = me.startX; me.startX = me.endX; me.endX = tempX; } if (me.startY > me.endY) { var tempY = me.startY; me.startY = me.endY; me.endY = tempY; } var xLowestValue = w.globals.xAxisScale.niceMin + me.startX * xyRatios.xRatio; var xHighestValue = w.globals.xAxisScale.niceMin + me.endX * xyRatios.xRatio; // TODO: we will consider the 1st y axis values here for getting highest and lowest y var yHighestValue = []; var yLowestValue = []; w.config.yaxis.forEach(function (yaxe, index) { yHighestValue.push(Math.floor(w.globals.yAxisScale[index].niceMax - xyRatios.yRatio[index] * me.startY)); yLowestValue.push(Math.floor(w.globals.yAxisScale[index].niceMax - xyRatios.yRatio[index] * me.endY)); }); if (me.dragged && (me.dragX > 10 || me.dragY > 10) && xLowestValue !== xHighestValue) { if (w.globals.zoomEnabled) { var yaxis = Utils.clone(w.config.yaxis); // before zooming in/out, store the last yaxis and xaxis range, so that when user hits the RESET button, we get the original range // also - make sure user is not already zoomed in/out - otherwise we will store zoomed values in lastAxis if (!w.globals.zoomed) { w.globals.lastXAxis = Utils.clone(w.config.xaxis); w.globals.lastYAxis = Utils.clone(w.config.yaxis); } var xaxis = { min: xLowestValue, max: xHighestValue }; if (zoomtype === 'xy' || zoomtype === 'y') { yaxis.forEach(function (yaxe, index) { yaxis[index].min = yLowestValue[index]; yaxis[index].max = yHighestValue[index]; }); } if (w.config.chart.zoom.autoScaleYaxis) { var scale = new Range(me.ctx); yaxis = scale.autoScaleY(me.ctx, { xaxis: xaxis }); } if (toolbar) { var beforeZoomRange = toolbar.getBeforeZoomRange(xaxis, yaxis); if (beforeZoomRange) { xaxis = beforeZoomRange.xaxis ? beforeZoomRange.xaxis : xaxis; yaxis = beforeZoomRange.yaxis ? beforeZoomRange.yaxe : yaxis; } } me.ctx._updateOptions({ xaxis: xaxis, yaxis: yaxis }, false, me.w.config.chart.animations.dynamicAnimation.enabled); if (typeof w.config.chart.events.zoomed === 'function') { toolbar.zoomCallback(xaxis, yaxis); } w.globals.zoomed = true; } else if (w.globals.selectionEnabled) { var _yaxis = null; var _xaxis = null; _xaxis = { min: xLowestValue, max: xHighestValue }; if (zoomtype === 'xy' || zoomtype === 'y') { _yaxis = Utils.clone(w.config.yaxis); _yaxis.forEach(function (yaxe, index) { _yaxis[index].min = yLowestValue[index]; _yaxis[index].max = yHighestValue[index]; }); } w.globals.selection = me.selection; if (typeof w.config.chart.events.selection === 'function') { w.config.chart.events.selection(me.ctx, { xaxis: _xaxis, yaxis: _yaxis }); } } } } }, { key: "panDragging", value: function panDragging(_ref5) { var context = _ref5.context, zoomtype = _ref5.zoomtype; var w = this.w; var me = context; var moveDirection; // check to make sure there is data to compare against if (typeof w.globals.lastClientPosition.x !== 'undefined') { // get the change from last position to this position var deltaX = w.globals.lastClientPosition.x - me.clientX; var deltaY = w.globals.lastClientPosition.y - me.clientY; // check which direction had the highest amplitude and then figure out direction by checking if the value is greater or less than zero if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX > 0) { moveDirection = 'left'; } else if (Math.abs(deltaX) > Math.abs(deltaY) && deltaX < 0) { moveDirection = 'right'; } else if (Math.abs(deltaY) > Math.abs(deltaX) && deltaY > 0) { moveDirection = 'up'; } else if (Math.abs(deltaY) > Math.abs(deltaX) && deltaY < 0) { moveDirection = 'down'; } } // set the new last position to the current for next time (to get the position of drag) w.globals.lastClientPosition = { x: me.clientX, y: me.clientY }; var xLowestValue = w.globals.minX; var xHighestValue = w.globals.maxX; this.panScrolled(moveDirection, xLowestValue, xHighestValue); } }, { key: "panScrolled", value: function panScrolled(moveDirection, xLowestValue, xHighestValue) { var w = this.w; var xyRatios = this.xyRatios; var yaxis = Utils.clone(w.config.yaxis); if (moveDirection === 'left') { xLowestValue = w.globals.minX + w.globals.gridWidth / 15 * xyRatios.xRatio; xHighestValue = w.globals.maxX + w.globals.gridWidth / 15 * xyRatios.xRatio; } else if (moveDirection === 'right') { xLowestValue = w.globals.minX - w.globals.gridWidth / 15 * xyRatios.xRatio; xHighestValue = w.globals.maxX - w.globals.gridWidth / 15 * xyRatios.xRatio; } if (xLowestValue < w.globals.initialminX || xHighestValue > w.globals.initialmaxX) { xLowestValue = w.globals.minX; xHighestValue = w.globals.maxX; } var xaxis = { min: xLowestValue, max: xHighestValue }; if (w.config.chart.zoom.autoScaleYaxis) { var scale = new Range(me.ctx); yaxis = scale.autoScaleY(me.ctx, { xaxis: xaxis }); } this.ctx._updateOptions({ xaxis: { min: xLowestValue, max: xHighestValue }, yaxis: yaxis }, false, false); if (typeof w.config.chart.events.scrolled === 'function') { w.config.chart.events.scrolled(this.ctx, { xaxis: { min: xLowestValue, max: xHighestValue } }); } } }]); return ZoomPanSelection; }(Toolbar); var TitleSubtitle = /*#__PURE__*/ function () { function TitleSubtitle(ctx) { _classCallCheck(this, TitleSubtitle); this.ctx = ctx; this.w = ctx.w; } _createClass(TitleSubtitle, [{ key: "draw", value: function draw() { this.drawTitleSubtitle('title'); this.drawTitleSubtitle('subtitle'); } }, { key: "drawTitleSubtitle", value: function drawTitleSubtitle(type) { var w = this.w; var tsConfig = type === 'title' ? w.config.title : w.config.subtitle; var x = w.globals.svgWidth / 2; var y = tsConfig.offsetY; var textAnchor = 'middle'; if (tsConfig.align === 'left') { x = 10; textAnchor = 'start'; } else if (tsConfig.align === 'right') { x = w.globals.svgWidth - 10; textAnchor = 'end'; } x = x + tsConfig.offsetX; y = y + parseInt(tsConfig.style.fontSize) + 2; if (tsConfig.text !== undefined) { var graphics = new Graphics(this.ctx); var titleText = graphics.drawText({ x: x, y: y, text: tsConfig.text, textAnchor: textAnchor, fontSize: tsConfig.style.fontSize, fontFamily: tsConfig.style.fontFamily, foreColor: tsConfig.style.color, opacity: 1 }); titleText.node.setAttribute('class', "apexcharts-".concat(type, "-text")); w.globals.dom.Paper.add(titleText); } } }]); return TitleSubtitle; }(); (function (root, factory) { /* istanbul ignore next */ if (typeof define === 'function' && define.amd) { define(function () { return factory(root, root.document); }); /* below check fixes #412 */ } else if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === 'object' && typeof module !== 'undefined') { module.exports = root.document ? factory(root, root.document) : function (w) { return factory(w, w.document); }; } else { root.SVG = factory(root, root.document); } })(typeof window !== 'undefined' ? window : undefined, function (window, document) { // Find global reference - uses 'this' by default when available, // falls back to 'window' otherwise (for bundlers like Webpack) var globalRef = typeof this !== 'undefined' ? this : window; // The main wrapping element var SVG = globalRef.SVG = function (element) { if (SVG.supported) { element = new SVG.Doc(element); if (!SVG.parser.draw) { SVG.prepare(); } return element; } }; // Default namespaces SVG.ns = 'http://www.w3.org/2000/svg'; SVG.xmlns = 'http://www.w3.org/2000/xmlns/'; SVG.xlink = 'http://www.w3.org/1999/xlink'; SVG.svgjs = 'http://svgjs.com/svgjs'; // Svg support test SVG.supported = function () { return true; // !!document.createElementNS && // !! document.createElementNS(SVG.ns,'svg').createSVGRect }(); // Don't bother to continue if SVG is not supported if (!SVG.supported) return false; // Element id sequence SVG.did = 1000; // Get next named element id SVG.eid = function (name) { return 'Svgjs' + capitalize(name) + SVG.did++; }; // Method for element creation SVG.create = function (name) { // create element var element = document.createElementNS(this.ns, name); // apply unique id element.setAttribute('id', this.eid(name)); return element; }; // Method for extending objects SVG.extend = function () { var modules, methods, key, i; // Get list of modules modules = [].slice.call(arguments); // Get object with extensions methods = modules.pop(); for (i = modules.length - 1; i >= 0; i--) { if (modules[i]) { for (key in methods) { modules[i].prototype[key] = methods[key]; } } } // Make sure SVG.Set inherits any newly added methods if (SVG.Set && SVG.Set.inherit) { SVG.Set.inherit(); } }; // Invent new element SVG.invent = function (config) { // Create element initializer var initializer = typeof config.create === 'function' ? config.create : function () { this.constructor.call(this, SVG.create(config.create)); }; // Inherit prototype if (config.inherit) { initializer.prototype = new config.inherit(); } // Extend with methods if (config.extend) { SVG.extend(initializer, config.extend); } // Attach construct method to parent if (config.construct) { SVG.extend(config.parent || SVG.Container, config.construct); } return initializer; }; // Adopt existing svg elements SVG.adopt = function (node) { // check for presence of node if (!node) return null; // make sure a node isn't already adopted if (node.instance) return node.instance; // initialize variables var element; // adopt with element-specific settings if (node.nodeName == 'svg') { element = node.parentNode instanceof window.SVGElement ? new SVG.Nested() : new SVG.Doc(); } else if (node.nodeName == 'linearGradient') { element = new SVG.Gradient('linear'); } else if (node.nodeName == 'radialGradient') { element = new SVG.Gradient('radial'); } else if (SVG[capitalize(node.nodeName)]) { element = new SVG[capitalize(node.nodeName)](); } else { element = new SVG.Element(node); } // ensure references element.type = node.nodeName; element.node = node; node.instance = element; // SVG.Class specific preparations if (element instanceof SVG.Doc) { element.namespace().defs(); } // pull svgjs data from the dom (getAttributeNS doesn't work in html5) element.setData(JSON.parse(node.getAttribute('svgjs:data')) || {}); return element; }; // Initialize parsing element SVG.prepare = function () { // Select document body and create invisible svg element var body = document.getElementsByTagName('body')[0], draw = (body ? new SVG.Doc(body) : SVG.adopt(document.documentElement).nested()).size(2, 0); // Create parser object SVG.parser = { body: body || document.documentElement, draw: draw.style('opacity:0;position:absolute;left:-100%;top:-100%;overflow:hidden').node, poly: draw.polyline().node, path: draw.path().node, native: SVG.create('svg') }; }; SVG.parser = { native: SVG.create('svg') }; document.addEventListener('DOMContentLoaded', function () { if (!SVG.parser.draw) { SVG.prepare(); } }, false); // Storage for regular expressions SVG.regex = { // Parse unit value numberAndUnit: /^([+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?)([a-z%]*)$/i, // Parse hex value hex: /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i, // Parse rgb value rgb: /rgb\((\d+),(\d+),(\d+)\)/, // Parse reference id reference: /#([a-z0-9\-_]+)/i, // splits a transformation chain transforms: /\)\s*,?\s*/, // Whitespace whitespace: /\s/g, // Test hex value isHex: /^#[a-f0-9]{3,6}$/i, // Test rgb value isRgb: /^rgb\(/, // Test css declaration isCss: /[^:]+:[^;]+;?/, // Test for blank string isBlank: /^(\s+)?$/, // Test for numeric string isNumber: /^[+-]?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i, // Test for percent value isPercent: /^-?[\d\.]+%$/, // Test for image url isImage: /\.(jpg|jpeg|png|gif|svg)(\?[^=]+.*)?/i, // split at whitespace and comma delimiter: /[\s,]+/, // The following regex are used to parse the d attribute of a path // Matches all hyphens which are not after an exponent hyphen: /([^e])\-/gi, // Replaces and tests for all path letters pathLetters: /[MLHVCSQTAZ]/gi, // yes we need this one, too isPathLetter: /[MLHVCSQTAZ]/i, // matches 0.154.23.45 numbersWithDots: /((\d?\.\d+(?:e[+-]?\d+)?)((?:\.\d+(?:e[+-]?\d+)?)+))+/gi, // matches . dots: /\./g }; SVG.utils = { // Map function map: function map(array, block) { var i, il = array.length, result = []; for (i = 0; i < il; i++) { result.push(block(array[i])); } return result; }, // Filter function filter: function filter(array, block) { var i, il = array.length, result = []; for (i = 0; i < il; i++) { if (block(array[i])) { result.push(array[i]); } } return result; }, // Degrees to radians radians: function radians(d) { return d % 360 * Math.PI / 180; }, // Radians to degrees degrees: function degrees(r) { return r * 180 / Math.PI % 360; }, filterSVGElements: function filterSVGElements(nodes) { return this.filter(nodes, function (el) { return el instanceof window.SVGElement; }); } }; SVG.defaults = { // Default attribute values attrs: { // fill and stroke 'fill-opacity': 1, 'stroke-opacity': 1, 'stroke-width': 0, 'stroke-linejoin': 'miter', 'stroke-linecap': 'butt', fill: '#000000', stroke: '#000000', opacity: 1, // position x: 0, y: 0, cx: 0, cy: 0, // size width: 0, height: 0, // radius r: 0, rx: 0, ry: 0, // gradient offset: 0, 'stop-opacity': 1, 'stop-color': '#000000', // text 'font-size': 16, 'font-family': 'Helvetica, Arial, sans-serif', 'text-anchor': 'start' } // Module for color convertions }; SVG.Color = function (color) { var match; // initialize defaults this.r = 0; this.g = 0; this.b = 0; if (!color) return; // parse color if (typeof color === 'string') { if (SVG.regex.isRgb.test(color)) { // get rgb values match = SVG.regex.rgb.exec(color.replace(SVG.regex.whitespace, '')); // parse numeric values this.r = parseInt(match[1]); this.g = parseInt(match[2]); this.b = parseInt(match[3]); } else if (SVG.regex.isHex.test(color)) { // get hex values match = SVG.regex.hex.exec(fullHex(color)); // parse numeric values this.r = parseInt(match[1], 16); this.g = parseInt(match[2], 16); this.b = parseInt(match[3], 16); } } else if (_typeof(color) === 'object') { this.r = color.r; this.g = color.g; this.b = color.b; } }; SVG.extend(SVG.Color, { // Default to hex conversion toString: function toString() { return this.toHex(); }, // Build hex value toHex: function toHex() { return '#' + compToHex(this.r) + compToHex(this.g) + compToHex(this.b); }, // Build rgb value toRgb: function toRgb() { return 'rgb(' + [this.r, this.g, this.b].join() + ')'; }, // Calculate true brightness brightness: function brightness() { return this.r / 255 * 0.30 + this.g / 255 * 0.59 + this.b / 255 * 0.11; }, // Make color morphable morph: function morph(color) { this.destination = new SVG.Color(color); return this; }, // Get morphed color at given position at: function at(pos) { // make sure a destination is defined if (!this.destination) return this; // normalise pos pos = pos < 0 ? 0 : pos > 1 ? 1 : pos; // generate morphed color return new SVG.Color({ r: ~~(this.r + (this.destination.r - this.r) * pos), g: ~~(this.g + (this.destination.g - this.g) * pos), b: ~~(this.b + (this.destination.b - this.b) * pos) }); } }); // Testers // Test if given value is a color string SVG.Color.test = function (color) { color += ''; return SVG.regex.isHex.test(color) || SVG.regex.isRgb.test(color); }; // Test if given value is a rgb object SVG.Color.isRgb = function (color) { return color && typeof color.r === 'number' && typeof color.g === 'number' && typeof color.b === 'number'; }; // Test if given value is a color SVG.Color.isColor = function (color) { return SVG.Color.isRgb(color) || SVG.Color.test(color); }; // Module for array conversion SVG.Array = function (array, fallback) { array = (array || []).valueOf(); // if array is empty and fallback is provided, use fallback if (array.length == 0 && fallback) { array = fallback.valueOf(); } // parse array this.value = this.parse(array); }; SVG.extend(SVG.Array, { // Make array morphable morph: function morph(array) { this.destination = this.parse(array); // normalize length of arrays if (this.value.length != this.destination.length) { var lastValue = this.value[this.value.length - 1], lastDestination = this.destination[this.destination.length - 1]; while (this.value.length > this.destination.length) { this.destination.push(lastDestination); } while (this.value.length < this.destination.length) { this.value.push(lastValue); } } return this; }, // Clean up any duplicate points settle: function settle() { // find all unique values for (var i = 0, il = this.value.length, seen = []; i < il; i++) { if (seen.indexOf(this.value[i]) == -1) { seen.push(this.value[i]); } } // set new value return this.value = seen; }, // Get morphed array at given position at: function at(pos) { // make sure a destination is defined if (!this.destination) return this; // generate morphed array for (var i = 0, il = this.value.length, array = []; i < il; i++) { array.push(this.value[i] + (this.destination[i] - this.value[i]) * pos); } return new SVG.Array(array); }, // Convert array to string toString: function toString() { return this.value.join(' '); }, // Real value valueOf: function valueOf() { return this.value; }, // Parse whitespace separated string parse: function parse(array) { array = array.valueOf(); // if already is an array, no need to parse it if (Array.isArray(array)) return array; return this.split(array); }, // Strip unnecessary whitespace split: function split(string) { return string.trim().split(SVG.regex.delimiter).map(parseFloat); }, // Reverse array reverse: function reverse() { this.value.reverse(); return this; }, clone: function clone() { var clone = new this.constructor(); clone.value = array_clone(this.value); return clone; } }); // Poly points array SVG.PointArray = function (array, fallback) { SVG.Array.call(this, array, fallback || [[0, 0]]); }; // Inherit from SVG.Array SVG.PointArray.prototype = new SVG.Array(); SVG.PointArray.prototype.constructor = SVG.PointArray; SVG.extend(SVG.PointArray, { // Convert array to string toString: function toString() { // convert to a poly point string for (var i = 0, il = this.value.length, array = []; i < il; i++) { array.push(this.value[i].join(',')); } return array.join(' '); }, // Convert array to line object toLine: function toLine() { return { x1: this.value[0][0], y1: this.value[0][1], x2: this.value[1][0], y2: this.value[1][1] }; }, // Get morphed array at given position at: function at(pos) { // make sure a destination is defined if (!this.destination) return this; // generate morphed point string for (var i = 0, il = this.value.length, array = []; i < il; i++) { array.push([this.value[i][0] + (this.destination[i][0] - this.value[i][0]) * pos, this.value[i][1] + (this.destination[i][1] - this.value[i][1]) * pos]); } return new SVG.PointArray(array); }, // Parse point string and flat array parse: function parse(array) { var points = []; array = array.valueOf(); // if it is an array if (Array.isArray(array)) { // and it is not flat, there is no need to parse it if (Array.isArray(array[0])) { // make sure to use a clone return array.map(function (el) { return el.slice(); }); } else if (array[0].x != null) { // allow point objects to be passed return array.map(function (el) { return [el.x, el.y]; }); } } else { // Else, it is considered as a string // parse points array = array.trim().split(SVG.regex.delimiter).map(parseFloat); } // validate points - https://svgwg.org/svg2-draft/shapes.html#DataTypePoints // Odd number of coordinates is an error. In such cases, drop the last odd coordinate. if (array.length % 2 !== 0) array.pop(); // wrap points in two-tuples and parse points as floats for (var i = 0, len = array.length; i < len; i = i + 2) { points.push([array[i], array[i + 1]]); } return points; }, // Move point string move: function move(x, y) { var box = this.bbox(); // get relative offset x -= box.x; y -= box.y; // move every point if (!isNaN(x) && !isNaN(y)) { for (var i = this.value.length - 1; i >= 0; i--) { this.value[i] = [this.value[i][0] + x, this.value[i][1] + y]; } } return this; }, // Resize poly string size: function size(width, height) { var i, box = this.bbox(); // recalculate position of all points according to new size for (i = this.value.length - 1; i >= 0; i--) { if (box.width) this.value[i][0] = (this.value[i][0] - box.x) * width / box.width + box.x; if (box.height) this.value[i][1] = (this.value[i][1] - box.y) * height / box.height + box.y; } return this; }, // Get bounding box of points bbox: function bbox() { if (!SVG.parser.draw) { SVG.prepare(); } SVG.parser.poly.setAttribute('points', this.toString()); return SVG.parser.poly.getBBox(); } }); var pathHandlers = { M: function M(c, p, p0) { p.x = p0.x = c[0]; p.y = p0.y = c[1]; return ['M', p.x, p.y]; }, L: function L(c, p) { p.x = c[0]; p.y = c[1]; return ['L', c[0], c[1]]; }, H: function H(c, p) { p.x = c[0]; return ['H', c[0]]; }, V: function V(c, p) { p.y = c[0]; return ['V', c[0]]; }, C: function C(c, p) { p.x = c[4]; p.y = c[5]; return ['C', c[0], c[1], c[2], c[3], c[4], c[5]]; }, S: function S(c, p) { p.x = c[2]; p.y = c[3]; return ['S', c[0], c[1], c[2], c[3]]; }, Q: function Q(c, p) { p.x = c[2]; p.y = c[3]; return ['Q', c[0], c[1], c[2], c[3]]; }, T: function T(c, p) { p.x = c[0]; p.y = c[1]; return ['T', c[0], c[1]]; }, Z: function Z(c, p, p0) { p.x = p0.x; p.y = p0.y; return ['Z']; }, A: function A(c, p) { p.x = c[5]; p.y = c[6]; return ['A', c[0], c[1], c[2], c[3], c[4], c[5], c[6]]; } }; var mlhvqtcsa = 'mlhvqtcsaz'.split(''); for (var i = 0, il = mlhvqtcsa.length; i < il; ++i) { pathHandlers[mlhvqtcsa[i]] = function (i) { return function (c, p, p0) { if (i == 'H') c[0] = c[0] + p.x;else if (i == 'V') c[0] = c[0] + p.y;else if (i == 'A') { c[5] = c[5] + p.x, c[6] = c[6] + p.y; } else { for (var j = 0, jl = c.length; j < jl; ++j) { c[j] = c[j] + (j % 2 ? p.y : p.x); } } return pathHandlers[i](c, p, p0); }; }(mlhvqtcsa[i].toUpperCase()); } // Path points array SVG.PathArray = function (array, fallback) { SVG.Array.call(this, array, fallback || [['M', 0, 0]]); }; // Inherit from SVG.Array SVG.PathArray.prototype = new SVG.Array(); SVG.PathArray.prototype.constructor = SVG.PathArray; SVG.extend(SVG.PathArray, { // Convert array to string toString: function toString() { return arrayToString(this.value); }, // Move path string move: function move(x, y) { // get bounding box of current situation var box = this.bbox(); // get relative offset x -= box.x; y -= box.y; if (!isNaN(x) && !isNaN(y)) { // move every point for (var l, i = this.value.length - 1; i >= 0; i--) { l = this.value[i][0]; if (l == 'M' || l == 'L' || l == 'T') { this.value[i][1] += x; this.value[i][2] += y; } else if (l == 'H') { this.value[i][1] += x; } else if (l == 'V') { this.value[i][1] += y; } else if (l == 'C' || l == 'S' || l == 'Q') { this.value[i][1] += x; this.value[i][2] += y; this.value[i][3] += x; this.value[i][4] += y; if (l == 'C') { this.value[i][5] += x; this.value[i][6] += y; } } else if (l == 'A') { this.value[i][6] += x; this.value[i][7] += y; } } } return this; }, // Resize path string size: function size(width, height) { // get bounding box of current situation var i, l, box = this.bbox(); // recalculate position of all points according to new size for (i = this.value.length - 1; i >= 0; i--) { l = this.value[i][0]; if (l == 'M' || l == 'L' || l == 'T') { this.value[i][1] = (this.value[i][1] - box.x) * width / box.width + box.x; this.value[i][2] = (this.value[i][2] - box.y) * height / box.height + box.y; } else if (l == 'H') { this.value[i][1] = (this.value[i][1] - box.x) * width / box.width + box.x; } else if (l == 'V') { this.value[i][1] = (this.value[i][1] - box.y) * height / box.height + box.y; } else if (l == 'C' || l == 'S' || l == 'Q') { this.value[i][1] = (this.value[i][1] - box.x) * width / box.width + box.x; this.value[i][2] = (this.value[i][2] - box.y) * height / box.height + box.y; this.value[i][3] = (this.value[i][3] - box.x) * width / box.width + box.x; this.value[i][4] = (this.value[i][4] - box.y) * height / box.height + box.y; if (l == 'C') { this.value[i][5] = (this.value[i][5] - box.x) * width / box.width + box.x; this.value[i][6] = (this.value[i][6] - box.y) * height / box.height + box.y; } } else if (l == 'A') { // resize radii this.value[i][1] = this.value[i][1] * width / box.width; this.value[i][2] = this.value[i][2] * height / box.height; // move position values this.value[i][6] = (this.value[i][6] - box.x) * width / box.width + box.x; this.value[i][7] = (this.value[i][7] - box.y) * height / box.height + box.y; } } return this; }, // Test if the passed path array use the same path data commands as this path array equalCommands: function equalCommands(pathArray) { var i, il, equalCommands; pathArray = new SVG.PathArray(pathArray); equalCommands = this.value.length === pathArray.value.length; for (i = 0, il = this.value.length; equalCommands && i < il; i++) { equalCommands = this.value[i][0] === pathArray.value[i][0]; } return equalCommands; }, // Make path array morphable morph: function morph(pathArray) { pathArray = new SVG.PathArray(pathArray); if (this.equalCommands(pathArray)) { this.destination = pathArray; } else { this.destination = null; } return this; }, // Get morphed path array at given position at: function at(pos) { // make sure a destination is defined if (!this.destination) return this; var sourceArray = this.value, destinationArray = this.destination.value, array = [], pathArray = new SVG.PathArray(), i, il, j, jl; // Animate has specified in the SVG spec // See: https://www.w3.org/TR/SVG11/paths.html#PathElement for (i = 0, il = sourceArray.length; i < il; i++) { array[i] = [sourceArray[i][0]]; for (j = 1, jl = sourceArray[i].length; j < jl; j++) { array[i][j] = sourceArray[i][j] + (destinationArray[i][j] - sourceArray[i][j]) * pos; } // For the two flags of the elliptical arc command, the SVG spec say: // Flags and booleans are interpolated as fractions between zero and one, with any non-zero value considered to be a value of one/true // Elliptical arc command as an array followed by corresponding indexes: // ['A', rx, ry, x-axis-rotation, large-arc-flag, sweep-flag, x, y] // 0 1 2 3 4 5 6 7 if (array[i][0] === 'A') { array[i][4] = +(array[i][4] != 0); array[i][5] = +(array[i][5] != 0); } } // Directly modify the value of a path array, this is done this way for performance pathArray.value = array; return pathArray; }, // Absolutize and parse path to array parse: function parse(array) { // if it's already a patharray, no need to parse it if (array instanceof SVG.PathArray) return array.valueOf(); // prepare for parsing var s, arr, paramCnt = { 'M': 2, 'L': 2, 'H': 1, 'V': 1, 'C': 6, 'S': 4, 'Q': 4, 'T': 2, 'A': 7, 'Z': 0 }; if (typeof array === 'string') { array = array.replace(SVG.regex.numbersWithDots, pathRegReplace) // convert 45.123.123 to 45.123 .123 .replace(SVG.regex.pathLetters, ' $& ') // put some room between letters and numbers .replace(SVG.regex.hyphen, '$1 -') // add space before hyphen .trim() // trim .split(SVG.regex.delimiter); // split into array } else { array = array.reduce(function (prev, curr) { return [].concat.call(prev, curr); }, []); } // array now is an array containing all parts of a path e.g. ['M', '0', '0', 'L', '30', '30' ...] var arr = [], p = new SVG.Point(), p0 = new SVG.Point(), index = 0, len = array.length; do { // Test if we have a path letter if (SVG.regex.isPathLetter.test(array[index])) { s = array[index]; ++index; // If last letter was a move command and we got no new, it defaults to [L]ine } else if (s == 'M') { s = 'L'; } else if (s == 'm') { s = 'l'; } arr.push(pathHandlers[s].call(null, array.slice(index, index = index + paramCnt[s.toUpperCase()]).map(parseFloat), p, p0)); } while (len > index); return arr; }, // Get bounding box of path bbox: function bbox() { if (!SVG.parser.draw) { SVG.prepare(); } SVG.parser.path.setAttribute('d', this.toString()); return SVG.parser.path.getBBox(); } }); // Module for unit convertions SVG.Number = SVG.invent({ // Initialize create: function create(value, unit) { // initialize defaults this.value = 0; this.unit = unit || ''; // parse value if (typeof value === 'number') { // ensure a valid numeric value this.value = isNaN(value) ? 0 : !isFinite(value) ? value < 0 ? -3.4e+38 : +3.4e+38 : value; } else if (typeof value === 'string') { unit = value.match(SVG.regex.numberAndUnit); if (unit) { // make value numeric this.value = parseFloat(unit[1]); // normalize if (unit[5] == '%') { this.value /= 100; } else if (unit[5] == 's') { this.value *= 1000; } // store unit this.unit = unit[5]; } } else { if (value instanceof SVG.Number) { this.value = value.valueOf(); this.unit = value.unit; } } }, // Add methods extend: { // Stringalize toString: function toString() { return (this.unit == '%' ? ~~(this.value * 1e8) / 1e6 : this.unit == 's' ? this.value / 1e3 : this.value) + this.unit; }, toJSON: function toJSON() { return this.toString(); }, // Convert to primitive valueOf: function valueOf() { return this.value; }, // Add number plus: function plus(number) { number = new SVG.Number(number); return new SVG.Number(this + number, this.unit || number.unit); }, // Subtract number minus: function minus(number) { number = new SVG.Number(number); return new SVG.Number(this - number, this.unit || number.unit); }, // Multiply number times: function times(number) { number = new SVG.Number(number); return new SVG.Number(this * number, this.unit || number.unit); }, // Divide number divide: function divide(number) { number = new SVG.Number(number); return new SVG.Number(this / number, this.unit || number.unit); }, // Convert to different unit to: function to(unit) { var number = new SVG.Number(this); if (typeof unit === 'string') { number.unit = unit; } return number; }, // Make number morphable morph: function morph(number) { this.destination = new SVG.Number(number); if (number.relative) { this.destination.value += this.value; } return this; }, // Get morphed number at given position at: function at(pos) { // Make sure a destination is defined if (!this.destination) return this; // Generate new morphed number return new SVG.Number(this.destination).minus(this).times(pos).plus(this); } } }); SVG.Element = SVG.invent({ // Initialize node create: function create(node) { // make stroke value accessible dynamically this._stroke = SVG.defaults.attrs.stroke; this._event = null; // initialize data object this.dom = {}; // create circular reference if (this.node = node) { this.type = node.nodeName; this.node.instance = this; // store current attribute value this._stroke = node.getAttribute('stroke') || this._stroke; } }, // Add class methods extend: { // Move over x-axis x: function x(_x) { return this.attr('x', _x); }, // Move over y-axis y: function y(_y) { return this.attr('y', _y); }, // Move by center over x-axis cx: function cx(x) { return x == null ? this.x() + this.width() / 2 : this.x(x - this.width() / 2); }, // Move by center over y-axis cy: function cy(y) { return y == null ? this.y() + this.height() / 2 : this.y(y - this.height() / 2); }, // Move element to given x and y values move: function move(x, y) { return this.x(x).y(y); }, // Move element by its center center: function center(x, y) { return this.cx(x).cy(y); }, // Set width of element width: function width(_width) { return this.attr('width', _width); }, // Set height of element height: function height(_height) { return this.attr('height', _height); }, // Set element size to given width and height size: function size(width, height) { var p = proportionalSize(this, width, height); return this.width(new SVG.Number(p.width)).height(new SVG.Number(p.height)); }, // Clone element clone: function clone(parent) { // write dom data to the dom so the clone can pickup the data this.writeDataToDom(); // clone element and assign new id var clone = assignNewId(this.node.cloneNode(true)); // insert the clone in the given parent or after myself if (parent) parent.add(clone);else this.after(clone); return clone; }, // Remove element remove: function remove() { if (this.parent()) { this.parent().removeElement(this); } return this; }, // Replace element replace: function replace(element) { this.after(element).remove(); return element; }, // Add element to given container and return self addTo: function addTo(parent) { return parent.put(this); }, // Add element to given container and return container putIn: function putIn(parent) { return parent.add(this); }, // Get / set id id: function id(_id) { return this.attr('id', _id); }, // Checks whether the given point inside the bounding box of the element inside: function inside(x, y) { var box = this.bbox(); return x > box.x && y > box.y && x < box.x + box.width && y < box.y + box.height; }, // Show element show: function show() { return this.style('display', ''); }, // Hide element hide: function hide() { return this.style('display', 'none'); }, // Is element visible? visible: function visible() { return this.style('display') != 'none'; }, // Return id on string conversion toString: function toString() { return this.attr('id'); }, // Return array of classes on the node classes: function classes() { var attr = this.attr('class'); return attr == null ? [] : attr.trim().split(SVG.regex.delimiter); }, // Return true if class exists on the node, false otherwise hasClass: function hasClass(name) { return this.classes().indexOf(name) != -1; }, // Add class to the node addClass: function addClass(name) { if (!this.hasClass(name)) { var array = this.classes(); array.push(name); this.attr('class', array.join(' ')); } return this; }, // Remove class from the node removeClass: function removeClass(name) { if (this.hasClass(name)) { this.attr('class', this.classes().filter(function (c) { return c != name; }).join(' ')); } return this; }, // Toggle the presence of a class on the node toggleClass: function toggleClass(name) { return this.hasClass(name) ? this.removeClass(name) : this.addClass(name); }, // Get referenced element form attribute value reference: function reference(attr) { return SVG.get(this.attr(attr)); }, // Returns the parent element instance parent: function parent(type) { var parent = this; // check for parent if (!parent.node.parentNode) return null; // get parent element parent = SVG.adopt(parent.node.parentNode); if (!type) return parent; // loop trough ancestors if type is given while (parent && parent.node instanceof window.SVGElement) { if (typeof type === 'string' ? parent.matches(type) : parent instanceof type) return parent; if (!parent.node.parentNode || parent.node.parentNode.nodeName == '#document') return null; // #759, #720 parent = SVG.adopt(parent.node.parentNode); } }, // Get parent document doc: function doc() { return this instanceof SVG.Doc ? this : this.parent(SVG.Doc); }, // return array of all ancestors of given type up to the root svg parents: function parents(type) { var parents = [], parent = this; do { parent = parent.parent(type); if (!parent || !parent.node) break; parents.push(parent); } while (parent.parent); return parents; }, // matches the element vs a css selector matches: function matches(selector) { return _matches(this.node, selector); }, // Returns the svg node to call native svg methods on it native: function native() { return this.node; }, // Import raw svg svg: function svg(_svg) { // create temporary holder var well = document.createElement('svg'); // act as a setter if svg is given if (_svg && this instanceof SVG.Parent) { // dump raw svg well.innerHTML = '<svg>' + _svg.replace(/\n/, '').replace(/<([\w:-]+)([^<]+?)\/>/g, '<$1$2></$1>') + '</svg>'; // transplant nodes for (var i = 0, il = well.firstChild.childNodes.length; i < il; i++) { this.node.appendChild(well.firstChild.firstChild); } // otherwise act as a getter } else { // create a wrapping svg element in case of partial content well.appendChild(_svg = document.createElement('svg')); // write svgjs data to the dom this.writeDataToDom(); // insert a copy of this node _svg.appendChild(this.node.cloneNode(true)); // return target element return well.innerHTML.replace(/^<svg>/, '').replace(/<\/svg>$/, ''); } return this; }, // write svgjs data to the dom writeDataToDom: function writeDataToDom() { // dump variables recursively if (this.each || this.lines) { var fn = this.each ? this : this.lines(); fn.each(function () { this.writeDataToDom(); }); } // remove previously set data this.node.removeAttribute('svgjs:data'); if (Object.keys(this.dom).length) { this.node.setAttribute('svgjs:data', JSON.stringify(this.dom)); } // see #428 return this; }, // set given data to the elements data property setData: function setData(o) { this.dom = o; return this; }, is: function is(obj) { return _is(this, obj); } } }); SVG.easing = { '-': function _(pos) { return pos; }, '<>': function _(pos) { return -Math.cos(pos * Math.PI) / 2 + 0.5; }, '>': function _(pos) { return Math.sin(pos * Math.PI / 2); }, '<': function _(pos) { return -Math.cos(pos * Math.PI / 2) + 1; } }; SVG.morph = function (pos) { return function (from, to) { return new SVG.MorphObj(from, to).at(pos); }; }; SVG.Situation = SVG.invent({ create: function create(o) { this.init = false; this.reversed = false; this.reversing = false; this.duration = new SVG.Number(o.duration).valueOf(); this.delay = new SVG.Number(o.delay).valueOf(); this.start = +new Date() + this.delay; this.finish = this.start + this.duration; this.ease = o.ease; // this.loop is incremented from 0 to this.loops // it is also incremented when in an infinite loop (when this.loops is true) this.loop = 0; this.loops = false; this.animations = {// functionToCall: [list of morphable objects] // e.g. move: [SVG.Number, SVG.Number] }; this.attrs = {// holds all attributes which are not represented from a function svg.js provides // e.g. someAttr: SVG.Number }; this.styles = {// holds all styles which should be animated // e.g. fill-color: SVG.Color }; this.transforms = [// holds all transformations as transformation objects // e.g. [SVG.Rotate, SVG.Translate, SVG.Matrix] ]; this.once = {// functions to fire at a specific position // e.g. "0.5": function foo(){} }; } }); SVG.FX = SVG.invent({ create: function create(element) { this._target = element; this.situations = []; this.active = false; this.situation = null; this.paused = false; this.lastPos = 0; this.pos = 0; // The absolute position of an animation is its position in the context of its complete duration (including delay and loops) // When performing a delay, absPos is below 0 and when performing a loop, its value is above 1 this.absPos = 0; this._speed = 1; }, extend: { /** * sets or returns the target of this animation * @param o object || number In case of Object it holds all parameters. In case of number its the duration of the animation * @param ease function || string Function which should be used for easing or easing keyword * @param delay Number indicating the delay before the animation starts * @return target || this */ animate: function animate(o, ease, delay) { if (_typeof(o) === 'object') { ease = o.ease; delay = o.delay; o = o.duration; } var situation = new SVG.Situation({ duration: o || 1000, delay: delay || 0, ease: SVG.easing[ease || '-'] || ease }); this.queue(situation); return this; }, /** * sets a delay before the next element of the queue is called * @param delay Duration of delay in milliseconds * @return this.target() */ delay: function delay(_delay) { // The delay is performed by an empty situation with its duration // attribute set to the duration of the delay var situation = new SVG.Situation({ duration: _delay, delay: 0, ease: SVG.easing['-'] }); return this.queue(situation); }, /** * sets or returns the target of this animation * @param null || target SVG.Element which should be set as new target * @return target || this */ target: function target(_target) { if (_target && _target instanceof SVG.Element) { this._target = _target; return this; } return this._target; }, // returns the absolute position at a given time timeToAbsPos: function timeToAbsPos(timestamp) { return (timestamp - this.situation.start) / (this.situation.duration / this._speed); }, // returns the timestamp from a given absolute positon absPosToTime: function absPosToTime(absPos) { return this.situation.duration / this._speed * absPos + this.situation.start; }, // starts the animationloop startAnimFrame: function startAnimFrame() { this.stopAnimFrame(); this.animationFrame = window.requestAnimationFrame(function () { this.step(); }.bind(this)); }, // cancels the animationframe stopAnimFrame: function stopAnimFrame() { window.cancelAnimationFrame(this.animationFrame); }, // kicks off the animation - only does something when the queue is currently not active and at least one situation is set start: function start() { // dont start if already started if (!this.active && this.situation) { this.active = true; this.startCurrent(); } return this; }, // start the current situation startCurrent: function startCurrent() { this.situation.start = +new Date() + this.situation.delay / this._speed; this.situation.finish = this.situation.start + this.situation.duration / this._speed; return this.initAnimations().step(); }, /** * adds a function / Situation to the animation queue * @param fn function / situation to add * @return this */ queue: function queue(fn) { if (typeof fn === 'function' || fn instanceof SVG.Situation) { this.situations.push(fn); } if (!this.situation) this.situation = this.situations.shift(); return this; }, /** * pulls next element from the queue and execute it * @return this */ dequeue: function dequeue() { // stop current animation this.stop(); // get next animation from queue this.situation = this.situations.shift(); if (this.situation) { if (this.situation instanceof SVG.Situation) { this.start(); } else { // If it is not a SVG.Situation, then it is a function, we execute it this.situation.call(this); } } return this; }, // updates all animations to the current state of the element // this is important when one property could be changed from another property initAnimations: function initAnimations() { var i, j, source; var s = this.situation; if (s.init) return this; for (i in s.animations) { source = this.target()[i](); if (!Array.isArray(source)) { source = [source]; } if (!Array.isArray(s.animations[i])) { s.animations[i] = [s.animations[i]]; } // if(s.animations[i].length > source.length) { // source.concat = source.concat(s.animations[i].slice(source.length, s.animations[i].length)) // } for (j = source.length; j--;) { // The condition is because some methods return a normal number instead // of a SVG.Number if (s.animations[i][j] instanceof SVG.Number) { source[j] = new SVG.Number(source[j]); } s.animations[i][j] = source[j].morph(s.animations[i][j]); } } for (i in s.attrs) { s.attrs[i] = new SVG.MorphObj(this.target().attr(i), s.attrs[i]); } for (i in s.styles) { s.styles[i] = new SVG.MorphObj(this.target().style(i), s.styles[i]); } s.initialTransformation = this.target().matrixify(); s.init = true; return this; }, clearQueue: function clearQueue() { this.situations = []; return this; }, clearCurrent: function clearCurrent() { this.situation = null; return this; }, /** stops the animation immediately * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. * @param clearQueue A Boolean indicating whether to remove queued animation as well. * @return this */ stop: function stop(jumpToEnd, clearQueue) { var active = this.active; this.active = false; if (clearQueue) { this.clearQueue(); } if (jumpToEnd && this.situation) { // initialize the situation if it was not !active && this.startCurrent(); this.atEnd(); } this.stopAnimFrame(); return this.clearCurrent(); }, /** resets the element to the state where the current element has started * @return this */ reset: function reset() { if (this.situation) { var temp = this.situation; this.stop(); this.situation = temp; this.atStart(); } return this; }, // Stop the currently-running animation, remove all queued animations, and complete all animations for the element. finish: function finish() { this.stop(true, false); while (this.dequeue().situation && this.stop(true, false)) { } this.clearQueue().clearCurrent(); return this; }, // set the internal animation pointer at the start position, before any loops, and updates the visualisation atStart: function atStart() { return this.at(0, true); }, // set the internal animation pointer at the end position, after all the loops, and updates the visualisation atEnd: function atEnd() { if (this.situation.loops === true) { // If in a infinite loop, we end the current iteration this.situation.loops = this.situation.loop + 1; } if (typeof this.situation.loops === 'number') { // If performing a finite number of loops, we go after all the loops return this.at(this.situation.loops, true); } else { // If no loops, we just go at the end return this.at(1, true); } }, // set the internal animation pointer to the specified position and updates the visualisation // if isAbsPos is true, pos is treated as an absolute position at: function at(pos, isAbsPos) { var durDivSpd = this.situation.duration / this._speed; this.absPos = pos; // If pos is not an absolute position, we convert it into one if (!isAbsPos) { if (this.situation.reversed) this.absPos = 1 - this.absPos; this.absPos += this.situation.loop; } this.situation.start = +new Date() - this.absPos * durDivSpd; this.situation.finish = this.situation.start + durDivSpd; return this.step(true); }, /** * sets or returns the speed of the animations * @param speed null || Number The new speed of the animations * @return Number || this */ speed: function speed(_speed) { if (_speed === 0) return this.pause(); if (_speed) { this._speed = _speed; // We use an absolute position here so that speed can affect the delay before the animation return this.at(this.absPos, true); } else return this._speed; }, // Make loopable loop: function loop(times, reverse) { var c = this.last(); // store total loops c.loops = times != null ? times : true; c.loop = 0; if (reverse) c.reversing = true; return this; }, // pauses the animation pause: function pause() { this.paused = true; this.stopAnimFrame(); return this; }, // unpause the animation play: function play() { if (!this.paused) return this; this.paused = false; // We use an absolute position here so that the delay before the animation can be paused return this.at(this.absPos, true); }, /** * toggle or set the direction of the animation * true sets direction to backwards while false sets it to forwards * @param reversed Boolean indicating whether to reverse the animation or not (default: toggle the reverse status) * @return this */ reverse: function reverse(reversed) { var c = this.last(); if (typeof reversed === 'undefined') c.reversed = !c.reversed;else c.reversed = reversed; return this; }, /** * returns a float from 0-1 indicating the progress of the current animation * @param eased Boolean indicating whether the returned position should be eased or not * @return number */ progress: function progress(easeIt) { return easeIt ? this.situation.ease(this.pos) : this.pos; }, /** * adds a callback function which is called when the current animation is finished * @param fn Function which should be executed as callback * @return number */ after: function after(fn) { var c = this.last(), wrapper = function wrapper(e) { if (e.detail.situation == c) { fn.call(this, c); this.off('finished.fx', wrapper); // prevent memory leak } }; this.target().on('finished.fx', wrapper); return this._callStart(); }, // adds a callback which is called whenever one animation step is performed during: function during(fn) { var c = this.last(), wrapper = function wrapper(e) { if (e.detail.situation == c) { fn.call(this, e.detail.pos, SVG.morph(e.detail.pos), e.detail.eased, c); } }; // see above this.target().off('during.fx', wrapper).on('during.fx', wrapper); this.after(function () { this.off('during.fx', wrapper); }); return this._callStart(); }, // calls after ALL animations in the queue are finished afterAll: function afterAll(fn) { var wrapper = function wrapper(e) { fn.call(this); this.off('allfinished.fx', wrapper); }; // see above this.target().off('allfinished.fx', wrapper).on('allfinished.fx', wrapper); return this._callStart(); }, // calls on every animation step for all animations duringAll: function duringAll(fn) { var wrapper = function wrapper(e) { fn.call(this, e.detail.pos, SVG.morph(e.detail.pos), e.detail.eased, e.detail.situation); }; this.target().off('during.fx', wrapper).on('during.fx', wrapper); this.afterAll(function () { this.off('during.fx', wrapper); }); return this._callStart(); }, last: function last() { return this.situations.length ? this.situations[this.situations.length - 1] : this.situation; }, // adds one property to the animations add: function add(method, args, type) { this.last()[type || 'animations'][method] = args; return this._callStart(); }, /** perform one step of the animation * @param ignoreTime Boolean indicating whether to ignore time and use position directly or recalculate position based on time * @return this */ step: function step(ignoreTime) { // convert current time to an absolute position if (!ignoreTime) this.absPos = this.timeToAbsPos(+new Date()); // This part convert an absolute position to a position if (this.situation.loops !== false) { var absPos, absPosInt, lastLoop; // If the absolute position is below 0, we just treat it as if it was 0 absPos = Math.max(this.absPos, 0); absPosInt = Math.floor(absPos); if (this.situation.loops === true || absPosInt < this.situation.loops) { this.pos = absPos - absPosInt; lastLoop = this.situation.loop; this.situation.loop = absPosInt; } else { this.absPos = this.situation.loops; this.pos = 1; // The -1 here is because we don't want to toggle reversed when all the loops have been completed lastLoop = this.situation.loop - 1; this.situation.loop = this.situation.loops; } if (this.situation.reversing) { // Toggle reversed if an odd number of loops as occured since the last call of step this.situation.reversed = this.situation.reversed != Boolean((this.situation.loop - lastLoop) % 2); } } else { // If there are no loop, the absolute position must not be above 1 this.absPos = Math.min(this.absPos, 1); this.pos = this.absPos; } // while the absolute position can be below 0, the position must not be below 0 if (this.pos < 0) this.pos = 0; if (this.situation.reversed) this.pos = 1 - this.pos; // apply easing var eased = this.situation.ease(this.pos); // call once-callbacks for (var i in this.situation.once) { if (i > this.lastPos && i <= eased) { this.situation.once[i].call(this.target(), this.pos, eased); delete this.situation.once[i]; } } // fire during callback with position, eased position and current situation as parameter if (this.active) this.target().fire('during', { pos: this.pos, eased: eased, fx: this, situation: this.situation }); // the user may call stop or finish in the during callback // so make sure that we still have a valid situation if (!this.situation) { return this; } // apply the actual animation to every property this.eachAt(); // do final code when situation is finished if (this.pos == 1 && !this.situation.reversed || this.situation.reversed && this.pos == 0) { // stop animation callback this.stopAnimFrame(); // fire finished callback with current situation as parameter this.target().fire('finished', { fx: this, situation: this.situation }); if (!this.situations.length) { this.target().fire('allfinished'); // Recheck the length since the user may call animate in the afterAll callback if (!this.situations.length) { this.target().off('.fx'); // there shouldnt be any binding left, but to make sure... this.active = false; } } // start next animation if (this.active) this.dequeue();else this.clearCurrent(); } else if (!this.paused && this.active) { // we continue animating when we are not at the end this.startAnimFrame(); } // save last eased position for once callback triggering this.lastPos = eased; return this; }, // calculates the step for every property and calls block with it eachAt: function eachAt() { var i, len, at, self = this, target = this.target(), s = this.situation; // apply animations which can be called trough a method for (i in s.animations) { at = [].concat(s.animations[i]).map(function (el) { return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el; }); target[i].apply(target, at); } // apply animation which has to be applied with attr() for (i in s.attrs) { at = [i].concat(s.attrs[i]).map(function (el) { return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el; }); target.attr.apply(target, at); } // apply animation which has to be applied with style() for (i in s.styles) { at = [i].concat(s.styles[i]).map(function (el) { return typeof el !== 'string' && el.at ? el.at(s.ease(self.pos), self.pos) : el; }); target.style.apply(target, at); } // animate initialTransformation which has to be chained if (s.transforms.length) { // get initial initialTransformation at = s.initialTransformation; for (i = 0, len = s.transforms.length; i < len; i++) { // get next transformation in chain var a = s.transforms[i]; // multiply matrix directly if (a instanceof SVG.Matrix) { if (a.relative) { at = at.multiply(new SVG.Matrix().morph(a).at(s.ease(this.pos))); } else { at = at.morph(a).at(s.ease(this.pos)); } continue; } // when transformation is absolute we have to reset the needed transformation first if (!a.relative) { a.undo(at.extract()); } // and reapply it after at = at.multiply(a.at(s.ease(this.pos))); } // set new matrix on element target.matrix(at); } return this; }, // adds an once-callback which is called at a specific position and never again once: function once(pos, fn, isEased) { var c = this.last(); if (!isEased) pos = c.ease(pos); c.once[pos] = fn; return this; }, _callStart: function _callStart() { setTimeout(function () { this.start(); }.bind(this), 0); return this; } }, parent: SVG.Element, // Add method to parent elements construct: { // Get fx module or create a new one, then animate with given duration and ease animate: function animate(o, ease, delay) { return (this.fx || (this.fx = new SVG.FX(this))).animate(o, ease, delay); }, delay: function delay(_delay2) { return (this.fx || (this.fx = new SVG.FX(this))).delay(_delay2); }, stop: function stop(jumpToEnd, clearQueue) { if (this.fx) { this.fx.stop(jumpToEnd, clearQueue); } return this; }, finish: function finish() { if (this.fx) { this.fx.finish(); } return this; }, // Pause current animation pause: function pause() { if (this.fx) { this.fx.pause(); } return this; }, // Play paused current animation play: function play() { if (this.fx) { this.fx.play(); } return this; }, // Set/Get the speed of the animations speed: function speed(_speed2) { if (this.fx) { if (_speed2 == null) { return this.fx.speed(); } else { this.fx.speed(_speed2); } } return this; } } }); // MorphObj is used whenever no morphable object is given SVG.MorphObj = SVG.invent({ create: function create(from, to) { // prepare color for morphing if (SVG.Color.isColor(to)) return new SVG.Color(from).morph(to); // check if we have a list of values if (SVG.regex.delimiter.test(from)) { // prepare path for morphing if (SVG.regex.pathLetters.test(from)) return new SVG.PathArray(from).morph(to); // prepare value list for morphing else return new SVG.Array(from).morph(to); } // prepare number for morphing if (SVG.regex.numberAndUnit.test(to)) return new SVG.Number(from).morph(to); // prepare for plain morphing this.value = from; this.destination = to; }, extend: { at: function at(pos, real) { return real < 1 ? this.value : this.destination; }, valueOf: function valueOf() { return this.value; } } }); SVG.extend(SVG.FX, { // Add animatable attributes attr: function attr(a, v, relative) { // apply attributes individually if (_typeof(a) === 'object') { for (var key in a) { this.attr(key, a[key]); } } else { this.add(a, v, 'attrs'); } return this; }, // Add animatable styles style: function style(s, v) { if (_typeof(s) === 'object') { for (var key in s) { this.style(key, s[key]); } } else { this.add(s, v, 'styles'); } return this; }, // Animatable x-axis x: function x(_x2, relative) { if (this.target() instanceof SVG.G) { this.transform({ x: _x2 }, relative); return this; } var num = new SVG.Number(_x2); num.relative = relative; return this.add('x', num); }, // Animatable y-axis y: function y(_y2, relative) { if (this.target() instanceof SVG.G) { this.transform({ y: _y2 }, relative); return this; } var num = new SVG.Number(_y2); num.relative = relative; return this.add('y', num); }, // Animatable center x-axis cx: function cx(x) { return this.add('cx', new SVG.Number(x)); }, // Animatable center y-axis cy: function cy(y) { return this.add('cy', new SVG.Number(y)); }, // Add animatable move move: function move(x, y) { return this.x(x).y(y); }, // Add animatable center center: function center(x, y) { return this.cx(x).cy(y); }, // Add animatable size size: function size(width, height) { if (this.target() instanceof SVG.Text) { // animate font size for Text elements this.attr('font-size', width); } else { // animate bbox based size for all other elements var box; if (!width || !height) { box = this.target().bbox(); } if (!width) { width = box.width / box.height * height; } if (!height) { height = box.height / box.width * width; } this.add('width', new SVG.Number(width)).add('height', new SVG.Number(height)); } return this; }, // Add animatable width width: function width(_width2) { return this.add('width', new SVG.Number(_width2)); }, // Add animatable height height: function height(_height2) { return this.add('height', new SVG.Number(_height2)); }, // Add animatable plot plot: function plot(a, b, c, d) { // Lines can be plotted with 4 arguments if (arguments.length == 4) { return this.plot([a, b, c, d]); } return this.add('plot', new (this.target().morphArray)(a)); }, // Add leading method leading: function leading(value) { return this.target().leading ? this.add('leading', new SVG.Number(value)) : this; }, // Add animatable viewbox viewbox: function viewbox(x, y, width, height) { if (this.target() instanceof SVG.Container) { this.add('viewbox', new SVG.ViewBox(x, y, width, height)); } return this; }, update: function update(o) { if (this.target() instanceof SVG.Stop) { if (typeof o === 'number' || o instanceof SVG.Number) { return this.update({ offset: arguments[0], color: arguments[1], opacity: arguments[2] }); } if (o.opacity != null) this.attr('stop-opacity', o.opacity); if (o.color != null) this.attr('stop-color', o.color); if (o.offset != null) this.attr('offset', o.offset); } return this; } }); SVG.Box = SVG.invent({ create: function create(x, y, width, height) { if (_typeof(x) === 'object' && !(x instanceof SVG.Element)) { // chromes getBoundingClientRect has no x and y property return SVG.Box.call(this, x.left != null ? x.left : x.x, x.top != null ? x.top : x.y, x.width, x.height); } else if (arguments.length == 4) { this.x = x; this.y = y; this.width = width; this.height = height; } // add center, right, bottom... fullBox(this); }, extend: { // Merge rect box with another, return a new instance merge: function merge(box) { var b = new this.constructor(); // merge boxes b.x = Math.min(this.x, box.x); b.y = Math.min(this.y, box.y); b.width = Math.max(this.x + this.width, box.x + box.width) - b.x; b.height = Math.max(this.y + this.height, box.y + box.height) - b.y; return fullBox(b); }, transform: function transform(m) { var xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, bbox; var pts = [new SVG.Point(this.x, this.y), new SVG.Point(this.x2, this.y), new SVG.Point(this.x, this.y2), new SVG.Point(this.x2, this.y2)]; pts.forEach(function (p) { p = p.transform(m); xMin = Math.min(xMin, p.x); xMax = Math.max(xMax, p.x); yMin = Math.min(yMin, p.y); yMax = Math.max(yMax, p.y); }); bbox = new this.constructor(); bbox.x = xMin; bbox.width = xMax - xMin; bbox.y = yMin; bbox.height = yMax - yMin; fullBox(bbox); return bbox; } } }); SVG.BBox = SVG.invent({ // Initialize create: function create(element) { SVG.Box.apply(this, [].slice.call(arguments)); // get values if element is given if (element instanceof SVG.Element) { var box; // yes this is ugly, but Firefox can be a pain when it comes to elements that are not yet rendered try { if (!document.documentElement.contains) { // This is IE - it does not support contains() for top-level SVGs var topParent = element.node; while (topParent.parentNode) { topParent = topParent.parentNode; } if (topParent != document) throw new Error('Element not in the dom'); } // the element is NOT in the dom, throw error // disabling the check below which fixes issue #76 // if (!document.documentElement.contains(element.node)) throw new Exception('Element not in the dom') // find native bbox box = element.node.getBBox(); } catch (e) { if (element instanceof SVG.Shape) { if (!SVG.parser.draw) { // fixes apexcharts/vue-apexcharts #14 SVG.prepare(); } var clone = element.clone(SVG.parser.draw.instance).show(); box = clone.node.getBBox(); clone.remove(); } else { box = { x: element.node.clientLeft, y: element.node.clientTop, width: element.node.clientWidth, height: element.node.clientHeight }; } } SVG.Box.call(this, box); } }, // Define ancestor inherit: SVG.Box, // Define Parent parent: SVG.Element, // Constructor construct: { // Get bounding box bbox: function bbox() { return new SVG.BBox(this); } } }); SVG.BBox.prototype.constructor = SVG.BBox; SVG.extend(SVG.Element, { tbox: function tbox() { console.warn('Use of TBox is deprecated and mapped to RBox. Use .rbox() instead.'); return this.rbox(this.doc()); } }); SVG.RBox = SVG.invent({ // Initialize create: function create(element) { SVG.Box.apply(this, [].slice.call(arguments)); if (element instanceof SVG.Element) { SVG.Box.call(this, element.node.getBoundingClientRect()); } }, inherit: SVG.Box, // define Parent parent: SVG.Element, extend: { addOffset: function addOffset() { // offset by window scroll position, because getBoundingClientRect changes when window is scrolled this.x += window.pageXOffset; this.y += window.pageYOffset; return this; } }, // Constructor construct: { // Get rect box rbox: function rbox(el) { if (el) return new SVG.RBox(this).transform(el.screenCTM().inverse()); return new SVG.RBox(this).addOffset(); } } }); SVG.RBox.prototype.constructor = SVG.RBox; SVG.Matrix = SVG.invent({ // Initialize create: function create(source) { var i, base = arrayToMatrix([1, 0, 0, 1, 0, 0]); // ensure source as object source = source instanceof SVG.Element ? source.matrixify() : typeof source === 'string' ? arrayToMatrix(source.split(SVG.regex.delimiter).map(parseFloat)) : arguments.length == 6 ? arrayToMatrix([].slice.call(arguments)) : Array.isArray(source) ? arrayToMatrix(source) : _typeof(source) === 'object' ? source : base; // merge source for (i = abcdef.length - 1; i >= 0; --i) { this[abcdef[i]] = source[abcdef[i]] != null ? source[abcdef[i]] : base[abcdef[i]]; } }, // Add methods extend: { // Extract individual transformations extract: function extract() { // find delta transform points var px = deltaTransformPoint(this, 0, 1), py = deltaTransformPoint(this, 1, 0), skewX = 180 / Math.PI * Math.atan2(px.y, px.x) - 90; return { // translation x: this.e, y: this.f, transformedX: (this.e * Math.cos(skewX * Math.PI / 180) + this.f * Math.sin(skewX * Math.PI / 180)) / Math.sqrt(this.a * this.a + this.b * this.b), transformedY: (this.f * Math.cos(skewX * Math.PI / 180) + this.e * Math.sin(-skewX * Math.PI / 180)) / Math.sqrt(this.c * this.c + this.d * this.d), // skew skewX: -skewX, skewY: 180 / Math.PI * Math.atan2(py.y, py.x), // scale scaleX: Math.sqrt(this.a * this.a + this.b * this.b), scaleY: Math.sqrt(this.c * this.c + this.d * this.d), // rotation rotation: skewX, a: this.a, b: this.b, c: this.c, d: this.d, e: this.e, f: this.f, matrix: new SVG.Matrix(this) }; }, // Clone matrix clone: function clone() { return new SVG.Matrix(this); }, // Morph one matrix into another morph: function morph(matrix) { // store new destination this.destination = new SVG.Matrix(matrix); return this; }, // Get morphed matrix at a given position at: function at(pos) { // make sure a destination is defined if (!this.destination) return this; // calculate morphed matrix at a given position var matrix = new SVG.Matrix({ a: this.a + (this.destination.a - this.a) * pos, b: this.b + (this.destination.b - this.b) * pos, c: this.c + (this.destination.c - this.c) * pos, d: this.d + (this.destination.d - this.d) * pos, e: this.e + (this.destination.e - this.e) * pos, f: this.f + (this.destination.f - this.f) * pos }); return matrix; }, // Multiplies by given matrix multiply: function multiply(matrix) { return new SVG.Matrix(this.native().multiply(parseMatrix(matrix).native())); }, // Inverses matrix inverse: function inverse() { return new SVG.Matrix(this.native().inverse()); }, // Translate matrix translate: function translate(x, y) { return new SVG.Matrix(this.native().translate(x || 0, y || 0)); }, // Scale matrix scale: function scale(x, y, cx, cy) { // support uniformal scale if (arguments.length == 1) { y = x; } else if (arguments.length == 3) { cy = cx; cx = y; y = x; } return this.around(cx, cy, new SVG.Matrix(x, 0, 0, y, 0, 0)); }, // Rotate matrix rotate: function rotate(r, cx, cy) { // convert degrees to radians r = SVG.utils.radians(r); return this.around(cx, cy, new SVG.Matrix(Math.cos(r), Math.sin(r), -Math.sin(r), Math.cos(r), 0, 0)); }, // Flip matrix on x or y, at a given offset flip: function flip(a, o) { return a == 'x' ? this.scale(-1, 1, o, 0) : a == 'y' ? this.scale(1, -1, 0, o) : this.scale(-1, -1, a, o != null ? o : a); }, // Skew skew: function skew(x, y, cx, cy) { // support uniformal skew if (arguments.length == 1) { y = x; } else if (arguments.length == 3) { cy = cx; cx = y; y = x; } // convert degrees to radians x = SVG.utils.radians(x); y = SVG.utils.radians(y); return this.around(cx, cy, new SVG.Matrix(1, Math.tan(y), Math.tan(x), 1, 0, 0)); }, // SkewX skewX: function skewX(x, cx, cy) { return this.skew(x, 0, cx, cy); }, // SkewY skewY: function skewY(y, cx, cy) { return this.skew(0, y, cx, cy); }, // Transform around a center point around: function around(cx, cy, matrix) { return this.multiply(new SVG.Matrix(1, 0, 0, 1, cx || 0, cy || 0)).multiply(matrix).multiply(new SVG.Matrix(1, 0, 0, 1, -cx || 0, -cy || 0)); }, // Convert to native SVGMatrix native: function native() { // create new matrix var matrix = SVG.parser.native.createSVGMatrix(); // update with current values for (var i = abcdef.length - 1; i >= 0; i--) { matrix[abcdef[i]] = this[abcdef[i]]; } return matrix; }, // Convert matrix to string toString: function toString() { // Construct the matrix directly, avoid values that are too small return 'matrix(' + float32String(this.a) + ',' + float32String(this.b) + ',' + float32String(this.c) + ',' + float32String(this.d) + ',' + float32String(this.e) + ',' + float32String(this.f) + ')'; } }, // Define parent parent: SVG.Element, // Add parent method construct: { // Get current matrix ctm: function ctm() { return new SVG.Matrix(this.node.getCTM()); }, // Get current screen matrix screenCTM: function screenCTM() { /* https://bugzilla.mozilla.org/show_bug.cgi?id=1344537 This is needed because FF does not return the transformation matrix for the inner coordinate system when getScreenCTM() is called on nested svgs. However all other Browsers do that */ if (this instanceof SVG.Nested) { var rect = this.rect(1, 1); var m = rect.node.getScreenCTM(); rect.remove(); return new SVG.Matrix(m); } return new SVG.Matrix(this.node.getScreenCTM()); } } }); SVG.Point = SVG.invent({ // Initialize create: function create(x, y) { var source, base = { x: 0, y: 0 // ensure source as object }; source = Array.isArray(x) ? { x: x[0], y: x[1] } : _typeof(x) === 'object' ? { x: x.x, y: x.y } : x != null ? { x: x, y: y != null ? y : x } : base; // If y has no value, then x is used has its value // merge source this.x = source.x; this.y = source.y; }, // Add methods extend: { // Clone point clone: function clone() { return new SVG.Point(this); }, // Morph one point into another morph: function morph(x, y) { // store new destination this.destination = new SVG.Point(x, y); return this; }, // Get morphed point at a given position at: function at(pos) { // make sure a destination is defined if (!this.destination) return this; // calculate morphed matrix at a given position var point = new SVG.Point({ x: this.x + (this.destination.x - this.x) * pos, y: this.y + (this.destination.y - this.y) * pos }); return point; }, // Convert to native SVGPoint native: function native() { // create new point var point = SVG.parser.native.createSVGPoint(); // update with current values point.x = this.x; point.y = this.y; return point; }, // transform point with matrix transform: function transform(matrix) { return new SVG.Point(this.native().matrixTransform(matrix.native())); } } }); SVG.extend(SVG.Element, { // Get point point: function point(x, y) { return new SVG.Point(x, y).transform(this.screenCTM().inverse()); } }); SVG.extend(SVG.Element, { // Set svg element attribute attr: function attr(a, v, n) { // act as full getter if (a == null) { // get an object of attributes a = {}; v = this.node.attributes; for (n = v.length - 1; n >= 0; n--) { a[v[n].nodeName] = SVG.regex.isNumber.test(v[n].nodeValue) ? parseFloat(v[n].nodeValue) : v[n].nodeValue; } return a; } else if (_typeof(a) === 'object') { // apply every attribute individually if an object is passed for (v in a) { this.attr(v, a[v]); } } else if (v === null) { // remove value this.node.removeAttribute(a); } else if (v == null) { // act as a getter if the first and only argument is not an object v = this.node.getAttribute(a); return v == null ? SVG.defaults.attrs[a] : SVG.regex.isNumber.test(v) ? parseFloat(v) : v; } else { // BUG FIX: some browsers will render a stroke if a color is given even though stroke width is 0 if (a == 'stroke-width') { this.attr('stroke', parseFloat(v) > 0 ? this._stroke : null); } else if (a == 'stroke') { this._stroke = v; } // convert image fill and stroke to patterns if (a == 'fill' || a == 'stroke') { if (SVG.regex.isImage.test(v)) { v = this.doc().defs().image(v, 0, 0); } if (v instanceof SVG.Image) { v = this.doc().defs().pattern(0, 0, function () { this.add(v); }); } } // ensure correct numeric values (also accepts NaN and Infinity) if (typeof v === 'number') { v = new SVG.Number(v); } // ensure full hex color else if (SVG.Color.isColor(v)) { v = new SVG.Color(v); } // parse array values else if (Array.isArray(v)) { v = new SVG.Array(v); } // if the passed attribute is leading... if (a == 'leading') { // ... call the leading method instead if (this.leading) { this.leading(v); } } else { // set given attribute on node typeof n === 'string' ? this.node.setAttributeNS(n, a, v.toString()) : this.node.setAttribute(a, v.toString()); } // rebuild if required if (this.rebuild && (a == 'font-size' || a == 'x')) { this.rebuild(a, v); } } return this; } }); SVG.extend(SVG.Element, { // Add transformations transform: function transform(o, relative) { // get target in case of the fx module, otherwise reference this var target = this, matrix, bbox; // act as a getter if (_typeof(o) !== 'object') { // get current matrix matrix = new SVG.Matrix(target).extract(); return typeof o === 'string' ? matrix[o] : matrix; } // get current matrix matrix = new SVG.Matrix(target); // ensure relative flag relative = !!relative || !!o.relative; // act on matrix if (o.a != null) { matrix = relative // relative ? matrix.multiply(new SVG.Matrix(o)) // absolute : new SVG.Matrix(o); // act on rotation } else if (o.rotation != null) { // ensure centre point ensureCentre(o, target); // apply transformation matrix = relative // relative ? matrix.rotate(o.rotation, o.cx, o.cy) // absolute : matrix.rotate(o.rotation - matrix.extract().rotation, o.cx, o.cy); // act on scale } else if (o.scale != null || o.scaleX != null || o.scaleY != null) { // ensure centre point ensureCentre(o, target); // ensure scale values on both axes o.scaleX = o.scale != null ? o.scale : o.scaleX != null ? o.scaleX : 1; o.scaleY = o.scale != null ? o.scale : o.scaleY != null ? o.scaleY : 1; if (!relative) { // absolute; multiply inversed values var e = matrix.extract(); o.scaleX = o.scaleX * 1 / e.scaleX; o.scaleY = o.scaleY * 1 / e.scaleY; } matrix = matrix.scale(o.scaleX, o.scaleY, o.cx, o.cy); // act on skew } else if (o.skew != null || o.skewX != null || o.skewY != null) { // ensure centre point ensureCentre(o, target); // ensure skew values on both axes o.skewX = o.skew != null ? o.skew : o.skewX != null ? o.skewX : 0; o.skewY = o.skew != null ? o.skew : o.skewY != null ? o.skewY : 0; if (!relative) { // absolute; reset skew values var e = matrix.extract(); matrix = matrix.multiply(new SVG.Matrix().skew(e.skewX, e.skewY, o.cx, o.cy).inverse()); } matrix = matrix.skew(o.skewX, o.skewY, o.cx, o.cy); // act on flip } else if (o.flip) { if (o.flip == 'x' || o.flip == 'y') { o.offset = o.offset == null ? target.bbox()['c' + o.flip] : o.offset; } else { if (o.offset == null) { bbox = target.bbox(); o.flip = bbox.cx; o.offset = bbox.cy; } else { o.flip = o.offset; } } matrix = new SVG.Matrix().flip(o.flip, o.offset); // act on translate } else if (o.x != null || o.y != null) { if (relative) { // relative matrix = matrix.translate(o.x, o.y); } else { // absolute if (o.x != null) matrix.e = o.x; if (o.y != null) matrix.f = o.y; } } return this.attr('transform', matrix); } }); SVG.extend(SVG.FX, { transform: function transform(o, relative) { // get target in case of the fx module, otherwise reference this var target = this.target(), matrix, bbox; // act as a getter if (_typeof(o) !== 'object') { // get current matrix matrix = new SVG.Matrix(target).extract(); return typeof o === 'string' ? matrix[o] : matrix; } // ensure relative flag relative = !!relative || !!o.relative; // act on matrix if (o.a != null) { matrix = new SVG.Matrix(o); // act on rotation } else if (o.rotation != null) { // ensure centre point ensureCentre(o, target); // apply transformation matrix = new SVG.Rotate(o.rotation, o.cx, o.cy); // act on scale } else if (o.scale != null || o.scaleX != null || o.scaleY != null) { // ensure centre point ensureCentre(o, target); // ensure scale values on both axes o.scaleX = o.scale != null ? o.scale : o.scaleX != null ? o.scaleX : 1; o.scaleY = o.scale != null ? o.scale : o.scaleY != null ? o.scaleY : 1; matrix = new SVG.Scale(o.scaleX, o.scaleY, o.cx, o.cy); // act on skew } else if (o.skewX != null || o.skewY != null) { // ensure centre point ensureCentre(o, target); // ensure skew values on both axes o.skewX = o.skewX != null ? o.skewX : 0; o.skewY = o.skewY != null ? o.skewY : 0; matrix = new SVG.Skew(o.skewX, o.skewY, o.cx, o.cy); // act on flip } else if (o.flip) { if (o.flip == 'x' || o.flip == 'y') { o.offset = o.offset == null ? target.bbox()['c' + o.flip] : o.offset; } else { if (o.offset == null) { bbox = target.bbox(); o.flip = bbox.cx; o.offset = bbox.cy; } else { o.flip = o.offset; } } matrix = new SVG.Matrix().flip(o.flip, o.offset); // act on translate } else if (o.x != null || o.y != null) { matrix = new SVG.Translate(o.x, o.y); } if (!matrix) return this; matrix.relative = relative; this.last().transforms.push(matrix); return this._callStart(); } }); SVG.extend(SVG.Element, { // Reset all transformations untransform: function untransform() { return this.attr('transform', null); }, // merge the whole transformation chain into one matrix and returns it matrixify: function matrixify() { var matrix = (this.attr('transform') || ''). // split transformations split(SVG.regex.transforms).slice(0, -1).map(function (str) { // generate key => value pairs var kv = str.trim().split('('); return [kv[0], kv[1].split(SVG.regex.delimiter).map(function (str) { return parseFloat(str); })]; }) // merge every transformation into one matrix .reduce(function (matrix, transform) { if (transform[0] == 'matrix') return matrix.multiply(arrayToMatrix(transform[1])); return matrix[transform[0]].apply(matrix, transform[1]); }, new SVG.Matrix()); return matrix; }, // add an element to another parent without changing the visual representation on the screen toParent: function toParent(parent) { if (this == parent) return this; var ctm = this.screenCTM(); var pCtm = parent.screenCTM().inverse(); this.addTo(parent).untransform().transform(pCtm.multiply(ctm)); return this; }, // same as above with parent equals root-svg toDoc: function toDoc() { return this.toParent(this.doc()); } }); SVG.Transformation = SVG.invent({ create: function create(source, inversed) { if (arguments.length > 1 && typeof inversed !== 'boolean') { return this.constructor.call(this, [].slice.call(arguments)); } if (Array.isArray(source)) { for (var i = 0, len = this.arguments.length; i < len; ++i) { this[this.arguments[i]] = source[i]; } } else if (_typeof(source) === 'object') { for (var i = 0, len = this.arguments.length; i < len; ++i) { this[this.arguments[i]] = source[this.arguments[i]]; } } this.inversed = false; if (inversed === true) { this.inversed = true; } }, extend: { arguments: [], method: '', at: function at(pos) { var params = []; for (var i = 0, len = this.arguments.length; i < len; ++i) { params.push(this[this.arguments[i]]); } var m = this._undo || new SVG.Matrix(); m = new SVG.Matrix().morph(SVG.Matrix.prototype[this.method].apply(m, params)).at(pos); return this.inversed ? m.inverse() : m; }, undo: function undo(o) { for (var i = 0, len = this.arguments.length; i < len; ++i) { o[this.arguments[i]] = typeof this[this.arguments[i]] === 'undefined' ? 0 : o[this.arguments[i]]; } // The method SVG.Matrix.extract which was used before calling this // method to obtain a value for the parameter o doesn't return a cx and // a cy so we use the ones that were provided to this object at its creation o.cx = this.cx; o.cy = this.cy; this._undo = new SVG[capitalize(this.method)](o, true).at(1); return this; } } }); SVG.Translate = SVG.invent({ parent: SVG.Matrix, inherit: SVG.Transformation, create: function create(source, inversed) { this.constructor.apply(this, [].slice.call(arguments)); }, extend: { arguments: ['transformedX', 'transformedY'], method: 'translate' } }); SVG.Rotate = SVG.invent({ parent: SVG.Matrix, inherit: SVG.Transformation, create: function create(source, inversed) { this.constructor.apply(this, [].slice.call(arguments)); }, extend: { arguments: ['rotation', 'cx', 'cy'], method: 'rotate', at: function at(pos) { var m = new SVG.Matrix().rotate(new SVG.Number().morph(this.rotation - (this._undo ? this._undo.rotation : 0)).at(pos), this.cx, this.cy); return this.inversed ? m.inverse() : m; }, undo: function undo(o) { this._undo = o; return this; } } }); SVG.Scale = SVG.invent({ parent: SVG.Matrix, inherit: SVG.Transformation, create: function create(source, inversed) { this.constructor.apply(this, [].slice.call(arguments)); }, extend: { arguments: ['scaleX', 'scaleY', 'cx', 'cy'], method: 'scale' } }); SVG.Skew = SVG.invent({ parent: SVG.Matrix, inherit: SVG.Transformation, create: function create(source, inversed) { this.constructor.apply(this, [].slice.call(arguments)); }, extend: { arguments: ['skewX', 'skewY', 'cx', 'cy'], method: 'skew' } }); SVG.extend(SVG.Element, { // Dynamic style generator style: function style(s, v) { if (arguments.length == 0) { // get full style return this.node.style.cssText || ''; } else if (arguments.length < 2) { // apply every style individually if an object is passed if (_typeof(s) === 'object') { for (v in s) { this.style(v, s[v]); } } else if (SVG.regex.isCss.test(s)) { // parse css string s = s.split(/\s*;\s*/) // filter out suffix ; and stuff like ;; .filter(function (e) { return !!e; }).map(function (e) { return e.split(/\s*:\s*/); }); // apply every definition individually while (v = s.pop()) { this.style(v[0], v[1]); } } else { // act as a getter if the first and only argument is not an object return this.node.style[camelCase(s)]; } } else { this.node.style[camelCase(s)] = v === null || SVG.regex.isBlank.test(v) ? '' : v; } return this; } }); SVG.Parent = SVG.invent({ // Initialize node create: function create(element) { this.constructor.call(this, element); }, // Inherit from inherit: SVG.Element, // Add class methods extend: { // Returns all child elements children: function children() { return SVG.utils.map(SVG.utils.filterSVGElements(this.node.childNodes), function (node) { return SVG.adopt(node); }); }, // Add given element at a position add: function add(element, i) { if (i == null) { this.node.appendChild(element.node); } else if (element.node != this.node.childNodes[i]) { this.node.insertBefore(element.node, this.node.childNodes[i]); } return this; }, // Basically does the same as `add()` but returns the added element instead put: function put(element, i) { this.add(element, i); return element; }, // Checks if the given element is a child has: function has(element) { return this.index(element) >= 0; }, // Gets index of given element index: function index(element) { return [].slice.call(this.node.childNodes).indexOf(element.node); }, // Get a element at the given index get: function get(i) { return SVG.adopt(this.node.childNodes[i]); }, // Get first child first: function first() { return this.get(0); }, // Get the last child last: function last() { return this.get(this.node.childNodes.length - 1); }, // Iterates over all children and invokes a given block each: function each(block, deep) { var i, il, children = this.children(); for (i = 0, il = children.length; i < il; i++) { if (children[i] instanceof SVG.Element) { block.apply(children[i], [i, children]); } if (deep && children[i] instanceof SVG.Container) { children[i].each(block, deep); } } return this; }, // Remove a given child removeElement: function removeElement(element) { this.node.removeChild(element.node); return this; }, // Remove all elements in this container clear: function clear() { // remove children while (this.node.hasChildNodes()) { this.node.removeChild(this.node.lastChild); } // remove defs reference delete this._defs; return this; }, // Get defs defs: function defs() { return this.doc().defs(); } } }); SVG.extend(SVG.Parent, { ungroup: function ungroup(parent, depth) { if (depth === 0 || this instanceof SVG.Defs || this.node == SVG.parser.draw) return this; parent = parent || (this instanceof SVG.Doc ? this : this.parent(SVG.Parent)); depth = depth || Infinity; this.each(function () { if (this instanceof SVG.Defs) return this; if (this instanceof SVG.Parent) return this.ungroup(parent, depth - 1); return this.toParent(parent); }); this.node.firstChild || this.remove(); return this; }, flatten: function flatten(parent, depth) { return this.ungroup(parent, depth); } }); SVG.Container = SVG.invent({ // Initialize node create: function create(element) { this.constructor.call(this, element); }, // Inherit from inherit: SVG.Parent }); SVG.ViewBox = SVG.invent({ create: function create(source) { var base = [0, 0, 0, 0]; var x, y, width, height, box, view, we, he, wm = 1, // width multiplier hm = 1, // height multiplier reg = /[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?/gi; if (source instanceof SVG.Element) { we = source; he = source; view = (source.attr('viewBox') || '').match(reg); box = source.bbox; // get dimensions of current node width = new SVG.Number(source.width()); height = new SVG.Number(source.height()); // find nearest non-percentual dimensions while (width.unit == '%') { wm *= width.value; width = new SVG.Number(we instanceof SVG.Doc ? we.parent().offsetWidth : we.parent().width()); we = we.parent(); } while (height.unit == '%') { hm *= height.value; height = new SVG.Number(he instanceof SVG.Doc ? he.parent().offsetHeight : he.parent().height()); he = he.parent(); } // ensure defaults this.x = 0; this.y = 0; this.width = width * wm; this.height = height * hm; this.zoom = 1; if (view) { // get width and height from viewbox x = parseFloat(view[0]); y = parseFloat(view[1]); width = parseFloat(view[2]); height = parseFloat(view[3]); // calculate zoom accoring to viewbox this.zoom = this.width / this.height > width / height ? this.height / height : this.width / width; // calculate real pixel dimensions on parent SVG.Doc element this.x = x; this.y = y; this.width = width; this.height = height; } } else { // ensure source as object source = typeof source === 'string' ? source.match(reg).map(function (el) { return parseFloat(el); }) : Array.isArray(source) ? source : _typeof(source) === 'object' ? [source.x, source.y, source.width, source.height] : arguments.length == 4 ? [].slice.call(arguments) : base; this.x = source[0]; this.y = source[1]; this.width = source[2]; this.height = source[3]; } }, extend: { toString: function toString() { return this.x + ' ' + this.y + ' ' + this.width + ' ' + this.height; }, morph: function morph(x, y, width, height) { this.destination = new SVG.ViewBox(x, y, width, height); return this; }, at: function at(pos) { if (!this.destination) return this; return new SVG.ViewBox([this.x + (this.destination.x - this.x) * pos, this.y + (this.destination.y - this.y) * pos, this.width + (this.destination.width - this.width) * pos, this.height + (this.destination.height - this.height) * pos]); } }, // Define parent parent: SVG.Container, // Add parent method construct: { // get/set viewbox viewbox: function viewbox(x, y, width, height) { if (arguments.length == 0) // act as a getter if there are no arguments { return new SVG.ViewBox(this); } // otherwise act as a setter return this.attr('viewBox', new SVG.ViewBox(x, y, width, height)); } } }) // Add events to elements ; ['click', 'dblclick', 'mousedown', 'mouseup', 'mouseover', 'mouseout', 'mousemove', // , 'mouseenter' -> not supported by IE // , 'mouseleave' -> not supported by IE 'touchstart', 'touchmove', 'touchleave', 'touchend', 'touchcancel'].forEach(function (event) { // add event to SVG.Element SVG.Element.prototype[event] = function (f) { // bind event to element rather than element node SVG.on(this.node, event, f); return this; }; }); // Initialize listeners stack SVG.listeners = []; SVG.handlerMap = []; SVG.listenerId = 0; // Add event binder in the SVG namespace SVG.on = function (node, event, listener, binding, options) { // create listener, get object-index var l = listener.bind(binding || node.instance || node), index = (SVG.handlerMap.indexOf(node) + 1 || SVG.handlerMap.push(node)) - 1, ev = event.split('.')[0], ns = event.split('.')[1] || '*'; // ensure valid object SVG.listeners[index] = SVG.listeners[index] || {}; SVG.listeners[index][ev] = SVG.listeners[index][ev] || {}; SVG.listeners[index][ev][ns] = SVG.listeners[index][ev][ns] || {}; if (!listener._svgjsListenerId) { listener._svgjsListenerId = ++SVG.listenerId; } // reference listener SVG.listeners[index][ev][ns][listener._svgjsListenerId] = l; // add listener node.addEventListener(ev, l, options || false); }; // Add event unbinder in the SVG namespace SVG.off = function (node, event, listener) { var index = SVG.handlerMap.indexOf(node), ev = event && event.split('.')[0], ns = event && event.split('.')[1], namespace = ''; if (index == -1) return; if (listener) { if (typeof listener === 'function') listener = listener._svgjsListenerId; if (!listener) return; // remove listener reference if (SVG.listeners[index][ev] && SVG.listeners[index][ev][ns || '*']) { // remove listener node.removeEventListener(ev, SVG.listeners[index][ev][ns || '*'][listener], false); delete SVG.listeners[index][ev][ns || '*'][listener]; } } else if (ns && ev) { // remove all listeners for a namespaced event if (SVG.listeners[index][ev] && SVG.listeners[index][ev][ns]) { for (listener in SVG.listeners[index][ev][ns]) { SVG.off(node, [ev, ns].join('.'), listener); } delete SVG.listeners[index][ev][ns]; } } else if (ns) { // remove all listeners for a specific namespace for (event in SVG.listeners[index]) { for (namespace in SVG.listeners[index][event]) { if (ns === namespace) { SVG.off(node, [event, ns].join('.')); } } } } else if (ev) { // remove all listeners for the event if (SVG.listeners[index][ev]) { for (namespace in SVG.listeners[index][ev]) { SVG.off(node, [ev, namespace].join('.')); } delete SVG.listeners[index][ev]; } } else { // remove all listeners on a given node for (event in SVG.listeners[index]) { SVG.off(node, event); } delete SVG.listeners[index]; delete SVG.handlerMap[index]; } }; // SVG.extend(SVG.Element, { // Bind given event to listener on: function on(event, listener, binding, options) { SVG.on(this.node, event, listener, binding, options); return this; }, // Unbind event from listener off: function off(event, listener) { SVG.off(this.node, event, listener); return this; }, // Fire given event fire: function fire(event, data) { // Dispatch event if (event instanceof window.Event) { this.node.dispatchEvent(event); } else { this.node.dispatchEvent(event = new SVG.CustomEvent(event, { detail: data, cancelable: true })); } this._event = event; return this; }, event: function event() { return this._event; } }); SVG.Defs = SVG.invent({ // Initialize node create: 'defs', // Inherit from inherit: SVG.Container }); SVG.G = SVG.invent({ // Initialize node create: 'g', // Inherit from inherit: SVG.Container, // Add class methods extend: { // Move over x-axis x: function x(_x3) { return _x3 == null ? this.transform('x') : this.transform({ x: _x3 - this.x() }, true); }, // Move over y-axis y: function y(_y3) { return _y3 == null ? this.transform('y') : this.transform({ y: _y3 - this.y() }, true); }, // Move by center over x-axis cx: function cx(x) { return x == null ? this.gbox().cx : this.x(x - this.gbox().width / 2); }, // Move by center over y-axis cy: function cy(y) { return y == null ? this.gbox().cy : this.y(y - this.gbox().height / 2); }, gbox: function gbox() { var bbox = this.bbox(), trans = this.transform(); bbox.x += trans.x; bbox.x2 += trans.x; bbox.cx += trans.x; bbox.y += trans.y; bbox.y2 += trans.y; bbox.cy += trans.y; return bbox; } }, // Add parent method construct: { // Create a group element group: function group() { return this.put(new SVG.G()); } } }); SVG.Doc = SVG.invent({ // Initialize node create: function create(element) { if (element) { // ensure the presence of a dom element element = typeof element === 'string' ? document.getElementById(element) : element; // If the target is an svg element, use that element as the main wrapper. // This allows svg.js to work with svg documents as well. if (element.nodeName == 'svg') { this.constructor.call(this, element); } else { this.constructor.call(this, SVG.create('svg')); element.appendChild(this.node); this.size('100%', '100%'); } // set svg element attributes and ensure defs node this.namespace().defs(); } }, // Inherit from inherit: SVG.Container, // Add class methods extend: { // Add namespaces namespace: function namespace() { return this.attr({ xmlns: SVG.ns, version: '1.1' }).attr('xmlns:xlink', SVG.xlink, SVG.xmlns).attr('xmlns:svgjs', SVG.svgjs, SVG.xmlns); }, // Creates and returns defs element defs: function defs() { if (!this._defs) { var defs; // Find or create a defs element in this instance if (defs = this.node.getElementsByTagName('defs')[0]) { this._defs = SVG.adopt(defs); } else { this._defs = new SVG.Defs(); } // Make sure the defs node is at the end of the stack this.node.appendChild(this._defs.node); } return this._defs; }, // custom parent method parent: function parent() { if (!this.node.parentNode || this.node.parentNode.nodeName == '#document') return null; return this.node.parentNode; }, // Fix for possible sub-pixel offset. See: // https://bugzilla.mozilla.org/show_bug.cgi?id=608812 spof: function spof() { var pos = this.node.getScreenCTM(); if (pos) { this.style('left', -pos.e % 1 + 'px').style('top', -pos.f % 1 + 'px'); } return this; }, // Removes the doc from the DOM remove: function remove() { if (this.parent()) { this.parent().removeChild(this.node); } return this; }, clear: function clear() { // remove children while (this.node.hasChildNodes()) { this.node.removeChild(this.node.lastChild); } // remove defs reference delete this._defs; // add back parser if (SVG.parser.draw && !SVG.parser.draw.parentNode) { this.node.appendChild(SVG.parser.draw); } return this; }, clone: function clone(parent) { // write dom data to the dom so the clone can pickup the data this.writeDataToDom(); // get reference to node var node = this.node; // clone element and assign new id var clone = assignNewId(node.cloneNode(true)); // insert the clone in the given parent or after myself if (parent) { (parent.node || parent).appendChild(clone.node); } else { node.parentNode.insertBefore(clone.node, node.nextSibling); } return clone; } } }); // ### This module adds backward / forward functionality to elements. // SVG.extend(SVG.Element, { // Get all siblings, including myself siblings: function siblings() { return this.parent().children(); }, // Get the curent position siblings position: function position() { return this.parent().index(this); }, // Get the next element (will return null if there is none) next: function next() { return this.siblings()[this.position() + 1]; }, // Get the next element (will return null if there is none) previous: function previous() { return this.siblings()[this.position() - 1]; }, // Send given element one step forward forward: function forward() { var i = this.position() + 1, p = this.parent(); // move node one step forward p.removeElement(this).add(this, i); // make sure defs node is always at the top if (p instanceof SVG.Doc) { p.node.appendChild(p.defs().node); } return this; }, // Send given element one step backward backward: function backward() { var i = this.position(); if (i > 0) { this.parent().removeElement(this).add(this, i - 1); } return this; }, // Send given element all the way to the front front: function front() { var p = this.parent(); // Move node forward p.node.appendChild(this.node); // Make sure defs node is always at the top if (p instanceof SVG.Doc) { p.node.appendChild(p.defs().node); } return this; }, // Send given element all the way to the back back: function back() { if (this.position() > 0) { this.parent().removeElement(this).add(this, 0); } return this; }, // Inserts a given element before the targeted element before: function before(element) { element.remove(); var i = this.position(); this.parent().add(element, i); return this; }, // Insters a given element after the targeted element after: function after(element) { element.remove(); var i = this.position(); this.parent().add(element, i + 1); return this; } }); SVG.Mask = SVG.invent({ // Initialize node create: function create() { this.constructor.call(this, SVG.create('mask')); // keep references to masked elements this.targets = []; }, // Inherit from inherit: SVG.Container, // Add class methods extend: { // Unmask all masked elements and remove itself remove: function remove() { // unmask all targets for (var i = this.targets.length - 1; i >= 0; i--) { if (this.targets[i]) { this.targets[i].unmask(); } } this.targets = []; // remove mask from parent SVG.Element.prototype.remove.call(this); return this; } }, // Add parent method construct: { // Create masking element mask: function mask() { return this.defs().put(new SVG.Mask()); } } }); SVG.extend(SVG.Element, { // Distribute mask to svg element maskWith: function maskWith(element) { // use given mask or create a new one this.masker = element instanceof SVG.Mask ? element : this.parent().mask().add(element); // store reverence on self in mask this.masker.targets.push(this); // apply mask return this.attr('mask', 'url("#' + this.masker.attr('id') + '")'); }, // Unmask element unmask: function unmask() { delete this.masker; return this.attr('mask', null); } }); SVG.ClipPath = SVG.invent({ // Initialize node create: function create() { this.constructor.call(this, SVG.create('clipPath')); // keep references to clipped elements this.targets = []; }, // Inherit from inherit: SVG.Container, // Add class methods extend: { // Unclip all clipped elements and remove itself remove: function remove() { // unclip all targets for (var i = this.targets.length - 1; i >= 0; i--) { if (this.targets[i]) { this.targets[i].unclip(); } } this.targets = []; // remove clipPath from parent this.parent().removeElement(this); return this; } }, // Add parent method construct: { // Create clipping element clip: function clip() { return this.defs().put(new SVG.ClipPath()); } } }); // SVG.extend(SVG.Element, { // Distribute clipPath to svg element clipWith: function clipWith(element) { // use given clip or create a new one this.clipper = element instanceof SVG.ClipPath ? element : this.parent().clip().add(element); // store reverence on self in mask this.clipper.targets.push(this); // apply mask return this.attr('clip-path', 'url("#' + this.clipper.attr('id') + '")'); }, // Unclip element unclip: function unclip() { delete this.clipper; return this.attr('clip-path', null); } }); SVG.Gradient = SVG.invent({ // Initialize node create: function create(type) { this.constructor.call(this, SVG.create(type + 'Gradient')); // store type this.type = type; }, // Inherit from inherit: SVG.Container, // Add class methods extend: { // Add a color stop at: function at(offset, color, opacity) { return this.put(new SVG.Stop()).update(offset, color, opacity); }, // Update gradient update: function update(block) { // remove all stops this.clear(); // invoke passed block if (typeof block === 'function') { block.call(this, this); } return this; }, // Return the fill id fill: function fill() { return 'url(#' + this.id() + ')'; }, // Alias string convertion to fill toString: function toString() { return this.fill(); }, // custom attr to handle transform attr: function attr(a, b, c) { if (a == 'transform') a = 'gradientTransform'; return SVG.Container.prototype.attr.call(this, a, b, c); } }, // Add parent method construct: { // Create gradient element in defs gradient: function gradient(type, block) { return this.defs().gradient(type, block); } } }); // Add animatable methods to both gradient and fx module SVG.extend(SVG.Gradient, SVG.FX, { // From position from: function from(x, y) { return (this._target || this).type == 'radial' ? this.attr({ fx: new SVG.Number(x), fy: new SVG.Number(y) }) : this.attr({ x1: new SVG.Number(x), y1: new SVG.Number(y) }); }, // To position to: function to(x, y) { return (this._target || this).type == 'radial' ? this.attr({ cx: new SVG.Number(x), cy: new SVG.Number(y) }) : this.attr({ x2: new SVG.Number(x), y2: new SVG.Number(y) }); } }); // Base gradient generation SVG.extend(SVG.Defs, { // define gradient gradient: function gradient(type, block) { return this.put(new SVG.Gradient(type)).update(block); } }); SVG.Stop = SVG.invent({ // Initialize node create: 'stop', // Inherit from inherit: SVG.Element, // Add class methods extend: { // add color stops update: function update(o) { if (typeof o === 'number' || o instanceof SVG.Number) { o = { offset: arguments[0], color: arguments[1], opacity: arguments[2] }; } // set attributes if (o.opacity != null) this.attr('stop-opacity', o.opacity); if (o.color != null) this.attr('stop-color', o.color); if (o.offset != null) this.attr('offset', new SVG.Number(o.offset)); return this; } } }); SVG.Pattern = SVG.invent({ // Initialize node create: 'pattern', // Inherit from inherit: SVG.Container, // Add class methods extend: { // Return the fill id fill: function fill() { return 'url(#' + this.id() + ')'; }, // Update pattern by rebuilding update: function update(block) { // remove content this.clear(); // invoke passed block if (typeof block === 'function') { block.call(this, this); } return this; }, // Alias string convertion to fill toString: function toString() { return this.fill(); }, // custom attr to handle transform attr: function attr(a, b, c) { if (a == 'transform') a = 'patternTransform'; return SVG.Container.prototype.attr.call(this, a, b, c); } }, // Add parent method construct: { // Create pattern element in defs pattern: function pattern(width, height, block) { return this.defs().pattern(width, height, block); } } }); SVG.extend(SVG.Defs, { // Define gradient pattern: function pattern(width, height, block) { return this.put(new SVG.Pattern()).update(block).attr({ x: 0, y: 0, width: width, height: height, patternUnits: 'userSpaceOnUse' }); } }); SVG.Shape = SVG.invent({ // Initialize node create: function create(element) { this.constructor.call(this, element); }, // Inherit from inherit: SVG.Element }); SVG.Bare = SVG.invent({ // Initialize create: function create(element, inherit) { // construct element this.constructor.call(this, SVG.create(element)); // inherit custom methods if (inherit) { for (var method in inherit.prototype) { if (typeof inherit.prototype[method] === 'function') { this[method] = inherit.prototype[method]; } } } }, // Inherit from inherit: SVG.Element, // Add methods extend: { // Insert some plain text words: function words(text) { // remove contents while (this.node.hasChildNodes()) { this.node.removeChild(this.node.lastChild); } // create text node this.node.appendChild(document.createTextNode(text)); return this; } } }); SVG.extend(SVG.Parent, { // Create an element that is not described by SVG.js element: function element(_element, inherit) { return this.put(new SVG.Bare(_element, inherit)); } }); SVG.Symbol = SVG.invent({ // Initialize node create: 'symbol', // Inherit from inherit: SVG.Container, construct: { // create symbol symbol: function symbol() { return this.put(new SVG.Symbol()); } } }); SVG.Use = SVG.invent({ // Initialize node create: 'use', // Inherit from inherit: SVG.Shape, // Add class methods extend: { // Use element as a reference element: function element(_element2, file) { // Set lined element return this.attr('href', (file || '') + '#' + _element2, SVG.xlink); } }, // Add parent method construct: { // Create a use element use: function use(element, file) { return this.put(new SVG.Use()).element(element, file); } } }); SVG.Rect = SVG.invent({ // Initialize node create: 'rect', // Inherit from inherit: SVG.Shape, // Add parent method construct: { // Create a rect element rect: function rect(width, height) { return this.put(new SVG.Rect()).size(width, height); } } }); SVG.Circle = SVG.invent({ // Initialize node create: 'circle', // Inherit from inherit: SVG.Shape, // Add parent method construct: { // Create circle element, based on ellipse circle: function circle(size) { return this.put(new SVG.Circle()).rx(new SVG.Number(size).divide(2)).move(0, 0); } } }); SVG.extend(SVG.Circle, SVG.FX, { // Radius x value rx: function rx(_rx) { return this.attr('r', _rx); }, // Alias radius x value ry: function ry(_ry) { return this.rx(_ry); } }); SVG.Ellipse = SVG.invent({ // Initialize node create: 'ellipse', // Inherit from inherit: SVG.Shape, // Add parent method construct: { // Create an ellipse ellipse: function ellipse(width, height) { return this.put(new SVG.Ellipse()).size(width, height).move(0, 0); } } }); SVG.extend(SVG.Ellipse, SVG.Rect, SVG.FX, { // Radius x value rx: function rx(_rx2) { return this.attr('rx', _rx2); }, // Radius y value ry: function ry(_ry2) { return this.attr('ry', _ry2); } }); // Add common method SVG.extend(SVG.Circle, SVG.Ellipse, { // Move over x-axis x: function x(_x4) { return _x4 == null ? this.cx() - this.rx() : this.cx(_x4 + this.rx()); }, // Move over y-axis y: function y(_y4) { return _y4 == null ? this.cy() - this.ry() : this.cy(_y4 + this.ry()); }, // Move by center over x-axis cx: function cx(x) { return x == null ? this.attr('cx') : this.attr('cx', x); }, // Move by center over y-axis cy: function cy(y) { return y == null ? this.attr('cy') : this.attr('cy', y); }, // Set width of element width: function width(_width3) { return _width3 == null ? this.rx() * 2 : this.rx(new SVG.Number(_width3).divide(2)); }, // Set height of element height: function height(_height3) { return _height3 == null ? this.ry() * 2 : this.ry(new SVG.Number(_height3).divide(2)); }, // Custom size function size: function size(width, height) { var p = proportionalSize(this, width, height); return this.rx(new SVG.Number(p.width).divide(2)).ry(new SVG.Number(p.height).divide(2)); } }); SVG.Line = SVG.invent({ // Initialize node create: 'line', // Inherit from inherit: SVG.Shape, // Add class methods extend: { // Get array array: function array() { return new SVG.PointArray([[this.attr('x1'), this.attr('y1')], [this.attr('x2'), this.attr('y2')]]); }, // Overwrite native plot() method plot: function plot(x1, y1, x2, y2) { if (x1 == null) { return this.array(); } else if (typeof y1 !== 'undefined') { x1 = { x1: x1, y1: y1, x2: x2, y2: y2 }; } else { x1 = new SVG.PointArray(x1).toLine(); } return this.attr(x1); }, // Move by left top corner move: function move(x, y) { return this.attr(this.array().move(x, y).toLine()); }, // Set element size to given width and height size: function size(width, height) { var p = proportionalSize(this, width, height); return this.attr(this.array().size(p.width, p.height).toLine()); } }, // Add parent method construct: { // Create a line element line: function line(x1, y1, x2, y2) { // make sure plot is called as a setter // x1 is not necessarily a number, it can also be an array, a string and a SVG.PointArray return SVG.Line.prototype.plot.apply(this.put(new SVG.Line()), x1 != null ? [x1, y1, x2, y2] : [0, 0, 0, 0]); } } }); SVG.Polyline = SVG.invent({ // Initialize node create: 'polyline', // Inherit from inherit: SVG.Shape, // Add parent method construct: { // Create a wrapped polyline element polyline: function polyline(p) { // make sure plot is called as a setter return this.put(new SVG.Polyline()).plot(p || new SVG.PointArray()); } } }); SVG.Polygon = SVG.invent({ // Initialize node create: 'polygon', // Inherit from inherit: SVG.Shape, // Add parent method construct: { // Create a wrapped polygon element polygon: function polygon(p) { // make sure plot is called as a setter return this.put(new SVG.Polygon()).plot(p || new SVG.PointArray()); } } }); // Add polygon-specific functions SVG.extend(SVG.Polyline, SVG.Polygon, { // Get array array: function array() { return this._array || (this._array = new SVG.PointArray(this.attr('points'))); }, // Plot new path plot: function plot(p) { return p == null ? this.array() : this.clear().attr('points', typeof p === 'string' ? p : this._array = new SVG.PointArray(p)); }, // Clear array cache clear: function clear() { delete this._array; return this; }, // Move by left top corner move: function move(x, y) { return this.attr('points', this.array().move(x, y)); }, // Set element size to given width and height size: function size(width, height) { var p = proportionalSize(this, width, height); return this.attr('points', this.array().size(p.width, p.height)); } }); // unify all point to point elements SVG.extend(SVG.Line, SVG.Polyline, SVG.Polygon, { // Define morphable array morphArray: SVG.PointArray, // Move by left top corner over x-axis x: function x(_x5) { return _x5 == null ? this.bbox().x : this.move(_x5, this.bbox().y); }, // Move by left top corner over y-axis y: function y(_y5) { return _y5 == null ? this.bbox().y : this.move(this.bbox().x, _y5); }, // Set width of element width: function width(_width4) { var b = this.bbox(); return _width4 == null ? b.width : this.size(_width4, b.height); }, // Set height of element height: function height(_height4) { var b = this.bbox(); return _height4 == null ? b.height : this.size(b.width, _height4); } }); SVG.Path = SVG.invent({ // Initialize node create: 'path', // Inherit from inherit: SVG.Shape, // Add class methods extend: { // Define morphable array morphArray: SVG.PathArray, // Get array array: function array() { return this._array || (this._array = new SVG.PathArray(this.attr('d'))); }, // Plot new path plot: function plot(d) { return d == null ? this.array() : this.clear().attr('d', typeof d === 'string' ? d : this._array = new SVG.PathArray(d)); }, // Clear array cache clear: function clear() { delete this._array; return this; }, // Move by left top corner move: function move(x, y) { return this.attr('d', this.array().move(x, y)); }, // Move by left top corner over x-axis x: function x(_x6) { return _x6 == null ? this.bbox().x : this.move(_x6, this.bbox().y); }, // Move by left top corner over y-axis y: function y(_y6) { return _y6 == null ? this.bbox().y : this.move(this.bbox().x, _y6); }, // Set element size to given width and height size: function size(width, height) { var p = proportionalSize(this, width, height); return this.attr('d', this.array().size(p.width, p.height)); }, // Set width of element width: function width(_width5) { return _width5 == null ? this.bbox().width : this.size(_width5, this.bbox().height); }, // Set height of element height: function height(_height5) { return _height5 == null ? this.bbox().height : this.size(this.bbox().width, _height5); } }, // Add parent method construct: { // Create a wrapped path element path: function path(d) { // make sure plot is called as a setter return this.put(new SVG.Path()).plot(d || new SVG.PathArray()); } } }); SVG.Image = SVG.invent({ // Initialize node create: 'image', // Inherit from inherit: SVG.Shape, // Add class methods extend: { // (re)load image load: function load(url) { if (!url) return this; var self = this, img = new window.Image(); // preload image SVG.on(img, 'load', function () { SVG.off(img); var p = self.parent(SVG.Pattern); if (p === null) return; // ensure image size if (self.width() == 0 && self.height() == 0) { self.size(img.width, img.height); } // ensure pattern size if not set if (p && p.width() == 0 && p.height() == 0) { p.size(self.width(), self.height()); } // callback if (typeof self._loaded === 'function') { self._loaded.call(self, { width: img.width, height: img.height, ratio: img.width / img.height, url: url }); } }); SVG.on(img, 'error', function (e) { SVG.off(img); if (typeof self._error === 'function') { self._error.call(self, e); } }); return this.attr('href', img.src = this.src = url, SVG.xlink); }, // Add loaded callback loaded: function loaded(_loaded) { this._loaded = _loaded; return this; }, error: function error(_error) { this._error = _error; return this; } }, // Add parent method construct: { // create image element, load image and set its size image: function image(source, width, height) { return this.put(new SVG.Image()).load(source).size(width || 0, height || width || 0); } } }); SVG.Text = SVG.invent({ // Initialize node create: function create() { this.constructor.call(this, SVG.create('text')); this.dom.leading = new SVG.Number(1.3); // store leading value for rebuilding this._rebuild = true; // enable automatic updating of dy values this._build = false; // disable build mode for adding multiple lines // set default font this.attr('font-family', SVG.defaults.attrs['font-family']); }, // Inherit from inherit: SVG.Shape, // Add class methods extend: { // Move over x-axis x: function x(_x7) { // act as getter if (_x7 == null) { return this.attr('x'); } return this.attr('x', _x7); }, // Move over y-axis y: function y(_y7) { var oy = this.attr('y'), o = typeof oy === 'number' ? oy - this.bbox().y : 0; // act as getter if (_y7 == null) { return typeof oy === 'number' ? oy - o : oy; } return this.attr('y', typeof _y7.valueOf() === 'number' ? _y7 + o : _y7); }, // Move center over x-axis cx: function cx(x) { return x == null ? this.bbox().cx : this.x(x - this.bbox().width / 2); }, // Move center over y-axis cy: function cy(y) { return y == null ? this.bbox().cy : this.y(y - this.bbox().height / 2); }, // Set the text content text: function text(_text) { // act as getter if (typeof _text === 'undefined') { var _text = ''; var children = this.node.childNodes; for (var i = 0, len = children.length; i < len; ++i) { // add newline if its not the first child and newLined is set to true if (i != 0 && children[i].nodeType != 3 && SVG.adopt(children[i]).dom.newLined == true) { _text += '\n'; } // add content of this node _text += children[i].textContent; } return _text; } // remove existing content this.clear().build(true); if (typeof _text === 'function') { // call block _text.call(this, this); } else { // store text and make sure text is not blank _text = _text.split('\n'); // build new lines for (var i = 0, il = _text.length; i < il; i++) { this.tspan(_text[i]).newLine(); } } // disable build mode and rebuild lines return this.build(false).rebuild(); }, // Set font size size: function size(_size) { return this.attr('font-size', _size).rebuild(); }, // Set / get leading leading: function leading(value) { // act as getter if (value == null) { return this.dom.leading; } // act as setter this.dom.leading = new SVG.Number(value); return this.rebuild(); }, // Get all the first level lines lines: function lines() { var node = (this.textPath && this.textPath() || this).node; // filter tspans and map them to SVG.js instances var lines = SVG.utils.map(SVG.utils.filterSVGElements(node.childNodes), function (el) { return SVG.adopt(el); }); // return an instance of SVG.set return new SVG.Set(lines); }, // Rebuild appearance type rebuild: function rebuild(_rebuild) { // store new rebuild flag if given if (typeof _rebuild === 'boolean') { this._rebuild = _rebuild; } // define position of all lines if (this._rebuild) { var self = this, blankLineOffset = 0, dy = this.dom.leading * new SVG.Number(this.attr('font-size')); this.lines().each(function () { if (this.dom.newLined) { if (!self.textPath()) { this.attr('x', self.attr('x')); } if (this.text() == '\n') { blankLineOffset += dy; } else { this.attr('dy', dy + blankLineOffset); blankLineOffset = 0; } } }); this.fire('rebuild'); } return this; }, // Enable / disable build mode build: function build(_build) { this._build = !!_build; return this; }, // overwrite method from parent to set data properly setData: function setData(o) { this.dom = o; this.dom.leading = new SVG.Number(o.leading || 1.3); return this; } }, // Add parent method construct: { // Create text element text: function text(_text2) { return this.put(new SVG.Text()).text(_text2); }, // Create plain text element plain: function plain(text) { return this.put(new SVG.Text()).plain(text); } } }); SVG.Tspan = SVG.invent({ // Initialize node create: 'tspan', // Inherit from inherit: SVG.Shape, // Add class methods extend: { // Set text content text: function text(_text3) { if (_text3 == null) return this.node.textContent + (this.dom.newLined ? '\n' : ''); typeof _text3 === 'function' ? _text3.call(this, this) : this.plain(_text3); return this; }, // Shortcut dx dx: function dx(_dx) { return this.attr('dx', _dx); }, // Shortcut dy dy: function dy(_dy) { return this.attr('dy', _dy); }, // Create new line newLine: function newLine() { // fetch text parent var t = this.parent(SVG.Text); // mark new line this.dom.newLined = true; // apply new hy¡n return this.dy(t.dom.leading * t.attr('font-size')).attr('x', t.x()); } } }); SVG.extend(SVG.Text, SVG.Tspan, { // Create plain text node plain: function plain(text) { // clear if build mode is disabled if (this._build === false) { this.clear(); } // create text node this.node.appendChild(document.createTextNode(text)); return this; }, // Create a tspan tspan: function tspan(text) { var node = (this.textPath && this.textPath() || this).node, tspan = new SVG.Tspan(); // clear if build mode is disabled if (this._build === false) { this.clear(); } // add new tspan node.appendChild(tspan.node); return tspan.text(text); }, // Clear all lines clear: function clear() { var node = (this.textPath && this.textPath() || this).node; // remove existing child nodes while (node.hasChildNodes()) { node.removeChild(node.lastChild); } return this; }, // Get length of text element length: function length() { return this.node.getComputedTextLength(); } }); SVG.TextPath = SVG.invent({ // Initialize node create: 'textPath', // Inherit from inherit: SVG.Parent, // Define parent class parent: SVG.Text, // Add parent method construct: { morphArray: SVG.PathArray, // Create path for text to run on path: function path(d) { // create textPath element var path = new SVG.TextPath(), track = this.doc().defs().path(d); // move lines to textpath while (this.node.hasChildNodes()) { path.node.appendChild(this.node.firstChild); } // add textPath element as child node this.node.appendChild(path.node); // link textPath to path and add content path.attr('href', '#' + track, SVG.xlink); return this; }, // return the array of the path track element array: function array() { var track = this.track(); return track ? track.array() : null; }, // Plot path if any plot: function plot(d) { var track = this.track(), pathArray = null; if (track) { pathArray = track.plot(d); } return d == null ? pathArray : this; }, // Get the path track element track: function track() { var path = this.textPath(); if (path) { return path.reference('href'); } }, // Get the textPath child textPath: function textPath() { if (this.node.firstChild && this.node.firstChild.nodeName == 'textPath') { return SVG.adopt(this.node.firstChild); } } } }); SVG.Nested = SVG.invent({ // Initialize node create: function create() { this.constructor.call(this, SVG.create('svg')); this.style('overflow', 'visible'); }, // Inherit from inherit: SVG.Container, // Add parent method construct: { // Create nested svg document nested: function nested() { return this.put(new SVG.Nested()); } } }); SVG.A = SVG.invent({ // Initialize node create: 'a', // Inherit from inherit: SVG.Container, // Add class methods extend: { // Link url to: function to(url) { return this.attr('href', url, SVG.xlink); }, // Link show attribute show: function show(target) { return this.attr('show', target, SVG.xlink); }, // Link target attribute target: function target(_target2) { return this.attr('target', _target2); } }, // Add parent method construct: { // Create a hyperlink element link: function link(url) { return this.put(new SVG.A()).to(url); } } }); SVG.extend(SVG.Element, { // Create a hyperlink element linkTo: function linkTo(url) { var link = new SVG.A(); if (typeof url === 'function') { url.call(link, link); } else { link.to(url); } return this.parent().put(link).put(this); } }); SVG.Marker = SVG.invent({ // Initialize node create: 'marker', // Inherit from inherit: SVG.Container, // Add class methods extend: { // Set width of element width: function width(_width6) { return this.attr('markerWidth', _width6); }, // Set height of element height: function height(_height6) { return this.attr('markerHeight', _height6); }, // Set marker refX and refY ref: function ref(x, y) { return this.attr('refX', x).attr('refY', y); }, // Update marker update: function update(block) { // remove all content this.clear(); // invoke passed block if (typeof block === 'function') { block.call(this, this); } return this; }, // Return the fill id toString: function toString() { return 'url(#' + this.id() + ')'; } }, // Add parent method construct: { marker: function marker(width, height, block) { // Create marker element in defs return this.defs().marker(width, height, block); } } }); SVG.extend(SVG.Defs, { // Create marker marker: function marker(width, height, block) { // Set default viewbox to match the width and height, set ref to cx and cy and set orient to auto return this.put(new SVG.Marker()).size(width, height).ref(width / 2, height / 2).viewbox(0, 0, width, height).attr('orient', 'auto').update(block); } }); SVG.extend(SVG.Line, SVG.Polyline, SVG.Polygon, SVG.Path, { // Create and attach markers marker: function marker(_marker, width, height, block) { var attr = ['marker']; // Build attribute name if (_marker != 'all') attr.push(_marker); attr = attr.join('-'); // Set marker attribute _marker = arguments[1] instanceof SVG.Marker ? arguments[1] : this.doc().marker(width, height, block); return this.attr(attr, _marker); } }); // Define list of available attributes for stroke and fill var sugar = { stroke: ['color', 'width', 'opacity', 'linecap', 'linejoin', 'miterlimit', 'dasharray', 'dashoffset'], fill: ['color', 'opacity', 'rule'], prefix: function prefix(t, a) { return a == 'color' ? t : t + '-' + a; } // Add sugar for fill and stroke }; ['fill', 'stroke'].forEach(function (m) { var i, extension = {}; extension[m] = function (o) { if (typeof o === 'undefined') { return this; } if (typeof o === 'string' || SVG.Color.isRgb(o) || o && typeof o.fill === 'function') { this.attr(m, o); } else // set all attributes from sugar.fill and sugar.stroke list { for (i = sugar[m].length - 1; i >= 0; i--) { if (o[sugar[m][i]] != null) { this.attr(sugar.prefix(m, sugar[m][i]), o[sugar[m][i]]); } } } return this; }; SVG.extend(SVG.Element, SVG.FX, extension); }); SVG.extend(SVG.Element, SVG.FX, { // Map rotation to transform rotate: function rotate(d, cx, cy) { return this.transform({ rotation: d, cx: cx, cy: cy }); }, // Map skew to transform skew: function skew(x, y, cx, cy) { return arguments.length == 1 || arguments.length == 3 ? this.transform({ skew: x, cx: y, cy: cx }) : this.transform({ skewX: x, skewY: y, cx: cx, cy: cy }); }, // Map scale to transform scale: function scale(x, y, cx, cy) { return arguments.length == 1 || arguments.length == 3 ? this.transform({ scale: x, cx: y, cy: cx }) : this.transform({ scaleX: x, scaleY: y, cx: cx, cy: cy }); }, // Map translate to transform translate: function translate(x, y) { return this.transform({ x: x, y: y }); }, // Map flip to transform flip: function flip(a, o) { o = typeof a === 'number' ? a : o; return this.transform({ flip: a || 'both', offset: o }); }, // Map matrix to transform matrix: function matrix(m) { return this.attr('transform', new SVG.Matrix(arguments.length == 6 ? [].slice.call(arguments) : m)); }, // Opacity opacity: function opacity(value) { return this.attr('opacity', value); }, // Relative move over x axis dx: function dx(x) { return this.x(new SVG.Number(x).plus(this instanceof SVG.FX ? 0 : this.x()), true); }, // Relative move over y axis dy: function dy(y) { return this.y(new SVG.Number(y).plus(this instanceof SVG.FX ? 0 : this.y()), true); }, // Relative move over x and y axes dmove: function dmove(x, y) { return this.dx(x).dy(y); } }); SVG.extend(SVG.Rect, SVG.Ellipse, SVG.Circle, SVG.Gradient, SVG.FX, { // Add x and y radius radius: function radius(x, y) { var type = (this._target || this).type; return type == 'radial' || type == 'circle' ? this.attr('r', new SVG.Number(x)) : this.rx(x).ry(y == null ? x : y); } }); SVG.extend(SVG.Path, { // Get path length length: function length() { return this.node.getTotalLength(); }, // Get point at length pointAt: function pointAt(length) { return this.node.getPointAtLength(length); } }); SVG.extend(SVG.Parent, SVG.Text, SVG.Tspan, SVG.FX, { // Set font font: function font(a, v) { if (_typeof(a) === 'object') { for (v in a) { this.font(v, a[v]); } } return a == 'leading' ? this.leading(v) : a == 'anchor' ? this.attr('text-anchor', v) : a == 'size' || a == 'family' || a == 'weight' || a == 'stretch' || a == 'variant' || a == 'style' ? this.attr('font-' + a, v) : this.attr(a, v); } }); SVG.Set = SVG.invent({ // Initialize create: function create(members) { // Set initial state Array.isArray(members) ? this.members = members : this.clear(); }, // Add class methods extend: { // Add element to set add: function add() { var i, il, elements = [].slice.call(arguments); for (i = 0, il = elements.length; i < il; i++) { this.members.push(elements[i]); } return this; }, // Remove element from set remove: function remove(element) { var i = this.index(element); // remove given child if (i > -1) { this.members.splice(i, 1); } return this; }, // Iterate over all members each: function each(block) { for (var i = 0, il = this.members.length; i < il; i++) { block.apply(this.members[i], [i, this.members]); } return this; }, // Restore to defaults clear: function clear() { // initialize store this.members = []; return this; }, // Get the length of a set length: function length() { return this.members.length; }, // Checks if a given element is present in set has: function has(element) { return this.index(element) >= 0; }, // retuns index of given element in set index: function index(element) { return this.members.indexOf(element); }, // Get member at given index get: function get(i) { return this.members[i]; }, // Get first member first: function first() { return this.get(0); }, // Get last member last: function last() { return this.get(this.members.length - 1); }, // Default value valueOf: function valueOf() { return this.members; }, // Get the bounding box of all members included or empty box if set has no items bbox: function bbox() { // return an empty box of there are no members if (this.members.length == 0) { return new SVG.RBox(); } // get the first rbox and update the target bbox var rbox = this.members[0].rbox(this.members[0].doc()); this.each(function () { // user rbox for correct position and visual representation rbox = rbox.merge(this.rbox(this.doc())); }); return rbox; } }, // Add parent method construct: { // Create a new set set: function set(members) { return new SVG.Set(members); } } }); SVG.FX.Set = SVG.invent({ // Initialize node create: function create(set) { // store reference to set this.set = set; } }); // Alias methods SVG.Set.inherit = function () { var m, methods = []; // gather shape methods for (var m in SVG.Shape.prototype) { if (typeof SVG.Shape.prototype[m] === 'function' && typeof SVG.Set.prototype[m] !== 'function') { methods.push(m); } } // apply shape aliasses methods.forEach(function (method) { SVG.Set.prototype[method] = function () { for (var i = 0, il = this.members.length; i < il; i++) { if (this.members[i] && typeof this.members[i][method] === 'function') { this.members[i][method].apply(this.members[i], arguments); } } return method == 'animate' ? this.fx || (this.fx = new SVG.FX.Set(this)) : this; }; }); // clear methods for the next round methods = []; // gather fx methods for (var m in SVG.FX.prototype) { if (typeof SVG.FX.prototype[m] === 'function' && typeof SVG.FX.Set.prototype[m] !== 'function') { methods.push(m); } } // apply fx aliasses methods.forEach(function (method) { SVG.FX.Set.prototype[method] = function () { for (var i = 0, il = this.set.members.length; i < il; i++) { this.set.members[i].fx[method].apply(this.set.members[i].fx, arguments); } return this; }; }); }; SVG.extend(SVG.Element, { // Store data values on svg nodes data: function data(a, v, r) { if (_typeof(a) === 'object') { for (v in a) { this.data(v, a[v]); } } else if (arguments.length < 2) { try { return JSON.parse(this.attr('data-' + a)); } catch (e) { return this.attr('data-' + a); } } else { this.attr('data-' + a, v === null ? null : r === true || typeof v === 'string' || typeof v === 'number' ? v : JSON.stringify(v)); } return this; } }); SVG.extend(SVG.Element, { // Remember arbitrary data remember: function remember(k, v) { // remember every item in an object individually if (_typeof(arguments[0]) === 'object') { for (var v in k) { this.remember(v, k[v]); } } // retrieve memory else if (arguments.length == 1) { return this.memory()[k]; } // store memory else { this.memory()[k] = v; } return this; }, // Erase a given memory forget: function forget() { if (arguments.length == 0) { this._memory = {}; } else { for (var i = arguments.length - 1; i >= 0; i--) { delete this.memory()[arguments[i]]; } } return this; }, // Initialize or return local memory object memory: function memory() { return this._memory || (this._memory = {}); } }); // Method for getting an element by id SVG.get = function (id) { var node = document.getElementById(idFromReference(id) || id); return SVG.adopt(node); }; // Select elements by query string SVG.select = function (query, parent) { return new SVG.Set(SVG.utils.map((parent || document).querySelectorAll(query), function (node) { return SVG.adopt(node); })); }; SVG.extend(SVG.Parent, { // Scoped select method select: function select(query) { return SVG.select(query, this.node); } }); function pathRegReplace(a, b, c, d) { return c + d.replace(SVG.regex.dots, ' .'); } // creates deep clone of array function array_clone(arr) { var clone = arr.slice(0); for (var i = clone.length; i--;) { if (Array.isArray(clone[i])) { clone[i] = array_clone(clone[i]); } } return clone; } // tests if a given element is instance of an object function _is(el, obj) { return el instanceof obj; } // tests if a given selector matches an element function _matches(el, selector) { return (el.matches || el.matchesSelector || el.msMatchesSelector || el.mozMatchesSelector || el.webkitMatchesSelector || el.oMatchesSelector).call(el, selector); } // Convert dash-separated-string to camelCase function camelCase(s) { return s.toLowerCase().replace(/-(.)/g, function (m, g) { return g.toUpperCase(); }); } // Capitalize first letter of a string function capitalize(s) { return s.charAt(0).toUpperCase() + s.slice(1); } // Ensure to six-based hex function fullHex(hex) { return hex.length == 4 ? ['#', hex.substring(1, 2), hex.substring(1, 2), hex.substring(2, 3), hex.substring(2, 3), hex.substring(3, 4), hex.substring(3, 4)].join('') : hex; } // Component to hex value function compToHex(comp) { var hex = comp.toString(16); return hex.length == 1 ? '0' + hex : hex; } // Calculate proportional width and height values when necessary function proportionalSize(element, width, height) { if (width == null || height == null) { var box = element.bbox(); if (width == null) { width = box.width / box.height * height; } else if (height == null) { height = box.height / box.width * width; } } return { width: width, height: height }; } // Delta transform point function deltaTransformPoint(matrix, x, y) { return { x: x * matrix.a + y * matrix.c + 0, y: x * matrix.b + y * matrix.d + 0 }; } // Map matrix array to object function arrayToMatrix(a) { return { a: a[0], b: a[1], c: a[2], d: a[3], e: a[4], f: a[5] }; } // Parse matrix if required function parseMatrix(matrix) { if (!(matrix instanceof SVG.Matrix)) { matrix = new SVG.Matrix(matrix); } return matrix; } // Add centre point to transform object function ensureCentre(o, target) { o.cx = o.cx == null ? target.bbox().cx : o.cx; o.cy = o.cy == null ? target.bbox().cy : o.cy; } // PathArray Helpers function arrayToString(a) { for (var i = 0, il = a.length, s = ''; i < il; i++) { s += a[i][0]; if (a[i][1] != null) { s += a[i][1]; if (a[i][2] != null) { s += ' '; s += a[i][2]; if (a[i][3] != null) { s += ' '; s += a[i][3]; s += ' '; s += a[i][4]; if (a[i][5] != null) { s += ' '; s += a[i][5]; s += ' '; s += a[i][6]; if (a[i][7] != null) { s += ' '; s += a[i][7]; } } } } } } return s + ' '; } // Deep new id assignment function assignNewId(node) { // do the same for SVG child nodes as well for (var i = node.childNodes.length - 1; i >= 0; i--) { if (node.childNodes[i] instanceof window.SVGElement) { assignNewId(node.childNodes[i]); } } return SVG.adopt(node).id(SVG.eid(node.nodeName)); } // Add more bounding box properties function fullBox(b) { if (b.x == null) { b.x = 0; b.y = 0; b.width = 0; b.height = 0; } b.w = b.width; b.h = b.height; b.x2 = b.x + b.width; b.y2 = b.y + b.height; b.cx = b.x + b.width / 2; b.cy = b.y + b.height / 2; return b; } // Get id from reference string function idFromReference(url) { var m = (url || '').toString().match(SVG.regex.reference); if (m) return m[1]; } // If values like 1e-88 are passed, this is not a valid 32 bit float, // but in those cases, we are so close to 0 that 0 works well! function float32String(v) { return Math.abs(v) > 1e-37 ? v : 0; } // Create matrix array for looping var abcdef = 'abcdef'.split(''); // Add CustomEvent to IE9 and IE10 if (typeof window.CustomEvent !== 'function') { // Code from: https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent var CustomEventPoly = function CustomEventPoly(event, options) { options = options || { bubbles: false, cancelable: false, detail: undefined }; var e = document.createEvent('CustomEvent'); e.initCustomEvent(event, options.bubbles, options.cancelable, options.detail); return e; }; CustomEventPoly.prototype = window.Event.prototype; SVG.CustomEvent = CustomEventPoly; } else { SVG.CustomEvent = window.CustomEvent; } // requestAnimationFrame / cancelAnimationFrame Polyfill with fallback based on Paul Irish (function (w) { var lastTime = 0; var vendors = ['moz', 'webkit']; for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { w.requestAnimationFrame = w[vendors[x] + 'RequestAnimationFrame']; w.cancelAnimationFrame = w[vendors[x] + 'CancelAnimationFrame'] || w[vendors[x] + 'CancelRequestAnimationFrame']; } w.requestAnimationFrame = w.requestAnimationFrame || function (callback) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = w.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; w.cancelAnimationFrame = w.cancelAnimationFrame || w.clearTimeout; })(window); return SVG; }); /*! svg.filter.js - v2.0.2 - 2016-02-24 * https://github.com/wout/svg.filter.js * Copyright (c) 2016 Wout Fierens; Licensed MIT */ (function() { // Main filter class SVG.Filter = SVG.invent({ create: 'filter', inherit: SVG.Parent, extend: { // Static strings source: 'SourceGraphic', sourceAlpha: 'SourceAlpha', background: 'BackgroundImage', backgroundAlpha: 'BackgroundAlpha', fill: 'FillPaint', stroke: 'StrokePaint', autoSetIn: true, // Custom put method for leaner code put: function(element, i) { this.add(element, i); if(!element.attr('in') && this.autoSetIn){ element.attr('in',this.source); } if(!element.attr('result')){ element.attr('result',element); } return element }, // Blend effect blend: function(in1, in2, mode) { return this.put(new SVG.BlendEffect(in1, in2, mode)) }, // ColorMatrix effect colorMatrix: function(type, values) { return this.put(new SVG.ColorMatrixEffect(type, values)) }, // ConvolveMatrix effect convolveMatrix: function(matrix) { return this.put(new SVG.ConvolveMatrixEffect(matrix)) }, // ComponentTransfer effect componentTransfer: function(components) { return this.put(new SVG.ComponentTransferEffect(components)) }, // Composite effect composite: function(in1, in2, operator) { return this.put(new SVG.CompositeEffect(in1, in2, operator)) }, // Flood effect flood: function(color, opacity) { return this.put(new SVG.FloodEffect(color, opacity)) }, // Offset effect offset: function(x, y) { return this.put(new SVG.OffsetEffect(x,y)) }, // Image effect image: function(src) { return this.put(new SVG.ImageEffect(src)) }, // Merge effect merge: function() { //pass the array of arguments to the constructor because we dont know if the user gave us an array as the first arguemnt or wether they listed the effects in the arguments var args = [undefined]; for(var i in arguments) args.push(arguments[i]); return this.put(new (SVG.MergeEffect.bind.apply(SVG.MergeEffect,args))) }, // Gaussian Blur effect gaussianBlur: function(x,y) { return this.put(new SVG.GaussianBlurEffect(x,y)) }, // Morphology effect morphology: function(operator,radius){ return this.put(new SVG.MorphologyEffect(operator,radius)) }, // DiffuseLighting effect diffuseLighting: function(surfaceScale,diffuseConstant,kernelUnitLength){ return this.put(new SVG.DiffuseLightingEffect(surfaceScale,diffuseConstant,kernelUnitLength)) }, // DisplacementMap effect displacementMap: function(in1,in2,scale,xChannelSelector,yChannelSelector){ return this.put(new SVG.DisplacementMapEffect(in1,in2,scale,xChannelSelector,yChannelSelector)) }, // SpecularLighting effect specularLighting: function(surfaceScale,diffuseConstant,specularExponent,kernelUnitLength){ return this.put(new SVG.SpecularLightingEffect(surfaceScale,diffuseConstant,specularExponent,kernelUnitLength)) }, // Tile effect tile: function(){ return this.put(new SVG.TileEffect()); }, // Turbulence effect turbulence: function(baseFrequency,numOctaves,seed,stitchTiles,type){ return this.put(new SVG.TurbulenceEffect(baseFrequency,numOctaves,seed,stitchTiles,type)) }, // Default string value toString: function() { return 'url(#' + this.attr('id') + ')' } } }); //add .filter function SVG.extend(SVG.Defs, { // Define filter filter: function(block) { var filter = this.put(new SVG.Filter); /* invoke passed block */ if (typeof block === 'function') block.call(filter, filter); return filter } }); SVG.extend(SVG.Container, { // Define filter on defs filter: function(block) { return this.defs().filter(block) } }); SVG.extend(SVG.Element, SVG.G, SVG.Nested, { // Create filter element in defs and store reference filter: function(block) { this.filterer = block instanceof SVG.Element ? block : this.doc().filter(block); if(this.doc() && this.filterer.doc() !== this.doc()){ this.doc().defs().add(this.filterer); } this.attr('filter', this.filterer); return this.filterer }, // Remove filter unfilter: function(remove) { /* also remove the filter node */ if (this.filterer && remove === true) this.filterer.remove(); /* delete reference to filterer */ delete this.filterer; /* remove filter attribute */ return this.attr('filter', null) } }); // Create SVG.Effect class SVG.Effect = SVG.invent({ create: function(){ this.constructor.call(this); }, inherit: SVG.Element, extend: { // Set in attribute in: function(effect) { return effect == null? this.parent() && this.parent().select('[result="'+this.attr('in')+'"]').get(0) || this.attr('in') : this.attr('in', effect) }, // Named result result: function(result) { return result == null? this.attr('result') : this.attr('result',result) }, // Stringification toString: function() { return this.result() } } }); // create class for parent effects like merge // Inherit from SVG.Parent SVG.ParentEffect = SVG.invent({ create: function(){ this.constructor.call(this); }, inherit: SVG.Parent, extend: { // Set in attribute in: function(effect) { return effect == null? this.parent() && this.parent().select('[result="'+this.attr('in')+'"]').get(0) || this.attr('in') : this.attr('in', effect) }, // Named result result: function(result) { return result == null? this.attr('result') : this.attr('result',result) }, // Stringification toString: function() { return this.result() } } }); //chaining var chainingEffects = { // Blend effect blend: function(in2, mode) { return this.parent() && this.parent().blend(this, in2, mode) //pass this as the first input }, // ColorMatrix effect colorMatrix: function(type, values) { return this.parent() && this.parent().colorMatrix(type, values).in(this) }, // ConvolveMatrix effect convolveMatrix: function(matrix) { return this.parent() && this.parent().convolveMatrix(matrix).in(this) }, // ComponentTransfer effect componentTransfer: function(components) { return this.parent() && this.parent().componentTransfer(components).in(this) }, // Composite effect composite: function(in2, operator) { return this.parent() && this.parent().composite(this, in2, operator) //pass this as the first input }, // Flood effect flood: function(color, opacity) { return this.parent() && this.parent().flood(color, opacity) //this effect dont have inputs }, // Offset effect offset: function(x, y) { return this.parent() && this.parent().offset(x,y).in(this) }, // Image effect image: function(src) { return this.parent() && this.parent().image(src) //this effect dont have inputs }, // Merge effect merge: function() { return this.parent() && this.parent().merge.apply(this.parent(),[this].concat(arguments)) //pass this as the first argument }, // Gaussian Blur effect gaussianBlur: function(x,y) { return this.parent() && this.parent().gaussianBlur(x,y).in(this) }, // Morphology effect morphology: function(operator,radius){ return this.parent() && this.parent().morphology(operator,radius).in(this) }, // DiffuseLighting effect diffuseLighting: function(surfaceScale,diffuseConstant,kernelUnitLength){ return this.parent() && this.parent().diffuseLighting(surfaceScale,diffuseConstant,kernelUnitLength).in(this) }, // DisplacementMap effect displacementMap: function(in2,scale,xChannelSelector,yChannelSelector){ return this.parent() && this.parent().displacementMap(this,in2,scale,xChannelSelector,yChannelSelector) //pass this as the first input }, // SpecularLighting effect specularLighting: function(surfaceScale,diffuseConstant,specularExponent,kernelUnitLength){ return this.parent() && this.parent().specularLighting(surfaceScale,diffuseConstant,specularExponent,kernelUnitLength).in(this) }, // Tile effect tile: function(){ return this.parent() && this.parent().tile().in(this) }, // Turbulence effect turbulence: function(baseFrequency,numOctaves,seed,stitchTiles,type){ return this.parent() && this.parent().turbulence(baseFrequency,numOctaves,seed,stitchTiles,type).in(this) } }; SVG.extend(SVG.Effect,chainingEffects); SVG.extend(SVG.ParentEffect,chainingEffects); //crea class for child effects, like MergeNode, FuncR and lights SVG.ChildEffect = SVG.invent({ create: function(){ this.constructor.call(this); }, inherit: SVG.Element, extend: { in: function(effect){ this.attr('in',effect); } //dont include any "result" functions because these types of nodes dont have them } }); // Create all different effects var effects = { blend: function(in1,in2,mode){ this.attr({ in: in1, in2: in2, mode: mode || 'normal' }); }, colorMatrix: function(type,values){ if (type == 'matrix') values = normaliseMatrix(values); this.attr({ type: type , values: typeof values == 'undefined' ? null : values }); }, convolveMatrix: function(matrix){ matrix = normaliseMatrix(matrix); this.attr({ order: Math.sqrt(matrix.split(' ').length) , kernelMatrix: matrix }); }, composite: function(in1, in2, operator){ this.attr({ in: in1, in2: in2, operator: operator }); }, flood: function(color,opacity){ this.attr('flood-color',color); if(opacity != null) this.attr('flood-opacity',opacity); }, offset: function(x,y){ this.attr({ dx: x, dy: y }); }, image: function(src){ this.attr('href', src, SVG.xlink); }, displacementMap: function(in1,in2,scale,xChannelSelector,yChannelSelector){ this.attr({ in: in1, in2: in2, scale: scale, xChannelSelector: xChannelSelector, yChannelSelector: yChannelSelector }); }, gaussianBlur: function(x,y){ if(x != null || y != null) this.attr('stdDeviation', listString(Array.prototype.slice.call(arguments))); else this.attr('stdDeviation', '0 0'); }, morphology: function(operator,radius){ this.attr({ operator: operator, radius: radius }); }, tile: function(){ }, turbulence: function(baseFrequency,numOctaves,seed,stitchTiles,type){ this.attr({ numOctaves: numOctaves, seed: seed, stitchTiles: stitchTiles, baseFrequency: baseFrequency, type: type }); } }; // Create all parent effects var parentEffects = { merge: function(){ var children; //test to see if we have a set if(arguments[0] instanceof SVG.Set){ var that = this; arguments[0].each(function(i){ if(this instanceof SVG.MergeNode) that.put(this); else if(this instanceof SVG.Effect || this instanceof SVG.ParentEffect) that.put(new SVG.MergeNode(this)); }); } else{ //if the first argument is an array use it if(Array.isArray(arguments[0])) children = arguments[0]; else children = arguments; for(var i = 0; i < children.length; i++){ if(children[i] instanceof SVG.MergeNode){ this.put(children[i]); } else this.put(new SVG.MergeNode(children[i])); } } }, componentTransfer: function(compontents){ /* create rgb set */ this.rgb = new SVG.Set /* create components */ ;(['r', 'g', 'b', 'a']).forEach(function(c) { /* create component */ this[c] = new SVG['Func' + c.toUpperCase()]('identity'); /* store component in set */ this.rgb.add(this[c]); /* add component node */ this.node.appendChild(this[c].node); }.bind(this)); //lost context in foreach /* set components */ if (compontents) { if (compontents.rgb) { (['r', 'g', 'b']).forEach(function(c) { this[c].attr(compontents.rgb); }.bind(this)); delete compontents.rgb; } /* set individual components */ for (var c in compontents) this[c].attr(compontents[c]); } }, diffuseLighting: function(surfaceScale,diffuseConstant,kernelUnitLength){ this.attr({ surfaceScale: surfaceScale, diffuseConstant: diffuseConstant, kernelUnitLength: kernelUnitLength }); }, specularLighting: function(surfaceScale,diffuseConstant,specularExponent,kernelUnitLength){ this.attr({ surfaceScale: surfaceScale, diffuseConstant: diffuseConstant, specularExponent: specularExponent, kernelUnitLength: kernelUnitLength }); }, }; // Create child effects like PointLight and MergeNode var childEffects = { distantLight: function(azimuth, elevation){ this.attr({ azimuth: azimuth, elevation: elevation }); }, pointLight: function(x,y,z){ this.attr({ x: x, y: y, z: z }); }, spotLight: function(x,y,z,pointsAtX,pointsAtY,pointsAtZ){ this.attr({ x: x, y: y, z: z, pointsAtX: pointsAtX, pointsAtY: pointsAtY, pointsAtZ: pointsAtZ }); }, mergeNode: function(in1){ this.attr('in',in1); } } // Create compontent functions ;(['r', 'g', 'b', 'a']).forEach(function(c) { /* create class */ childEffects['Func' + c.toUpperCase()] = function(type) { this.attr('type',type); // take diffent arguments based on the type switch(type){ case 'table': this.attr('tableValues',arguments[1]); break case 'linear': this.attr('slope',arguments[1]); this.attr('intercept',arguments[2]); break case 'gamma': this.attr('amplitude',arguments[1]); this.attr('exponent',arguments[2]); this.attr('offset',arguments[2]); break } }; }); //create effects foreach(effects,function(effect,i){ /* capitalize name */ var name = i.charAt(0).toUpperCase() + i.slice(1); var proto = {}; /* create class */ SVG[name + 'Effect'] = SVG.invent({ create: function() { //call super this.constructor.call(this, SVG.create('fe' + name)); //call constructor for this effect effect.apply(this,arguments); //set the result this.result(this.attr('id') + 'Out'); }, inherit: SVG.Effect, extend: proto }); }); //create parent effects foreach(parentEffects,function(effect,i){ /* capitalize name */ var name = i.charAt(0).toUpperCase() + i.slice(1); var proto = {}; /* create class */ SVG[name + 'Effect'] = SVG.invent({ create: function() { //call super this.constructor.call(this, SVG.create('fe' + name)); //call constructor for this effect effect.apply(this,arguments); //set the result this.result(this.attr('id') + 'Out'); }, inherit: SVG.ParentEffect, extend: proto }); }); //create child effects foreach(childEffects,function(effect,i){ /* capitalize name */ var name = i.charAt(0).toUpperCase() + i.slice(1); var proto = {}; /* create class */ SVG[name] = SVG.invent({ create: function() { //call super this.constructor.call(this, SVG.create('fe' + name)); //call constructor for this effect effect.apply(this,arguments); }, inherit: SVG.ChildEffect, extend: proto }); }); // Effect-specific extensions SVG.extend(SVG.MergeEffect,{ in: function(effect){ if(effect instanceof SVG.MergeNode) this.add(effect,0); else this.add(new SVG.MergeNode(effect),0); return this } }); SVG.extend(SVG.CompositeEffect,SVG.BlendEffect,SVG.DisplacementMapEffect,{ in2: function(effect){ return effect == null? this.parent() && this.parent().select('[result="'+this.attr('in2')+'"]').get(0) || this.attr('in2') : this.attr('in2', effect) } }); // Presets SVG.filter = { sepiatone: [ .343, .669, .119, 0, 0 , .249, .626, .130, 0, 0 , .172, .334, .111, 0, 0 , .000, .000, .000, 1, 0 ] }; // Helpers function normaliseMatrix(matrix) { /* convert possible array value to string */ if (Array.isArray(matrix)) matrix = new SVG.Array(matrix); /* ensure there are no leading, tailing or double spaces */ return matrix.toString().replace(/^\s+/, '').replace(/\s+$/, '').replace(/\s+/g, ' ') } function listString(list) { if (!Array.isArray(list)) return list for (var i = 0, l = list.length, s = []; i < l; i++) s.push(list[i]); return s.join(' ') } function foreach(){ //loops through mutiple objects var fn = function(){}; if(typeof arguments[arguments.length-1] == 'function'){ fn = arguments[arguments.length-1]; Array.prototype.splice.call(arguments,arguments.length-1,1); } for(var k in arguments){ for(var i in arguments[k]){ fn(arguments[k][i],i,arguments[k]); } } } }).call(undefined); (function() { SVG.extend(SVG.PathArray, { morph: function(array) { var startArr = this.value , destArr = this.parse(array); var startOffsetM = 0 , destOffsetM = 0; var startOffsetNextM = false , destOffsetNextM = false; while(true){ // stop if there is no M anymore if(startOffsetM === false && destOffsetM === false) break // find the next M in path array startOffsetNextM = findNextM(startArr, startOffsetM === false ? false : startOffsetM+1); destOffsetNextM = findNextM( destArr, destOffsetM === false ? false : destOffsetM+1); // We have to add one M to the startArray if(startOffsetM === false){ var bbox = new SVG.PathArray(result.start).bbox(); // when the last block had no bounding box we simply take the first M we got if(bbox.height == 0 || bbox.width == 0){ startOffsetM = startArr.push(startArr[0]) - 1; }else{ // we take the middle of the bbox instead when we got one startOffsetM = startArr.push( ['M', bbox.x + bbox.width/2, bbox.y + bbox.height/2 ] ) - 1; } } // We have to add one M to the destArray if( destOffsetM === false){ var bbox = new SVG.PathArray(result.dest).bbox(); if(bbox.height == 0 || bbox.width == 0){ destOffsetM = destArr.push(destArr[0]) - 1; }else{ destOffsetM = destArr.push( ['M', bbox.x + bbox.width/2, bbox.y + bbox.height/2 ] ) - 1; } } // handle block from M to next M var result = handleBlock(startArr, startOffsetM, startOffsetNextM, destArr, destOffsetM, destOffsetNextM); // update the arrays to their new values startArr = startArr.slice(0, startOffsetM).concat(result.start, startOffsetNextM === false ? [] : startArr.slice(startOffsetNextM)); destArr = destArr.slice(0, destOffsetM).concat(result.dest , destOffsetNextM === false ? [] : destArr.slice( destOffsetNextM)); // update offsets startOffsetM = startOffsetNextM === false ? false : startOffsetM + result.start.length; destOffsetM = destOffsetNextM === false ? false : destOffsetM + result.dest.length; } // copy back arrays this.value = startArr; this.destination = new SVG.PathArray(); this.destination.value = destArr; return this } }); // sorry for the long declaration // slices out one block (from M to M) and syncronize it so the types and length match function handleBlock(startArr, startOffsetM, startOffsetNextM, destArr, destOffsetM, destOffsetNextM, undefined){ // slice out the block we need var startArrTemp = startArr.slice(startOffsetM, startOffsetNextM || undefined) , destArrTemp = destArr.slice( destOffsetM, destOffsetNextM || undefined); var i = 0 , posStart = {pos:[0,0], start:[0,0]} , posDest = {pos:[0,0], start:[0,0]}; do{ // convert shorthand types to long form startArrTemp[i] = simplyfy.call(posStart, startArrTemp[i]); destArrTemp[i] = simplyfy.call(posDest , destArrTemp[i]); // check if both shape types match // 2 elliptical arc curve commands ('A'), are considered different if the // flags (large-arc-flag, sweep-flag) don't match if(startArrTemp[i][0] != destArrTemp[i][0] || startArrTemp[i][0] == 'M' || (startArrTemp[i][0] == 'A' && (startArrTemp[i][4] != destArrTemp[i][4] || startArrTemp[i][5] != destArrTemp[i][5]) ) ) { // if not, convert shapes to beziere Array.prototype.splice.apply(startArrTemp, [i, 1].concat(toBeziere.call(posStart, startArrTemp[i]))); Array.prototype.splice.apply(destArrTemp, [i, 1].concat(toBeziere.call(posDest, destArrTemp[i]))); } else { // only update positions otherwise startArrTemp[i] = setPosAndReflection.call(posStart, startArrTemp[i]); destArrTemp[i] = setPosAndReflection.call(posDest , destArrTemp[i]); } // we are at the end at both arrays. stop here if(++i == startArrTemp.length && i == destArrTemp.length) break // destArray is longer. Add one element if(i == startArrTemp.length){ startArrTemp.push([ 'C', posStart.pos[0], posStart.pos[1], posStart.pos[0], posStart.pos[1], posStart.pos[0], posStart.pos[1], ]); } // startArr is longer. Add one element if(i == destArrTemp.length){ destArrTemp.push([ 'C', posDest.pos[0], posDest.pos[1], posDest.pos[0], posDest.pos[1], posDest.pos[0], posDest.pos[1] ]); } }while(true) // return the updated block return {start:startArrTemp, dest:destArrTemp} } // converts shorthand types to long form function simplyfy(val){ switch(val[0]){ case 'z': // shorthand line to start case 'Z': val[0] = 'L'; val[1] = this.start[0]; val[2] = this.start[1]; break case 'H': // shorthand horizontal line val[0] = 'L'; val[2] = this.pos[1]; break case 'V': // shorthand vertical line val[0] = 'L'; val[2] = val[1]; val[1] = this.pos[0]; break case 'T': // shorthand quadratic beziere val[0] = 'Q'; val[3] = val[1]; val[4] = val[2]; val[1] = this.reflection[1]; val[2] = this.reflection[0]; break case 'S': // shorthand cubic beziere val[0] = 'C'; val[6] = val[4]; val[5] = val[3]; val[4] = val[2]; val[3] = val[1]; val[2] = this.reflection[1]; val[1] = this.reflection[0]; break } return val } // updates reflection point and current position function setPosAndReflection(val){ var len = val.length; this.pos = [ val[len-2], val[len-1] ]; if('SCQT'.indexOf(val[0]) != -1) this.reflection = [ 2 * this.pos[0] - val[len-4], 2 * this.pos[1] - val[len-3] ]; return val } // converts all types to cubic beziere function toBeziere(val){ var retVal = [val]; switch(val[0]){ case 'M': // special handling for M this.pos = this.start = [val[1], val[2]]; return retVal case 'L': val[5] = val[3] = val[1]; val[6] = val[4] = val[2]; val[1] = this.pos[0]; val[2] = this.pos[1]; break case 'Q': val[6] = val[4]; val[5] = val[3]; val[4] = val[4] * 1/3 + val[2] * 2/3; val[3] = val[3] * 1/3 + val[1] * 2/3; val[2] = this.pos[1] * 1/3 + val[2] * 2/3; val[1] = this.pos[0] * 1/3 + val[1] * 2/3; break case 'A': retVal = arcToBeziere(this.pos, val); val = retVal[0]; break } val[0] = 'C'; this.pos = [val[5], val[6]]; this.reflection = [2 * val[5] - val[3], 2 * val[6] - val[4]]; return retVal } // finds the next position of type M function findNextM(arr, offset){ if(offset === false) return false for(var i = offset, len = arr.length;i < len;++i){ if(arr[i][0] == 'M') return i } return false } // Convert an arc segment into equivalent cubic Bezier curves // Depending on the arc, up to 4 curves might be used to represent it since a // curve gives a good approximation for only a quarter of an ellipse // The curves are returned as an array of SVG curve commands: // [ ['C', x1, y1, x2, y2, x, y] ... ] function arcToBeziere(pos, val) { // Parameters extraction, handle out-of-range parameters as specified in the SVG spec // See: https://www.w3.org/TR/SVG11/implnote.html#ArcOutOfRangeParameters var rx = Math.abs(val[1]), ry = Math.abs(val[2]), xAxisRotation = val[3] % 360 , largeArcFlag = val[4], sweepFlag = val[5], x = val[6], y = val[7] , A = new SVG.Point(pos), B = new SVG.Point(x, y) , primedCoord, lambda, mat, k, c, cSquare, t, O, OA, OB, tetaStart, tetaEnd , deltaTeta, nbSectors, f, arcSegPoints, angle, sinAngle, cosAngle, pt, i, il , retVal = [], x1, y1, x2, y2; // Ensure radii are non-zero if(rx === 0 || ry === 0 || (A.x === B.x && A.y === B.y)) { // treat this arc as a straight line segment return [['C', A.x, A.y, B.x, B.y, B.x, B.y]] } // Ensure radii are large enough using the algorithm provided in the SVG spec // See: https://www.w3.org/TR/SVG11/implnote.html#ArcCorrectionOutOfRangeRadii primedCoord = new SVG.Point((A.x-B.x)/2, (A.y-B.y)/2).transform(new SVG.Matrix().rotate(xAxisRotation)); lambda = (primedCoord.x * primedCoord.x) / (rx * rx) + (primedCoord.y * primedCoord.y) / (ry * ry); if(lambda > 1) { lambda = Math.sqrt(lambda); rx = lambda*rx; ry = lambda*ry; } // To simplify calculations, we make the arc part of a unit circle (rayon is 1) instead of an ellipse mat = new SVG.Matrix().rotate(xAxisRotation).scale(1/rx, 1/ry).rotate(-xAxisRotation); A = A.transform(mat); B = B.transform(mat); // Calculate the horizontal and vertical distance between the initial and final point of the arc k = [B.x-A.x, B.y-A.y]; // Find the length of the chord formed by A and B cSquare = k[0]*k[0] + k[1]*k[1]; c = Math.sqrt(cSquare); // Calculate the ratios of the horizontal and vertical distance on the length of the chord k[0] /= c; k[1] /= c; // Calculate the distance between the circle center and the chord midpoint // using this formula: t = sqrt(r^2 - c^2 / 4) // where t is the distance between the cirle center and the chord midpoint, // r is the rayon of the circle and c is the chord length // From: http://www.ajdesigner.com/phpcircle/circle_segment_chord_t.php // Because of the imprecision of floating point numbers, cSquare might end // up being slightly above 4 which would result in a negative radicand // To prevent that, a test is made before computing the square root t = (cSquare < 4) ? Math.sqrt(1 - cSquare/4) : 0; // For most situations, there are actually two different ellipses that // satisfy the constraints imposed by the points A and B, the radii rx and ry, // and the xAxisRotation // When the flags largeArcFlag and sweepFlag are equal, it means that the // second ellipse is used as a solution // See: https://www.w3.org/TR/SVG/paths.html#PathDataEllipticalArcCommands if(largeArcFlag === sweepFlag) { t *= -1; } // Calculate the coordinates of the center of the circle from the midpoint of the chord // This is done by multiplying the ratios calculated previously by the distance between // the circle center and the chord midpoint and using these values to go from the midpoint // to the center of the circle // The negative of the vertical distance ratio is used to modify the x coordinate while // the horizontal distance ratio is used to modify the y coordinate // That is because the center of the circle is perpendicular to the chord and perpendicular // lines are negative reciprocals O = new SVG.Point((B.x+A.x)/2 + t*-k[1], (B.y+A.y)/2 + t*k[0]); // Move the center of the circle at the origin OA = new SVG.Point(A.x-O.x, A.y-O.y); OB = new SVG.Point(B.x-O.x, B.y-O.y); // Calculate the start and end angle tetaStart = Math.acos(OA.x/Math.sqrt(OA.x*OA.x + OA.y*OA.y)); if (OA.y < 0) { tetaStart *= -1; } tetaEnd = Math.acos(OB.x/Math.sqrt(OB.x*OB.x + OB.y*OB.y)); if (OB.y < 0) { tetaEnd *= -1; } // If sweep-flag is '1', then the arc will be drawn in a "positive-angle" direction, // make sure that the end angle is above the start angle if (sweepFlag && tetaStart > tetaEnd) { tetaEnd += 2*Math.PI; } // If sweep-flag is '0', then the arc will be drawn in a "negative-angle" direction, // make sure that the end angle is below the start angle if (!sweepFlag && tetaStart < tetaEnd) { tetaEnd -= 2*Math.PI; } // Find the number of Bezier curves that are required to represent the arc // A cubic Bezier curve gives a good enough approximation when representing at most a quarter of a circle nbSectors = Math.ceil(Math.abs(tetaStart-tetaEnd) * 2/Math.PI); // Calculate the coordinates of the points of all the Bezier curves required to represent the arc // For an in-depth explanation of this part see: http://pomax.github.io/bezierinfo/#circles_cubic arcSegPoints = []; angle = tetaStart; deltaTeta = (tetaEnd-tetaStart)/nbSectors; f = 4*Math.tan(deltaTeta/4)/3; for (i = 0; i <= nbSectors; i++) { // The <= is because a Bezier curve have a start and a endpoint cosAngle = Math.cos(angle); sinAngle = Math.sin(angle); pt = new SVG.Point(O.x+cosAngle, O.y+sinAngle); arcSegPoints[i] = [new SVG.Point(pt.x+f*sinAngle, pt.y-f*cosAngle), pt, new SVG.Point(pt.x-f*sinAngle, pt.y+f*cosAngle)]; angle += deltaTeta; } // Remove the first control point of the first segment point and remove the second control point of the last segment point // These two control points are not used in the approximation of the arc, that is why they are removed arcSegPoints[0][0] = arcSegPoints[0][1].clone(); arcSegPoints[arcSegPoints.length-1][2] = arcSegPoints[arcSegPoints.length-1][1].clone(); // Revert the transformation that was applied to make the arc part of a unit circle instead of an ellipse mat = new SVG.Matrix().rotate(xAxisRotation).scale(rx, ry).rotate(-xAxisRotation); for (i = 0, il = arcSegPoints.length; i < il; i++) { arcSegPoints[i][0] = arcSegPoints[i][0].transform(mat); arcSegPoints[i][1] = arcSegPoints[i][1].transform(mat); arcSegPoints[i][2] = arcSegPoints[i][2].transform(mat); } // Convert the segments points to SVG curve commands for (i = 1, il = arcSegPoints.length; i < il; i++) { pt = arcSegPoints[i-1][2]; x1 = pt.x; y1 = pt.y; pt = arcSegPoints[i][0]; x2 = pt.x; y2 = pt.y; pt = arcSegPoints[i][1]; x = pt.x; y = pt.y; retVal.push(['C', x1, y1, x2, y2, x, y]); } return retVal } }()); /*! svg.draggable.js - v2.2.1 - 2016-08-25 * https://github.com/wout/svg.draggable.js * Copyright (c) 2016 Wout Fierens; Licensed MIT */ (function() { // creates handler, saves it function DragHandler(el){ el.remember('_draggable', this); this.el = el; } // Sets new parameter, starts dragging DragHandler.prototype.init = function(constraint, val){ var _this = this; this.constraint = constraint; this.value = val; this.el.on('mousedown.drag', function(e){ _this.start(e); }); this.el.on('touchstart.drag', function(e){ _this.start(e); }); }; // transforms one point from screen to user coords DragHandler.prototype.transformPoint = function(event, offset){ event = event || window.event; var touches = event.changedTouches && event.changedTouches[0] || event; this.p.x = touches.pageX - (offset || 0); this.p.y = touches.pageY; return this.p.matrixTransform(this.m) }; // gets elements bounding box with special handling of groups, nested and use DragHandler.prototype.getBBox = function(){ var box = this.el.bbox(); if(this.el instanceof SVG.Nested) box = this.el.rbox(); if (this.el instanceof SVG.G || this.el instanceof SVG.Use || this.el instanceof SVG.Nested) { box.x = this.el.x(); box.y = this.el.y(); } return box }; // start dragging DragHandler.prototype.start = function(e){ // check for left button if(e.type == 'click'|| e.type == 'mousedown' || e.type == 'mousemove'){ if((e.which || e.buttons) != 1){ return } } var _this = this; // fire beforedrag event this.el.fire('beforedrag', { event: e, handler: this }); // search for parent on the fly to make sure we can call // draggable() even when element is not in the dom currently this.parent = this.parent || this.el.parent(SVG.Nested) || this.el.parent(SVG.Doc); this.p = this.parent.node.createSVGPoint(); // save current transformation matrix this.m = this.el.node.getScreenCTM().inverse(); var box = this.getBBox(); var anchorOffset; // fix text-anchor in text-element (#37) if(this.el instanceof SVG.Text){ anchorOffset = this.el.node.getComputedTextLength(); switch(this.el.attr('text-anchor')){ case 'middle': anchorOffset /= 2; break case 'start': anchorOffset = 0; break; } } this.startPoints = { // We take absolute coordinates since we are just using a delta here point: this.transformPoint(e, anchorOffset), box: box, transform: this.el.transform() }; // add drag and end events to window SVG.on(window, 'mousemove.drag', function(e){ _this.drag(e); }); SVG.on(window, 'touchmove.drag', function(e){ _this.drag(e); }); SVG.on(window, 'mouseup.drag', function(e){ _this.end(e); }); SVG.on(window, 'touchend.drag', function(e){ _this.end(e); }); // fire dragstart event this.el.fire('dragstart', {event: e, p: this.startPoints.point, m: this.m, handler: this}); // prevent browser drag behavior e.preventDefault(); // prevent propagation to a parent that might also have dragging enabled e.stopPropagation(); }; // while dragging DragHandler.prototype.drag = function(e){ var box = this.getBBox() , p = this.transformPoint(e) , x = this.startPoints.box.x + p.x - this.startPoints.point.x , y = this.startPoints.box.y + p.y - this.startPoints.point.y , c = this.constraint , gx = p.x - this.startPoints.point.x , gy = p.y - this.startPoints.point.y; var event = new CustomEvent('dragmove', { detail: { event: e , p: p , m: this.m , handler: this } , cancelable: true }); this.el.fire(event); if(event.defaultPrevented) return p // move the element to its new position, if possible by constraint if (typeof c == 'function') { var coord = c.call(this.el, x, y, this.m); // bool, just show us if movement is allowed or not if (typeof coord == 'boolean') { coord = { x: coord, y: coord }; } // if true, we just move. If !false its a number and we move it there if (coord.x === true) { this.el.x(x); } else if (coord.x !== false) { this.el.x(coord.x); } if (coord.y === true) { this.el.y(y); } else if (coord.y !== false) { this.el.y(coord.y); } } else if (typeof c == 'object') { // keep element within constrained box if (c.minX != null && x < c.minX) x = c.minX; else if (c.maxX != null && x > c.maxX - box.width){ x = c.maxX - box.width; }if (c.minY != null && y < c.minY) y = c.minY; else if (c.maxY != null && y > c.maxY - box.height) y = c.maxY - box.height; if(this.el instanceof SVG.G) this.el.matrix(this.startPoints.transform).transform({x:gx, y: gy}, true); else this.el.move(x, y); } // so we can use it in the end-method, too return p }; DragHandler.prototype.end = function(e){ // final drag var p = this.drag(e); // fire dragend event this.el.fire('dragend', { event: e, p: p, m: this.m, handler: this }); // unbind events SVG.off(window, 'mousemove.drag'); SVG.off(window, 'touchmove.drag'); SVG.off(window, 'mouseup.drag'); SVG.off(window, 'touchend.drag'); }; SVG.extend(SVG.Element, { // Make element draggable // Constraint might be an object (as described in readme.md) or a function in the form "function (x, y)" that gets called before every move. // The function can return a boolean or an object of the form {x, y}, to which the element will be moved. "False" skips moving, true moves to raw x, y. draggable: function(value, constraint) { // Check the parameters and reassign if needed if (typeof value == 'function' || typeof value == 'object') { constraint = value; value = true; } var dragHandler = this.remember('_draggable') || new DragHandler(this); // When no parameter is given, value is true value = typeof value === 'undefined' ? true : value; if(value) dragHandler.init(constraint || {}, value); else { this.off('mousedown.drag'); this.off('touchstart.drag'); } return this } }); }).call(undefined); (function() { function SelectHandler(el) { this.el = el; el.remember('_selectHandler', this); this.pointSelection = {isSelected: false}; this.rectSelection = {isSelected: false}; } SelectHandler.prototype.init = function (value, options) { var bbox = this.el.bbox(); this.options = {}; // Merging the defaults and the options-object together for (var i in this.el.selectize.defaults) { this.options[i] = this.el.selectize.defaults[i]; if (options[i] !== undefined) { this.options[i] = options[i]; } } this.parent = this.el.parent(); this.nested = (this.nested || this.parent.group()); this.nested.matrix(new SVG.Matrix(this.el).translate(bbox.x, bbox.y)); // When deepSelect is enabled and the element is a line/polyline/polygon, draw only points for moving if (this.options.deepSelect && ['line', 'polyline', 'polygon'].indexOf(this.el.type) !== -1) { this.selectPoints(value); } else { this.selectRect(value); } this.observe(); this.cleanup(); }; SelectHandler.prototype.selectPoints = function (value) { this.pointSelection.isSelected = value; // When set is already there we dont have to create one if (this.pointSelection.set) { return this; } // Create our set of elements this.pointSelection.set = this.parent.set(); // draw the circles and mark the element as selected this.drawCircles(); return this; }; // create the point-array which contains the 2 points of a line or simply the points-array of polyline/polygon SelectHandler.prototype.getPointArray = function () { var bbox = this.el.bbox(); return this.el.array().valueOf().map(function (el) { return [el[0] - bbox.x, el[1] - bbox.y]; }); }; // The function to draw the circles SelectHandler.prototype.drawCircles = function () { var _this = this, array = this.getPointArray(); // go through the array of points for (var i = 0, len = array.length; i < len; ++i) { var curriedEvent = (function (k) { return function (ev) { ev = ev || window.event; ev.preventDefault ? ev.preventDefault() : ev.returnValue = false; ev.stopPropagation(); var x = ev.pageX || ev.touches[0].pageX; var y = ev.pageY || ev.touches[0].pageY; _this.el.fire('point', {x: x, y: y, i: k, event: ev}); }; })(i); // add every point to the set this.pointSelection.set.add( // a circle with our css-classes and a touchstart-event which fires our event for moving points this.nested.circle(this.options.radius) .center(array[i][0], array[i][1]) .addClass(this.options.classPoints) .addClass(this.options.classPoints + '_point') .on('touchstart', curriedEvent) .on('mousedown', curriedEvent) ); } }; // every time a circle is moved, we have to update the positions of our circle SelectHandler.prototype.updatePointSelection = function () { var array = this.getPointArray(); this.pointSelection.set.each(function (i) { if (this.cx() === array[i][0] && this.cy() === array[i][1]) { return; } this.center(array[i][0], array[i][1]); }); }; SelectHandler.prototype.updateRectSelection = function () { var bbox = this.el.bbox(); this.rectSelection.set.get(0).attr({ width: bbox.width, height: bbox.height }); // set.get(1) is always in the upper left corner. no need to move it if (this.options.points) { this.rectSelection.set.get(2).center(bbox.width, 0); this.rectSelection.set.get(3).center(bbox.width, bbox.height); this.rectSelection.set.get(4).center(0, bbox.height); this.rectSelection.set.get(5).center(bbox.width / 2, 0); this.rectSelection.set.get(6).center(bbox.width, bbox.height / 2); this.rectSelection.set.get(7).center(bbox.width / 2, bbox.height); this.rectSelection.set.get(8).center(0, bbox.height / 2); } if (this.options.rotationPoint) { if (this.options.points) { this.rectSelection.set.get(9).center(bbox.width / 2, 20); } else { this.rectSelection.set.get(1).center(bbox.width / 2, 20); } } }; SelectHandler.prototype.selectRect = function (value) { var _this = this, bbox = this.el.bbox(); this.rectSelection.isSelected = value; // when set is already p this.rectSelection.set = this.rectSelection.set || this.parent.set(); // helperFunction to create a mouse-down function which triggers the event specified in `eventName` function getMoseDownFunc(eventName) { return function (ev) { ev = ev || window.event; ev.preventDefault ? ev.preventDefault() : ev.returnValue = false; ev.stopPropagation(); var x = ev.pageX || ev.touches[0].pageX; var y = ev.pageY || ev.touches[0].pageY; _this.el.fire(eventName, {x: x, y: y, event: ev}); }; } // create the selection-rectangle and add the css-class if (!this.rectSelection.set.get(0)) { this.rectSelection.set.add(this.nested.rect(bbox.width, bbox.height).addClass(this.options.classRect)); } // Draw Points at the edges, if enabled if (this.options.points && !this.rectSelection.set.get(1)) { var ename ="touchstart", mname = "mousedown"; this.rectSelection.set.add(this.nested.circle(this.options.radius).center(0, 0).attr('class', this.options.classPoints + '_lt').on(mname, getMoseDownFunc('lt')).on(ename, getMoseDownFunc('lt'))); this.rectSelection.set.add(this.nested.circle(this.options.radius).center(bbox.width, 0).attr('class', this.options.classPoints + '_rt').on(mname, getMoseDownFunc('rt')).on(ename, getMoseDownFunc('rt'))); this.rectSelection.set.add(this.nested.circle(this.options.radius).center(bbox.width, bbox.height).attr('class', this.options.classPoints + '_rb').on(mname, getMoseDownFunc('rb')).on(ename, getMoseDownFunc('rb'))); this.rectSelection.set.add(this.nested.circle(this.options.radius).center(0, bbox.height).attr('class', this.options.classPoints + '_lb').on(mname, getMoseDownFunc('lb')).on(ename, getMoseDownFunc('lb'))); this.rectSelection.set.add(this.nested.circle(this.options.radius).center(bbox.width / 2, 0).attr('class', this.options.classPoints + '_t').on(mname, getMoseDownFunc('t')).on(ename, getMoseDownFunc('t'))); this.rectSelection.set.add(this.nested.circle(this.options.radius).center(bbox.width, bbox.height / 2).attr('class', this.options.classPoints + '_r').on(mname, getMoseDownFunc('r')).on(ename, getMoseDownFunc('r'))); this.rectSelection.set.add(this.nested.circle(this.options.radius).center(bbox.width / 2, bbox.height).attr('class', this.options.classPoints + '_b').on(mname, getMoseDownFunc('b')).on(ename, getMoseDownFunc('b'))); this.rectSelection.set.add(this.nested.circle(this.options.radius).center(0, bbox.height / 2).attr('class', this.options.classPoints + '_l').on(mname, getMoseDownFunc('l')).on(ename, getMoseDownFunc('l'))); this.rectSelection.set.each(function () { this.addClass(_this.options.classPoints); }); } // draw rotationPint, if enabled if (this.options.rotationPoint && ((this.options.points && !this.rectSelection.set.get(9)) || (!this.options.points && !this.rectSelection.set.get(1)))) { var curriedEvent = function (ev) { ev = ev || window.event; ev.preventDefault ? ev.preventDefault() : ev.returnValue = false; ev.stopPropagation(); var x = ev.pageX || ev.touches[0].pageX; var y = ev.pageY || ev.touches[0].pageY; _this.el.fire('rot', {x: x, y: y, event: ev}); }; this.rectSelection.set.add(this.nested.circle(this.options.radius).center(bbox.width / 2, 20).attr('class', this.options.classPoints + '_rot') .on("touchstart", curriedEvent).on("mousedown", curriedEvent)); } }; SelectHandler.prototype.handler = function () { var bbox = this.el.bbox(); this.nested.matrix(new SVG.Matrix(this.el).translate(bbox.x, bbox.y)); if (this.rectSelection.isSelected) { this.updateRectSelection(); } if (this.pointSelection.isSelected) { this.updatePointSelection(); } }; SelectHandler.prototype.observe = function () { var _this = this; if (MutationObserver) { if (this.rectSelection.isSelected || this.pointSelection.isSelected) { this.observerInst = this.observerInst || new MutationObserver(function () { _this.handler(); }); this.observerInst.observe(this.el.node, {attributes: true}); } else { try { this.observerInst.disconnect(); delete this.observerInst; } catch (e) { } } } else { this.el.off('DOMAttrModified.select'); if (this.rectSelection.isSelected || this.pointSelection.isSelected) { this.el.on('DOMAttrModified.select', function () { _this.handler(); }); } } }; SelectHandler.prototype.cleanup = function () { //var _this = this; if (!this.rectSelection.isSelected && this.rectSelection.set) { // stop watching the element, remove the selection this.rectSelection.set.each(function () { this.remove(); }); this.rectSelection.set.clear(); delete this.rectSelection.set; } if (!this.pointSelection.isSelected && this.pointSelection.set) { // Remove all points, clear the set, stop watching the element this.pointSelection.set.each(function () { this.remove(); }); this.pointSelection.set.clear(); delete this.pointSelection.set; } if (!this.pointSelection.isSelected && !this.rectSelection.isSelected) { this.nested.remove(); delete this.nested; } }; SVG.extend(SVG.Element, { // Select element with mouse selectize: function (value, options) { // Check the parameters and reassign if needed if (typeof value === 'object') { options = value; value = true; } var selectHandler = this.remember('_selectHandler') || new SelectHandler(this); selectHandler.init(value === undefined ? true : value, options || {}); return this; } }); SVG.Element.prototype.selectize.defaults = { points: true, // If true, points at the edges are drawn. Needed for resize! classRect: 'svg_select_boundingRect', // Css-class added to the rect classPoints: 'svg_select_points', // Css-class added to the points radius: 7, // radius of the points rotationPoint: true, // If true, rotation point is drawn. Needed for rotation! deepSelect: false // If true, moving of single points is possible (only line, polyline, polyon) }; }()); (function() { (function () { function ResizeHandler(el) { el.remember('_resizeHandler', this); this.el = el; this.parameters = {}; this.lastUpdateCall = null; this.p = el.doc().node.createSVGPoint(); } ResizeHandler.prototype.transformPoint = function(x, y, m){ this.p.x = x - (this.offset.x - window.pageXOffset); this.p.y = y - (this.offset.y - window.pageYOffset); return this.p.matrixTransform(m || this.m); }; ResizeHandler.prototype._extractPosition = function(event) { // Extract a position from a mouse/touch event. // Returns { x: .., y: .. } return { x: event.clientX != null ? event.clientX : event.touches[0].clientX, y: event.clientY != null ? event.clientY : event.touches[0].clientY } }; ResizeHandler.prototype.init = function (options) { var _this = this; this.stop(); if (options === 'stop') { return; } this.options = {}; // Merge options and defaults for (var i in this.el.resize.defaults) { this.options[i] = this.el.resize.defaults[i]; if (typeof options[i] !== 'undefined') { this.options[i] = options[i]; } } // We listen to all these events which are specifying different edges this.el.on('lt.resize', function(e){ _this.resize(e || window.event); }); // Left-Top this.el.on('rt.resize', function(e){ _this.resize(e || window.event); }); // Right-Top this.el.on('rb.resize', function(e){ _this.resize(e || window.event); }); // Right-Bottom this.el.on('lb.resize', function(e){ _this.resize(e || window.event); }); // Left-Bottom this.el.on('t.resize', function(e){ _this.resize(e || window.event); }); // Top this.el.on('r.resize', function(e){ _this.resize(e || window.event); }); // Right this.el.on('b.resize', function(e){ _this.resize(e || window.event); }); // Bottom this.el.on('l.resize', function(e){ _this.resize(e || window.event); }); // Left this.el.on('rot.resize', function(e){ _this.resize(e || window.event); }); // Rotation this.el.on('point.resize', function(e){ _this.resize(e || window.event); }); // Point-Moving // This call ensures, that the plugin reacts to a change of snapToGrid immediately this.update(); }; ResizeHandler.prototype.stop = function(){ this.el.off('lt.resize'); this.el.off('rt.resize'); this.el.off('rb.resize'); this.el.off('lb.resize'); this.el.off('t.resize'); this.el.off('r.resize'); this.el.off('b.resize'); this.el.off('l.resize'); this.el.off('rot.resize'); this.el.off('point.resize'); return this; }; ResizeHandler.prototype.resize = function (event) { var _this = this; this.m = this.el.node.getScreenCTM().inverse(); this.offset = { x: window.pageXOffset, y: window.pageYOffset }; var txPt = this._extractPosition(event.detail.event); this.parameters = { type: this.el.type, // the type of element p: this.transformPoint(txPt.x, txPt.y), x: event.detail.x, // x-position of the mouse when resizing started y: event.detail.y, // y-position of the mouse when resizing started box: this.el.bbox(), // The bounding-box of the element rotation: this.el.transform().rotation // The current rotation of the element }; // Add font-size parameter if the element type is text if (this.el.type === "text") { this.parameters.fontSize = this.el.attr()["font-size"]; } // the i-param in the event holds the index of the point which is moved, when using `deepSelect` if (event.detail.i !== undefined) { // get the point array var array = this.el.array().valueOf(); // Save the index and the point which is moved this.parameters.i = event.detail.i; this.parameters.pointCoords = [array[event.detail.i][0], array[event.detail.i][1]]; } // Lets check which edge of the bounding-box was clicked and resize the this.el according to this switch (event.type) { // Left-Top-Edge case 'lt': // We build a calculating function for every case which gives us the new position of the this.el this.calc = function (diffX, diffY) { // The procedure is always the same // First we snap the edge to the given grid (snapping to 1px grid is normal resizing) var snap = this.snapToGrid(diffX, diffY); // Now we check if the new height and width still valid (> 0) if (this.parameters.box.width - snap[0] > 0 && this.parameters.box.height - snap[1] > 0) { // ...if valid, we resize the this.el (which can include moving because the coord-system starts at the left-top and this edge is moving sometimes when resized) /* * but first check if the element is text box, so we can change the font size instead of * the width and height */ if (this.parameters.type === "text") { this.el.move(this.parameters.box.x + snap[0], this.parameters.box.y); this.el.attr("font-size", this.parameters.fontSize - snap[0]); return; } snap = this.checkAspectRatio(snap); this.el.move(this.parameters.box.x + snap[0], this.parameters.box.y + snap[1]).size(this.parameters.box.width - snap[0], this.parameters.box.height - snap[1]); } }; break; // Right-Top case 'rt': // s.a. this.calc = function (diffX, diffY) { var snap = this.snapToGrid(diffX, diffY, 1 << 1); if (this.parameters.box.width + snap[0] > 0 && this.parameters.box.height - snap[1] > 0) { if (this.parameters.type === "text") { this.el.move(this.parameters.box.x - snap[0], this.parameters.box.y); this.el.attr("font-size", this.parameters.fontSize + snap[0]); return; } snap = this.checkAspectRatio(snap); this.el.move(this.parameters.box.x, this.parameters.box.y + snap[1]).size(this.parameters.box.width + snap[0], this.parameters.box.height - snap[1]); } }; break; // Right-Bottom case 'rb': // s.a. this.calc = function (diffX, diffY) { var snap = this.snapToGrid(diffX, diffY, 0); if (this.parameters.box.width + snap[0] > 0 && this.parameters.box.height + snap[1] > 0) { if (this.parameters.type === "text") { this.el.move(this.parameters.box.x - snap[0], this.parameters.box.y); this.el.attr("font-size", this.parameters.fontSize + snap[0]); return; } snap = this.checkAspectRatio(snap); this.el.move(this.parameters.box.x, this.parameters.box.y).size(this.parameters.box.width + snap[0], this.parameters.box.height + snap[1]); } }; break; // Left-Bottom case 'lb': // s.a. this.calc = function (diffX, diffY) { var snap = this.snapToGrid(diffX, diffY, 1); if (this.parameters.box.width - snap[0] > 0 && this.parameters.box.height + snap[1] > 0) { if (this.parameters.type === "text") { this.el.move(this.parameters.box.x + snap[0], this.parameters.box.y); this.el.attr("font-size", this.parameters.fontSize - snap[0]); return; } snap = this.checkAspectRatio(snap); this.el.move(this.parameters.box.x + snap[0], this.parameters.box.y).size(this.parameters.box.width - snap[0], this.parameters.box.height + snap[1]); } }; break; // Top case 't': // s.a. this.calc = function (diffX, diffY) { var snap = this.snapToGrid(diffX, diffY, 1 << 1); if (this.parameters.box.height - snap[1] > 0) { // Disable the font-resizing if it is not from the corner of bounding-box if (this.parameters.type === "text") { return; } this.el.move(this.parameters.box.x, this.parameters.box.y + snap[1]).height(this.parameters.box.height - snap[1]); } }; break; // Right case 'r': // s.a. this.calc = function (diffX, diffY) { var snap = this.snapToGrid(diffX, diffY, 0); if (this.parameters.box.width + snap[0] > 0) { if (this.parameters.type === "text") { return; } this.el.move(this.parameters.box.x, this.parameters.box.y).width(this.parameters.box.width + snap[0]); } }; break; // Bottom case 'b': // s.a. this.calc = function (diffX, diffY) { var snap = this.snapToGrid(diffX, diffY, 0); if (this.parameters.box.height + snap[1] > 0) { if (this.parameters.type === "text") { return; } this.el.move(this.parameters.box.x, this.parameters.box.y).height(this.parameters.box.height + snap[1]); } }; break; // Left case 'l': // s.a. this.calc = function (diffX, diffY) { var snap = this.snapToGrid(diffX, diffY, 1); if (this.parameters.box.width - snap[0] > 0) { if (this.parameters.type === "text") { return; } this.el.move(this.parameters.box.x + snap[0], this.parameters.box.y).width(this.parameters.box.width - snap[0]); } }; break; // Rotation case 'rot': // s.a. this.calc = function (diffX, diffY) { // yes this is kinda stupid but we need the mouse coords back... var current = {x: diffX + this.parameters.p.x, y: diffY + this.parameters.p.y}; // start minus middle var sAngle = Math.atan2((this.parameters.p.y - this.parameters.box.y - this.parameters.box.height / 2), (this.parameters.p.x - this.parameters.box.x - this.parameters.box.width / 2)); // end minus middle var pAngle = Math.atan2((current.y - this.parameters.box.y - this.parameters.box.height / 2), (current.x - this.parameters.box.x - this.parameters.box.width / 2)); var angle = (pAngle - sAngle) * 180 / Math.PI; // We have to move the element to the center of the box first and change the rotation afterwards // because rotation always works around a rotation-center, which is changed when moving the element // We also set the new rotation center to the center of the box. this.el.center(this.parameters.box.cx, this.parameters.box.cy).rotate(this.parameters.rotation + angle - angle % this.options.snapToAngle, this.parameters.box.cx, this.parameters.box.cy); }; break; // Moving one single Point (needed when an element is deepSelected which means you can move every single point of the object) case 'point': this.calc = function (diffX, diffY) { // Snapping the point to the grid var snap = this.snapToGrid(diffX, diffY, this.parameters.pointCoords[0], this.parameters.pointCoords[1]); // Get the point array var array = this.el.array().valueOf(); // Changing the moved point in the array array[this.parameters.i][0] = this.parameters.pointCoords[0] + snap[0]; array[this.parameters.i][1] = this.parameters.pointCoords[1] + snap[1]; // And plot the new this.el this.el.plot(array); }; } this.el.fire('resizestart', {dx: this.parameters.x, dy: this.parameters.y, event: event}); // When resizing started, we have to register events for... // Touches. SVG.on(window, 'touchmove.resize', function(e) { _this.update(e || window.event); }); SVG.on(window, 'touchend.resize', function() { _this.done(); }); // Mouse. SVG.on(window, 'mousemove.resize', function (e) { _this.update(e || window.event); }); SVG.on(window, 'mouseup.resize', function () { _this.done(); }); }; // The update-function redraws the element every time the mouse is moving ResizeHandler.prototype.update = function (event) { if (!event) { if (this.lastUpdateCall) { this.calc(this.lastUpdateCall[0], this.lastUpdateCall[1]); } return; } // Calculate the difference between the mouseposition at start and now var txPt = this._extractPosition(event); var p = this.transformPoint(txPt.x, txPt.y); var diffX = p.x - this.parameters.p.x, diffY = p.y - this.parameters.p.y; this.lastUpdateCall = [diffX, diffY]; // Calculate the new position and height / width of the element this.calc(diffX, diffY); // Emit an event to say we have changed. this.el.fire('resizing', {dx: diffX, dy: diffY, event: event}); }; // Is called on mouseup. // Removes the update-function from the mousemove event ResizeHandler.prototype.done = function () { this.lastUpdateCall = null; SVG.off(window, 'mousemove.resize'); SVG.off(window, 'mouseup.resize'); SVG.off(window, 'touchmove.resize'); SVG.off(window, 'touchend.resize'); this.el.fire('resizedone'); }; // The flag is used to determine whether the resizing is used with a left-Point (first bit) and top-point (second bit) // In this cases the temp-values are calculated differently ResizeHandler.prototype.snapToGrid = function (diffX, diffY, flag, pointCoordsY) { var temp; // If `pointCoordsY` is given, a single Point has to be snapped (deepSelect). That's why we need a different temp-value if (typeof pointCoordsY !== 'undefined') { // Note that flag = pointCoordsX in this case temp = [(flag + diffX) % this.options.snapToGrid, (pointCoordsY + diffY) % this.options.snapToGrid]; } else { // We check if the flag is set and if not we set a default-value (both bits set - which means upper-left-edge) flag = flag == null ? 1 | 1 << 1 : flag; temp = [(this.parameters.box.x + diffX + (flag & 1 ? 0 : this.parameters.box.width)) % this.options.snapToGrid, (this.parameters.box.y + diffY + (flag & (1 << 1) ? 0 : this.parameters.box.height)) % this.options.snapToGrid]; } diffX -= (Math.abs(temp[0]) < this.options.snapToGrid / 2 ? temp[0] : temp[0] - (diffX < 0 ? -this.options.snapToGrid : this.options.snapToGrid)); diffY -= (Math.abs(temp[1]) < this.options.snapToGrid / 2 ? temp[1] : temp[1] - (diffY < 0 ? -this.options.snapToGrid : this.options.snapToGrid)); return this.constraintToBox(diffX, diffY, flag, pointCoordsY); }; // keep element within constrained box ResizeHandler.prototype.constraintToBox = function (diffX, diffY, flag, pointCoordsY) { //return [diffX, diffY] var c = this.options.constraint || {}; var orgX, orgY; if (typeof pointCoordsY !== 'undefined') { orgX = flag; orgY = pointCoordsY; } else { orgX = this.parameters.box.x + (flag & 1 ? 0 : this.parameters.box.width); orgY = this.parameters.box.y + (flag & (1<<1) ? 0 : this.parameters.box.height); } if (typeof c.minX !== 'undefined' && orgX + diffX < c.minX) { diffX = c.minX - orgX; } if (typeof c.maxX !== 'undefined' && orgX + diffX > c.maxX) { diffX = c.maxX - orgX; } if (typeof c.minY !== 'undefined' && orgY + diffY < c.minY) { diffY = c.minY - orgY; } if (typeof c.maxY !== 'undefined' && orgY + diffY > c.maxY) { diffY = c.maxY - orgY; } return [diffX, diffY]; }; ResizeHandler.prototype.checkAspectRatio = function (snap) { if (!this.options.saveAspectRatio) { return snap; } var updatedSnap = snap.slice(); var aspectRatio = this.parameters.box.width / this.parameters.box.height; var newW = this.parameters.box.width + snap[0]; var newH = this.parameters.box.height - snap[1]; var newAspectRatio = newW / newH; if (newAspectRatio < aspectRatio) { // Height is too big. Adapt it updatedSnap[1] = newW / aspectRatio - this.parameters.box.height; } else if (newAspectRatio > aspectRatio) { // Width is too big. Adapt it updatedSnap[0] = this.parameters.box.width - newH * aspectRatio; } return updatedSnap; }; SVG.extend(SVG.Element, { // Resize element with mouse resize: function (options) { (this.remember('_resizeHandler') || new ResizeHandler(this)).init(options || {}); return this; } }); SVG.Element.prototype.resize.defaults = { snapToAngle: 0.1, // Specifies the speed the rotation is happening when moving the mouse snapToGrid: 1, // Snaps to a grid of `snapToGrid` Pixels constraint: {}, // keep element within constrained box saveAspectRatio: false // Save aspect ratio when resizing using lt, rt, rb or lb points }; }).call(this); }()); function styleInject(css, ref) { if ( ref === void 0 ) ref = {}; var insertAt = ref.insertAt; if (!css || typeof document === 'undefined') { return; } var head = document.head || document.getElementsByTagName('head')[0]; var style = document.createElement('style'); style.type = 'text/css'; if (insertAt === 'top') { if (head.firstChild) { head.insertBefore(style, head.firstChild); } else { head.appendChild(style); } } else { head.appendChild(style); } if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } } var css = ".apexcharts-canvas {\n position: relative;\n user-select: none;\n /* cannot give overflow: hidden as it will crop tooltips which overflow outside chart area */\n}\n\n/* scrollbar is not visible by default for legend, hence forcing the visibility */\n.apexcharts-canvas ::-webkit-scrollbar {\n -webkit-appearance: none;\n width: 6px;\n}\n.apexcharts-canvas ::-webkit-scrollbar-thumb {\n border-radius: 4px;\n background-color: rgba(0,0,0,.5);\n box-shadow: 0 0 1px rgba(255,255,255,.5);\n -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);\n}\n.apexcharts-canvas.dark {\n background: #343F57;\n}\n\n.apexcharts-inner {\n position: relative;\n}\n\n.legend-mouseover-inactive {\n transition: 0.15s ease all;\n opacity: 0.20;\n}\n\n.apexcharts-series-collapsed {\n opacity: 0;\n}\n\n.apexcharts-gridline, .apexcharts-text {\n pointer-events: none;\n}\n\n.apexcharts-tooltip {\n border-radius: 5px;\n box-shadow: 2px 2px 6px -4px #999;\n cursor: default;\n font-size: 14px;\n left: 62px;\n opacity: 0;\n pointer-events: none;\n position: absolute;\n top: 20px;\n overflow: hidden;\n white-space: nowrap;\n z-index: 12;\n transition: 0.15s ease all;\n}\n.apexcharts-tooltip.light {\n border: 1px solid #e3e3e3;\n background: rgba(255, 255, 255, 0.96);\n}\n.apexcharts-tooltip.dark {\n color: #fff;\n background: rgba(30,30,30, 0.8);\n}\n.apexcharts-tooltip * {\n font-family: inherit;\n}\n\n.apexcharts-tooltip .apexcharts-marker,\n.apexcharts-area-series .apexcharts-area,\n.apexcharts-line {\n pointer-events: none;\n}\n\n.apexcharts-tooltip.active {\n opacity: 1;\n transition: 0.15s ease all;\n}\n\n.apexcharts-tooltip-title {\n padding: 6px;\n font-size: 15px;\n margin-bottom: 4px;\n}\n.apexcharts-tooltip.light .apexcharts-tooltip-title {\n background: #ECEFF1;\n border-bottom: 1px solid #ddd;\n}\n.apexcharts-tooltip.dark .apexcharts-tooltip-title {\n background: rgba(0, 0, 0, 0.7);\n border-bottom: 1px solid #333;\n}\n\n.apexcharts-tooltip-text-value,\n.apexcharts-tooltip-text-z-value {\n display: inline-block;\n font-weight: 600;\n margin-left: 5px;\n}\n\n.apexcharts-tooltip-text-z-label:empty,\n.apexcharts-tooltip-text-z-value:empty {\n display: none;\n}\n\n.apexcharts-tooltip-text-value, \n.apexcharts-tooltip-text-z-value {\n font-weight: 600;\n}\n\n.apexcharts-tooltip-marker {\n width: 12px;\n height: 12px;\n position: relative;\n top: 0px;\n margin-right: 10px;\n border-radius: 50%;\n}\n\n.apexcharts-tooltip-series-group {\n padding: 0 10px;\n display: none;\n text-align: left;\n justify-content: left;\n align-items: center;\n}\n\n.apexcharts-tooltip-series-group.active .apexcharts-tooltip-marker {\n opacity: 1;\n}\n.apexcharts-tooltip-series-group.active, .apexcharts-tooltip-series-group:last-child {\n padding-bottom: 4px;\n}\n.apexcharts-tooltip-y-group {\n padding: 6px 0 5px;\n}\n.apexcharts-tooltip-candlestick {\n padding: 4px 8px;\n}\n.apexcharts-tooltip-candlestick > div {\n margin: 4px 0;\n}\n.apexcharts-tooltip-candlestick span.value {\n font-weight: bold;\n}\n\n.apexcharts-tooltip-rangebar {\n padding: 5px 8px;\n}\n\n.apexcharts-tooltip-rangebar .category {\n font-weight: 600;\n color: #777;\n}\n\n.apexcharts-tooltip-rangebar .series-name {\n font-weight: bold;\n display: block;\n margin-bottom: 5px;\n}\n\n.apexcharts-xaxistooltip {\n opacity: 0;\n padding: 9px 10px;\n pointer-events: none;\n color: #373d3f;\n font-size: 13px;\n text-align: center;\n border-radius: 2px;\n position: absolute;\n z-index: 10;\n\tbackground: #ECEFF1;\n border: 1px solid #90A4AE;\n transition: 0.15s ease all;\n}\n\n.apexcharts-xaxistooltip.dark {\n background: rgba(0, 0, 0, 0.7);\n border: 1px solid rgba(0, 0, 0, 0.5);\n color: #fff;\n}\n\n.apexcharts-xaxistooltip:after, .apexcharts-xaxistooltip:before {\n\tleft: 50%;\n\tborder: solid transparent;\n\tcontent: \" \";\n\theight: 0;\n\twidth: 0;\n\tposition: absolute;\n\tpointer-events: none;\n}\n\n.apexcharts-xaxistooltip:after {\n\tborder-color: rgba(236, 239, 241, 0);\n\tborder-width: 6px;\n\tmargin-left: -6px;\n}\n.apexcharts-xaxistooltip:before {\n\tborder-color: rgba(144, 164, 174, 0);\n\tborder-width: 7px;\n\tmargin-left: -7px;\n}\n\n.apexcharts-xaxistooltip-bottom:after, .apexcharts-xaxistooltip-bottom:before {\n bottom: 100%;\n}\n\n.apexcharts-xaxistooltip-top:after, .apexcharts-xaxistooltip-top:before {\n top: 100%;\n}\n\n.apexcharts-xaxistooltip-bottom:after {\n border-bottom-color: #ECEFF1;\n}\n.apexcharts-xaxistooltip-bottom:before {\n border-bottom-color: #90A4AE;\n}\n\n.apexcharts-xaxistooltip-bottom.dark:after {\n border-bottom-color: rgba(0, 0, 0, 0.5);\n}\n.apexcharts-xaxistooltip-bottom.dark:before {\n border-bottom-color: rgba(0, 0, 0, 0.5);\n}\n\n.apexcharts-xaxistooltip-top:after {\n border-top-color:#ECEFF1\n}\n.apexcharts-xaxistooltip-top:before {\n border-top-color: #90A4AE;\n}\n.apexcharts-xaxistooltip-top.dark:after {\n border-top-color:rgba(0, 0, 0, 0.5);\n}\n.apexcharts-xaxistooltip-top.dark:before {\n border-top-color: rgba(0, 0, 0, 0.5);\n}\n\n\n.apexcharts-xaxistooltip.active {\n opacity: 1;\n transition: 0.15s ease all;\n}\n\n.apexcharts-yaxistooltip {\n opacity: 0;\n padding: 4px 10px;\n pointer-events: none;\n color: #373d3f;\n font-size: 13px;\n text-align: center;\n border-radius: 2px;\n position: absolute;\n z-index: 10;\n\tbackground: #ECEFF1;\n border: 1px solid #90A4AE;\n}\n\n.apexcharts-yaxistooltip.dark {\n background: rgba(0, 0, 0, 0.7);\n border: 1px solid rgba(0, 0, 0, 0.5);\n color: #fff;\n}\n\n.apexcharts-yaxistooltip:after, .apexcharts-yaxistooltip:before {\n\ttop: 50%;\n\tborder: solid transparent;\n\tcontent: \" \";\n\theight: 0;\n\twidth: 0;\n\tposition: absolute;\n\tpointer-events: none;\n}\n.apexcharts-yaxistooltip:after {\n\tborder-color: rgba(236, 239, 241, 0);\n\tborder-width: 6px;\n\tmargin-top: -6px;\n}\n.apexcharts-yaxistooltip:before {\n\tborder-color: rgba(144, 164, 174, 0);\n\tborder-width: 7px;\n\tmargin-top: -7px;\n}\n\n.apexcharts-yaxistooltip-left:after, .apexcharts-yaxistooltip-left:before {\n left: 100%;\n}\n\n.apexcharts-yaxistooltip-right:after, .apexcharts-yaxistooltip-right:before {\n right: 100%;\n}\n\n.apexcharts-yaxistooltip-left:after {\n border-left-color: #ECEFF1;\n}\n.apexcharts-yaxistooltip-left:before {\n border-left-color: #90A4AE;\n}\n.apexcharts-yaxistooltip-left.dark:after {\n border-left-color: rgba(0, 0, 0, 0.5);\n}\n.apexcharts-yaxistooltip-left.dark:before {\n border-left-color: rgba(0, 0, 0, 0.5);\n}\n\n.apexcharts-yaxistooltip-right:after {\n border-right-color: #ECEFF1;\n}\n.apexcharts-yaxistooltip-right:before {\n border-right-color: #90A4AE;\n}\n.apexcharts-yaxistooltip-right.dark:after {\n border-right-color: rgba(0, 0, 0, 0.5);\n}\n.apexcharts-yaxistooltip-right.dark:before {\n border-right-color: rgba(0, 0, 0, 0.5);\n}\n\n.apexcharts-yaxistooltip.active {\n opacity: 1;\n}\n\n.apexcharts-xcrosshairs, .apexcharts-ycrosshairs {\n pointer-events: none;\n opacity: 0;\n transition: 0.15s ease all;\n}\n\n.apexcharts-xcrosshairs.active, .apexcharts-ycrosshairs.active {\n opacity: 1;\n transition: 0.15s ease all;\n}\n\n.apexcharts-ycrosshairs-hidden {\n opacity: 0;\n}\n\n.apexcharts-zoom-rect {\n pointer-events: none;\n}\n.apexcharts-selection-rect {\n cursor: move;\n}\n\n.svg_select_points, .svg_select_points_rot {\n opacity: 0;\n visibility: hidden;\n}\n.svg_select_points_l, .svg_select_points_r {\n cursor: ew-resize;\n opacity: 1;\n visibility: visible;\n fill: #888;\n}\n.apexcharts-canvas.zoomable .hovering-zoom {\n cursor: crosshair\n}\n.apexcharts-canvas.zoomable .hovering-pan {\n cursor: move\n}\n\n.apexcharts-xaxis,\n.apexcharts-yaxis {\n pointer-events: none;\n}\n\n.apexcharts-zoom-icon, \n.apexcharts-zoom-in-icon,\n.apexcharts-zoom-out-icon,\n.apexcharts-reset-zoom-icon, \n.apexcharts-pan-icon, \n.apexcharts-selection-icon,\n.apexcharts-menu-icon, \n.apexcharts-toolbar-custom-icon {\n cursor: pointer;\n width: 20px;\n height: 20px;\n line-height: 24px;\n color: #6E8192;\n text-align: center;\n}\n\n\n.apexcharts-zoom-icon svg, \n.apexcharts-zoom-in-icon svg,\n.apexcharts-zoom-out-icon svg,\n.apexcharts-reset-zoom-icon svg,\n.apexcharts-menu-icon svg {\n fill: #6E8192;\n}\n.apexcharts-selection-icon svg {\n fill: #444;\n transform: scale(0.76)\n}\n\n.dark .apexcharts-zoom-icon svg, \n.dark .apexcharts-zoom-in-icon svg,\n.dark .apexcharts-zoom-out-icon svg,\n.dark .apexcharts-reset-zoom-icon svg, \n.dark .apexcharts-pan-icon svg, \n.dark .apexcharts-selection-icon svg,\n.dark .apexcharts-menu-icon svg, \n.dark .apexcharts-toolbar-custom-icon svg{\n fill: #f3f4f5;\n}\n\n.apexcharts-canvas .apexcharts-zoom-icon.selected svg, \n.apexcharts-canvas .apexcharts-selection-icon.selected svg, \n.apexcharts-canvas .apexcharts-reset-zoom-icon.selected svg {\n fill: #008FFB;\n}\n.light .apexcharts-selection-icon:not(.selected):hover svg,\n.light .apexcharts-zoom-icon:not(.selected):hover svg, \n.light .apexcharts-zoom-in-icon:hover svg, \n.light .apexcharts-zoom-out-icon:hover svg, \n.light .apexcharts-reset-zoom-icon:hover svg, \n.light .apexcharts-menu-icon:hover svg {\n fill: #333;\n}\n\n.apexcharts-selection-icon, .apexcharts-menu-icon {\n position: relative;\n}\n.apexcharts-reset-zoom-icon {\n margin-left: 5px;\n}\n.apexcharts-zoom-icon, .apexcharts-reset-zoom-icon, .apexcharts-menu-icon {\n transform: scale(0.85);\n}\n\n.apexcharts-zoom-in-icon, .apexcharts-zoom-out-icon {\n transform: scale(0.7)\n}\n\n.apexcharts-zoom-out-icon {\n margin-right: 3px;\n}\n\n.apexcharts-pan-icon {\n transform: scale(0.62);\n position: relative;\n left: 1px;\n top: 0px;\n}\n.apexcharts-pan-icon svg {\n fill: #fff;\n stroke: #6E8192;\n stroke-width: 2;\n}\n.apexcharts-pan-icon.selected svg {\n stroke: #008FFB;\n}\n.apexcharts-pan-icon:not(.selected):hover svg {\n stroke: #333;\n}\n\n.apexcharts-toolbar {\n position: absolute;\n z-index: 11;\n top: 0px;\n right: 3px;\n max-width: 176px;\n text-align: right;\n border-radius: 3px;\n padding: 0px 6px 2px 6px;\n display: flex;\n justify-content: space-between;\n align-items: center; \n}\n\n.apexcharts-toolbar svg {\n pointer-events: none;\n}\n\n.apexcharts-menu {\n background: #fff;\n position: absolute;\n top: 100%;\n border: 1px solid #ddd;\n border-radius: 3px;\n padding: 3px;\n right: 10px;\n opacity: 0;\n min-width: 110px;\n transition: 0.15s ease all;\n pointer-events: none;\n}\n\n.apexcharts-menu.open {\n opacity: 1;\n pointer-events: all;\n transition: 0.15s ease all;\n}\n\n.apexcharts-menu-item {\n padding: 6px 7px;\n font-size: 12px;\n cursor: pointer;\n}\n.light .apexcharts-menu-item:hover {\n background: #eee;\n}\n.dark .apexcharts-menu {\n background: rgba(0, 0, 0, 0.7);\n color: #fff;\n}\n\n@media screen and (min-width: 768px) {\n .apexcharts-toolbar {\n /*opacity: 0;*/\n }\n\n .apexcharts-canvas:hover .apexcharts-toolbar {\n opacity: 1;\n } \n}\n\n.apexcharts-datalabel.hidden {\n opacity: 0;\n}\n\n.apexcharts-pie-label,\n.apexcharts-datalabel, .apexcharts-datalabel-label, .apexcharts-datalabel-value {\n cursor: default;\n pointer-events: none;\n}\n\n.apexcharts-pie-label-delay {\n opacity: 0;\n animation-name: opaque;\n animation-duration: 0.3s;\n animation-fill-mode: forwards;\n animation-timing-function: ease;\n}\n\n.apexcharts-canvas .hidden {\n opacity: 0;\n}\n\n.apexcharts-hide .apexcharts-series-points {\n opacity: 0;\n}\n\n.apexcharts-area-series .apexcharts-series-markers .apexcharts-marker.no-pointer-events,\n.apexcharts-line-series .apexcharts-series-markers .apexcharts-marker.no-pointer-events, .apexcharts-radar-series path, .apexcharts-radar-series polygon {\n pointer-events: none;\n}\n\n/* markers */\n\n.apexcharts-marker {\n transition: 0.15s ease all;\n}\n\n@keyframes opaque {\n 0% {\n opacity: 0;\n }\n 100% {\n opacity: 1;\n }\n}"; styleInject(css); /* * classList.js: Cross-browser full element.classList implementation. * 1.2.20171210 * * By Eli Grey, http://eligrey.com * License: Dedicated to the public domain. * See https://github.com/eligrey/classList.js/blob/master/LICENSE.md */ /*global self, document, DOMException */ /*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js */ if ("document" in self) { // Full polyfill for browsers with no classList support // Including IE < Edge missing SVGElement.classList if (!("classList" in document.createElement("_")) || document.createElementNS && !("classList" in document.createElementNS("http://www.w3.org/2000/svg", "g"))) { (function (view) { if (!('Element' in view)) return; var classListProp = "classList", protoProp = "prototype", elemCtrProto = view.Element[protoProp], objCtr = Object, strTrim = String[protoProp].trim || function () { return this.replace(/^\s+|\s+$/g, ""); }, arrIndexOf = Array[protoProp].indexOf || function (item) { var i = 0, len = this.length; for (; i < len; i++) { if (i in this && this[i] === item) { return i; } } return -1; } // Vendors: please allow content code to instantiate DOMExceptions , DOMEx = function DOMEx(type, message) { this.name = type; this.code = DOMException[type]; this.message = message; }, checkTokenAndGetIndex = function checkTokenAndGetIndex(classList, token) { if (token === "") { throw new DOMEx("SYNTAX_ERR", "The token must not be empty."); } if (/\s/.test(token)) { throw new DOMEx("INVALID_CHARACTER_ERR", "The token must not contain space characters."); } return arrIndexOf.call(classList, token); }, ClassList = function ClassList(elem) { var trimmedClasses = strTrim.call(elem.getAttribute("class") || ""), classes = trimmedClasses ? trimmedClasses.split(/\s+/) : [], i = 0, len = classes.length; for (; i < len; i++) { this.push(classes[i]); } this._updateClassName = function () { elem.setAttribute("class", this.toString()); }; }, classListProto = ClassList[protoProp] = [], classListGetter = function classListGetter() { return new ClassList(this); }; // Most DOMException implementations don't allow calling DOMException's toString() // on non-DOMExceptions. Error's toString() is sufficient here. DOMEx[protoProp] = Error[protoProp]; classListProto.item = function (i) { return this[i] || null; }; classListProto.contains = function (token) { return ~checkTokenAndGetIndex(this, token + ""); }; classListProto.add = function () { var tokens = arguments, i = 0, l = tokens.length, token, updated = false; do { token = tokens[i] + ""; if (!~checkTokenAndGetIndex(this, token)) { this.push(token); updated = true; } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.remove = function () { var tokens = arguments, i = 0, l = tokens.length, token, updated = false, index; do { token = tokens[i] + ""; index = checkTokenAndGetIndex(this, token); while (~index) { this.splice(index, 1); updated = true; index = checkTokenAndGetIndex(this, token); } } while (++i < l); if (updated) { this._updateClassName(); } }; classListProto.toggle = function (token, force) { var result = this.contains(token), method = result ? force !== true && "remove" : force !== false && "add"; if (method) { this[method](token); } if (force === true || force === false) { return force; } else { return !result; } }; classListProto.replace = function (token, replacement_token) { var index = checkTokenAndGetIndex(token + ""); if (~index) { this.splice(index, 1, replacement_token); this._updateClassName(); } }; classListProto.toString = function () { return this.join(" "); }; if (objCtr.defineProperty) { var classListPropDesc = { get: classListGetter, enumerable: true, configurable: true }; try { objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } catch (ex) { // IE 8 doesn't support enumerable:true // adding undefined to fight this issue https://github.com/eligrey/classList.js/issues/36 // modernie IE8-MSW7 machine has IE8 8.0.6001.18702 and is affected if (ex.number === undefined || ex.number === -0x7FF5EC54) { classListPropDesc.enumerable = false; objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc); } } } else if (objCtr[protoProp].__defineGetter__) { elemCtrProto.__defineGetter__(classListProp, classListGetter); } })(self); } // There is full or partial native classList support, so just check if we need // to normalize the add/remove and toggle APIs. (function () { var testElement = document.createElement("_"); testElement.classList.add("c1", "c2"); // Polyfill for IE 10/11 and Firefox <26, where classList.add and // classList.remove exist but support only one argument at a time. if (!testElement.classList.contains("c2")) { var createMethod = function createMethod(method) { var original = DOMTokenList.prototype[method]; DOMTokenList.prototype[method] = function (token) { var i, len = arguments.length; for (i = 0; i < len; i++) { token = arguments[i]; original.call(this, token); } }; }; createMethod('add'); createMethod('remove'); } testElement.classList.toggle("c3", false); // Polyfill for IE 10 and Firefox <24, where classList.toggle does not // support the second argument. if (testElement.classList.contains("c3")) { var _toggle = DOMTokenList.prototype.toggle; DOMTokenList.prototype.toggle = function (token, force) { if (1 in arguments && !this.contains(token) === !force) { return force; } else { return _toggle.call(this, token); } }; } // replace() polyfill if (!("replace" in document.createElement("_").classList)) { DOMTokenList.prototype.replace = function (token, replacement_token) { var tokens = this.toString().split(" "), index = tokens.indexOf(token + ""); if (~index) { tokens = tokens.slice(index); this.remove.apply(this, tokens); this.add(replacement_token); this.add.apply(this, tokens.slice(1)); } }; } testElement = null; })(); } /** * Detect Element Resize * * https://github.com/sdecima/javascript-detect-element-resize * Sebastian Decima * * version: 0.5.3 **/ (function () { var stylesCreated = false; function resetTriggers(element) { var triggers = element.__resizeTriggers__, expand = triggers.firstElementChild, contract = triggers.lastElementChild, expandChild = expand.firstElementChild; contract.scrollLeft = contract.scrollWidth; contract.scrollTop = contract.scrollHeight; expandChild.style.width = expand.offsetWidth + 1 + 'px'; expandChild.style.height = expand.offsetHeight + 1 + 'px'; expand.scrollLeft = expand.scrollWidth; expand.scrollTop = expand.scrollHeight; } function checkTriggers(element) { return element.offsetWidth != element.__resizeLast__.width || element.offsetHeight != element.__resizeLast__.height; } function scrollListener(e) { var element = this; resetTriggers(this); if (this.__resizeRAF__) cancelFrame(this.__resizeRAF__); this.__resizeRAF__ = requestFrame(function () { if (checkTriggers(element)) { element.__resizeLast__.width = element.offsetWidth; element.__resizeLast__.height = element.offsetHeight; element.__resizeListeners__.forEach(function (fn) { fn.call(e); }); } }); } function createStyles() { if (!stylesCreated) { // opacity:0 works around a chrome bug https://code.google.com/p/chromium/issues/detail?id=286360 var css = (animationKeyframes || '') + '.resize-triggers { ' + (animationStyle || '') + 'visibility: hidden; opacity: 0; } ' + '.resize-triggers, .resize-triggers > div, .contract-trigger:before { content: \" \"; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }', head = document.head || document.getElementsByTagName('head')[0], style = document.createElement('style'); style.type = 'text/css'; if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.appendChild(document.createTextNode(css)); } head.appendChild(style); stylesCreated = true; } } var requestFrame = function () { var raf = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || function (fn) { return window.setTimeout(fn, 20); }; return function (fn) { return raf(fn); }; }(); var cancelFrame = function () { var cancel = window.cancelAnimationFrame || window.mozCancelAnimationFrame || window.webkitCancelAnimationFrame || window.clearTimeout; return function (id) { return cancel(id); }; }(); /* Detect CSS Animations support to detect element display/re-attach */ var animation = false, keyframeprefix = '', animationstartevent = 'animationstart', domPrefixes = 'Webkit Moz O ms'.split(' '), startEvents = 'webkitAnimationStart animationstart oAnimationStart MSAnimationStart'.split(' '), pfx = ''; { var elm = document.createElement('fakeelement'); if (elm.style.animationName !== undefined) { animation = true; } if (animation === false) { for (var i = 0; i < domPrefixes.length; i++) { if (elm.style[domPrefixes[i] + 'AnimationName'] !== undefined) { pfx = domPrefixes[i]; keyframeprefix = '-' + pfx.toLowerCase() + '-'; animationstartevent = startEvents[i]; break; } } } } var animationName = 'resizeanim'; var animationKeyframes = '@' + keyframeprefix + 'keyframes ' + animationName + ' { from { opacity: 0; } to { opacity: 0; } } '; var animationStyle = keyframeprefix + 'animation: 1ms ' + animationName + '; '; window.addResizeListener = function (element, fn) { if (!element.__resizeTriggers__) { if (getComputedStyle(element).position == 'static') element.style.position = 'relative'; createStyles(); element.__resizeLast__ = {}; element.__resizeListeners__ = []; (element.__resizeTriggers__ = document.createElement('div')).className = 'resize-triggers'; element.__resizeTriggers__.innerHTML = '<div class="expand-trigger"><div></div></div>' + '<div class="contract-trigger"></div>'; element.appendChild(element.__resizeTriggers__); resetTriggers(element); element.addEventListener('scroll', scrollListener, true); /* Listen for a css animation to detect element display/re-attach */ animationstartevent && element.__resizeTriggers__.addEventListener(animationstartevent, function (e) { if (e.animationName == animationName) { resetTriggers(element); } }); } element.__resizeListeners__.push(fn); }; window.removeResizeListener = function (element, fn) { if (element) { element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1); if (!element.__resizeListeners__.length) { element.removeEventListener('scroll', scrollListener); element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__); } } }; })(); window.Apex = {}; /** * * @module ApexCharts **/ var ApexCharts$1 = /*#__PURE__*/ function () { function ApexCharts(el, opts) { _classCallCheck(this, ApexCharts); this.opts = opts; this.ctx = this; // Pass the user supplied options to the Base Class where these options will be extended with defaults. The returned object from Base Class will become the config object in the entire codebase. this.w = new Base(opts).init(); this.el = el; this.w.globals.cuid = (Math.random() + 1).toString(36).substring(4); this.w.globals.chartID = this.w.config.chart.id ? this.w.config.chart.id : this.w.globals.cuid; this.initModules(); this.create = Utils.bind(this.create, this); this.windowResizeHandler = this.windowResize.bind(this); } /** * The primary method user will call to render the chart. */ _createClass(ApexCharts, [{ key: "render", value: function render() { var _this = this; // main method return new Promise$1(function (resolve, reject) { // only draw chart, if element found if (_this.el !== null) { if (typeof Apex._chartInstances === 'undefined') { Apex._chartInstances = []; } if (_this.w.config.chart.id) { Apex._chartInstances.push({ id: _this.w.globals.chartID, group: _this.w.config.chart.group, chart: _this }); } // set the locale here _this.setLocale(_this.w.config.chart.defaultLocale); var beforeMount = _this.w.config.chart.events.beforeMount; if (typeof beforeMount === 'function') { beforeMount(_this, _this.w); } _this.fireEvent('beforeMount', [_this, _this.w]); window.addEventListener('resize', _this.windowResizeHandler); window.addResizeListener(_this.el.parentNode, _this.parentResizeCallback.bind(_this)); var graphData = _this.create(_this.w.config.series, {}); if (!graphData) return resolve(_this); _this.mount(graphData).then(function () { resolve(graphData); if (typeof _this.w.config.chart.events.mounted === 'function') { _this.w.config.chart.events.mounted(_this, _this.w); } _this.fireEvent('mounted', [_this, _this.w]); }).catch(function (e) { reject(e); // handle error in case no data or element not found }); } else { reject(new Error('Element not found')); } }); } }, { key: "initModules", value: function initModules() { this.animations = new Animations(this); this.annotations = new Annotations(this); this.core = new Core(this.el, this); this.grid = new Grid(this); this.coreUtils = new CoreUtils(this); this.config = new Config({}); this.crosshairs = new Crosshairs(this); this.options = new Options(); this.responsive = new Responsive(this); this.series = new Series(this); this.theme = new Theme(this); this.formatters = new Formatters(this); this.titleSubtitle = new TitleSubtitle(this); this.legend = new Legend(this); this.toolbar = new Toolbar(this); this.dimensions = new Dimensions(this); this.zoomPanSelection = new ZoomPanSelection(this); this.w.globals.tooltip = new Tooltip(this); } }, { key: "addEventListener", value: function addEventListener(name$$1, handler) { var w = this.w; if (w.globals.events.hasOwnProperty(name$$1)) { w.globals.events[name$$1].push(handler); } else { w.globals.events[name$$1] = [handler]; } } }, { key: "removeEventListener", value: function removeEventListener(name$$1, handler) { var w = this.w; if (!w.globals.events.hasOwnProperty(name$$1)) { return; } var index = w.globals.events[name$$1].indexOf(handler); if (index !== -1) { w.globals.events[name$$1].splice(index, 1); } } }, { key: "fireEvent", value: function fireEvent(name$$1, args) { var w = this.w; if (!w.globals.events.hasOwnProperty(name$$1)) { return; } if (!args || !args.length) { args = []; } var evs = w.globals.events[name$$1]; var l = evs.length; for (var i = 0; i < l; i++) { evs[i].apply(null, args); } } }, { key: "create", value: function create(ser, opts) { var w = this.w; this.initModules(); var gl = this.w.globals; gl.noData = false; gl.animationEnded = false; this.responsive.checkResponsiveConfig(opts); if (this.el === null) { gl.animationEnded = true; return null; } this.core.setupElements(); if (gl.svgWidth === 0) { // if the element is hidden, skip drawing gl.animationEnded = true; return null; } var combo = CoreUtils.checkComboSeries(ser); gl.comboCharts = combo.comboCharts; gl.comboChartsHasBars = combo.comboChartsHasBars; if (ser.length === 0 || ser.length === 1 && ser[0].data && ser[0].data.length === 0) { this.series.handleNoData(); } this.setupEventHandlers(); // Handle the data inputted by user and set some of the global variables (for eg, if data is datetime / numeric / category). Don't calculate the range / min / max at this time this.core.parseData(ser); // this is a good time to set theme colors first this.theme.init(); // as markers accepts array, we need to setup global markers for easier access var markers = new Markers(this); markers.setGlobalMarkerSize(); // labelFormatters should be called before dimensions as in dimensions we need text labels width this.formatters.setLabelFormatters(); this.titleSubtitle.draw(); // legend is calculated here before coreCalculations because it affects the plottable area this.legend.init(); // check whether in multiple series, all series share the same X this.series.hasAllSeriesEqualX(); // coreCalculations will give the min/max range and yaxis/axis values. It should be called here to set series variable from config to globals if (gl.axisCharts) { this.core.coreCalculations(); if (w.config.xaxis.type !== 'category') { // as we have minX and maxX values, determine the default DateTimeFormat for time series this.formatters.setLabelFormatters(); } } // we need to generate yaxis for heatmap separately as we are not showing numerics there, but seriesNames. There are some tweaks which are required for heatmap to align labels correctly which are done in below function // Also we need to do this before calcuting Dimentions plotCoords() method of Dimensions this.formatters.heatmapLabelFormatters(); // We got plottable area here, next task would be to calculate axis areas this.dimensions.plotCoords(); var xyRatios = this.core.xySettings(); this.grid.createGridMask(); var elGraph = this.core.plotChartType(ser, xyRatios); // after all the drawing calculations, shift the graphical area (actual charts/bars) excluding legends this.core.shiftGraphPosition(); var dim = { plot: { left: w.globals.translateX, top: w.globals.translateY, width: w.globals.gridWidth, height: w.globals.gridHeight } }; return { elGraph: elGraph, xyRatios: xyRatios, elInner: w.globals.dom.elGraphical, dimensions: dim }; } }, { key: "mount", value: function mount() { var graphData = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; var me = this; var w = me.w; return new Promise$1(function (resolve, reject) { // no data to display if (me.el === null) { return reject(new Error('Not enough data to display or target element not found')); } else if (graphData === null || w.globals.allSeriesCollapsed) { me.series.handleNoData(); } me.core.drawAxis(w.config.chart.type, graphData.xyRatios); me.grid = new Grid(me); if (w.config.grid.position === 'back') { me.grid.drawGrid(); } if (w.config.annotations.position === 'back') { me.annotations.drawAnnotations(); } if (graphData.elGraph instanceof Array) { for (var g = 0; g < graphData.elGraph.length; g++) { w.globals.dom.elGraphical.add(graphData.elGraph[g]); } } else { w.globals.dom.elGraphical.add(graphData.elGraph); } if (w.config.grid.position === 'front') { me.grid.drawGrid(); } if (w.config.xaxis.crosshairs.position === 'front') { me.crosshairs.drawXCrosshairs(); } if (w.config.yaxis[0].crosshairs.position === 'front') { me.crosshairs.drawYCrosshairs(); } if (w.config.annotations.position === 'front') { me.annotations.drawAnnotations(); } if (!w.globals.noData) { // draw tooltips at the end if (w.config.tooltip.enabled && !w.globals.noData) { me.w.globals.tooltip.drawTooltip(graphData.xyRatios); } if (w.globals.axisCharts && w.globals.isXNumeric) { if (w.config.chart.zoom.enabled || w.config.chart.selection && w.config.chart.selection.enabled || w.config.chart.pan && w.config.chart.pan.enabled) { me.zoomPanSelection.init({ xyRatios: graphData.xyRatios }); } } else { var tools = w.config.chart.toolbar.tools; tools.zoom = false; tools.zoomin = false; tools.zoomout = false; tools.selection = false; tools.pan = false; tools.reset = false; } if (w.config.chart.toolbar.show && !w.globals.allSeriesCollapsed) { me.toolbar.createToolbar(); } } if (w.globals.memory.methodsToExec.length > 0) { w.globals.memory.methodsToExec.forEach(function (fn) { fn.method(fn.params, false, fn.context); }); } resolve(me); }); } }, { key: "clearPreviousPaths", value: function clearPreviousPaths() { var w = this.w; w.globals.previousPaths = []; w.globals.allSeriesCollapsed = false; w.globals.collapsedSeries = []; w.globals.collapsedSeriesIndices = []; } /** * Allows users to update Options after the chart has rendered. * * @param {object} options - A new config object can be passed which will be merged with the existing config object * @param {boolean} redraw - should redraw from beginning or should use existing paths and redraw from there * @param {boolean} animate - should animate or not on updating Options */ }, { key: "updateOptions", value: function updateOptions(options$$1) { var redraw = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var animate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var overwriteInitialConfig = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; var w = this.w; if (options$$1.series) { if (options$$1.series[0].data) { options$$1.series = options$$1.series.map(function (s, i) { return _objectSpread({}, w.config.series[i], { name: s.name ? s.name : w.config.series[i] && w.config.series[i].name, type: s.type ? s.type : w.config.series[i] && w.config.series[i].type, data: s.data ? s.data : w.config.series[i] && w.config.series[i].data }); }); } // user updated the series via updateOptions() function. // Hence, we need to reset axis min/max to avoid zooming issues this.revertDefaultAxisMinMax(); } // user has set x-axis min/max externally - hence we need to forcefully set the xaxis min/max if (options$$1.xaxis) { if (options$$1.xaxis.min || options$$1.xaxis.max) { this.forceXAxisUpdate(options$$1); } /* fixes apexcharts.js#369 and react-apexcharts#46 */ if (options$$1.xaxis.categories && options$$1.xaxis.categories.length && w.config.xaxis.convertedCatToNumeric) { options$$1 = Defaults.convertCatToNumeric(options$$1); } } if (w.globals.collapsedSeriesIndices.length > 0) { this.clearPreviousPaths(); } /* update theme mode#459 */ if (options$$1.theme) { options$$1 = this.theme.updateThemeOptions(options$$1); } return this._updateOptions(options$$1, redraw, animate, overwriteInitialConfig); } /** * private method to update Options. * * @param {object} options - A new config object can be passed which will be merged with the existing config object * @param {boolean} redraw - should redraw from beginning or should use existing paths and redraw from there * @param {boolean} animate - should animate or not on updating Options * @param {boolean} overwriteInitialConfig - should update the initial config or not */ }, { key: "_updateOptions", value: function _updateOptions(options$$1) { var redraw = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var animate = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var overwriteInitialConfig = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var charts = this.getSyncedCharts(); charts.forEach(function (ch) { var w = ch.w; w.globals.shouldAnimate = animate; if (!redraw) { w.globals.resized = true; w.globals.dataChanged = true; if (animate) { ch.series.getPreviousPaths(); } } if (options$$1 && _typeof(options$$1) === 'object') { ch.config = new Config(options$$1); options$$1 = CoreUtils.extendArrayProps(ch.config, options$$1); w.config = Utils.extend(w.config, options$$1); if (overwriteInitialConfig) { // we need to forget the lastXAxis and lastYAxis is user forcefully overwriteInitialConfig. If we do not do this, and next time when user zooms the chart after setting yaxis.min/max or xaxis.min/max - the stored lastXAxis will never allow the chart to use the updated min/max by user. w.globals.lastXAxis = []; w.globals.lastYAxis = []; // After forgetting lastAxes, we need to restore the new config in initialConfig/initialSeries w.globals.initialConfig = Utils.extend({}, w.config); w.globals.initialSeries = JSON.parse(JSON.stringify(w.config.series)); } } return ch.update(options$$1); }); } /** * Allows users to update Series after the chart has rendered. * * @param {array} series - New series which will override the existing */ }, { key: "updateSeries", value: function updateSeries() { var newSeries = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var animate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var overwriteInitialSeries = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; this.revertDefaultAxisMinMax(); return this._updateSeries(newSeries, animate, overwriteInitialSeries); } /** * Allows users to append a new series after the chart has rendered. * * @param {array} newSerie - New serie which will be appended to the existing series */ }, { key: "appendSeries", value: function appendSeries(newSerie) { var animate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var overwriteInitialSeries = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true; var newSeries = this.w.config.series.slice(); newSeries.push(newSerie); this.revertDefaultAxisMinMax(); return this._updateSeries(newSeries, animate, overwriteInitialSeries); } /** * Private method to update Series. * * @param {array} series - New series which will override the existing */ }, { key: "_updateSeries", value: function _updateSeries(newSeries, animate) { var overwriteInitialSeries = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var w = this.w; this.w.globals.shouldAnimate = animate; w.globals.dataChanged = true; // if user has collapsed some series with legend, we need to clear those if (w.globals.allSeriesCollapsed) { w.globals.allSeriesCollapsed = false; } if (animate) { this.series.getPreviousPaths(); } var existingSeries; // axis charts if (w.globals.axisCharts) { existingSeries = newSeries.map(function (s, i) { return _objectSpread({}, w.config.series[i], { name: s.name ? s.name : w.config.series[i] && w.config.series[i].name, type: s.type ? s.type : w.config.series[i] && w.config.series[i].type, data: s.data ? s.data : w.config.series[i] && w.config.series[i].data }); }); if (existingSeries.length === 0) { existingSeries = [{ data: [] }]; } w.config.series = existingSeries; } else { // non-axis chart (pie/radialbar) w.config.series = newSeries.slice(); } if (overwriteInitialSeries) { w.globals.initialConfig.series = JSON.parse(JSON.stringify(w.config.series)); w.globals.initialSeries = JSON.parse(JSON.stringify(w.config.series)); } return this.update(); } /** * Get all charts in the same "group" (including the instance which is called upon) to sync them when user zooms in/out or pan. */ }, { key: "getSyncedCharts", value: function getSyncedCharts() { var chartGroups = this.getGroupedCharts(); var allCharts = [this]; if (chartGroups.length) { allCharts = []; chartGroups.forEach(function (ch) { allCharts.push(ch); }); } return allCharts; } /** * Get charts in the same "group" (excluding the instance which is called upon) to perform operations on the other charts of the same group (eg., tooltip hovering) */ }, { key: "getGroupedCharts", value: function getGroupedCharts() { var _this2 = this; return Apex._chartInstances.filter(function (ch) { if (ch.group) { return true; } }).map(function (ch) { return _this2.w.config.chart.group === ch.group ? ch.chart : _this2; }); } /** * Allows users to append Data to series. * * @param {array} newData - New data in the same format as series */ }, { key: "appendData", value: function appendData(newData) { var overwriteInitialSeries = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var me = this; me.w.globals.dataChanged = true; me.series.getPreviousPaths(); var newSeries = me.w.config.series.slice(); for (var i = 0; i < newSeries.length; i++) { if (typeof newData[i] !== 'undefined') { for (var j = 0; j < newData[i].data.length; j++) { newSeries[i].data.push(newData[i].data[j]); } } } me.w.config.series = newSeries; if (overwriteInitialSeries) { me.w.globals.initialSeries = JSON.parse(JSON.stringify(me.w.config.series)); } return this.update(); } }, { key: "update", value: function update(options$$1) { var _this3 = this; return new Promise$1(function (resolve, reject) { _this3.clear(); var graphData = _this3.create(_this3.w.config.series, options$$1); if (!graphData) return resolve(_this3); _this3.mount(graphData).then(function () { if (typeof _this3.w.config.chart.events.updated === 'function') { _this3.w.config.chart.events.updated(_this3, _this3.w); } _this3.fireEvent('updated', [_this3, _this3.w]); _this3.w.globals.isDirty = true; resolve(_this3); }).catch(function (e) { reject(e); }); }); } }, { key: "forceXAxisUpdate", value: function forceXAxisUpdate(options$$1) { var w = this.w; if (typeof options$$1.xaxis.min !== 'undefined') { w.config.xaxis.min = options$$1.xaxis.min; w.globals.lastXAxis.min = options$$1.xaxis.min; } if (typeof options$$1.xaxis.max !== 'undefined') { w.config.xaxis.max = options$$1.xaxis.max; w.globals.lastXAxis.max = options$$1.xaxis.max; } } /** * This function reverts the yaxis and xaxis min/max values to what it was when the chart was defined. * This function fixes an important bug where a user might load a new series after zooming in/out of previous series which resulted in wrong min/max * Also, this should never be called internally on zoom/pan - the reset should only happen when user calls the updateSeries() function externally */ }, { key: "revertDefaultAxisMinMax", value: function revertDefaultAxisMinMax() { var w = this.w; w.config.xaxis.min = w.globals.lastXAxis.min; w.config.xaxis.max = w.globals.lastXAxis.max; w.config.yaxis.map(function (yaxe, index) { if (w.globals.zoomed) { // if user has zoomed, and this function is called // then we need to get the lastAxis min and max if (typeof w.globals.lastYAxis[index] !== 'undefined') { yaxe.min = w.globals.lastYAxis[index].min; yaxe.max = w.globals.lastYAxis[index].max; } } }); } }, { key: "clear", value: function clear() { if (this.zoomPanSelection) { this.zoomPanSelection.destroy(); } if (this.toolbar) { this.toolbar.destroy(); } this.animations = null; this.annotations = null; this.core = null; this.grid = null; this.series = null; this.responsive = null; this.theme = null; this.formatters = null; this.titleSubtitle = null; this.legend = null; this.dimensions = null; this.options = null; this.crosshairs = null; this.zoomPanSelection = null; this.toolbar = null; this.w.globals.tooltip = null; this.clearDomElements(); } }, { key: "killSVG", value: function killSVG(draw) { return new Promise$1(function (resolve, reject) { draw.each(function (i, children) { this.removeClass('*'); this.off(); this.stop(); }, true); draw.ungroup(); draw.clear(); resolve('done'); }); } }, { key: "clearDomElements", value: function clearDomElements() { var domEls = this.w.globals.dom; if (this.el !== null) { // remove all child elements - resetting the whole chart while (this.el.firstChild) { this.el.removeChild(this.el.firstChild); } } this.killSVG(domEls.Paper); domEls.Paper.remove(); domEls.elWrap = null; domEls.elGraphical = null; domEls.elLegendWrap = null; domEls.baseEl = null; domEls.elGridRect = null; domEls.elGridRectMask = null; domEls.elGridRectMarkerMask = null; domEls.elDefs = null; } /** * Destroy the chart instance by removing all elements which also clean up event listeners on those elements. */ }, { key: "destroy", value: function destroy() { this.clear(); // remove the chart's instance from the global Apex._chartInstances var chartID = this.w.config.chart.id; if (chartID) { Apex._chartInstances.forEach(function (c, i) { if (c.id === chartID) { Apex._chartInstances.splice(i, 1); } }); } window.removeEventListener('resize', this.windowResizeHandler); window.removeResizeListener(this.el.parentNode, this.parentResizeCallback.bind(this)); } /** * Allows the user to provide data attrs in the element and the chart will render automatically when this method is called by searching for the elements containing 'data-apexcharts' attribute */ }, { key: "toggleSeries", value: function toggleSeries(seriesName) { var targetElement = this.series.getSeriesByName(seriesName); var seriesCnt = parseInt(targetElement.getAttribute('data:realIndex')); var isHidden = targetElement.classList.contains('apexcharts-series-collapsed'); this.legend.toggleDataSeries(seriesCnt, isHidden); } }, { key: "resetToggleSeries", value: function resetToggleSeries() { this.legend.resetToggleDataSeries(); } }, { key: "setupEventHandlers", value: function setupEventHandlers() { var w = this.w; var me = this; var clickableArea = w.globals.dom.baseEl.querySelector(w.globals.chartClass); var eventList = ['mousedown', 'mousemove', 'touchstart', 'touchmove', 'mouseup', 'touchend']; eventList.forEach(function (event) { clickableArea.addEventListener(event, function (e) { if (e.type === 'mousedown' && e.which === 1) ; else if (e.type === 'mouseup' && e.which === 1 || e.type === 'touchend') { if (typeof w.config.chart.events.click === 'function') { w.config.chart.events.click(e, me, w); } me.fireEvent('click', [e, me, w]); } }, { capture: false, passive: true }); }); eventList.forEach(function (event) { document.addEventListener(event, function (e) { w.globals.clientX = e.type === 'touchmove' ? e.touches[0].clientX : e.clientX; w.globals.clientY = e.type === 'touchmove' ? e.touches[0].clientY : e.clientY; }); }); this.core.setupBrushHandler(); } }, { key: "addXaxisAnnotation", value: function addXaxisAnnotation(opts) { var pushToMemory = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var me = this; if (context) { me = context; } me.annotations.addXaxisAnnotationExternal(opts, pushToMemory, me); } }, { key: "addYaxisAnnotation", value: function addYaxisAnnotation(opts) { var pushToMemory = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var me = this; if (context) { me = context; } me.annotations.addYaxisAnnotationExternal(opts, pushToMemory, me); } }, { key: "addPointAnnotation", value: function addPointAnnotation(opts) { var pushToMemory = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var me = this; if (context) { me = context; } me.annotations.addPointAnnotationExternal(opts, pushToMemory, me); } }, { key: "clearAnnotations", value: function clearAnnotations() { var context = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; var me = this; if (context) { me = context; } me.annotations.clearAnnotations(me); } // This method is never used internally and will be only called externally on the chart instance. // Hence, we need to keep all these elements in memory when the chart gets updated and redraw again }, { key: "addText", value: function addText(options$$1) { var pushToMemory = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true; var context = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var me = this; if (context) { me = context; } me.annotations.addText(options$$1, pushToMemory, me); } }, { key: "getChartArea", value: function getChartArea() { var el = this.w.globals.dom.baseEl.querySelector('.apexcharts-inner'); return el; } }, { key: "getSeriesTotalXRange", value: function getSeriesTotalXRange(minX, maxX) { return this.coreUtils.getSeriesTotalsXRange(minX, maxX); } }, { key: "getHighestValueInSeries", value: function getHighestValueInSeries() { var seriesIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var range = new Range$1(this.ctx); var minYmaxY = range.getMinYMaxY(seriesIndex); return minYmaxY.highestY; } }, { key: "getLowestValueInSeries", value: function getLowestValueInSeries() { var seriesIndex = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0; var range = new Range$1(this.ctx); var minYmaxY = range.getMinYMaxY(seriesIndex); return minYmaxY.lowestY; } }, { key: "getSeriesTotal", value: function getSeriesTotal() { return this.w.globals.seriesTotals; } }, { key: "setLocale", value: function setLocale(localeName) { this.setCurrentLocaleValues(localeName); } }, { key: "setCurrentLocaleValues", value: function setCurrentLocaleValues(localeName) { var locales = this.w.config.chart.locales; // check if user has specified locales in global Apex variable // if yes - then extend those with local chart's locale if (window.Apex.chart && window.Apex.chart.locales && window.Apex.chart.locales.length > 0) { locales = this.w.config.chart.locales.concat(window.Apex.chart.locales); } // find the locale from the array of locales which user has set (either by chart.defaultLocale or by calling setLocale() method.) var selectedLocale = locales.filter(function (c) { return c.name === localeName; })[0]; if (selectedLocale) { // create a complete locale object by extending defaults so you don't get undefined errors. var ret = Utils.extend(en, selectedLocale); // store these locale options in global var for ease access this.w.globals.locale = ret.options; } else { throw new Error('Wrong locale name provided. Please make sure you set the correct locale name in options'); } } }, { key: "dataURI", value: function dataURI() { var exp = new Exports(this.ctx); return exp.dataURI(); } }, { key: "paper", value: function paper() { return this.w.globals.dom.Paper; } }, { key: "parentResizeCallback", value: function parentResizeCallback() { if (this.w.globals.animationEnded) { this.windowResize(); } } /** * Handle window resize and re-draw the whole chart. */ }, { key: "windowResize", value: function windowResize() { var _this4 = this; clearTimeout(this.w.globals.resizeTimer); this.w.globals.resizeTimer = window.setTimeout(function () { _this4.w.globals.resized = true; _this4.w.globals.dataChanged = false; // we need to redraw the whole chart on window resize (with a small delay). _this4.update(); }, 150); } }], [{ key: "initOnLoad", value: function initOnLoad() { var els = document.querySelectorAll('[data-apexcharts]'); for (var i = 0; i < els.length; i++) { var el = els[i]; var options$$1 = JSON.parse(els[i].getAttribute('data-options')); var apexChart = new ApexCharts(el, options$$1); apexChart.render(); } } /** * This static method allows users to call chart methods without necessarily from the * instance of the chart in case user has assigned chartID to the targetted chart. * The chartID is used for mapping the instance stored in Apex._chartInstances global variable * * This is helpful in cases when you don't have reference of the chart instance * easily and need to call the method from anywhere. * For eg, in React/Vue applications when you have many parent/child components, * and need easy reference to other charts for performing dynamic operations * * @param {string} chartID - The unique identifier which will be used to call methods * on that chart instance * @param {function} fn - The method name to call * @param {object} opts - The parameters which are accepted in the original method will be passed here in the same order. */ }, { key: "exec", value: function exec(chartID, fn) { var chart = this.getChartByID(chartID); if (!chart) return; for (var _len = arguments.length, opts = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { opts[_key - 2] = arguments[_key]; } switch (fn) { case 'updateOptions': { return chart.updateOptions.apply(chart, opts); } case 'updateSeries': { return chart.updateSeries.apply(chart, opts); } case 'appendData': { return chart.appendData.apply(chart, opts); } case 'appendSeries': { return chart.appendSeries.apply(chart, opts); } case 'toggleSeries': { return chart.toggleSeries.apply(chart, opts); } case 'dataURI': { return chart.dataURI.apply(chart, opts); } case 'addXaxisAnnotation': { return chart.addXaxisAnnotation.apply(chart, opts); } case 'addYaxisAnnotation': { return chart.addYaxisAnnotation.apply(chart, opts); } case 'addPointAnnotation': { return chart.addPointAnnotation.apply(chart, opts); } case 'addText': { return chart.addText.apply(chart, opts); } case 'clearAnnotations': { return chart.clearAnnotations.apply(chart, opts); } case 'paper': { return chart.paper.apply(chart, opts); } case 'destroy': { return chart.destroy(); } } } }, { key: "merge", value: function merge(target, source) { return Utils.extend(target, source); } }, { key: "getChartByID", value: function getChartByID(chartID) { var c = Apex._chartInstances.filter(function (ch) { return ch.id === chartID; })[0]; return c.chart; } }]); return ApexCharts; }(); return ApexCharts$1; }));
packages/material/src/components/FlatFieldset.js
wq/wq.app
import React from 'react'; import Typography from '@material-ui/core/Typography'; import PropTypes from 'prop-types'; export default function FlatFieldset({ label, children }) { return ( <> <Typography color="textSecondary">{label}</Typography> {children} </> ); } FlatFieldset.propTypes = { label: PropTypes.string, children: PropTypes.node };
site/src/components/Stack.js
sapegin/react-styleguidist
import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import styles from './Stack.module.css'; export const Stack = ({ children, gap, className, as: Component = 'div', ...rest }) => ( <Component className={clsx(styles.stack, styles[`stack--${gap}`], className)} {...rest}> {children} </Component> ); Stack.propTypes = { children: PropTypes.node.isRequired, gap: PropTypes.oneOf(['xxs', 'xs', 's', 'm', 'l', 'xl']).isRequired, className: PropTypes.string, as: PropTypes.string, };
ajax/libs/phaser/2.0.7/custom/p2.js
chrillep/cdnjs
/** * The MIT License (MIT) * * Copyright (c) 2013 p2.js authors * * 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(e){"object"==typeof exports?module.exports=e():"function"==typeof define&&define.amd?define('p2', (function() { return this.p2 = e(); })()):"undefined"!=typeof window?window.p2=e():"undefined"!=typeof global?self.p2=e():"undefined"!=typeof self&&(self.p2=e())}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ /* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ if(!GLMAT_EPSILON) { var GLMAT_EPSILON = 0.000001; } if(!GLMAT_ARRAY_TYPE) { var GLMAT_ARRAY_TYPE = (typeof Float32Array !== 'undefined') ? Float32Array : Array; } /** * @class Common utilities * @name glMatrix */ var glMatrix = {}; /** * Sets the type of array used when creating new vectors and matricies * * @param {Type} type Array type, such as Float32Array or Array */ glMatrix.setMatrixArrayType = function(type) { GLMAT_ARRAY_TYPE = type; } if(typeof(exports) !== 'undefined') { exports.glMatrix = glMatrix; } /* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @class 2 Dimensional Vector * @name vec2 */ var vec2 = {}; /** * Creates a new, empty vec2 * * @returns {vec2} a new 2D vector */ vec2.create = function() { var out = new GLMAT_ARRAY_TYPE(2); out[0] = 0; out[1] = 0; return out; }; /** * Creates a new vec2 initialized with values from an existing vector * * @param {vec2} a vector to clone * @returns {vec2} a new 2D vector */ vec2.clone = function(a) { var out = new GLMAT_ARRAY_TYPE(2); out[0] = a[0]; out[1] = a[1]; return out; }; /** * Creates a new vec2 initialized with the given values * * @param {Number} x X component * @param {Number} y Y component * @returns {vec2} a new 2D vector */ vec2.fromValues = function(x, y) { var out = new GLMAT_ARRAY_TYPE(2); out[0] = x; out[1] = y; return out; }; /** * Copy the values from one vec2 to another * * @param {vec2} out the receiving vector * @param {vec2} a the source vector * @returns {vec2} out */ vec2.copy = function(out, a) { out[0] = a[0]; out[1] = a[1]; return out; }; /** * Set the components of a vec2 to the given values * * @param {vec2} out the receiving vector * @param {Number} x X component * @param {Number} y Y component * @returns {vec2} out */ vec2.set = function(out, x, y) { out[0] = x; out[1] = y; return out; }; /** * Adds two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ vec2.add = function(out, a, b) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; return out; }; /** * Subtracts two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ vec2.subtract = function(out, a, b) { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; return out; }; /** * Alias for {@link vec2.subtract} * @function */ vec2.sub = vec2.subtract; /** * Multiplies two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ vec2.multiply = function(out, a, b) { out[0] = a[0] * b[0]; out[1] = a[1] * b[1]; return out; }; /** * Alias for {@link vec2.multiply} * @function */ vec2.mul = vec2.multiply; /** * Divides two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ vec2.divide = function(out, a, b) { out[0] = a[0] / b[0]; out[1] = a[1] / b[1]; return out; }; /** * Alias for {@link vec2.divide} * @function */ vec2.div = vec2.divide; /** * Returns the minimum of two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ vec2.min = function(out, a, b) { out[0] = Math.min(a[0], b[0]); out[1] = Math.min(a[1], b[1]); return out; }; /** * Returns the maximum of two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ vec2.max = function(out, a, b) { out[0] = Math.max(a[0], b[0]); out[1] = Math.max(a[1], b[1]); return out; }; /** * Scales a vec2 by a scalar number * * @param {vec2} out the receiving vector * @param {vec2} a the vector to scale * @param {Number} b amount to scale the vector by * @returns {vec2} out */ vec2.scale = function(out, a, b) { out[0] = a[0] * b; out[1] = a[1] * b; return out; }; /** * Calculates the euclidian distance between two vec2's * * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {Number} distance between a and b */ vec2.distance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return Math.sqrt(x*x + y*y); }; /** * Alias for {@link vec2.distance} * @function */ vec2.dist = vec2.distance; /** * Calculates the squared euclidian distance between two vec2's * * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {Number} squared distance between a and b */ vec2.squaredDistance = function(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return x*x + y*y; }; /** * Alias for {@link vec2.squaredDistance} * @function */ vec2.sqrDist = vec2.squaredDistance; /** * Calculates the length of a vec2 * * @param {vec2} a vector to calculate length of * @returns {Number} length of a */ vec2.length = function (a) { var x = a[0], y = a[1]; return Math.sqrt(x*x + y*y); }; /** * Alias for {@link vec2.length} * @function */ vec2.len = vec2.length; /** * Calculates the squared length of a vec2 * * @param {vec2} a vector to calculate squared length of * @returns {Number} squared length of a */ vec2.squaredLength = function (a) { var x = a[0], y = a[1]; return x*x + y*y; }; /** * Alias for {@link vec2.squaredLength} * @function */ vec2.sqrLen = vec2.squaredLength; /** * Negates the components of a vec2 * * @param {vec2} out the receiving vector * @param {vec2} a vector to negate * @returns {vec2} out */ vec2.negate = function(out, a) { out[0] = -a[0]; out[1] = -a[1]; return out; }; /** * Normalize a vec2 * * @param {vec2} out the receiving vector * @param {vec2} a vector to normalize * @returns {vec2} out */ vec2.normalize = function(out, a) { var x = a[0], y = a[1]; var len = x*x + y*y; if (len > 0) { //TODO: evaluate use of glm_invsqrt here? len = 1 / Math.sqrt(len); out[0] = a[0] * len; out[1] = a[1] * len; } return out; }; /** * Calculates the dot product of two vec2's * * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {Number} dot product of a and b */ vec2.dot = function (a, b) { return a[0] * b[0] + a[1] * b[1]; }; /** * Computes the cross product of two vec2's * Note that the cross product must by definition produce a 3D vector * * @param {vec3} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec3} out */ vec2.cross = function(out, a, b) { var z = a[0] * b[1] - a[1] * b[0]; out[0] = out[1] = 0; out[2] = z; return out; }; /** * Performs a linear interpolation between two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @param {Number} t interpolation amount between the two inputs * @returns {vec2} out */ vec2.lerp = function (out, a, b, t) { var ax = a[0], ay = a[1]; out[0] = ax + t * (b[0] - ax); out[1] = ay + t * (b[1] - ay); return out; }; /** * Transforms the vec2 with a mat2 * * @param {vec2} out the receiving vector * @param {vec2} a the vector to transform * @param {mat2} m matrix to transform with * @returns {vec2} out */ vec2.transformMat2 = function(out, a, m) { var x = a[0], y = a[1]; out[0] = m[0] * x + m[2] * y; out[1] = m[1] * x + m[3] * y; return out; }; /** * Transforms the vec2 with a mat2d * * @param {vec2} out the receiving vector * @param {vec2} a the vector to transform * @param {mat2d} m matrix to transform with * @returns {vec2} out */ vec2.transformMat2d = function(out, a, m) { var x = a[0], y = a[1]; out[0] = m[0] * x + m[2] * y + m[4]; out[1] = m[1] * x + m[3] * y + m[5]; return out; }; /** * Transforms the vec2 with a mat3 * 3rd vector component is implicitly '1' * * @param {vec2} out the receiving vector * @param {vec2} a the vector to transform * @param {mat3} m matrix to transform with * @returns {vec2} out */ vec2.transformMat3 = function(out, a, m) { var x = a[0], y = a[1]; out[0] = m[0] * x + m[3] * y + m[6]; out[1] = m[1] * x + m[4] * y + m[7]; return out; }; /** * Transforms the vec2 with a mat4 * 3rd vector component is implicitly '0' * 4th vector component is implicitly '1' * * @param {vec2} out the receiving vector * @param {vec2} a the vector to transform * @param {mat4} m matrix to transform with * @returns {vec2} out */ vec2.transformMat4 = function(out, a, m) { var x = a[0], y = a[1]; out[0] = m[0] * x + m[4] * y + m[12]; out[1] = m[1] * x + m[5] * y + m[13]; return out; }; /** * Perform some operation over an array of vec2s. * * @param {Array} a the array of vectors to iterate over * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed * @param {Number} offset Number of elements to skip at the beginning of the array * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array * @param {Function} fn Function to call for each vector in the array * @param {Object} [arg] additional argument to pass to fn * @returns {Array} a * @function */ vec2.forEach = (function() { var vec = vec2.create(); return function(a, stride, offset, count, fn, arg) { var i, l; if(!stride) { stride = 2; } if(!offset) { offset = 0; } if(count) { l = Math.min((count * stride) + offset, a.length); } else { l = a.length; } for(i = offset; i < l; i += stride) { vec[0] = a[i]; vec[1] = a[i+1]; fn(vec, vec, arg); a[i] = vec[0]; a[i+1] = vec[1]; } return a; }; })(); /** * Returns a string representation of a vector * * @param {vec2} vec vector to represent as a string * @returns {String} string representation of the vector */ vec2.str = function (a) { return 'vec2(' + a[0] + ', ' + a[1] + ')'; }; if(typeof(exports) !== 'undefined') { exports.vec2 = vec2; } },{}],2:[function(require,module,exports){ var Scalar = require('./Scalar'); module.exports = Line; /** * Container for line-related functions * @class Line */ function Line(){}; /** * Compute the intersection between two lines. * @static * @method lineInt * @param {Array} l1 Line vector 1 * @param {Array} l2 Line vector 2 * @param {Number} precision Precision to use when checking if the lines are parallel * @return {Array} The intersection point. */ Line.lineInt = function(l1,l2,precision){ precision = precision || 0; var i = [0,0]; // point var a1, b1, c1, a2, b2, c2, det; // scalars a1 = l1[1][1] - l1[0][1]; b1 = l1[0][0] - l1[1][0]; c1 = a1 * l1[0][0] + b1 * l1[0][1]; a2 = l2[1][1] - l2[0][1]; b2 = l2[0][0] - l2[1][0]; c2 = a2 * l2[0][0] + b2 * l2[0][1]; det = a1 * b2 - a2*b1; if (!Scalar.eq(det, 0, precision)) { // lines are not parallel i[0] = (b2 * c1 - b1 * c2) / det; i[1] = (a1 * c2 - a2 * c1) / det; } return i; }; /** * Checks if two line segments intersects. * @method segmentsIntersect * @param {Array} p1 The start vertex of the first line segment. * @param {Array} p2 The end vertex of the first line segment. * @param {Array} q1 The start vertex of the second line segment. * @param {Array} q2 The end vertex of the second line segment. * @return {Boolean} True if the two line segments intersect */ Line.segmentsIntersect = function(p1, p2, q1, q2){ var dx = p2[0] - p1[0]; var dy = p2[1] - p1[1]; var da = q2[0] - q1[0]; var db = q2[1] - q1[1]; // segments are parallel if(da*dy - db*dx == 0) return false; var s = (dx * (q1[1] - p1[1]) + dy * (p1[0] - q1[0])) / (da * dy - db * dx) var t = (da * (p1[1] - q1[1]) + db * (q1[0] - p1[0])) / (db * dx - da * dy) return (s>=0 && s<=1 && t>=0 && t<=1); }; },{"./Scalar":5}],3:[function(require,module,exports){ module.exports = Point; /** * Point related functions * @class Point */ function Point(){}; /** * Get the area of a triangle spanned by the three given points. Note that the area will be negative if the points are not given in counter-clockwise order. * @static * @method area * @param {Array} a * @param {Array} b * @param {Array} c * @return {Number} */ Point.area = function(a,b,c){ return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))); }; Point.left = function(a,b,c){ return Point.area(a,b,c) > 0; }; Point.leftOn = function(a,b,c) { return Point.area(a, b, c) >= 0; }; Point.right = function(a,b,c) { return Point.area(a, b, c) < 0; }; Point.rightOn = function(a,b,c) { return Point.area(a, b, c) <= 0; }; var tmpPoint1 = [], tmpPoint2 = []; /** * Check if three points are collinear * @method collinear * @param {Array} a * @param {Array} b * @param {Array} c * @param {Number} [thresholdAngle=0] Threshold angle to use when comparing the vectors. The function will return true if the angle between the resulting vectors is less than this value. Use zero for max precision. * @return {Boolean} */ Point.collinear = function(a,b,c,thresholdAngle) { if(!thresholdAngle) return Point.area(a, b, c) == 0; else { var ab = tmpPoint1, bc = tmpPoint2; ab[0] = b[0]-a[0]; ab[1] = b[1]-a[1]; bc[0] = c[0]-b[0]; bc[1] = c[1]-b[1]; var dot = ab[0]*bc[0] + ab[1]*bc[1], magA = Math.sqrt(ab[0]*ab[0] + ab[1]*ab[1]), magB = Math.sqrt(bc[0]*bc[0] + bc[1]*bc[1]), angle = Math.acos(dot/(magA*magB)); return angle < thresholdAngle; } }; Point.sqdist = function(a,b){ var dx = b[0] - a[0]; var dy = b[1] - a[1]; return dx * dx + dy * dy; }; },{}],4:[function(require,module,exports){ var Line = require("./Line") , Point = require("./Point") , Scalar = require("./Scalar") module.exports = Polygon; /** * Polygon class. * @class Polygon * @constructor */ function Polygon(){ /** * Vertices that this polygon consists of. An array of array of numbers, example: [[0,0],[1,0],..] * @property vertices * @type {Array} */ this.vertices = []; } /** * Get a vertex at position i. It does not matter if i is out of bounds, this function will just cycle. * @method at * @param {Number} i * @return {Array} */ Polygon.prototype.at = function(i){ var v = this.vertices, s = v.length; return v[i < 0 ? i % s + s : i % s]; }; /** * Get first vertex * @method first * @return {Array} */ Polygon.prototype.first = function(){ return this.vertices[0]; }; /** * Get last vertex * @method last * @return {Array} */ Polygon.prototype.last = function(){ return this.vertices[this.vertices.length-1]; }; /** * Clear the polygon data * @method clear * @return {Array} */ Polygon.prototype.clear = function(){ this.vertices.length = 0; }; /** * Append points "from" to "to"-1 from an other polygon "poly" onto this one. * @method append * @param {Polygon} poly The polygon to get points from. * @param {Number} from The vertex index in "poly". * @param {Number} to The end vertex index in "poly". Note that this vertex is NOT included when appending. * @return {Array} */ Polygon.prototype.append = function(poly,from,to){ if(typeof(from) == "undefined") throw new Error("From is not given!"); if(typeof(to) == "undefined") throw new Error("To is not given!"); if(to-1 < from) throw new Error("lol1"); if(to > poly.vertices.length) throw new Error("lol2"); if(from < 0) throw new Error("lol3"); for(var i=from; i<to; i++){ this.vertices.push(poly.vertices[i]); } }; /** * Make sure that the polygon vertices are ordered counter-clockwise. * @method makeCCW */ Polygon.prototype.makeCCW = function(){ var br = 0, v = this.vertices; // find bottom right point for (var i = 1; i < this.vertices.length; ++i) { if (v[i][1] < v[br][1] || (v[i][1] == v[br][1] && v[i][0] > v[br][0])) { br = i; } } // reverse poly if clockwise if (!Point.left(this.at(br - 1), this.at(br), this.at(br + 1))) { this.reverse(); } }; /** * Reverse the vertices in the polygon * @method reverse */ Polygon.prototype.reverse = function(){ var tmp = []; for(var i=0, N=this.vertices.length; i!==N; i++){ tmp.push(this.vertices.pop()); } this.vertices = tmp; }; /** * Check if a point in the polygon is a reflex point * @method isReflex * @param {Number} i * @return {Boolean} */ Polygon.prototype.isReflex = function(i){ return Point.right(this.at(i - 1), this.at(i), this.at(i + 1)); }; var tmpLine1=[], tmpLine2=[]; /** * Check if two vertices in the polygon can see each other * @method canSee * @param {Number} a Vertex index 1 * @param {Number} b Vertex index 2 * @return {Boolean} */ Polygon.prototype.canSee = function(a,b) { var p, dist, l1=tmpLine1, l2=tmpLine2; if (Point.leftOn(this.at(a + 1), this.at(a), this.at(b)) && Point.rightOn(this.at(a - 1), this.at(a), this.at(b))) { return false; } dist = Point.sqdist(this.at(a), this.at(b)); for (var i = 0; i !== this.vertices.length; ++i) { // for each edge if ((i + 1) % this.vertices.length === a || i === a) // ignore incident edges continue; if (Point.leftOn(this.at(a), this.at(b), this.at(i + 1)) && Point.rightOn(this.at(a), this.at(b), this.at(i))) { // if diag intersects an edge l1[0] = this.at(a); l1[1] = this.at(b); l2[0] = this.at(i); l2[1] = this.at(i + 1); p = Line.lineInt(l1,l2); if (Point.sqdist(this.at(a), p) < dist) { // if edge is blocking visibility to b return false; } } } return true; }; /** * Copy the polygon from vertex i to vertex j. * @method copy * @param {Number} i * @param {Number} j * @param {Polygon} [targetPoly] Optional target polygon to save in. * @return {Polygon} The resulting copy. */ Polygon.prototype.copy = function(i,j,targetPoly){ var p = targetPoly || new Polygon(); p.clear(); if (i < j) { // Insert all vertices from i to j for(var k=i; k<=j; k++) p.vertices.push(this.vertices[k]); } else { // Insert vertices 0 to j for(var k=0; k<=j; k++) p.vertices.push(this.vertices[k]); // Insert vertices i to end for(var k=i; k<this.vertices.length; k++) p.vertices.push(this.vertices[k]); } return p; }; /** * Decomposes the polygon into convex pieces. Returns a list of edges [[p1,p2],[p2,p3],...] that cuts the polygon. * Note that this algorithm has complexity O(N^4) and will be very slow for polygons with many vertices. * @method getCutEdges * @return {Array} */ Polygon.prototype.getCutEdges = function() { var min=[], tmp1=[], tmp2=[], tmpPoly = new Polygon(); var nDiags = Number.MAX_VALUE; for (var i = 0; i < this.vertices.length; ++i) { if (this.isReflex(i)) { for (var j = 0; j < this.vertices.length; ++j) { if (this.canSee(i, j)) { tmp1 = this.copy(i, j, tmpPoly).getCutEdges(); tmp2 = this.copy(j, i, tmpPoly).getCutEdges(); for(var k=0; k<tmp2.length; k++) tmp1.push(tmp2[k]); if (tmp1.length < nDiags) { min = tmp1; nDiags = tmp1.length; min.push([this.at(i), this.at(j)]); } } } } } return min; }; /** * Decomposes the polygon into one or more convex sub-Polygons. * @method decomp * @return {Array} An array or Polygon objects. */ Polygon.prototype.decomp = function(){ var edges = this.getCutEdges(); if(edges.length > 0) return this.slice(edges); else return [this]; }; /** * Slices the polygon given one or more cut edges. If given one, this function will return two polygons (false on failure). If many, an array of polygons. * @method slice * @param {Array} cutEdges A list of edges, as returned by .getCutEdges() * @return {Array} */ Polygon.prototype.slice = function(cutEdges){ if(cutEdges.length == 0) return [this]; if(cutEdges instanceof Array && cutEdges.length && cutEdges[0] instanceof Array && cutEdges[0].length==2 && cutEdges[0][0] instanceof Array){ var polys = [this]; for(var i=0; i<cutEdges.length; i++){ var cutEdge = cutEdges[i]; // Cut all polys for(var j=0; j<polys.length; j++){ var poly = polys[j]; var result = poly.slice(cutEdge); if(result){ // Found poly! Cut and quit polys.splice(j,1); polys.push(result[0],result[1]); break; } } } return polys; } else { // Was given one edge var cutEdge = cutEdges; var i = this.vertices.indexOf(cutEdge[0]); var j = this.vertices.indexOf(cutEdge[1]); if(i != -1 && j != -1){ return [this.copy(i,j), this.copy(j,i)]; } else { return false; } } }; /** * Checks that the line segments of this polygon do not intersect each other. * @method isSimple * @param {Array} path An array of vertices e.g. [[0,0],[0,1],...] * @return {Boolean} * @todo Should it check all segments with all others? */ Polygon.prototype.isSimple = function(){ var path = this.vertices; // Check for(var i=0; i<path.length-1; i++){ for(var j=0; j<i-1; j++){ if(Line.segmentsIntersect(path[i], path[i+1], path[j], path[j+1] )){ return false; } } } // Check the segment between the last and the first point to all others for(var i=1; i<path.length-2; i++){ if(Line.segmentsIntersect(path[0], path[path.length-1], path[i], path[i+1] )){ return false; } } return true; }; function getIntersectionPoint(p1, p2, q1, q2, delta){ delta = delta || 0; var a1 = p2[1] - p1[1]; var b1 = p1[0] - p2[0]; var c1 = (a1 * p1[0]) + (b1 * p1[1]); var a2 = q2[1] - q1[1]; var b2 = q1[0] - q2[0]; var c2 = (a2 * q1[0]) + (b2 * q1[1]); var det = (a1 * b2) - (a2 * b1); if(!Scalar.eq(det,0,delta)) return [((b2 * c1) - (b1 * c2)) / det, ((a1 * c2) - (a2 * c1)) / det] else return [0,0] } /** * Quickly decompose the Polygon into convex sub-polygons. * @method quickDecomp * @param {Array} result * @param {Array} [reflexVertices] * @param {Array} [steinerPoints] * @param {Number} [delta] * @param {Number} [maxlevel] * @param {Number} [level] * @return {Array} */ Polygon.prototype.quickDecomp = function(result,reflexVertices,steinerPoints,delta,maxlevel,level){ maxlevel = maxlevel || 100; level = level || 0; delta = delta || 25; result = typeof(result)!="undefined" ? result : []; reflexVertices = reflexVertices || []; steinerPoints = steinerPoints || []; var upperInt=[0,0], lowerInt=[0,0], p=[0,0]; // Points var upperDist=0, lowerDist=0, d=0, closestDist=0; // scalars var upperIndex=0, lowerIndex=0, closestIndex=0; // Integers var lowerPoly=new Polygon(), upperPoly=new Polygon(); // polygons var poly = this, v = this.vertices; if(v.length < 3) return result; level++; if(level > maxlevel){ console.warn("quickDecomp: max level ("+maxlevel+") reached."); return result; } for (var i = 0; i < this.vertices.length; ++i) { if (poly.isReflex(i)) { reflexVertices.push(poly.vertices[i]); upperDist = lowerDist = Number.MAX_VALUE; for (var j = 0; j < this.vertices.length; ++j) { if (Point.left(poly.at(i - 1), poly.at(i), poly.at(j)) && Point.rightOn(poly.at(i - 1), poly.at(i), poly.at(j - 1))) { // if line intersects with an edge p = getIntersectionPoint(poly.at(i - 1), poly.at(i), poly.at(j), poly.at(j - 1)); // find the point of intersection if (Point.right(poly.at(i + 1), poly.at(i), p)) { // make sure it's inside the poly d = Point.sqdist(poly.vertices[i], p); if (d < lowerDist) { // keep only the closest intersection lowerDist = d; lowerInt = p; lowerIndex = j; } } } if (Point.left(poly.at(i + 1), poly.at(i), poly.at(j + 1)) && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { p = getIntersectionPoint(poly.at(i + 1), poly.at(i), poly.at(j), poly.at(j + 1)); if (Point.left(poly.at(i - 1), poly.at(i), p)) { d = Point.sqdist(poly.vertices[i], p); if (d < upperDist) { upperDist = d; upperInt = p; upperIndex = j; } } } } // if there are no vertices to connect to, choose a point in the middle if (lowerIndex == (upperIndex + 1) % this.vertices.length) { //console.log("Case 1: Vertex("+i+"), lowerIndex("+lowerIndex+"), upperIndex("+upperIndex+"), poly.size("+this.vertices.length+")"); p[0] = (lowerInt[0] + upperInt[0]) / 2; p[1] = (lowerInt[1] + upperInt[1]) / 2; steinerPoints.push(p); if (i < upperIndex) { //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.begin() + upperIndex + 1); lowerPoly.append(poly, i, upperIndex+1); lowerPoly.vertices.push(p); upperPoly.vertices.push(p); if (lowerIndex != 0){ //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.end()); upperPoly.append(poly,lowerIndex,poly.vertices.length); } //upperPoly.insert(upperPoly.end(), poly.begin(), poly.begin() + i + 1); upperPoly.append(poly,0,i+1); } else { if (i != 0){ //lowerPoly.insert(lowerPoly.end(), poly.begin() + i, poly.end()); lowerPoly.append(poly,i,poly.vertices.length); } //lowerPoly.insert(lowerPoly.end(), poly.begin(), poly.begin() + upperIndex + 1); lowerPoly.append(poly,0,upperIndex+1); lowerPoly.vertices.push(p); upperPoly.vertices.push(p); //upperPoly.insert(upperPoly.end(), poly.begin() + lowerIndex, poly.begin() + i + 1); upperPoly.append(poly,lowerIndex,i+1); } } else { // connect to the closest point within the triangle //console.log("Case 2: Vertex("+i+"), closestIndex("+closestIndex+"), poly.size("+this.vertices.length+")\n"); if (lowerIndex > upperIndex) { upperIndex += this.vertices.length; } closestDist = Number.MAX_VALUE; if(upperIndex < lowerIndex){ return result; } for (var j = lowerIndex; j <= upperIndex; ++j) { if (Point.leftOn(poly.at(i - 1), poly.at(i), poly.at(j)) && Point.rightOn(poly.at(i + 1), poly.at(i), poly.at(j))) { d = Point.sqdist(poly.at(i), poly.at(j)); if (d < closestDist) { closestDist = d; closestIndex = j % this.vertices.length; } } } if (i < closestIndex) { lowerPoly.append(poly,i,closestIndex+1); if (closestIndex != 0){ upperPoly.append(poly,closestIndex,v.length); } upperPoly.append(poly,0,i+1); } else { if (i != 0){ lowerPoly.append(poly,i,v.length); } lowerPoly.append(poly,0,closestIndex+1); upperPoly.append(poly,closestIndex,i+1); } } // solve smallest poly first if (lowerPoly.vertices.length < upperPoly.vertices.length) { lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); } else { upperPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); lowerPoly.quickDecomp(result,reflexVertices,steinerPoints,delta,maxlevel,level); } return result; } } result.push(this); return result; }; /** * Remove collinear points in the polygon. * @method removeCollinearPoints * @param {Number} [precision] The threshold angle to use when determining whether two edges are collinear. Use zero for finest precision. * @return {Number} The number of points removed */ Polygon.prototype.removeCollinearPoints = function(precision){ var num = 0; for(var i=this.vertices.length-1; this.vertices.length>3 && i>=0; --i){ if(Point.collinear(this.at(i-1),this.at(i),this.at(i+1),precision)){ // Remove the middle point this.vertices.splice(i%this.vertices.length,1); i--; // Jump one point forward. Otherwise we may get a chain removal num++; } } return num; }; },{"./Line":2,"./Point":3,"./Scalar":5}],5:[function(require,module,exports){ module.exports = Scalar; /** * Scalar functions * @class Scalar */ function Scalar(){} /** * Check if two scalars are equal * @static * @method eq * @param {Number} a * @param {Number} b * @param {Number} [precision] * @return {Boolean} */ Scalar.eq = function(a,b,precision){ precision = precision || 0; return Math.abs(a-b) < precision; }; },{}],6:[function(require,module,exports){ module.exports = { Polygon : require("./Polygon"), Point : require("./Point"), }; },{"./Point":3,"./Polygon":4}],7:[function(require,module,exports){ module.exports={ "name": "p2", "version": "0.5.0", "description": "A JavaScript 2D physics engine.", "author": "Stefan Hedman <[email protected]> (http://steffe.se)", "keywords": [ "p2.js", "p2", "physics", "engine", "2d" ], "main": "./src/p2.js", "engines": { "node": "*" }, "repository": { "type": "git", "url": "https://github.com/schteppe/p2.js.git" }, "bugs": { "url": "https://github.com/schteppe/p2.js/issues" }, "licenses": [ { "type": "MIT" } ], "devDependencies": { "grunt": "~0.4.0", "grunt-contrib-jshint": "~0.9.2", "grunt-contrib-nodeunit": "~0.1.2", "grunt-contrib-uglify": "~0.4.0", "grunt-contrib-watch": "~0.5.0", "grunt-browserify": "~2.0.1", "z-schema": "~2.4.6" }, "dependencies": { "poly-decomp": "0.1.0", "gl-matrix": "2.1.0" } } },{}],8:[function(require,module,exports){ var vec2 = require('../math/vec2') , Utils = require('../utils/Utils'); module.exports = AABB; /** * Axis aligned bounding box class. * @class AABB * @constructor * @param {Object} [options] * @param {Array} [options.upperBound] * @param {Array} [options.lowerBound] */ function AABB(options){ /** * The lower bound of the bounding box. * @property lowerBound * @type {Array} */ this.lowerBound = vec2.create(); if(options && options.lowerBound){ vec2.copy(this.lowerBound, options.lowerBound); } /** * The upper bound of the bounding box. * @property upperBound * @type {Array} */ this.upperBound = vec2.create(); if(options && options.upperBound){ vec2.copy(this.upperBound, options.upperBound); } } var tmp = vec2.create(); /** * Set the AABB bounds from a set of points. * @method setFromPoints * @param {Array} points An array of vec2's. */ AABB.prototype.setFromPoints = function(points,position,angle){ var l = this.lowerBound, u = this.upperBound; vec2.set(l, Number.MAX_VALUE, Number.MAX_VALUE); vec2.set(u, -Number.MAX_VALUE, -Number.MAX_VALUE); for(var i=0; i<points.length; i++){ var p = points[i]; if(typeof(angle) === "number"){ vec2.rotate(tmp,p,angle); p = tmp; } for(var j=0; j<2; j++){ if(p[j] > u[j]){ u[j] = p[j]; } if(p[j] < l[j]){ l[j] = p[j]; } } } // Add offset if(position){ vec2.add(this.lowerBound, this.lowerBound, position); vec2.add(this.upperBound, this.upperBound, position); } }; /** * Copy bounds from an AABB to this AABB * @method copy * @param {AABB} aabb */ AABB.prototype.copy = function(aabb){ vec2.copy(this.lowerBound, aabb.lowerBound); vec2.copy(this.upperBound, aabb.upperBound); }; /** * Extend this AABB so that it covers the given AABB too. * @method extend * @param {AABB} aabb */ AABB.prototype.extend = function(aabb){ // Loop over x and y for(var i=0; i<2; i++){ // Extend lower bound if(aabb.lowerBound[i] < this.lowerBound[i]){ this.lowerBound[i] = aabb.lowerBound[i]; } // Upper if(aabb.upperBound[i] > this.upperBound[i]){ this.upperBound[i] = aabb.upperBound[i]; } } }; /** * Returns true if the given AABB overlaps this AABB. * @method overlaps * @param {AABB} aabb * @return {Boolean} */ AABB.prototype.overlaps = function(aabb){ var l1 = this.lowerBound, u1 = this.upperBound, l2 = aabb.lowerBound, u2 = aabb.upperBound; // l2 u2 // |---------| // |--------| // l1 u1 return ((l2[0] <= u1[0] && u1[0] <= u2[0]) || (l1[0] <= u2[0] && u2[0] <= u1[0])) && ((l2[1] <= u1[1] && u1[1] <= u2[1]) || (l1[1] <= u2[1] && u2[1] <= u1[1])); }; },{"../math/vec2":30,"../utils/Utils":47}],9:[function(require,module,exports){ var vec2 = require('../math/vec2') var Body = require('../objects/Body') module.exports = Broadphase; /** * Base class for broadphase implementations. * @class Broadphase * @constructor */ function Broadphase(type){ this.type = type; /** * The resulting overlapping pairs. Will be filled with results during .getCollisionPairs(). * @property result * @type {Array} */ this.result = []; /** * The world to search for collision pairs in. To change it, use .setWorld() * @property world * @type {World} * @readOnly */ this.world = null; /** * The bounding volume type to use in the broadphase algorithms. * @property {Number} boundingVolumeType */ this.boundingVolumeType = Broadphase.AABB; } /** * Axis aligned bounding box type. * @static * @property {Number} AABB */ Broadphase.AABB = 1; /** * Bounding circle type. * @static * @property {Number} BOUNDING_CIRCLE */ Broadphase.BOUNDING_CIRCLE = 2; /** * Set the world that we are searching for collision pairs in * @method setWorld * @param {World} world */ Broadphase.prototype.setWorld = function(world){ this.world = world; }; /** * Get all potential intersecting body pairs. * @method getCollisionPairs * @param {World} world The world to search in. * @return {Array} An array of the bodies, ordered in pairs. Example: A result of [a,b,c,d] means that the potential pairs are: (a,b), (c,d). */ Broadphase.prototype.getCollisionPairs = function(world){ throw new Error("getCollisionPairs must be implemented in a subclass!"); }; var dist = vec2.create(); /** * Check whether the bounding radius of two bodies overlap. * @method boundingRadiusCheck * @param {Body} bodyA * @param {Body} bodyB * @return {Boolean} */ Broadphase.boundingRadiusCheck = function(bodyA, bodyB){ vec2.sub(dist, bodyA.position, bodyB.position); var d2 = vec2.squaredLength(dist), r = bodyA.boundingRadius + bodyB.boundingRadius; return d2 <= r*r; }; /** * Check whether the bounding radius of two bodies overlap. * @method boundingRadiusCheck * @param {Body} bodyA * @param {Body} bodyB * @return {Boolean} */ Broadphase.aabbCheck = function(bodyA, bodyB){ if(bodyA.aabbNeedsUpdate){ bodyA.updateAABB(); } if(bodyB.aabbNeedsUpdate){ bodyB.updateAABB(); } return bodyA.aabb.overlaps(bodyB.aabb); }; /** * Check whether the bounding radius of two bodies overlap. * @method boundingRadiusCheck * @param {Body} bodyA * @param {Body} bodyB * @return {Boolean} */ Broadphase.prototype.boundingVolumeCheck = function(bodyA, bodyB){ var result; switch(this.boundingVolumeType){ case Broadphase.BOUNDING_CIRCLE: result = Broadphase.boundingRadiusCheck(bodyA,bodyB); break; case Broadphase.AABB: result = Broadphase.aabbCheck(bodyA,bodyB); break; default: throw new Error('Bounding volume type not recognized: '+this.boundingVolumeType); } return result; }; /** * Check whether two bodies are allowed to collide at all. * @method canCollide * @param {Body} bodyA * @param {Body} bodyB * @return {Boolean} */ Broadphase.canCollide = function(bodyA, bodyB){ // Cannot collide static bodies if(bodyA.motionState === Body.STATIC && bodyB.motionState === Body.STATIC){ return false; } // Cannot collide static vs kinematic bodies if( (bodyA.motionState === Body.KINEMATIC && bodyB.motionState === Body.STATIC) || (bodyA.motionState === Body.STATIC && bodyB.motionState === Body.KINEMATIC)){ return false; } // Cannot collide kinematic vs kinematic if(bodyA.motionState === Body.KINEMATIC && bodyB.motionState === Body.KINEMATIC){ return false; } // Cannot collide both sleeping bodies if(bodyA.sleepState === Body.SLEEPING && bodyB.sleepState === Body.SLEEPING){ return false; } // Cannot collide if one is static and the other is sleeping if( (bodyA.sleepState === Body.SLEEPING && bodyB.motionState === Body.STATIC) || (bodyB.sleepState === Body.SLEEPING && bodyA.motionState === Body.STATIC)){ return false; } return true; }; Broadphase.NAIVE = 1; Broadphase.SAP = 2; },{"../math/vec2":30,"../objects/Body":31}],10:[function(require,module,exports){ var Circle = require('../shapes/Circle') , Plane = require('../shapes/Plane') , Particle = require('../shapes/Particle') , Broadphase = require('../collision/Broadphase') , vec2 = require('../math/vec2') , Utils = require('../utils/Utils') module.exports = GridBroadphase; /** * Broadphase that uses axis-aligned bins. * @class GridBroadphase * @constructor * @extends Broadphase * @param {object} [options] * @param {number} [options.xmin] Lower x bound of the grid * @param {number} [options.xmax] Upper x bound * @param {number} [options.ymin] Lower y bound * @param {number} [options.ymax] Upper y bound * @param {number} [options.nx] Number of bins along x axis * @param {number} [options.ny] Number of bins along y axis * @todo Should have an option for dynamic scene size */ function GridBroadphase(options){ Broadphase.apply(this); options = Utils.defaults(options,{ xmin: -100, xmax: 100, ymin: -100, ymax: 100, nx: 10, ny: 10 }); this.xmin = options.xmin; this.ymin = options.ymin; this.xmax = options.xmax; this.ymax = options.ymax; this.nx = options.nx; this.ny = options.ny; this.binsizeX = (this.xmax-this.xmin) / this.nx; this.binsizeY = (this.ymax-this.ymin) / this.ny; } GridBroadphase.prototype = new Broadphase(); /** * Get collision pairs. * @method getCollisionPairs * @param {World} world * @return {Array} */ GridBroadphase.prototype.getCollisionPairs = function(world){ var result = [], bodies = world.bodies, Ncolliding = bodies.length, binsizeX = this.binsizeX, binsizeY = this.binsizeY, nx = this.nx, ny = this.ny, xmin = this.xmin, ymin = this.ymin, xmax = this.xmax, ymax = this.ymax; // Todo: make garbage free var bins=[], Nbins=nx*ny; for(var i=0; i<Nbins; i++){ bins.push([]); } var xmult = nx / (xmax-xmin); var ymult = ny / (ymax-ymin); // Put all bodies into bins for(var i=0; i!==Ncolliding; i++){ var bi = bodies[i]; var aabb = bi.aabb; var lowerX = Math.max(aabb.lowerBound[0], xmin); var lowerY = Math.max(aabb.lowerBound[1], ymin); var upperX = Math.min(aabb.upperBound[0], xmax); var upperY = Math.min(aabb.upperBound[1], ymax); var xi1 = Math.floor(xmult * (lowerX - xmin)); var yi1 = Math.floor(ymult * (lowerY - ymin)); var xi2 = Math.floor(xmult * (upperX - xmin)); var yi2 = Math.floor(ymult * (upperY - ymin)); // Put in bin for(var j=xi1; j<=xi2; j++){ for(var k=yi1; k<=yi2; k++){ var xi = j; var yi = k; var idx = xi*(ny-1) + yi; if(idx >= 0 && idx < Nbins){ bins[ idx ].push(bi); } } } } // Check each bin for(var i=0; i!==Nbins; i++){ var bin = bins[i]; for(var j=0, NbodiesInBin=bin.length; j!==NbodiesInBin; j++){ var bi = bin[j]; for(var k=0; k!==j; k++){ var bj = bin[k]; if(Broadphase.canCollide(bi,bj) && this.boundingVolumeCheck(bi,bj)){ result.push(bi,bj); } } } } return result; }; },{"../collision/Broadphase":9,"../math/vec2":30,"../shapes/Circle":35,"../shapes/Particle":39,"../shapes/Plane":40,"../utils/Utils":47}],11:[function(require,module,exports){ var Circle = require('../shapes/Circle'), Plane = require('../shapes/Plane'), Shape = require('../shapes/Shape'), Particle = require('../shapes/Particle'), Broadphase = require('../collision/Broadphase'), vec2 = require('../math/vec2'); module.exports = NaiveBroadphase; /** * Naive broadphase implementation. Does N^2 tests. * * @class NaiveBroadphase * @constructor * @extends Broadphase */ function NaiveBroadphase(){ Broadphase.call(this, Broadphase.NAIVE); } NaiveBroadphase.prototype = new Broadphase(); /** * Get the colliding pairs * @method getCollisionPairs * @param {World} world * @return {Array} */ NaiveBroadphase.prototype.getCollisionPairs = function(world){ var bodies = world.bodies, result = this.result; result.length = 0; for(var i=0, Ncolliding=bodies.length; i!==Ncolliding; i++){ var bi = bodies[i]; for(var j=0; j<i; j++){ var bj = bodies[j]; if(Broadphase.canCollide(bi,bj) && this.boundingVolumeCheck(bi,bj)){ result.push(bi,bj); } } } return result; }; },{"../collision/Broadphase":9,"../math/vec2":30,"../shapes/Circle":35,"../shapes/Particle":39,"../shapes/Plane":40,"../shapes/Shape":42}],12:[function(require,module,exports){ var vec2 = require('../math/vec2') , sub = vec2.sub , add = vec2.add , dot = vec2.dot , Utils = require('../utils/Utils') , TupleDictionary = require('../utils/TupleDictionary') , Equation = require('../equations/Equation') , ContactEquation = require('../equations/ContactEquation') , FrictionEquation = require('../equations/FrictionEquation') , Circle = require('../shapes/Circle') , Convex = require('../shapes/Convex') , Shape = require('../shapes/Shape') , Body = require('../objects/Body') , Rectangle = require('../shapes/Rectangle'); module.exports = Narrowphase; // Temp things var yAxis = vec2.fromValues(0,1); var tmp1 = vec2.fromValues(0,0) , tmp2 = vec2.fromValues(0,0) , tmp3 = vec2.fromValues(0,0) , tmp4 = vec2.fromValues(0,0) , tmp5 = vec2.fromValues(0,0) , tmp6 = vec2.fromValues(0,0) , tmp7 = vec2.fromValues(0,0) , tmp8 = vec2.fromValues(0,0) , tmp9 = vec2.fromValues(0,0) , tmp10 = vec2.fromValues(0,0) , tmp11 = vec2.fromValues(0,0) , tmp12 = vec2.fromValues(0,0) , tmp13 = vec2.fromValues(0,0) , tmp14 = vec2.fromValues(0,0) , tmp15 = vec2.fromValues(0,0) , tmp16 = vec2.fromValues(0,0) , tmp17 = vec2.fromValues(0,0) , tmp18 = vec2.fromValues(0,0) , tmpArray = []; /** * Narrowphase. Creates contacts and friction given shapes and transforms. * @class Narrowphase * @constructor */ function Narrowphase(){ /** * @property contactEquations * @type {Array} */ this.contactEquations = []; /** * @property frictionEquations * @type {Array} */ this.frictionEquations = []; /** * Whether to make friction equations in the upcoming contacts. * @property enableFriction * @type {Boolean} */ this.enableFriction = true; /** * The friction slip force to use when creating friction equations. * @property slipForce * @type {Number} */ this.slipForce = 10.0; /** * The friction value to use in the upcoming friction equations. * @property frictionCoefficient * @type {Number} */ this.frictionCoefficient = 0.3; /** * Will be the .relativeVelocity in each produced FrictionEquation. * @property {Number} surfaceVelocity */ this.surfaceVelocity = 0; this.reuseObjects = true; this.reusableContactEquations = []; this.reusableFrictionEquations = []; /** * The restitution value to use in the next contact equations. * @property restitution * @type {Number} */ this.restitution = 0; /** * The stiffness value to use in the next contact equations. * @property {Number} stiffness */ this.stiffness = Equation.DEFAULT_STIFFNESS; /** * The stiffness value to use in the next contact equations. * @property {Number} stiffness */ this.relaxation = Equation.DEFAULT_RELAXATION; /** * The stiffness value to use in the next friction equations. * @property frictionStiffness * @type {Number} */ this.frictionStiffness = Equation.DEFAULT_STIFFNESS; /** * The relaxation value to use in the next friction equations. * @property frictionRelaxation * @type {Number} */ this.frictionRelaxation = Equation.DEFAULT_RELAXATION; // Keep track of the colliding bodies last step this.collidingBodiesLastStep = new TupleDictionary(); } /** * Check if the bodies were in contact since the last reset(). * @method collidedLastStep * @param {Body} bi * @param {Body} bj * @return {Boolean} */ Narrowphase.prototype.collidedLastStep = function(bi,bj){ var id1 = bi.id|0, id2 = bj.id|0; return !!this.collidingBodiesLastStep.get(id1, id2); }; // "for in" loops aren't optimised in chrome... is there a better way to handle last-step collision memory? // Maybe do this: http://jsperf.com/reflection-vs-array-of-keys function clearObject(obj){ var l = obj.keys.length; while(l--){ delete obj[obj.keys[l]]; } obj.keys.length = 0; } /** * Throws away the old equations and gets ready to create new * @method reset * @param {World} world */ Narrowphase.prototype.reset = function(world){ this.collidingBodiesLastStep.reset(); for(var i=0; i!==this.contactEquations.length; i++){ var eq = this.contactEquations[i], id1 = eq.bodyA.id|0, id2 = eq.bodyB.id|0; this.collidingBodiesLastStep.set(id1, id2, true); } if(this.reuseObjects){ var ce = this.contactEquations, fe = this.frictionEquations, rfe = this.reusableFrictionEquations, rce = this.reusableContactEquations; Utils.appendArray(rce,ce); Utils.appendArray(rfe,fe); } // Reset this.contactEquations.length = this.frictionEquations.length = 0; }; /** * Creates a ContactEquation, either by reusing an existing object or creating a new one. * @method createContactEquation * @param {Body} bodyA * @param {Body} bodyB * @return {ContactEquation} */ Narrowphase.prototype.createContactEquation = function(bodyA,bodyB,shapeA,shapeB){ var c = this.reusableContactEquations.length ? this.reusableContactEquations.pop() : new ContactEquation(bodyA,bodyB); c.bodyA = bodyA; c.bodyB = bodyB; c.shapeA = shapeA; c.shapeB = shapeB; c.restitution = this.restitution; c.firstImpact = !this.collidedLastStep(bodyA,bodyB); c.stiffness = this.stiffness; c.relaxation = this.relaxation; c.needsUpdate = true; c.enabled = true; return c; }; /** * Creates a FrictionEquation, either by reusing an existing object or creating a new one. * @method createFrictionEquation * @param {Body} bodyA * @param {Body} bodyB * @return {FrictionEquation} */ Narrowphase.prototype.createFrictionEquation = function(bodyA,bodyB,shapeA,shapeB){ var c = this.reusableFrictionEquations.length ? this.reusableFrictionEquations.pop() : new FrictionEquation(bodyA,bodyB); c.bodyA = bodyA; c.bodyB = bodyB; c.shapeA = shapeA; c.shapeB = shapeB; c.setSlipForce(this.slipForce); c.frictionCoefficient = this.frictionCoefficient; c.relativeVelocity = this.surfaceVelocity; c.enabled = true; c.needsUpdate = true; c.stiffness = this.frictionStiffness; c.relaxation = this.frictionRelaxation; return c; }; /** * Creates a FrictionEquation given the data in the ContactEquation. Uses same offset vectors ri and rj, but the tangent vector will be constructed from the collision normal. * @method createFrictionFromContact * @param {ContactEquation} contactEquation * @return {FrictionEquation} */ Narrowphase.prototype.createFrictionFromContact = function(c){ var eq = this.createFrictionEquation(c.bodyA, c.bodyB, c.shapeA, c.shapeB); vec2.copy(eq.contactPointA, c.contactPointA); vec2.copy(eq.contactPointB, c.contactPointB); vec2.rotate90cw(eq.t, c.normalA); eq.contactEquation = c; return eq; }; /** * Convex/line narrowphase * @method convexLine * @param {Body} bi * @param {Convex} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Line} sj * @param {Array} xj * @param {Number} aj * @todo Implement me! */ Narrowphase.prototype[Shape.LINE | Shape.CONVEX] = Narrowphase.prototype.convexLine = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ // TODO if(justTest) return false; else return 0; }; /** * Line/rectangle narrowphase * @method lineRectangle * @param {Body} bi * @param {Line} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Rectangle} sj * @param {Array} xj * @param {Number} aj * @todo Implement me! */ Narrowphase.prototype[Shape.LINE | Shape.RECTANGLE] = Narrowphase.prototype.lineRectangle = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ // TODO if(justTest) return false; else return 0; }; function setConvexToCapsuleShapeMiddle(convexShape, capsuleShape){ vec2.set(convexShape.vertices[0], -capsuleShape.length * 0.5, -capsuleShape.radius); vec2.set(convexShape.vertices[1], capsuleShape.length * 0.5, -capsuleShape.radius); vec2.set(convexShape.vertices[2], capsuleShape.length * 0.5, capsuleShape.radius); vec2.set(convexShape.vertices[3], -capsuleShape.length * 0.5, capsuleShape.radius); } var convexCapsule_tempRect = new Rectangle(1,1), convexCapsule_tempVec = vec2.create(); /** * Convex/capsule narrowphase * @method convexCapsule * @param {Body} bi * @param {Convex} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Capsule} sj * @param {Array} xj * @param {Number} aj * @todo Implement me! */ Narrowphase.prototype[Shape.CAPSULE | Shape.CONVEX] = Narrowphase.prototype[Shape.CAPSULE | Shape.RECTANGLE] = Narrowphase.prototype.convexCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ // Check the circles // Add offsets! var circlePos = convexCapsule_tempVec; vec2.set(circlePos, sj.length/2,0); vec2.rotate(circlePos,circlePos,aj); vec2.add(circlePos,circlePos,xj); var result1 = this.circleConvex(bj,sj,circlePos,aj, bi,si,xi,ai, justTest, sj.radius); vec2.set(circlePos,-sj.length/2, 0); vec2.rotate(circlePos,circlePos,aj); vec2.add(circlePos,circlePos,xj); var result2 = this.circleConvex(bj,sj,circlePos,aj, bi,si,xi,ai, justTest, sj.radius); if(justTest && (result1 || result2)) return true; // Check center rect var r = convexCapsule_tempRect; setConvexToCapsuleShapeMiddle(r,sj); var result = this.convexConvex(bi,si,xi,ai, bj,r,xj,aj, justTest); return result + result1 + result2; }; /** * Capsule/line narrowphase * @method lineCapsule * @param {Body} bi * @param {Line} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Capsule} sj * @param {Array} xj * @param {Number} aj * @todo Implement me! */ Narrowphase.prototype[Shape.CAPSULE | Shape.LINE] = Narrowphase.prototype.lineCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ // TODO if(justTest) return false; else return 0; }; var capsuleCapsule_tempVec1 = vec2.create(); var capsuleCapsule_tempVec2 = vec2.create(); var capsuleCapsule_tempRect1 = new Rectangle(1,1); /** * Capsule/capsule narrowphase * @method capsuleCapsule * @param {Body} bi * @param {Capsule} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Capsule} sj * @param {Array} xj * @param {Number} aj * @todo Implement me! */ Narrowphase.prototype[Shape.CAPSULE | Shape.CAPSULE] = Narrowphase.prototype.capsuleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ // Check the circles // Add offsets! var circlePosi = capsuleCapsule_tempVec1, circlePosj = capsuleCapsule_tempVec2; var numContacts = 0; // Need 4 circle checks, between all for(var i=0; i<2; i++){ vec2.set(circlePosi,(i==0?-1:1)*si.length/2,0); vec2.rotate(circlePosi,circlePosi,ai); vec2.add(circlePosi,circlePosi,xi); for(var j=0; j<2; j++){ vec2.set(circlePosj,(j==0?-1:1)*sj.length/2, 0); vec2.rotate(circlePosj,circlePosj,aj); vec2.add(circlePosj,circlePosj,xj); var result = this.circleCircle(bi,si,circlePosi,ai, bj,sj,circlePosj,aj, justTest, si.radius, sj.radius); if(justTest && result) return true; numContacts += result; } } // Check circles against the center rectangles var rect = capsuleCapsule_tempRect1; setConvexToCapsuleShapeMiddle(rect,si); var result1 = this.convexCapsule(bi,rect,xi,ai, bj,sj,xj,aj, justTest); if(justTest && result1) return true; numContacts += result1; setConvexToCapsuleShapeMiddle(rect,sj); var result2 = this.convexCapsule(bj,rect,xj,aj, bi,si,xi,ai, justTest); if(justTest && result2) return true; numContacts += result2; return numContacts; }; /** * Line/line narrowphase * @method lineLine * @param {Body} bi * @param {Line} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Line} sj * @param {Array} xj * @param {Number} aj * @todo Implement me! */ Narrowphase.prototype[Shape.LINE | Shape.LINE] = Narrowphase.prototype.lineLine = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ // TODO if(justTest) return false; else return 0; }; /** * Plane/line Narrowphase * @method planeLine * @param {Body} planeBody * @param {Plane} planeShape * @param {Array} planeOffset * @param {Number} planeAngle * @param {Body} lineBody * @param {Line} lineShape * @param {Array} lineOffset * @param {Number} lineAngle */ Narrowphase.prototype[Shape.PLANE | Shape.LINE] = Narrowphase.prototype.planeLine = function(planeBody, planeShape, planeOffset, planeAngle, lineBody, lineShape, lineOffset, lineAngle, justTest){ var worldVertex0 = tmp1, worldVertex1 = tmp2, worldVertex01 = tmp3, worldVertex11 = tmp4, worldEdge = tmp5, worldEdgeUnit = tmp6, dist = tmp7, worldNormal = tmp8, worldTangent = tmp9, verts = tmpArray numContacts = 0; // Get start and end points vec2.set(worldVertex0, -lineShape.length/2, 0); vec2.set(worldVertex1, lineShape.length/2, 0); // Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired. vec2.rotate(worldVertex01, worldVertex0, lineAngle); vec2.rotate(worldVertex11, worldVertex1, lineAngle); add(worldVertex01, worldVertex01, lineOffset); add(worldVertex11, worldVertex11, lineOffset); vec2.copy(worldVertex0,worldVertex01); vec2.copy(worldVertex1,worldVertex11); // Get vector along the line sub(worldEdge, worldVertex1, worldVertex0); vec2.normalize(worldEdgeUnit, worldEdge); // Get tangent to the edge. vec2.rotate90cw(worldTangent, worldEdgeUnit); vec2.rotate(worldNormal, yAxis, planeAngle); // Check line ends verts[0] = worldVertex0; verts[1] = worldVertex1; for(var i=0; i<verts.length; i++){ var v = verts[i]; sub(dist, v, planeOffset); var d = dot(dist,worldNormal); if(d < 0){ if(justTest) return true; var c = this.createContactEquation(planeBody,lineBody,planeShape,lineShape); numContacts++; vec2.copy(c.normalA, worldNormal); vec2.normalize(c.normalA,c.normalA); // distance vector along plane normal vec2.scale(dist, worldNormal, d); // Vector from plane center to contact sub(c.contactPointA, v, dist); sub(c.contactPointA, c.contactPointA, planeBody.position); // From line center to contact sub(c.contactPointB, v, lineOffset); add(c.contactPointB, c.contactPointB, lineOffset); sub(c.contactPointB, c.contactPointB, lineBody.position); this.contactEquations.push(c); // TODO : only need one friction equation if both points touch if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } } } return numContacts; }; Narrowphase.prototype[Shape.PARTICLE | Shape.CAPSULE] = Narrowphase.prototype.particleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ return this.circleLine(bi,si,xi,ai, bj,sj,xj,aj, justTest, sj.radius, 0); }; /** * Circle/line Narrowphase * @method circleLine * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Line} sj * @param {Array} xj * @param {Number} aj * @param {Boolean} justTest If set to true, this function will return the result (intersection or not) without adding equations. * @param {Number} lineRadius Radius to add to the line. Can be used to test Capsules. * @param {Number} circleRadius If set, this value overrides the circle shape radius. */ Narrowphase.prototype[Shape.CIRCLE | Shape.LINE] = Narrowphase.prototype.circleLine = function(bi,si,xi,ai, bj,sj,xj,aj, justTest, lineRadius, circleRadius){ var lineShape = sj, lineAngle = aj, lineBody = bj, lineOffset = xj, circleOffset = xi, circleBody = bi, circleShape = si, lineRadius = lineRadius || 0, circleRadius = typeof(circleRadius)!="undefined" ? circleRadius : circleShape.radius, orthoDist = tmp1, lineToCircleOrthoUnit = tmp2, projectedPoint = tmp3, centerDist = tmp4, worldTangent = tmp5, worldEdge = tmp6, worldEdgeUnit = tmp7, worldVertex0 = tmp8, worldVertex1 = tmp9, worldVertex01 = tmp10, worldVertex11 = tmp11, dist = tmp12, lineToCircle = tmp13, lineEndToLineRadius = tmp14, verts = tmpArray; // Get start and end points vec2.set(worldVertex0, -lineShape.length/2, 0); vec2.set(worldVertex1, lineShape.length/2, 0); // Not sure why we have to use worldVertex*1 here, but it won't work otherwise. Tired. vec2.rotate(worldVertex01, worldVertex0, lineAngle); vec2.rotate(worldVertex11, worldVertex1, lineAngle); add(worldVertex01, worldVertex01, lineOffset); add(worldVertex11, worldVertex11, lineOffset); vec2.copy(worldVertex0,worldVertex01); vec2.copy(worldVertex1,worldVertex11); // Get vector along the line sub(worldEdge, worldVertex1, worldVertex0); vec2.normalize(worldEdgeUnit, worldEdge); // Get tangent to the edge. vec2.rotate90cw(worldTangent, worldEdgeUnit); // Check distance from the plane spanned by the edge vs the circle sub(dist, circleOffset, worldVertex0); var d = dot(dist, worldTangent); // Distance from center of line to circle center sub(centerDist, worldVertex0, lineOffset); sub(lineToCircle, circleOffset, lineOffset); if(Math.abs(d) < circleRadius+lineRadius){ // Now project the circle onto the edge vec2.scale(orthoDist, worldTangent, d); sub(projectedPoint, circleOffset, orthoDist); // Add the missing line radius vec2.scale(lineToCircleOrthoUnit, worldTangent, dot(worldTangent, lineToCircle)); vec2.normalize(lineToCircleOrthoUnit,lineToCircleOrthoUnit); vec2.scale(lineToCircleOrthoUnit, lineToCircleOrthoUnit, lineRadius); add(projectedPoint,projectedPoint,lineToCircleOrthoUnit); // Check if the point is within the edge span var pos = dot(worldEdgeUnit, projectedPoint); var pos0 = dot(worldEdgeUnit, worldVertex0); var pos1 = dot(worldEdgeUnit, worldVertex1); if(pos > pos0 && pos < pos1){ // We got contact! if(justTest) return true; var c = this.createContactEquation(circleBody,lineBody,si,sj); vec2.scale(c.normalA, orthoDist, -1); vec2.normalize(c.normalA, c.normalA); vec2.scale( c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, projectedPoint, lineOffset); add(c.contactPointB, c.contactPointB, lineOffset); sub(c.contactPointB, c.contactPointB, lineBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; } } // Add corner // @todo reuse array object verts[0] = worldVertex0; verts[1] = worldVertex1; for(var i=0; i<verts.length; i++){ var v = verts[i]; sub(dist, v, circleOffset); if(vec2.squaredLength(dist) < (circleRadius+lineRadius)*(circleRadius+lineRadius)){ if(justTest) return true; var c = this.createContactEquation(circleBody,lineBody,si,sj); vec2.copy(c.normalA, dist); vec2.normalize(c.normalA,c.normalA); // Vector from circle to contact point is the normal times the circle radius vec2.scale(c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, v, lineOffset); vec2.scale(lineEndToLineRadius, c.normalA, -lineRadius); add(c.contactPointB, c.contactPointB, lineEndToLineRadius); add(c.contactPointB, c.contactPointB, lineOffset); sub(c.contactPointB, c.contactPointB, lineBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; } } return 0; }; /** * Circle/capsule Narrowphase * @method circleCapsule * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Line} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CIRCLE | Shape.CAPSULE] = Narrowphase.prototype.circleCapsule = function(bi,si,xi,ai, bj,sj,xj,aj, justTest){ return this.circleLine(bi,si,xi,ai, bj,sj,xj,aj, justTest, sj.radius); }; /** * Circle/convex Narrowphase * @method circleConvex * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Convex} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CIRCLE | Shape.CONVEX] = Narrowphase.prototype[Shape.CIRCLE | Shape.RECTANGLE] = Narrowphase.prototype.circleConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest, circleRadius){ var convexShape = sj, convexAngle = aj, convexBody = bj, convexOffset = xj, circleOffset = xi, circleBody = bi, circleShape = si, circleRadius = typeof(circleRadius)=="number" ? circleRadius : circleShape.radius; var worldVertex0 = tmp1, worldVertex1 = tmp2, worldEdge = tmp3, worldEdgeUnit = tmp4, worldTangent = tmp5, centerDist = tmp6, convexToCircle = tmp7, orthoDist = tmp8, projectedPoint = tmp9, dist = tmp10, worldVertex = tmp11, closestEdge = -1, closestEdgeDistance = null, closestEdgeOrthoDist = tmp12, closestEdgeProjectedPoint = tmp13, candidate = tmp14, candidateDist = tmp15, minCandidate = tmp16, found = false, minCandidateDistance = Number.MAX_VALUE; var numReported = 0; // New algorithm: // 1. Check so center of circle is not inside the polygon. If it is, this wont work... // 2. For each edge // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) // 2. 2. Check if point is inside. verts = convexShape.vertices; // Check all edges first for(var i=0; i!==verts.length+1; i++){ var v0 = verts[i%verts.length], v1 = verts[(i+1)%verts.length]; vec2.rotate(worldVertex0, v0, convexAngle); vec2.rotate(worldVertex1, v1, convexAngle); add(worldVertex0, worldVertex0, convexOffset); add(worldVertex1, worldVertex1, convexOffset); sub(worldEdge, worldVertex1, worldVertex0); vec2.normalize(worldEdgeUnit, worldEdge); // Get tangent to the edge. Points out of the Convex vec2.rotate90cw(worldTangent, worldEdgeUnit); // Get point on circle, closest to the polygon vec2.scale(candidate,worldTangent,-circleShape.radius); add(candidate,candidate,circleOffset); if(pointInConvex(candidate,convexShape,convexOffset,convexAngle)){ vec2.sub(candidateDist,worldVertex0,candidate); var candidateDistance = Math.abs(vec2.dot(candidateDist,worldTangent)); /* // Check distance from the plane spanned by the edge vs the circle sub(dist, circleOffset, worldVertex0); var d = dot(dist, worldTangent); sub(centerDist, worldVertex0, convexOffset); sub(convexToCircle, circleOffset, convexOffset); if(d < circleRadius && dot(centerDist,convexToCircle) > 0){ // Now project the circle onto the edge vec2.scale(orthoDist, worldTangent, d); sub(projectedPoint, circleOffset, orthoDist); // Check if the point is within the edge span var pos = dot(worldEdgeUnit, projectedPoint); var pos0 = dot(worldEdgeUnit, worldVertex0); var pos1 = dot(worldEdgeUnit, worldVertex1); if(pos > pos0 && pos < pos1){ // We got contact! if(justTest) return true; if(closestEdgeDistance === null || d*d<closestEdgeDistance*closestEdgeDistance){ closestEdgeDistance = d; closestEdge = i; vec2.copy(closestEdgeOrthoDist, orthoDist); vec2.copy(closestEdgeProjectedPoint, projectedPoint); } } } */ if(candidateDistance < minCandidateDistance){ vec2.copy(minCandidate,candidate); minCandidateDistance = candidateDistance; vec2.scale(closestEdgeProjectedPoint,worldTangent,candidateDistance); vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,candidate); found = true; } } } if(found){ if(justTest) return true; var c = this.createContactEquation(circleBody,convexBody,si,sj); vec2.sub(c.normalA, minCandidate, circleOffset) vec2.normalize(c.normalA, c.normalA); vec2.scale(c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, closestEdgeProjectedPoint, convexOffset); add(c.contactPointB, c.contactPointB, convexOffset); sub(c.contactPointB, c.contactPointB, convexBody.position); this.contactEquations.push(c); if(this.enableFriction) this.frictionEquations.push( this.createFrictionFromContact(c) ); return 1; } /* if(closestEdge != -1){ var c = this.createContactEquation(circleBody,convexBody); vec2.scale(c.normalA, closestEdgeOrthoDist, -1); vec2.normalize(c.normalA, c.normalA); vec2.scale(c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, closestEdgeProjectedPoint, convexOffset); add(c.contactPointB, c.contactPointB, convexOffset); sub(c.contactPointB, c.contactPointB, convexBody.position); this.contactEquations.push(c); if(this.enableFriction) this.frictionEquations.push( this.createFrictionFromContact(c) ); return true; } */ // Check all vertices if(circleRadius > 0){ for(var i=0; i<verts.length; i++){ var localVertex = verts[i]; vec2.rotate(worldVertex, localVertex, convexAngle); add(worldVertex, worldVertex, convexOffset); sub(dist, worldVertex, circleOffset); if(vec2.squaredLength(dist) < circleRadius*circleRadius){ if(justTest) return true; var c = this.createContactEquation(circleBody,convexBody,si,sj); vec2.copy(c.normalA, dist); vec2.normalize(c.normalA,c.normalA); // Vector from circle to contact point is the normal times the circle radius vec2.scale(c.contactPointA, c.normalA, circleRadius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); sub(c.contactPointB, worldVertex, convexOffset); add(c.contactPointB, c.contactPointB, convexOffset); sub(c.contactPointB, c.contactPointB, convexBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; } } } return 0; }; // Check if a point is in a polygon var pic_worldVertex0 = vec2.create(), pic_worldVertex1 = vec2.create(), pic_r0 = vec2.create(), pic_r1 = vec2.create(); function pointInConvex(worldPoint,convexShape,convexOffset,convexAngle){ var worldVertex0 = pic_worldVertex0, worldVertex1 = pic_worldVertex1, r0 = pic_r0, r1 = pic_r1, point = worldPoint, verts = convexShape.vertices, lastCross = null; for(var i=0; i!==verts.length+1; i++){ var v0 = verts[i%verts.length], v1 = verts[(i+1)%verts.length]; // Transform vertices to world // can we instead transform point to local of the convex??? vec2.rotate(worldVertex0, v0, convexAngle); vec2.rotate(worldVertex1, v1, convexAngle); add(worldVertex0, worldVertex0, convexOffset); add(worldVertex1, worldVertex1, convexOffset); sub(r0, worldVertex0, point); sub(r1, worldVertex1, point); var cross = vec2.crossLength(r0,r1); if(lastCross===null) lastCross = cross; // If we got a different sign of the distance vector, the point is out of the polygon if(cross*lastCross <= 0){ return false; } lastCross = cross; } return true; }; /** * Particle/convex Narrowphase * @method particleConvex * @param {Body} bi * @param {Particle} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Convex} sj * @param {Array} xj * @param {Number} aj * @todo use pointInConvex and code more similar to circleConvex */ Narrowphase.prototype[Shape.PARTICLE | Shape.CONVEX] = Narrowphase.prototype[Shape.PARTICLE | Shape.RECTANGLE] = Narrowphase.prototype.particleConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ var convexShape = sj, convexAngle = aj, convexBody = bj, convexOffset = xj, particleOffset = xi, particleBody = bi, particleShape = si, worldVertex0 = tmp1, worldVertex1 = tmp2, worldEdge = tmp3, worldEdgeUnit = tmp4, worldTangent = tmp5, centerDist = tmp6, convexToparticle = tmp7, orthoDist = tmp8, projectedPoint = tmp9, dist = tmp10, worldVertex = tmp11, closestEdge = -1, closestEdgeDistance = null, closestEdgeOrthoDist = tmp12, closestEdgeProjectedPoint = tmp13, r0 = tmp14, // vector from particle to vertex0 r1 = tmp15, localPoint = tmp16, candidateDist = tmp17, minEdgeNormal = tmp18, minCandidateDistance = Number.MAX_VALUE; var numReported = 0, found = false, verts = convexShape.vertices; // Check if the particle is in the polygon at all if(!pointInConvex(particleOffset,convexShape,convexOffset,convexAngle)){ return 0; } if(justTest) return true; // Check edges first var lastCross = null; for(var i=0; i!==verts.length+1; i++){ var v0 = verts[i%verts.length], v1 = verts[(i+1)%verts.length]; // Transform vertices to world vec2.rotate(worldVertex0, v0, convexAngle); vec2.rotate(worldVertex1, v1, convexAngle); add(worldVertex0, worldVertex0, convexOffset); add(worldVertex1, worldVertex1, convexOffset); // Get world edge sub(worldEdge, worldVertex1, worldVertex0); vec2.normalize(worldEdgeUnit, worldEdge); // Get tangent to the edge. Points out of the Convex vec2.rotate90cw(worldTangent, worldEdgeUnit); // Check distance from the infinite line (spanned by the edge) to the particle sub(dist, particleOffset, worldVertex0); var d = dot(dist, worldTangent); sub(centerDist, worldVertex0, convexOffset); sub(convexToparticle, particleOffset, convexOffset); /* if(d < 0 && dot(centerDist,convexToparticle) >= 0){ // Now project the particle onto the edge vec2.scale(orthoDist, worldTangent, d); sub(projectedPoint, particleOffset, orthoDist); // Check if the point is within the edge span var pos = dot(worldEdgeUnit, projectedPoint); var pos0 = dot(worldEdgeUnit, worldVertex0); var pos1 = dot(worldEdgeUnit, worldVertex1); if(pos > pos0 && pos < pos1){ // We got contact! if(justTest) return true; if(closestEdgeDistance === null || d*d<closestEdgeDistance*closestEdgeDistance){ closestEdgeDistance = d; closestEdge = i; vec2.copy(closestEdgeOrthoDist, orthoDist); vec2.copy(closestEdgeProjectedPoint, projectedPoint); } } } */ vec2.sub(candidateDist,worldVertex0,particleOffset); var candidateDistance = Math.abs(vec2.dot(candidateDist,worldTangent)); if(candidateDistance < minCandidateDistance){ minCandidateDistance = candidateDistance; vec2.scale(closestEdgeProjectedPoint,worldTangent,candidateDistance); vec2.add(closestEdgeProjectedPoint,closestEdgeProjectedPoint,particleOffset); vec2.copy(minEdgeNormal,worldTangent); found = true; } } if(found){ var c = this.createContactEquation(particleBody,convexBody,si,sj); vec2.scale(c.normalA, minEdgeNormal, -1); vec2.normalize(c.normalA, c.normalA); // Particle has no extent to the contact point vec2.set(c.contactPointA, 0, 0); add(c.contactPointA, c.contactPointA, particleOffset); sub(c.contactPointA, c.contactPointA, particleBody.position); // From convex center to point sub(c.contactPointB, closestEdgeProjectedPoint, convexOffset); add(c.contactPointB, c.contactPointB, convexOffset); sub(c.contactPointB, c.contactPointB, convexBody.position); this.contactEquations.push(c); if(this.enableFriction) this.frictionEquations.push( this.createFrictionFromContact(c) ); return 1; } return 0; }; /** * Circle/circle Narrowphase * @method circleCircle * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Circle} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CIRCLE] = Narrowphase.prototype.circleCircle = function( bi,si,xi,ai, bj,sj,xj,aj, justTest, radiusA, radiusB){ var bodyA = bi, shapeA = si, offsetA = xi, bodyB = bj, shapeB = sj, offsetB = xj, dist = tmp1, radiusA = radiusA || shapeA.radius, radiusB = radiusB || shapeB.radius; sub(dist,xi,xj); var r = radiusA + radiusB; if(vec2.squaredLength(dist) > r*r){ return 0; } if(justTest){ return true; } var c = this.createContactEquation(bodyA,bodyB,si,sj); sub(c.normalA, offsetB, offsetA); vec2.normalize(c.normalA,c.normalA); vec2.scale( c.contactPointA, c.normalA, radiusA); vec2.scale( c.contactPointB, c.normalA, -radiusB); add(c.contactPointA, c.contactPointA, offsetA); sub(c.contactPointA, c.contactPointA, bodyA.position); add(c.contactPointB, c.contactPointB, offsetB); sub(c.contactPointB, c.contactPointB, bodyB.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; }; /** * Plane/Convex Narrowphase * @method planeConvex * @param {Body} bi * @param {Plane} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Convex} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.PLANE | Shape.CONVEX] = Narrowphase.prototype[Shape.PLANE | Shape.RECTANGLE] = Narrowphase.prototype.planeConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ var convexBody = bj, convexOffset = xj, convexShape = sj, convexAngle = aj, planeBody = bi, planeShape = si, planeOffset = xi, planeAngle = ai; var worldVertex = tmp1, worldNormal = tmp2, dist = tmp3; var numReported = 0; vec2.rotate(worldNormal, yAxis, planeAngle); for(var i=0; i<convexShape.vertices.length; i++){ var v = convexShape.vertices[i]; vec2.rotate(worldVertex, v, convexAngle); add(worldVertex, worldVertex, convexOffset); sub(dist, worldVertex, planeOffset); if(dot(dist,worldNormal) <= Narrowphase.convexPrecision){ if(justTest){ return true; } // Found vertex numReported++; var c = this.createContactEquation(planeBody,convexBody,planeShape,convexShape); sub(dist, worldVertex, planeOffset); vec2.copy(c.normalA, worldNormal); var d = dot(dist, c.normalA); vec2.scale(dist, c.normalA, d); // rj is from convex center to contact sub(c.contactPointB, worldVertex, convexBody.position); // ri is from plane center to contact sub( c.contactPointA, worldVertex, dist); sub( c.contactPointA, c.contactPointA, planeBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } } } return numReported; }; /** * @method convexPlane * @deprecated Use .planeConvex() instead! */ Narrowphase.prototype.convexPlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ console.warn("Narrowphase.prototype.convexPlane is deprecated. Use planeConvex instead!"); return this.planeConvex( bj,sj,xj,aj, bi,si,xi,ai, justTest ); } /** * Narrowphase for particle vs plane * @method particlePlane * @param {Body} bi The particle body * @param {Particle} si Particle shape * @param {Array} xi World position for the particle * @param {Number} ai World angle for the particle * @param {Body} bj Plane body * @param {Plane} sj Plane shape * @param {Array} xj World position for the plane * @param {Number} aj World angle for the plane */ Narrowphase.prototype[Shape.PARTICLE | Shape.PLANE] = Narrowphase.prototype.particlePlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ var particleBody = bi, particleShape = si, particleOffset = xi, planeBody = bj, planeShape = sj, planeOffset = xj, planeAngle = aj; var dist = tmp1, worldNormal = tmp2; planeAngle = planeAngle || 0; sub(dist, particleOffset, planeOffset); vec2.rotate(worldNormal, yAxis, planeAngle); var d = dot(dist, worldNormal); if(d > 0) return 0; if(justTest) return true; var c = this.createContactEquation(planeBody,particleBody,sj,si); vec2.copy(c.normalA, worldNormal); vec2.scale( dist, c.normalA, d ); // dist is now the distance vector in the normal direction // ri is the particle position projected down onto the plane, from the plane center sub( c.contactPointA, particleOffset, dist); sub( c.contactPointA, c.contactPointA, planeBody.position); // rj is from the body center to the particle center sub( c.contactPointB, particleOffset, particleBody.position ); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; }; /** * Circle/Particle Narrowphase * @method circleParticle * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Particle} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CIRCLE | Shape.PARTICLE] = Narrowphase.prototype.circleParticle = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ var circleBody = bi, circleShape = si, circleOffset = xi, particleBody = bj, particleShape = sj, particleOffset = xj, dist = tmp1; sub(dist, particleOffset, circleOffset); if(vec2.squaredLength(dist) > circleShape.radius*circleShape.radius) return 0; if(justTest) return true; var c = this.createContactEquation(circleBody,particleBody,si,sj); vec2.copy(c.normalA, dist); vec2.normalize(c.normalA,c.normalA); // Vector from circle to contact point is the normal times the circle radius vec2.scale(c.contactPointA, c.normalA, circleShape.radius); add(c.contactPointA, c.contactPointA, circleOffset); sub(c.contactPointA, c.contactPointA, circleBody.position); // Vector from particle center to contact point is zero sub(c.contactPointB, particleOffset, particleBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } return 1; }; var capsulePlane_tmpCircle = new Circle(1), capsulePlane_tmp1 = vec2.create(), capsulePlane_tmp2 = vec2.create(), capsulePlane_tmp3 = vec2.create(); Narrowphase.prototype[Shape.PLANE | Shape.CAPSULE] = Narrowphase.prototype.planeCapsule = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ var end1 = capsulePlane_tmp1, end2 = capsulePlane_tmp2, circle = capsulePlane_tmpCircle, dst = capsulePlane_tmp3; // Compute world end positions vec2.set(end1, -sj.length/2, 0); vec2.rotate(end1,end1,aj); add(end1,end1,xj); vec2.set(end2, sj.length/2, 0); vec2.rotate(end2,end2,aj); add(end2,end2,xj); circle.radius = sj.radius; // Do Narrowphase as two circles var numContacts1 = this.circlePlane(bj,circle,end1,0, bi,si,xi,ai, justTest), numContacts2 = this.circlePlane(bj,circle,end2,0, bi,si,xi,ai, justTest); if(justTest) return numContacts1 || numContacts2; else return numContacts1 + numContacts2; }; /** * @method capsulePlane * @deprecated Use .planeCapsule() instead! */ Narrowphase.prototype.capsulePlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ console.warn("Narrowphase.prototype.capsulePlane() is deprecated. Use .planeCapsule() instead!"); return this.planeCapsule( bj,sj,xj,aj, bi,si,xi,ai, justTest ); } /** * Creates ContactEquations and FrictionEquations for a collision. * @method circlePlane * @param {Body} bi The first body that should be connected to the equations. * @param {Circle} si The circle shape participating in the collision. * @param {Array} xi Extra offset to take into account for the Shape, in addition to the one in circleBody.position. Will *not* be rotated by circleBody.angle (maybe it should, for sake of homogenity?). Set to null if none. * @param {Body} bj The second body that should be connected to the equations. * @param {Plane} sj The Plane shape that is participating * @param {Array} xj Extra offset for the plane shape. * @param {Number} aj Extra angle to apply to the plane */ Narrowphase.prototype[Shape.CIRCLE | Shape.PLANE] = Narrowphase.prototype.circlePlane = function( bi,si,xi,ai, bj,sj,xj,aj, justTest ){ var circleBody = bi, circleShape = si, circleOffset = xi, // Offset from body center, rotated! planeBody = bj, shapeB = sj, planeOffset = xj, planeAngle = aj; planeAngle = planeAngle || 0; // Vector from plane to circle var planeToCircle = tmp1, worldNormal = tmp2, temp = tmp3; sub(planeToCircle, circleOffset, planeOffset); // World plane normal vec2.rotate(worldNormal, yAxis, planeAngle); // Normal direction distance var d = dot(worldNormal, planeToCircle); if(d > circleShape.radius){ return 0; // No overlap. Abort. } if(justTest){ return true; } // Create contact var contact = this.createContactEquation(planeBody,circleBody,sj,si); // ni is the plane world normal vec2.copy(contact.normalA, worldNormal); // rj is the vector from circle center to the contact point vec2.scale(contact.contactPointB, contact.normalA, -circleShape.radius); add(contact.contactPointB, contact.contactPointB, circleOffset); sub(contact.contactPointB, contact.contactPointB, circleBody.position); // ri is the distance from plane center to contact. vec2.scale(temp, contact.normalA, d); sub(contact.contactPointA, planeToCircle, temp ); // Subtract normal distance vector from the distance vector add(contact.contactPointA, contact.contactPointA, planeOffset); sub(contact.contactPointA, contact.contactPointA, planeBody.position); this.contactEquations.push(contact); if(this.enableFriction){ this.frictionEquations.push( this.createFrictionFromContact(contact) ); } return 1; }; Narrowphase.convexPrecision = 1e-7; /** * Convex/convex Narrowphase.See <a href="http://www.altdevblogaday.com/2011/05/13/contact-generation-between-3d-convex-meshes/">this article</a> for more info. * @method convexConvex * @param {Body} bi * @param {Convex} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Convex} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CONVEX] = Narrowphase.prototype[Shape.CONVEX | Shape.RECTANGLE] = Narrowphase.prototype[Shape.RECTANGLE] = Narrowphase.prototype.convexConvex = function( bi,si,xi,ai, bj,sj,xj,aj, justTest, precision ){ var sepAxis = tmp1, worldPoint = tmp2, worldPoint0 = tmp3, worldPoint1 = tmp4, worldEdge = tmp5, projected = tmp6, penetrationVec = tmp7, dist = tmp8, worldNormal = tmp9, numContacts = 0, precision = precision || Narrowphase.convexPrecision; var found = Narrowphase.findSeparatingAxis(si,xi,ai,sj,xj,aj,sepAxis); if(!found){ return 0; } // Make sure the separating axis is directed from shape i to shape j sub(dist,xj,xi); if(dot(sepAxis,dist) > 0){ vec2.scale(sepAxis,sepAxis,-1); } // Find edges with normals closest to the separating axis var closestEdge1 = Narrowphase.getClosestEdge(si,ai,sepAxis,true), // Flipped axis closestEdge2 = Narrowphase.getClosestEdge(sj,aj,sepAxis); if(closestEdge1 === -1 || closestEdge2 === -1){ return 0; } // Loop over the shapes for(var k=0; k<2; k++){ var closestEdgeA = closestEdge1, closestEdgeB = closestEdge2, shapeA = si, shapeB = sj, offsetA = xi, offsetB = xj, angleA = ai, angleB = aj, bodyA = bi, bodyB = bj; if(k === 0){ // Swap! var tmp; tmp = closestEdgeA; closestEdgeA = closestEdgeB; closestEdgeB = tmp; tmp = shapeA; shapeA = shapeB; shapeB = tmp; tmp = offsetA; offsetA = offsetB; offsetB = tmp; tmp = angleA; angleA = angleB; angleB = tmp; tmp = bodyA; bodyA = bodyB; bodyB = tmp; } // Loop over 2 points in convex B for(var j=closestEdgeB; j<closestEdgeB+2; j++){ // Get world point var v = shapeB.vertices[(j+shapeB.vertices.length)%shapeB.vertices.length]; vec2.rotate(worldPoint, v, angleB); add(worldPoint, worldPoint, offsetB); var insideNumEdges = 0; // Loop over the 3 closest edges in convex A for(var i=closestEdgeA-1; i<closestEdgeA+2; i++){ var v0 = shapeA.vertices[(i +shapeA.vertices.length)%shapeA.vertices.length], v1 = shapeA.vertices[(i+1+shapeA.vertices.length)%shapeA.vertices.length]; // Construct the edge vec2.rotate(worldPoint0, v0, angleA); vec2.rotate(worldPoint1, v1, angleA); add(worldPoint0, worldPoint0, offsetA); add(worldPoint1, worldPoint1, offsetA); sub(worldEdge, worldPoint1, worldPoint0); vec2.rotate90cw(worldNormal, worldEdge); // Normal points out of convex 1 vec2.normalize(worldNormal,worldNormal); sub(dist, worldPoint, worldPoint0); var d = dot(worldNormal,dist); if(d <= precision){ insideNumEdges++; } } if(insideNumEdges >= 3){ if(justTest){ return true; } // worldPoint was on the "inside" side of each of the 3 checked edges. // Project it to the center edge and use the projection direction as normal // Create contact var c = this.createContactEquation(bodyA,bodyB,shapeA,shapeB); numContacts++; // Get center edge from body A var v0 = shapeA.vertices[(closestEdgeA) % shapeA.vertices.length], v1 = shapeA.vertices[(closestEdgeA+1) % shapeA.vertices.length]; // Construct the edge vec2.rotate(worldPoint0, v0, angleA); vec2.rotate(worldPoint1, v1, angleA); add(worldPoint0, worldPoint0, offsetA); add(worldPoint1, worldPoint1, offsetA); sub(worldEdge, worldPoint1, worldPoint0); vec2.rotate90cw(c.normalA, worldEdge); // Normal points out of convex A vec2.normalize(c.normalA,c.normalA); sub(dist, worldPoint, worldPoint0); // From edge point to the penetrating point var d = dot(c.normalA,dist); // Penetration vec2.scale(penetrationVec, c.normalA, d); // Vector penetration sub(c.contactPointA, worldPoint, offsetA); sub(c.contactPointA, c.contactPointA, penetrationVec); add(c.contactPointA, c.contactPointA, offsetA); sub(c.contactPointA, c.contactPointA, bodyA.position); sub(c.contactPointB, worldPoint, offsetB); add(c.contactPointB, c.contactPointB, offsetB); sub(c.contactPointB, c.contactPointB, bodyB.position); this.contactEquations.push(c); // Todo reduce to 1 friction equation if we have 2 contact points if(this.enableFriction) this.frictionEquations.push(this.createFrictionFromContact(c)); } } } return numContacts; }; // .projectConvex is called by other functions, need local tmp vectors var pcoa_tmp1 = vec2.fromValues(0,0); /** * Project a Convex onto a world-oriented axis * @method projectConvexOntoAxis * @static * @param {Convex} convexShape * @param {Array} convexOffset * @param {Number} convexAngle * @param {Array} worldAxis * @param {Array} result */ Narrowphase.projectConvexOntoAxis = function(convexShape, convexOffset, convexAngle, worldAxis, result){ var max=null, min=null, v, value, localAxis = pcoa_tmp1; // Convert the axis to local coords of the body vec2.rotate(localAxis, worldAxis, -convexAngle); // Get projected position of all vertices for(var i=0; i<convexShape.vertices.length; i++){ v = convexShape.vertices[i]; value = dot(v,localAxis); if(max === null || value > max) max = value; if(min === null || value < min) min = value; } if(min > max){ var t = min; min = max; max = t; } // Project the position of the body onto the axis - need to add this to the result var offset = dot(convexOffset, worldAxis); vec2.set( result, min + offset, max + offset); }; // .findSeparatingAxis is called by other functions, need local tmp vectors var fsa_tmp1 = vec2.fromValues(0,0) , fsa_tmp2 = vec2.fromValues(0,0) , fsa_tmp3 = vec2.fromValues(0,0) , fsa_tmp4 = vec2.fromValues(0,0) , fsa_tmp5 = vec2.fromValues(0,0) , fsa_tmp6 = vec2.fromValues(0,0) /** * Find a separating axis between the shapes, that maximizes the separating distance between them. * @method findSeparatingAxis * @static * @param {Convex} c1 * @param {Array} offset1 * @param {Number} angle1 * @param {Convex} c2 * @param {Array} offset2 * @param {Number} angle2 * @param {Array} sepAxis The resulting axis * @return {Boolean} Whether the axis could be found. */ Narrowphase.findSeparatingAxis = function(c1,offset1,angle1,c2,offset2,angle2,sepAxis){ var maxDist = null, overlap = false, found = false, edge = fsa_tmp1, worldPoint0 = fsa_tmp2, worldPoint1 = fsa_tmp3, normal = fsa_tmp4, span1 = fsa_tmp5, span2 = fsa_tmp6; for(var j=0; j!==2; j++){ var c = c1, angle = angle1; if(j===1){ c = c2; angle = angle2; } for(var i=0; i!==c.vertices.length; i++){ // Get the world edge vec2.rotate(worldPoint0, c.vertices[i], angle); vec2.rotate(worldPoint1, c.vertices[(i+1)%c.vertices.length], angle); sub(edge, worldPoint1, worldPoint0); // Get normal - just rotate 90 degrees since vertices are given in CCW vec2.rotate90cw(normal, edge); vec2.normalize(normal,normal); // Project hulls onto that normal Narrowphase.projectConvexOntoAxis(c1,offset1,angle1,normal,span1); Narrowphase.projectConvexOntoAxis(c2,offset2,angle2,normal,span2); // Order by span position var a=span1, b=span2, swapped = false; if(span1[0] > span2[0]){ b=span1; a=span2; swapped = true; } // Get separating distance var dist = b[0] - a[1]; overlap = (dist <= Narrowphase.convexPrecision); if(maxDist===null || dist > maxDist){ vec2.copy(sepAxis, normal); maxDist = dist; found = overlap; } } } return found; }; // .getClosestEdge is called by other functions, need local tmp vectors var gce_tmp1 = vec2.fromValues(0,0) , gce_tmp2 = vec2.fromValues(0,0) , gce_tmp3 = vec2.fromValues(0,0) /** * Get the edge that has a normal closest to an axis. * @method getClosestEdge * @static * @param {Convex} c * @param {Number} angle * @param {Array} axis * @param {Boolean} flip * @return {Number} Index of the edge that is closest. This index and the next spans the resulting edge. Returns -1 if failed. */ Narrowphase.getClosestEdge = function(c,angle,axis,flip){ var localAxis = gce_tmp1, edge = gce_tmp2, normal = gce_tmp3; // Convert the axis to local coords of the body vec2.rotate(localAxis, axis, -angle); if(flip){ vec2.scale(localAxis,localAxis,-1); } var closestEdge = -1, N = c.vertices.length; for(var i=0; i!==N; i++){ // Get the edge sub(edge, c.vertices[(i+1)%N], c.vertices[i%N]); // Get normal - just rotate 90 degrees since vertices are given in CCW vec2.rotate90cw(normal, edge); vec2.normalize(normal,normal); var d = dot(normal,localAxis); if(closestEdge == -1 || d > maxDot){ closestEdge = i % N; maxDot = d; } } return closestEdge; }; var circleHeightfield_candidate = vec2.create(), circleHeightfield_dist = vec2.create(), circleHeightfield_v0 = vec2.create(), circleHeightfield_v1 = vec2.create(), circleHeightfield_minCandidate = vec2.create(), circleHeightfield_worldNormal = vec2.create(), circleHeightfield_minCandidateNormal = vec2.create(); /** * @method circleHeightfield * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Body} bj * @param {Heightfield} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.CIRCLE | Shape.HEIGHTFIELD] = Narrowphase.prototype.circleHeightfield = function( circleBody,circleShape,circlePos,circleAngle, hfBody,hfShape,hfPos,hfAngle, justTest, radius ){ var data = hfShape.data, radius = radius || circleShape.radius, w = hfShape.elementWidth, dist = circleHeightfield_dist, candidate = circleHeightfield_candidate, minCandidate = circleHeightfield_minCandidate, minCandidateNormal = circleHeightfield_minCandidateNormal, worldNormal = circleHeightfield_worldNormal, v0 = circleHeightfield_v0, v1 = circleHeightfield_v1; // Get the index of the points to test against var idxA = Math.floor( (circlePos[0] - radius - hfPos[0]) / w ), idxB = Math.ceil( (circlePos[0] + radius - hfPos[0]) / w ); /*if(idxB < 0 || idxA >= data.length) return justTest ? false : 0;*/ if(idxA < 0) idxA = 0; if(idxB >= data.length) idxB = data.length-1; // Get max and min var max = data[idxA], min = data[idxB]; for(var i=idxA; i<idxB; i++){ if(data[i] < min) min = data[i]; if(data[i] > max) max = data[i]; } if(circlePos[1]-radius > max) return justTest ? false : 0; if(circlePos[1]+radius < min){ // Below the minimum point... We can just guess. // TODO } // 1. Check so center of circle is not inside the field. If it is, this wont work... // 2. For each edge // 2. 1. Get point on circle that is closest to the edge (scale normal with -radius) // 2. 2. Check if point is inside. var found = false; // Check all edges first for(var i=idxA; i<idxB; i++){ // Get points vec2.set(v0, i*w, data[i] ); vec2.set(v1, (i+1)*w, data[i+1]); vec2.add(v0,v0,hfPos); vec2.add(v1,v1,hfPos); // Get normal vec2.sub(worldNormal, v1, v0); vec2.rotate(worldNormal, worldNormal, Math.PI/2); vec2.normalize(worldNormal,worldNormal); // Get point on circle, closest to the edge vec2.scale(candidate,worldNormal,-radius); vec2.add(candidate,candidate,circlePos); // Distance from v0 to the candidate point vec2.sub(dist,candidate,v0); // Check if it is in the element "stick" var d = vec2.dot(dist,worldNormal); if(candidate[0] >= v0[0] && candidate[0] < v1[0] && d <= 0){ if(justTest){ return true; } found = true; // Store the candidate point, projected to the edge vec2.scale(dist,worldNormal,-d); vec2.add(minCandidate,candidate,dist); vec2.copy(minCandidateNormal,worldNormal); var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); // Normal is out of the heightfield vec2.copy(c.normalA, minCandidateNormal); // Vector from circle to heightfield vec2.scale(c.contactPointB, c.normalA, -radius); add(c.contactPointB, c.contactPointB, circlePos); sub(c.contactPointB, c.contactPointB, circleBody.position); vec2.copy(c.contactPointA, minCandidate); vec2.sub(c.contactPointA, c.contactPointA, hfBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push( this.createFrictionFromContact(c) ); } } } // Check all vertices found = false; if(radius > 0){ for(var i=idxA; i<=idxB; i++){ // Get point vec2.set(v0, i*w, data[i]); vec2.add(v0,v0,hfPos); vec2.sub(dist, circlePos, v0); if(vec2.squaredLength(dist) < radius*radius){ if(justTest) return true; found = true; var c = this.createContactEquation(hfBody,circleBody,hfShape,circleShape); // Construct normal - out of heightfield vec2.copy(c.normalA, dist); vec2.normalize(c.normalA,c.normalA); vec2.scale(c.contactPointB, c.normalA, -radius); add(c.contactPointB, c.contactPointB, circlePos); sub(c.contactPointB, c.contactPointB, circleBody.position); sub(c.contactPointA, v0, hfPos); add(c.contactPointA, c.contactPointA, hfPos); sub(c.contactPointA, c.contactPointA, hfBody.position); this.contactEquations.push(c); if(this.enableFriction){ this.frictionEquations.push(this.createFrictionFromContact(c)); } } } } if(found){ return 1; } return 0; }; var convexHeightfield_v0 = vec2.create(), convexHeightfield_v1 = vec2.create(), convexHeightfield_tilePos = vec2.create(), convexHeightfield_tempConvexShape = new Convex([vec2.create(),vec2.create(),vec2.create(),vec2.create()]); /** * @method circleHeightfield * @param {Body} bi * @param {Circle} si * @param {Array} xi * @param {Body} bj * @param {Heightfield} sj * @param {Array} xj * @param {Number} aj */ Narrowphase.prototype[Shape.RECTANGLE | Shape.HEIGHTFIELD] = Narrowphase.prototype[Shape.CONVEX | Shape.HEIGHTFIELD] = Narrowphase.prototype.convexHeightfield = function( convexBody,convexShape,convexPos,convexAngle, hfBody,hfShape,hfPos,hfAngle, justTest ){ var data = hfShape.data, w = hfShape.elementWidth, v0 = convexHeightfield_v0, v1 = convexHeightfield_v1, tilePos = convexHeightfield_tilePos, tileConvex = convexHeightfield_tempConvexShape; // Get the index of the points to test against var idxA = Math.floor( (convexBody.aabb.lowerBound[0] - hfPos[0]) / w ), idxB = Math.ceil( (convexBody.aabb.upperBound[0] - hfPos[0]) / w ); if(idxA < 0) idxA = 0; if(idxB >= data.length) idxB = data.length-1; // Get max and min var max = data[idxA], min = data[idxB]; for(var i=idxA; i<idxB; i++){ if(data[i] < min) min = data[i]; if(data[i] > max) max = data[i]; } if(convexBody.aabb.lowerBound[1] > max){ return justTest ? false : 0; } var found = false; var numContacts = 0; // Loop over all edges for(var i=idxA; i<idxB; i++){ // Get points vec2.set(v0, i*w, data[i] ); vec2.set(v1, (i+1)*w, data[i+1]); vec2.add(v0,v0,hfPos); vec2.add(v1,v1,hfPos); // Construct a convex var tileHeight = 100; // todo vec2.set(tilePos, (v1[0] + v0[0])*0.5, (v1[1] + v0[1] - tileHeight)*0.5); vec2.sub(tileConvex.vertices[0], v1, tilePos); vec2.sub(tileConvex.vertices[1], v0, tilePos); vec2.copy(tileConvex.vertices[2], tileConvex.vertices[1]); vec2.copy(tileConvex.vertices[3], tileConvex.vertices[0]); tileConvex.vertices[2][1] -= tileHeight; tileConvex.vertices[3][1] -= tileHeight; // Do convex collision numContacts += this.convexConvex( convexBody, convexShape, convexPos, convexAngle, hfBody, tileConvex, tilePos, 0, justTest); } return numContacts; }; },{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/FrictionEquation":23,"../math/vec2":30,"../objects/Body":31,"../shapes/Circle":35,"../shapes/Convex":36,"../shapes/Rectangle":41,"../shapes/Shape":42,"../utils/TupleDictionary":46,"../utils/Utils":47}],13:[function(require,module,exports){ var Utils = require('../utils/Utils') , Broadphase = require('../collision/Broadphase'); module.exports = SAPBroadphase; /** * Sweep and prune broadphase along one axis. * * @class SAPBroadphase * @constructor * @extends Broadphase */ function SAPBroadphase(){ Broadphase.call(this,Broadphase.SAP); /** * List of bodies currently in the broadphase. * @property axisList * @type {Array} */ this.axisList = []; /** * The world to search in. * @property world * @type {World} */ this.world = null; /** * The axis to sort along. * @property axisIndex * @type {Number} */ this.axisIndex = 0; var axisList = this.axisList; this._addBodyHandler = function(e){ axisList.push(e.body); }; this._removeBodyHandler = function(e){ // Remove from list var idx = axisList.indexOf(e.body); if(idx !== -1){ axisList.splice(idx,1); } }; } SAPBroadphase.prototype = new Broadphase(); /** * Change the world * @method setWorld * @param {World} world */ SAPBroadphase.prototype.setWorld = function(world){ // Clear the old axis array this.axisList.length = 0; // Add all bodies from the new world Utils.appendArray(this.axisList, world.bodies); // Remove old handlers, if any world .off("addBody",this._addBodyHandler) .off("removeBody",this._removeBodyHandler); // Add handlers to update the list of bodies. world.on("addBody",this._addBodyHandler).on("removeBody",this._removeBodyHandler); this.world = world; }; /** * Sorts bodies along an axis. * @method sortAxisList * @param {Array} a * @param {number} axisIndex * @return {Array} */ SAPBroadphase.sortAxisList = function(a, axisIndex){ axisIndex = axisIndex|0; for(var i=1,l=a.length; i<l; i++) { var v = a[i]; for(var j=i - 1;j>=0;j--) { if(a[j].aabb.lowerBound[axisIndex] <= v.aabb.lowerBound[axisIndex]){ break; } a[j+1] = a[j]; } a[j+1] = v; } return a; }; /** * Get the colliding pairs * @method getCollisionPairs * @param {World} world * @return {Array} */ SAPBroadphase.prototype.getCollisionPairs = function(world){ var bodies = this.axisList, result = this.result, axisIndex = this.axisIndex; result.length = 0; // Update all AABBs if needed var l = bodies.length; while(l--){ var b = bodies[l]; if(b.aabbNeedsUpdate){ b.updateAABB(); } } // Sort the lists SAPBroadphase.sortAxisList(bodies, axisIndex); // Look through the X list for(var i=0, N=bodies.length|0; i!==N; i++){ var bi = bodies[i]; for(var j=i+1; j<N; j++){ var bj = bodies[j]; // Bounds overlap? var overlaps = (bj.aabb.lowerBound[axisIndex] <= bi.aabb.upperBound[axisIndex]); if(!overlaps){ break; } if(Broadphase.canCollide(bi,bj) && this.boundingVolumeCheck(bi,bj)){ result.push(bi,bj); } } } return result; }; },{"../collision/Broadphase":9,"../utils/Utils":47}],14:[function(require,module,exports){ module.exports = Constraint; var Utils = require('../utils/Utils'); /** * Base constraint class. * * @class Constraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {Number} type * @param {Object} [options] * @param {Object} [options.collideConnected=true] */ function Constraint(bodyA, bodyB, type, options){ this.type = type; options = Utils.defaults(options,{ collideConnected : true, wakeUpBodies : true, }); /** * Equations to be solved in this constraint * * @property equations * @type {Array} */ this.equations = []; /** * First body participating in the constraint. * @property bodyA * @type {Body} */ this.bodyA = bodyA; /** * Second body participating in the constraint. * @property bodyB * @type {Body} */ this.bodyB = bodyB; /** * Set to true if you want the connected bodies to collide. * @property collideConnected * @type {Boolean} * @default true */ this.collideConnected = options.collideConnected; // Wake up bodies when connected if(options.wakeUpBodies){ if(bodyA){ bodyA.wakeUp(); } if(bodyB){ bodyB.wakeUp(); } } } /** * Updates the internal constraint parameters before solve. * @method update */ Constraint.prototype.update = function(){ throw new Error("method update() not implmemented in this Constraint subclass!"); }; Constraint.DISTANCE = 1; Constraint.GEAR = 2; Constraint.LOCK = 3; Constraint.PRISMATIC = 4; Constraint.REVOLUTE = 5; /** * Set stiffness for this constraint. * @method setStiffness * @param {Number} stiffness */ Constraint.prototype.setStiffness = function(stiffness){ var eqs = this.equations; for(var i=0; i !== eqs.length; i++){ var eq = eqs[i]; eq.stiffness = stiffness; eq.needsUpdate = true; } }; /** * Set relaxation for this constraint. * @method setRelaxation * @param {Number} relaxation */ Constraint.prototype.setRelaxation = function(relaxation){ var eqs = this.equations; for(var i=0; i !== eqs.length; i++){ var eq = eqs[i]; eq.relaxation = relaxation; eq.needsUpdate = true; } }; },{"../utils/Utils":47}],15:[function(require,module,exports){ var Constraint = require('./Constraint') , Equation = require('../equations/Equation') , vec2 = require('../math/vec2') module.exports = DistanceConstraint; /** * Constraint that tries to keep the distance between two bodies constant. * * @class DistanceConstraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {number} distance The distance to keep between the bodies. * @param {object} [options] * @param {object} [options.maxForce=Number.MAX_VALUE] Maximum force to apply. * @extends Constraint */ function DistanceConstraint(bodyA,bodyB,distance,options){ options = options || {}; Constraint.call(this,bodyA,bodyB,Constraint.DISTANCE,options); /** * The distance to keep. * @property distance * @type {Number} */ this.distance = distance; /** * Local anchor in body A. * @property localAnchorA * @type {Array} */ this.localAnchorA = vec2.create(); /** * Local anchor in body B. * @property localAnchorB * @type {Array} */ this.localAnchorB = vec2.create(); var localAnchorA = this.localAnchorA; var localAnchorB = this.localAnchorB; var maxForce; if(typeof(options.maxForce)==="undefined" ){ maxForce = Number.MAX_VALUE; } else { maxForce = options.maxForce; } var normal = new Equation(bodyA,bodyB,-maxForce,maxForce); // Just in the normal direction this.equations = [ normal ]; // g = (xi - xj).dot(n) // dg/dt = (vi - vj).dot(n) = G*W = [n 0 -n 0] * [vi wi vj wj]' // ...and if we were to include offset points (TODO for now): // g = // (xj + rj - xi - ri).dot(n) - distance // // dg/dt = // (vj + wj x rj - vi - wi x ri).dot(n) = // { term 2 is near zero } = // [-n -ri x n n rj x n] * [vi wi vj wj]' = // G * W // // => G = [-n -rixn n rjxn] var r = vec2.create(); var ri = vec2.create(); // worldAnchorA var rj = vec2.create(); // worldAnchorB var that = this; normal.computeGq = function(){ var bodyA = this.bodyA, bodyB = this.bodyB, xi = bodyA.position, xj = bodyB.position; // Transform local anchors to world vec2.rotate(ri, localAnchorA, bodyA.angle); vec2.rotate(rj, localAnchorB, bodyB.angle); vec2.add(r, xi, rj); vec2.sub(r, r, ri); vec2.sub(r, r, xi); vec2.sub(r, bodyB.position, bodyA.position); return vec2.length(r) - that.distance; }; // Make the contact constraint bilateral this.setMaxForce(maxForce); } DistanceConstraint.prototype = new Constraint(); /** * Update the constraint equations. Should be done if any of the bodies changed position, before solving. * @method update */ var n = vec2.create(); var ri = vec2.create(); // worldAnchorA var rj = vec2.create(); // worldAnchorB DistanceConstraint.prototype.update = function(){ var normal = this.equations[0], bodyA = this.bodyA, bodyB = this.bodyB, distance = this.distance, xi = bodyA.position, xj = bodyB.position, G = normal.G; // Transform local anchors to world vec2.rotate(ri, this.localAnchorA, bodyA.angle); vec2.rotate(rj, this.localAnchorB, bodyB.angle); // Caluclate cross products var rixn = vec2.crossLength(ri, n), rjxn = vec2.crossLength(rj, n); /* // G = [-n -rixn n rjxn] G[0] = -n[0]; G[1] = -n[1]; G[2] = -rixn; G[3] = n[0]; G[4] = n[1]; G[5] = rjxn; */ vec2.sub(n, bodyB.position, bodyA.position); vec2.normalize(n,n); G[0] = -n[0]; G[1] = -n[1]; G[3] = n[0]; G[4] = n[1]; }; /** * Set the max force to be used * @method setMaxForce * @param {Number} f */ DistanceConstraint.prototype.setMaxForce = function(f){ var normal = this.equations[0]; normal.minForce = -f; normal.maxForce = f; }; /** * Get the max force * @method getMaxForce * @return {Number} */ DistanceConstraint.prototype.getMaxForce = function(f){ var normal = this.equations[0]; return normal.maxForce; }; },{"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],16:[function(require,module,exports){ var Constraint = require('./Constraint') , Equation = require('../equations/Equation') , AngleLockEquation = require('../equations/AngleLockEquation') , vec2 = require('../math/vec2') module.exports = GearConstraint; /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * @class GearConstraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Number} [options.angle=0] Relative angle between the bodies. * @param {Number} [options.ratio=1] Gear ratio. * @param {Number} [options.maxTorque] Maximum torque to apply. * @extends Constraint * @todo Ability to specify world points */ function GearConstraint(bodyA, bodyB, options){ options = options || {}; Constraint.call(this, bodyA, bodyB, Constraint.GEAR, options); this.equations = [ new AngleLockEquation(bodyA,bodyB,options), ]; /** * The relative angle * @property angle * @type {Number} */ this.angle = typeof(options.angle) === "number" ? options.angle : 0; /** * The gear ratio. * @property ratio * @type {Number} */ this.ratio = typeof(options.ratio) === "number" ? options.ratio : 1; // Set max torque if(typeof(options.maxTorque) === "number"){ this.setMaxTorque(options.maxTorque); } } GearConstraint.prototype = new Constraint(); GearConstraint.prototype.update = function(){ var eq = this.equations[0]; if(eq.ratio !== this.ratio){ eq.setRatio(this.ratio); } eq.angle = this.angle; }; /** * Set the max torque for the constraint. * @method setMaxTorque * @param {Number} torque */ GearConstraint.prototype.setMaxTorque = function(torque){ this.equations[0].setMaxTorque(torque); }; /** * Get the max torque for the constraint. * @method getMaxTorque * @return {Number} */ GearConstraint.prototype.getMaxTorque = function(torque){ return this.equations[0].maxForce; }; },{"../equations/AngleLockEquation":20,"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],17:[function(require,module,exports){ var Constraint = require('./Constraint') , vec2 = require('../math/vec2') , Equation = require('../equations/Equation') module.exports = LockConstraint; /** * Locks the relative position between two bodies. * * @class LockConstraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Array} [options.localOffsetB] The offset of bodyB in bodyA's frame. Default is the zero vector. * @param {number} [options.localAngleB=0] The angle of bodyB in bodyA's frame. * @param {number} [options.maxForce] * @extends Constraint */ function LockConstraint(bodyA, bodyB, options){ options = options || {}; Constraint.call(this,bodyA,bodyB,Constraint.LOCK,options); var maxForce = ( typeof(options.maxForce)==="undefined" ? Number.MAX_VALUE : options.maxForce ); var localOffsetB = options.localOffsetB || vec2.fromValues(0,0); localOffsetB = vec2.fromValues(localOffsetB[0],localOffsetB[1]); var localAngleB = options.localAngleB || 0; // Use 3 equations: // gx = (xj - xi - l) * xhat = 0 // gy = (xj - xi - l) * yhat = 0 // gr = (xi - xj + r) * that = 0 // // ...where: // l is the localOffsetB vector rotated to world in bodyA frame // r is the same vector but reversed and rotated from bodyB frame // xhat, yhat are world axis vectors // that is the tangent of r // // For the first two constraints, we get // G*W = (vj - vi - ldot ) * xhat // = (vj - vi - wi x l) * xhat // // Since (wi x l) * xhat = (l x xhat) * wi, we get // G*W = [ -1 0 (-l x xhat) 1 0 0] * [vi wi vj wj] // // The last constraint gives // GW = (vi - vj + wj x r) * that // = [ that 0 -that (r x t) ] var x = new Equation(bodyA,bodyB,-maxForce,maxForce), y = new Equation(bodyA,bodyB,-maxForce,maxForce), rot = new Equation(bodyA,bodyB,-maxForce,maxForce); var l = vec2.create(), g = vec2.create(), that = this; x.computeGq = function(){ vec2.rotate(l, that.localOffsetB, bodyA.angle); vec2.sub(g, bodyB.position, bodyA.position); vec2.sub(g, g, l); return g[0]; }; y.computeGq = function(){ vec2.rotate(l, that.localOffsetB, bodyA.angle); vec2.sub(g, bodyB.position, bodyA.position); vec2.sub(g, g, l); return g[1]; }; var r = vec2.create(), t = vec2.create(); rot.computeGq = function(){ vec2.rotate(r, that.localOffsetB, bodyB.angle - that.localAngleB); vec2.scale(r,r,-1); vec2.sub(g,bodyA.position,bodyB.position); vec2.add(g,g,r); vec2.rotate(t,r,-Math.PI/2); vec2.normalize(t,t); return vec2.dot(g,t); }; /** * The offset of bodyB in bodyA's frame. * @property {Array} localOffsetB */ this.localOffsetB = localOffsetB; /** * The offset angle of bodyB in bodyA's frame. * @property {Number} localAngleB */ this.localAngleB = localAngleB; this.equations.push(x, y, rot); this.setMaxForce(maxForce); } LockConstraint.prototype = new Constraint(); /** * Set the maximum force to be applied. * @method setMaxForce * @param {Number} force */ LockConstraint.prototype.setMaxForce = function(force){ var eqs = this.equations; for(var i=0; i<this.equations.length; i++){ eqs[i].maxForce = force; eqs[i].minForce = -force; } }; /** * Get the max force. * @method getMaxForce * @return {Number} */ LockConstraint.prototype.getMaxForce = function(){ return this.equations[0].maxForce; }; var l = vec2.create(); var r = vec2.create(); var t = vec2.create(); var xAxis = vec2.fromValues(1,0); var yAxis = vec2.fromValues(0,1); LockConstraint.prototype.update = function(){ var x = this.equations[0], y = this.equations[1], rot = this.equations[2], bodyA = this.bodyA, bodyB = this.bodyB; vec2.rotate(l,this.localOffsetB,bodyA.angle); vec2.rotate(r,this.localOffsetB,bodyB.angle - this.localAngleB); vec2.scale(r,r,-1); vec2.rotate(t,r,Math.PI/2); vec2.normalize(t,t); x.G[0] = -1; x.G[1] = 0; x.G[2] = -vec2.crossLength(l,xAxis); x.G[3] = 1; y.G[0] = 0; y.G[1] = -1; y.G[2] = -vec2.crossLength(l,yAxis); y.G[4] = 1; rot.G[0] = -t[0]; rot.G[1] = -t[1]; rot.G[3] = t[0]; rot.G[4] = t[1]; rot.G[5] = vec2.crossLength(r,t); }; },{"../equations/Equation":22,"../math/vec2":30,"./Constraint":14}],18:[function(require,module,exports){ var Constraint = require('./Constraint') , ContactEquation = require('../equations/ContactEquation') , Equation = require('../equations/Equation') , vec2 = require('../math/vec2') , RotationalLockEquation = require('../equations/RotationalLockEquation') module.exports = PrismaticConstraint; /** * Constraint that only allows bodies to move along a line, relative to each other. See <a href="http://www.iforce2d.net/b2dtut/joints-prismatic">this tutorial</a>. * * @class PrismaticConstraint * @constructor * @extends Constraint * @author schteppe * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Number} [options.maxForce] Max force to be applied by the constraint * @param {Array} [options.localAnchorA] Body A's anchor point, defined in its own local frame. * @param {Array} [options.localAnchorB] Body B's anchor point, defined in its own local frame. * @param {Array} [options.localAxisA] An axis, defined in body A frame, that body B's anchor point may slide along. * @param {Boolean} [options.disableRotationalLock] If set to true, bodyB will be free to rotate around its anchor point. * @param {Number} [options.upperLimit] * @param {Number} [options.lowerLimit] */ function PrismaticConstraint(bodyA, bodyB, options){ options = options || {}; Constraint.call(this,bodyA,bodyB,Constraint.PRISMATIC,options); // Get anchors var localAnchorA = vec2.fromValues(0,0), localAxisA = vec2.fromValues(1,0), localAnchorB = vec2.fromValues(0,0); if(options.localAnchorA) vec2.copy(localAnchorA, options.localAnchorA); if(options.localAxisA) vec2.copy(localAxisA, options.localAxisA); if(options.localAnchorB) vec2.copy(localAnchorB, options.localAnchorB); /** * @property localAnchorA * @type {Array} */ this.localAnchorA = localAnchorA; /** * @property localAnchorB * @type {Array} */ this.localAnchorB = localAnchorB; /** * @property localAxisA * @type {Array} */ this.localAxisA = localAxisA; /* The constraint violation for the common axis point is g = ( xj + rj - xi - ri ) * t := gg*t where r are body-local anchor points, and t is a tangent to the constraint axis defined in body i frame. gdot = ( vj + wj x rj - vi - wi x ri ) * t + ( xj + rj - xi - ri ) * ( wi x t ) Note the use of the chain rule. Now we identify the jacobian G*W = [ -t -ri x t + t x gg t rj x t ] * [vi wi vj wj] The rotational part is just a rotation lock. */ var maxForce = this.maxForce = typeof(options.maxForce)!="undefined" ? options.maxForce : Number.MAX_VALUE; // Translational part var trans = new Equation(bodyA,bodyB,-maxForce,maxForce); var ri = new vec2.create(), rj = new vec2.create(), gg = new vec2.create(), t = new vec2.create(); trans.computeGq = function(){ // g = ( xj + rj - xi - ri ) * t return vec2.dot(gg,t); }; trans.updateJacobian = function(){ var G = this.G, xi = bodyA.position, xj = bodyB.position; vec2.rotate(ri,localAnchorA,bodyA.angle); vec2.rotate(rj,localAnchorB,bodyB.angle); vec2.add(gg,xj,rj); vec2.sub(gg,gg,xi); vec2.sub(gg,gg,ri); vec2.rotate(t,localAxisA,bodyA.angle+Math.PI/2); G[0] = -t[0]; G[1] = -t[1]; G[2] = -vec2.crossLength(ri,t) + vec2.crossLength(t,gg); G[3] = t[0]; G[4] = t[1]; G[5] = vec2.crossLength(rj,t); }; this.equations.push(trans); // Rotational part if(!options.disableRotationalLock){ var rot = new RotationalLockEquation(bodyA,bodyB,-maxForce,maxForce); this.equations.push(rot); } /** * The position of anchor A relative to anchor B, along the constraint axis. * @property position * @type {Number} */ this.position = 0; this.velocity = 0; /** * Set to true to enable lower limit. * @property lowerLimitEnabled * @type {Boolean} */ this.lowerLimitEnabled = typeof(options.lowerLimit)!=="undefined" ? true : false; /** * Set to true to enable upper limit. * @property upperLimitEnabled * @type {Boolean} */ this.upperLimitEnabled = typeof(options.upperLimit)!=="undefined" ? true : false; /** * Lower constraint limit. The constraint position is forced to be larger than this value. * @property lowerLimit * @type {Number} */ this.lowerLimit = typeof(options.lowerLimit)!=="undefined" ? options.lowerLimit : 0; /** * Upper constraint limit. The constraint position is forced to be smaller than this value. * @property upperLimit * @type {Number} */ this.upperLimit = typeof(options.upperLimit)!=="undefined" ? options.upperLimit : 1; // Equations used for limits this.upperLimitEquation = new ContactEquation(bodyA,bodyB); this.lowerLimitEquation = new ContactEquation(bodyA,bodyB); // Set max/min forces this.upperLimitEquation.minForce = this.lowerLimitEquation.minForce = 0; this.upperLimitEquation.maxForce = this.lowerLimitEquation.maxForce = maxForce; /** * Equation used for the motor. * @property motorEquation * @type {Equation} */ this.motorEquation = new Equation(bodyA,bodyB); /** * The current motor state. Enable or disable the motor using .enableMotor * @property motorEnabled * @type {Boolean} */ this.motorEnabled = false; /** * Set the target speed for the motor. * @property motorSpeed * @type {Number} */ this.motorSpeed = 0; var that = this; var motorEquation = this.motorEquation; var old = motorEquation.computeGW; motorEquation.computeGq = function(){ return 0; }; motorEquation.computeGW = function(){ var G = this.G, bi = this.bodyA, bj = this.bodyB, vi = bi.velocity, vj = bj.velocity, wi = bi.angularVelocity, wj = bj.angularVelocity; return this.transformedGmult(G,vi,wi,vj,wj) + that.motorSpeed; }; } PrismaticConstraint.prototype = new Constraint(); var worldAxisA = vec2.create(), worldAnchorA = vec2.create(), worldAnchorB = vec2.create(), orientedAnchorA = vec2.create(), orientedAnchorB = vec2.create(), tmp = vec2.create(); /** * Update the constraint equations. Should be done if any of the bodies changed position, before solving. * @method update */ PrismaticConstraint.prototype.update = function(){ var eqs = this.equations, trans = eqs[0], upperLimit = this.upperLimit, lowerLimit = this.lowerLimit, upperLimitEquation = this.upperLimitEquation, lowerLimitEquation = this.lowerLimitEquation, bodyA = this.bodyA, bodyB = this.bodyB, localAxisA = this.localAxisA, localAnchorA = this.localAnchorA, localAnchorB = this.localAnchorB; trans.updateJacobian(); // Transform local things to world vec2.rotate(worldAxisA, localAxisA, bodyA.angle); vec2.rotate(orientedAnchorA, localAnchorA, bodyA.angle); vec2.add(worldAnchorA, orientedAnchorA, bodyA.position); vec2.rotate(orientedAnchorB, localAnchorB, bodyB.angle); vec2.add(worldAnchorB, orientedAnchorB, bodyB.position); var relPosition = this.position = vec2.dot(worldAnchorB,worldAxisA) - vec2.dot(worldAnchorA,worldAxisA); // Motor if(this.motorEnabled){ // G = [ a a x ri -a -a x rj ] var G = this.motorEquation.G; G[0] = worldAxisA[0]; G[1] = worldAxisA[1]; G[2] = vec2.crossLength(worldAxisA,orientedAnchorB); G[3] = -worldAxisA[0]; G[4] = -worldAxisA[1]; G[5] = -vec2.crossLength(worldAxisA,orientedAnchorA); } /* Limits strategy: Add contact equation, with normal along the constraint axis. min/maxForce is set so the constraint is repulsive in the correct direction. Some offset is added to either equation.contactPointA or .contactPointB to get the correct upper/lower limit. ^ | upperLimit x | ------ anchorB x<---| B | | | | ------ | ------ | | | | A |-->x anchorA ------ | x lowerLimit | axis */ if(this.upperLimitEnabled && relPosition > upperLimit){ // Update contact constraint normal, etc vec2.scale(upperLimitEquation.normalA, worldAxisA, -1); vec2.sub(upperLimitEquation.contactPointA, worldAnchorA, bodyA.position); vec2.sub(upperLimitEquation.contactPointB, worldAnchorB, bodyB.position); vec2.scale(tmp,worldAxisA,upperLimit); vec2.add(upperLimitEquation.contactPointA,upperLimitEquation.contactPointA,tmp); if(eqs.indexOf(upperLimitEquation)==-1) eqs.push(upperLimitEquation); } else { var idx = eqs.indexOf(upperLimitEquation); if(idx != -1) eqs.splice(idx,1); } if(this.lowerLimitEnabled && relPosition < lowerLimit){ // Update contact constraint normal, etc vec2.scale(lowerLimitEquation.normalA, worldAxisA, 1); vec2.sub(lowerLimitEquation.contactPointA, worldAnchorA, bodyA.position); vec2.sub(lowerLimitEquation.contactPointB, worldAnchorB, bodyB.position); vec2.scale(tmp,worldAxisA,lowerLimit); vec2.sub(lowerLimitEquation.contactPointB,lowerLimitEquation.contactPointB,tmp); if(eqs.indexOf(lowerLimitEquation)==-1) eqs.push(lowerLimitEquation); } else { var idx = eqs.indexOf(lowerLimitEquation); if(idx != -1) eqs.splice(idx,1); } }; /** * Enable the motor * @method enableMotor */ PrismaticConstraint.prototype.enableMotor = function(){ if(this.motorEnabled) return; this.equations.push(this.motorEquation); this.motorEnabled = true; }; /** * Disable the rotational motor * @method disableMotor */ PrismaticConstraint.prototype.disableMotor = function(){ if(!this.motorEnabled) return; var i = this.equations.indexOf(this.motorEquation); this.equations.splice(i,1); this.motorEnabled = false; }; },{"../equations/ContactEquation":21,"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../math/vec2":30,"./Constraint":14}],19:[function(require,module,exports){ var Constraint = require('./Constraint') , Equation = require('../equations/Equation') , RotationalVelocityEquation = require('../equations/RotationalVelocityEquation') , RotationalLockEquation = require('../equations/RotationalLockEquation') , vec2 = require('../math/vec2') module.exports = RevoluteConstraint; var worldPivotA = vec2.create(), worldPivotB = vec2.create(), xAxis = vec2.fromValues(1,0), yAxis = vec2.fromValues(0,1), g = vec2.create(); /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * @class RevoluteConstraint * @constructor * @author schteppe * @param {Body} bodyA * @param {Array} pivotA The point relative to the center of mass of bodyA which bodyA is constrained to. * @param {Body} bodyB Body that will be constrained in a similar way to the same point as bodyA. We will therefore get sort of a link between bodyA and bodyB. If not specified, bodyA will be constrained to a static point. * @param {Array} pivotB See pivotA. * @param {Object} [options] * @param {Number} [options.maxForce] The maximum force that should be applied to constrain the bodies. * @extends Constraint * @todo Ability to specify world points * @todo put pivot parameters in the options object? */ function RevoluteConstraint(bodyA, pivotA, bodyB, pivotB, options){ options = options || {}; Constraint.call(this,bodyA,bodyB,Constraint.REVOLUTE,options); var maxForce = this.maxForce = typeof(options.maxForce) !== "undefined" ? options.maxForce : Number.MAX_VALUE; /** * @property {Array} pivotA */ this.pivotA = vec2.fromValues(pivotA[0],pivotA[1]); /** * @property {Array} pivotB */ this.pivotB = vec2.fromValues(pivotB[0],pivotB[1]); // Equations to be fed to the solver var eqs = this.equations = [ new Equation(bodyA,bodyB,-maxForce,maxForce), new Equation(bodyA,bodyB,-maxForce,maxForce), ]; var x = eqs[0]; var y = eqs[1]; var that = this; x.computeGq = function(){ vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); vec2.add(g, bodyB.position, worldPivotB); vec2.sub(g, g, bodyA.position); vec2.sub(g, g, worldPivotA); return vec2.dot(g,xAxis); }; y.computeGq = function(){ vec2.rotate(worldPivotA, that.pivotA, bodyA.angle); vec2.rotate(worldPivotB, that.pivotB, bodyB.angle); vec2.add(g, bodyB.position, worldPivotB); vec2.sub(g, g, bodyA.position); vec2.sub(g, g, worldPivotA); return vec2.dot(g,yAxis); }; y.minForce = x.minForce = -maxForce; y.maxForce = x.maxForce = maxForce; this.motorEquation = new RotationalVelocityEquation(bodyA,bodyB); /** * Indicates whether the motor is enabled. Use .enableMotor() to enable the constraint motor. * @property {Boolean} motorEnabled * @readOnly */ this.motorEnabled = false; /** * The constraint position. * @property angle * @type {Number} * @readOnly */ this.angle = 0; /** * Set to true to enable lower limit * @property lowerLimitEnabled * @type {Boolean} */ this.lowerLimitEnabled = false; /** * Set to true to enable upper limit * @property upperLimitEnabled * @type {Boolean} */ this.upperLimitEnabled = false; /** * The lower limit on the constraint angle. * @property lowerLimit * @type {Boolean} */ this.lowerLimit = 0; /** * The upper limit on the constraint angle. * @property upperLimit * @type {Boolean} */ this.upperLimit = 0; this.upperLimitEquation = new RotationalLockEquation(bodyA,bodyB); this.lowerLimitEquation = new RotationalLockEquation(bodyA,bodyB); this.upperLimitEquation.minForce = 0; this.lowerLimitEquation.maxForce = 0; } RevoluteConstraint.prototype = new Constraint(); RevoluteConstraint.prototype.update = function(){ var bodyA = this.bodyA, bodyB = this.bodyB, pivotA = this.pivotA, pivotB = this.pivotB, eqs = this.equations, normal = eqs[0], tangent= eqs[1], x = eqs[0], y = eqs[1], upperLimit = this.upperLimit, lowerLimit = this.lowerLimit, upperLimitEquation = this.upperLimitEquation, lowerLimitEquation = this.lowerLimitEquation; var relAngle = this.angle = bodyB.angle - bodyA.angle; if(this.upperLimitEnabled && relAngle > upperLimit){ upperLimitEquation.angle = upperLimit; if(eqs.indexOf(upperLimitEquation)==-1) eqs.push(upperLimitEquation); } else { var idx = eqs.indexOf(upperLimitEquation); if(idx != -1) eqs.splice(idx,1); } if(this.lowerLimitEnabled && relAngle < lowerLimit){ lowerLimitEquation.angle = lowerLimit; if(eqs.indexOf(lowerLimitEquation)==-1) eqs.push(lowerLimitEquation); } else { var idx = eqs.indexOf(lowerLimitEquation); if(idx != -1) eqs.splice(idx,1); } /* The constraint violation is g = xj + rj - xi - ri ...where xi and xj are the body positions and ri and rj world-oriented offset vectors. Differentiate: gdot = vj + wj x rj - vi - wi x ri We split this into x and y directions. (let x and y be unit vectors along the respective axes) gdot * x = ( vj + wj x rj - vi - wi x ri ) * x = ( vj*x + (wj x rj)*x -vi*x -(wi x ri)*x = ( vj*x + (rj x x)*wj -vi*x -(ri x x)*wi = [ -x -(ri x x) x (rj x x)] * [vi wi vj wj] = G*W ...and similar for y. We have then identified the jacobian entries for x and y directions: Gx = [ x (rj x x) -x -(ri x x)] Gy = [ y (rj x y) -y -(ri x y)] */ vec2.rotate(worldPivotA, pivotA, bodyA.angle); vec2.rotate(worldPivotB, pivotB, bodyB.angle); // todo: these are a bit sparse. We could save some computations on making custom eq.computeGW functions, etc x.G[0] = -1; x.G[1] = 0; x.G[2] = -vec2.crossLength(worldPivotA,xAxis); x.G[3] = 1; x.G[4] = 0; x.G[5] = vec2.crossLength(worldPivotB,xAxis); y.G[0] = 0; y.G[1] = -1; y.G[2] = -vec2.crossLength(worldPivotA,yAxis); y.G[3] = 0; y.G[4] = 1; y.G[5] = vec2.crossLength(worldPivotB,yAxis); }; /** * Enable the rotational motor * @method enableMotor */ RevoluteConstraint.prototype.enableMotor = function(){ if(this.motorEnabled) return; this.equations.push(this.motorEquation); this.motorEnabled = true; }; /** * Disable the rotational motor * @method disableMotor */ RevoluteConstraint.prototype.disableMotor = function(){ if(!this.motorEnabled) return; var i = this.equations.indexOf(this.motorEquation); this.equations.splice(i,1); this.motorEnabled = false; }; /** * Check if the motor is enabled. * @method motorIsEnabled * @return {Boolean} */ RevoluteConstraint.prototype.motorIsEnabled = function(){ return !!this.motorEnabled; }; /** * Set the speed of the rotational constraint motor * @method setMotorSpeed * @param {Number} speed */ RevoluteConstraint.prototype.setMotorSpeed = function(speed){ if(!this.motorEnabled){ return; } var i = this.equations.indexOf(this.motorEquation); this.equations[i].relativeVelocity = speed; }; /** * Get the speed of the rotational constraint motor * @method getMotorSpeed * @return {Number} The current speed, or false if the motor is not enabled. */ RevoluteConstraint.prototype.getMotorSpeed = function(){ if(!this.motorEnabled) return false; return this.motorEquation.relativeVelocity; }; },{"../equations/Equation":22,"../equations/RotationalLockEquation":24,"../equations/RotationalVelocityEquation":25,"../math/vec2":30,"./Constraint":14}],20:[function(require,module,exports){ var Equation = require("./Equation"), vec2 = require('../math/vec2'); module.exports = AngleLockEquation; /** * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. * * @class AngleLockEquation * @constructor * @extends Equation * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Number} [options.angle] Angle to add to the local vector in body A. * @param {Number} [options.ratio] Gear ratio */ function AngleLockEquation(bodyA, bodyB, options){ options = options || {}; Equation.call(this,bodyA,bodyB,-Number.MAX_VALUE,Number.MAX_VALUE); this.angle = options.angle || 0; /** * The gear ratio. * @property {Number} ratio * @private * @see setRatio */ this.ratio = typeof(options.ratio)==="number" ? options.ratio : 1; this.setRatio(this.ratio); } AngleLockEquation.prototype = new Equation(); AngleLockEquation.prototype.constructor = AngleLockEquation; AngleLockEquation.prototype.computeGq = function(){ return this.ratio * this.bodyA.angle - this.bodyB.angle + this.angle; }; /** * Set the gear ratio for this equation * @method setRatio * @param {Number} ratio */ AngleLockEquation.prototype.setRatio = function(ratio){ var G = this.G; G[2] = ratio; G[5] = -1; this.ratio = ratio; }; /** * Set the max force for the equation. * @method setMaxTorque * @param {Number} torque */ AngleLockEquation.prototype.setMaxTorque = function(torque){ this.maxForce = torque; this.minForce = -torque; }; },{"../math/vec2":30,"./Equation":22}],21:[function(require,module,exports){ var Equation = require("./Equation"), vec2 = require('../math/vec2'); module.exports = ContactEquation; /** * Non-penetration constraint equation. Tries to make the ri and rj vectors the same point. * * @class ContactEquation * @constructor * @extends Equation * @param {Body} bodyA * @param {Body} bodyB */ function ContactEquation(bodyA, bodyB){ Equation.call(this, bodyA, bodyB, 0, Number.MAX_VALUE); /** * Vector from body i center of mass to the contact point. * @property contactPointA * @type {Array} */ this.contactPointA = vec2.create(); this.penetrationVec = vec2.create(); /** * World-oriented vector from body A center of mass to the contact point. * @property contactPointB * @type {Array} */ this.contactPointB = vec2.create(); /** * The normal vector, pointing out of body i * @property normalA * @type {Array} */ this.normalA = vec2.create(); /** * The restitution to use (0=no bounciness, 1=max bounciness). * @property restitution * @type {Number} */ this.restitution = 0; /** * This property is set to true if this is the first impact between the bodies (not persistant contact). * @property firstImpact * @type {Boolean} * @readOnly */ this.firstImpact = false; /** * The shape in body i that triggered this contact. * @property shapeA * @type {Shape} */ this.shapeA = null; /** * The shape in body j that triggered this contact. * @property shapeB * @type {Shape} */ this.shapeB = null; } ContactEquation.prototype = new Equation(); ContactEquation.prototype.constructor = ContactEquation; ContactEquation.prototype.computeB = function(a,b,h){ var bi = this.bodyA, bj = this.bodyB, ri = this.contactPointA, rj = this.contactPointB, xi = bi.position, xj = bj.position; var penetrationVec = this.penetrationVec, n = this.normalA, G = this.G; // Caluclate cross products var rixn = vec2.crossLength(ri,n), rjxn = vec2.crossLength(rj,n); // G = [-n -rixn n rjxn] G[0] = -n[0]; G[1] = -n[1]; G[2] = -rixn; G[3] = n[0]; G[4] = n[1]; G[5] = rjxn; // Calculate q = xj+rj -(xi+ri) i.e. the penetration vector vec2.add(penetrationVec,xj,rj); vec2.sub(penetrationVec,penetrationVec,xi); vec2.sub(penetrationVec,penetrationVec,ri); // Compute iteration var GW, Gq; if(this.firstImpact && this.restitution !== 0){ Gq = 0; GW = (1/b)*(1+this.restitution) * this.computeGW(); } else { Gq = vec2.dot(n,penetrationVec); GW = this.computeGW(); } var GiMf = this.computeGiMf(); var B = - Gq * a - GW * b - h*GiMf; return B; }; },{"../math/vec2":30,"./Equation":22}],22:[function(require,module,exports){ module.exports = Equation; var vec2 = require('../math/vec2'), Utils = require('../utils/Utils'), Body = require('../objects/Body'); /** * Base class for constraint equations. * @class Equation * @constructor * @param {Body} bodyA First body participating in the equation * @param {Body} bodyB Second body participating in the equation * @param {number} minForce Minimum force to apply. Default: -Number.MAX_VALUE * @param {number} maxForce Maximum force to apply. Default: Number.MAX_VALUE */ function Equation(bodyA, bodyB, minForce, maxForce){ /** * Minimum force to apply when solving. * @property minForce * @type {Number} */ this.minForce = typeof(minForce)==="undefined" ? -Number.MAX_VALUE : minForce; /** * Max force to apply when solving. * @property maxForce * @type {Number} */ this.maxForce = typeof(maxForce)==="undefined" ? Number.MAX_VALUE : maxForce; /** * First body participating in the constraint * @property bodyA * @type {Body} */ this.bodyA = bodyA; /** * Second body participating in the constraint * @property bodyB * @type {Body} */ this.bodyB = bodyB; /** * The stiffness of this equation. Typically chosen to a large number (~1e7), but can be chosen somewhat freely to get a stable simulation. * @property stiffness * @type {Number} */ this.stiffness = Equation.DEFAULT_STIFFNESS; /** * The number of time steps needed to stabilize the constraint equation. Typically between 3 and 5 time steps. * @property relaxation * @type {Number} */ this.relaxation = Equation.DEFAULT_RELAXATION; /** * The Jacobian entry of this equation. 6 numbers, 3 per body (x,y,angle). * @property G * @type {Array} */ this.G = new Utils.ARRAY_TYPE(6); for(var i=0; i<6; i++){ this.G[i]=0; } // Constraint frames for body i and j /* this.xi = vec2.create(); this.xj = vec2.create(); this.ai = 0; this.aj = 0; */ this.offset = 0; this.a = 0; this.b = 0; this.epsilon = 0; this.timeStep = 1/60; /** * Indicates if stiffness or relaxation was changed. * @property {Boolean} needsUpdate */ this.needsUpdate = true; /** * The resulting constraint multiplier from the last solve. This is mostly equivalent to the force produced by the constraint. * @property multiplier * @type {Number} */ this.multiplier = 0; /** * Relative velocity. * @property {Number} relativeVelocity */ this.relativeVelocity = 0; /** * Whether this equation is enabled or not. If true, it will be added to the solver. * @property {Boolean} enabled */ this.enabled = true; } Equation.prototype.constructor = Equation; /** * The default stiffness when creating a new Equation. * @static * @property {Number} DEFAULT_STIFFNESS * @default 1e6 */ Equation.DEFAULT_STIFFNESS = 1e6; /** * The default relaxation when creating a new Equation. * @static * @property {Number} DEFAULT_RELAXATION * @default 4 */ Equation.DEFAULT_RELAXATION = 4; /** * Compute SPOOK parameters .a, .b and .epsilon according to the current parameters. See equations 9, 10 and 11 in the <a href="http://www8.cs.umu.se/kurser/5DV058/VT09/lectures/spooknotes.pdf">SPOOK notes</a>. * @method update */ Equation.prototype.update = function(){ var k = this.stiffness, d = this.relaxation, h = this.timeStep; this.a = 4.0 / (h * (1 + 4 * d)); this.b = (4.0 * d) / (1 + 4 * d); this.epsilon = 4.0 / (h * h * k * (1 + 4 * d)); this.needsUpdate = false; }; function Gmult(G,vi,wi,vj,wj){ return G[0] * vi[0] + G[1] * vi[1] + G[2] * wi + G[3] * vj[0] + G[4] * vj[1] + G[5] * wj; } /** * Computes the RHS of the SPOOK equation * @method computeB * @return {Number} */ Equation.prototype.computeB = function(a,b,h){ var GW = this.computeGW(); var Gq = this.computeGq(); var GiMf = this.computeGiMf(); return - Gq * a - GW * b - GiMf*h; }; /** * Computes G*q, where q are the generalized body coordinates * @method computeGq * @return {Number} */ var qi = vec2.create(), qj = vec2.create(); Equation.prototype.computeGq = function(){ var G = this.G, bi = this.bodyA, bj = this.bodyB, xi = bi.position, xj = bj.position, ai = bi.angle, aj = bj.angle; return Gmult(G, qi, ai, qj, aj) + this.offset; }; /** * Computes G*W, where W are the body velocities * @method computeGW * @return {Number} */ Equation.prototype.computeGW = function(){ var G = this.G, bi = this.bodyA, bj = this.bodyB, vi = bi.velocity, vj = bj.velocity, wi = bi.angularVelocity, wj = bj.angularVelocity; return Gmult(G,vi,wi,vj,wj) + this.relativeVelocity; }; /** * Computes G*Wlambda, where W are the body velocities * @method computeGWlambda * @return {Number} */ Equation.prototype.computeGWlambda = function(){ var G = this.G, bi = this.bodyA, bj = this.bodyB, vi = bi.vlambda, vj = bj.vlambda, wi = bi.wlambda, wj = bj.wlambda; return Gmult(G,vi,wi,vj,wj); }; /** * Computes G*inv(M)*f, where M is the mass matrix with diagonal blocks for each body, and f are the forces on the bodies. * @method computeGiMf * @return {Number} */ var iMfi = vec2.create(), iMfj = vec2.create(); Equation.prototype.computeGiMf = function(){ var bi = this.bodyA, bj = this.bodyB, fi = bi.force, ti = bi.angularForce, fj = bj.force, tj = bj.angularForce, invMassi = getBodyInvMass(bi), invMassj = getBodyInvMass(bj), invIi = getBodyInvInertia(bi), invIj = getBodyInvInertia(bj), G = this.G; vec2.scale(iMfi, fi,invMassi); vec2.scale(iMfj, fj,invMassj); return Gmult(G,iMfi,ti*invIi,iMfj,tj*invIj); }; function getBodyInvMass(body){ if(body.sleepState === Body.SLEEPING){ return 0; } else { return body.invMass; } } function getBodyInvInertia(body){ if(body.sleepState === Body.SLEEPING){ return 0; } else { return body.invInertia; } } /** * Computes G*inv(M)*G' * @method computeGiMGt * @return {Number} */ Equation.prototype.computeGiMGt = function(){ var bi = this.bodyA, bj = this.bodyB, invMassi = getBodyInvMass(bi), invMassj = getBodyInvMass(bj), invIi = getBodyInvInertia(bi), invIj = getBodyInvInertia(bj), G = this.G; return G[0] * G[0] * invMassi + G[1] * G[1] * invMassi + G[2] * G[2] * invIi + G[3] * G[3] * invMassj + G[4] * G[4] * invMassj + G[5] * G[5] * invIj; }; var addToWlambda_temp = vec2.create(), addToWlambda_Gi = vec2.create(), addToWlambda_Gj = vec2.create(), addToWlambda_ri = vec2.create(), addToWlambda_rj = vec2.create(), addToWlambda_Mdiag = vec2.create(); /** * Add constraint velocity to the bodies. * @method addToWlambda * @param {Number} deltalambda */ Equation.prototype.addToWlambda = function(deltalambda){ var bi = this.bodyA, bj = this.bodyB, temp = addToWlambda_temp, Gi = addToWlambda_Gi, Gj = addToWlambda_Gj, ri = addToWlambda_ri, rj = addToWlambda_rj, invMassi = getBodyInvMass(bi), invMassj = getBodyInvMass(bj), invIi = getBodyInvInertia(bi), invIj = getBodyInvInertia(bj), Mdiag = addToWlambda_Mdiag, G = this.G; Gi[0] = G[0]; Gi[1] = G[1]; Gj[0] = G[3]; Gj[1] = G[4]; // Add to linear velocity // v_lambda += inv(M) * delta_lamba * G vec2.scale(temp, Gi, invMassi*deltalambda); vec2.add( bi.vlambda, bi.vlambda, temp); // This impulse is in the offset frame // Also add contribution to angular //bi.wlambda -= vec2.crossLength(temp,ri); bi.wlambda += invIi * G[2] * deltalambda; vec2.scale(temp, Gj, invMassj*deltalambda); vec2.add( bj.vlambda, bj.vlambda, temp); //bj.wlambda -= vec2.crossLength(temp,rj); bj.wlambda += invIj * G[5] * deltalambda; }; /** * Compute the denominator part of the SPOOK equation: C = G*inv(M)*G' + eps * @method computeInvC * @param {Number} eps * @return {Number} */ Equation.prototype.computeInvC = function(eps){ return 1.0 / (this.computeGiMGt() + eps); }; },{"../math/vec2":30,"../objects/Body":31,"../utils/Utils":47}],23:[function(require,module,exports){ var vec2 = require('../math/vec2') , Equation = require('./Equation') , Utils = require('../utils/Utils'); module.exports = FrictionEquation; /** * Constrains the slipping in a contact along a tangent * * @class FrictionEquation * @constructor * @param {Body} bodyA * @param {Body} bodyB * @param {Number} slipForce * @extends Equation */ function FrictionEquation(bodyA, bodyB, slipForce){ Equation.call(this, bodyA, bodyB, -slipForce, slipForce); /** * Relative vector from center of body A to the contact point, world oriented. * @property contactPointA * @type {Array} */ this.contactPointA = vec2.create(); /** * Relative vector from center of body B to the contact point, world oriented. * @property contactPointB * @type {Array} */ this.contactPointB = vec2.create(); /** * Tangent vector that the friction force will act along. World oriented. * @property t * @type {Array} */ this.t = vec2.create(); /** * A ContactEquation connected to this friction. The contact equation can be used to rescale the max force for the friction. * @property contactEquation * @type {ContactEquation} */ this.contactEquation = null; /** * The shape in body i that triggered this friction. * @property shapeA * @type {Shape} * @todo Needed? The shape can be looked up via contactEquation.shapeA... */ this.shapeA = null; /** * The shape in body j that triggered this friction. * @property shapeB * @type {Shape} * @todo Needed? The shape can be looked up via contactEquation.shapeB... */ this.shapeB = null; /** * The friction coefficient to use. * @property frictionCoefficient * @type {Number} */ this.frictionCoefficient = 0.3; } FrictionEquation.prototype = new Equation(); FrictionEquation.prototype.constructor = FrictionEquation; /** * Set the slipping condition for the constraint. The friction force cannot be * larger than this value. * @method setSlipForce * @param {Number} slipForce */ FrictionEquation.prototype.setSlipForce = function(slipForce){ this.maxForce = slipForce; this.minForce = -slipForce; }; /** * Get the max force for the constraint. * @method getSlipForce * @return {Number} */ FrictionEquation.prototype.getSlipForce = function(){ return this.maxForce; }; FrictionEquation.prototype.computeB = function(a,b,h){ var bi = this.bodyA, bj = this.bodyB, ri = this.contactPointA, rj = this.contactPointB, t = this.t, G = this.G; // G = [-t -rixt t rjxt] // And remember, this is a pure velocity constraint, g is always zero! G[0] = -t[0]; G[1] = -t[1]; G[2] = -vec2.crossLength(ri,t); G[3] = t[0]; G[4] = t[1]; G[5] = vec2.crossLength(rj,t); var GW = this.computeGW(), GiMf = this.computeGiMf(); var B = /* - g * a */ - GW * b - h*GiMf; return B; }; },{"../math/vec2":30,"../utils/Utils":47,"./Equation":22}],24:[function(require,module,exports){ var Equation = require("./Equation"), vec2 = require('../math/vec2'); module.exports = RotationalLockEquation; /** * Locks the relative angle between two bodies. The constraint tries to keep the dot product between two vectors, local in each body, to zero. The local angle in body i is a parameter. * * @class RotationalLockEquation * @constructor * @extends Equation * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {Number} [options.angle] Angle to add to the local vector in body i. */ function RotationalLockEquation(bodyA, bodyB, options){ options = options || {}; Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); this.angle = options.angle || 0; var G = this.G; G[2] = 1; G[5] = -1; } RotationalLockEquation.prototype = new Equation(); RotationalLockEquation.prototype.constructor = RotationalLockEquation; var worldVectorA = vec2.create(), worldVectorB = vec2.create(), xAxis = vec2.fromValues(1,0), yAxis = vec2.fromValues(0,1); RotationalLockEquation.prototype.computeGq = function(){ vec2.rotate(worldVectorA,xAxis,this.bodyA.angle+this.angle); vec2.rotate(worldVectorB,yAxis,this.bodyB.angle); return vec2.dot(worldVectorA,worldVectorB); }; },{"../math/vec2":30,"./Equation":22}],25:[function(require,module,exports){ var Equation = require("./Equation"), vec2 = require('../math/vec2'); module.exports = RotationalVelocityEquation; /** * Syncs rotational velocity of two bodies, or sets a relative velocity (motor). * * @class RotationalVelocityEquation * @constructor * @extends Equation * @param {Body} bodyA * @param {Body} bodyB */ function RotationalVelocityEquation(bodyA, bodyB){ Equation.call(this, bodyA, bodyB, -Number.MAX_VALUE, Number.MAX_VALUE); this.relativeVelocity = 1; this.ratio = 1; } RotationalVelocityEquation.prototype = new Equation(); RotationalVelocityEquation.prototype.constructor = RotationalVelocityEquation; RotationalVelocityEquation.prototype.computeB = function(a,b,h){ var G = this.G; G[2] = -1; G[5] = this.ratio; var GiMf = this.computeGiMf(); var GW = this.computeGW(); var B = - GW * b - h*GiMf; return B; }; },{"../math/vec2":30,"./Equation":22}],26:[function(require,module,exports){ /** * Base class for objects that dispatches events. * @class EventEmitter * @constructor */ var EventEmitter = function () {} module.exports = EventEmitter; EventEmitter.prototype = { constructor: EventEmitter, /** * Add an event listener * @method on * @param {String} type * @param {Function} listener * @return {EventEmitter} The self object, for chainability. */ on: function ( type, listener, context ) { listener.context = context || this; if ( this._listeners === undefined ) this._listeners = {}; var listeners = this._listeners; if ( listeners[ type ] === undefined ) { listeners[ type ] = []; } if ( listeners[ type ].indexOf( listener ) === - 1 ) { listeners[ type ].push( listener ); } return this; }, /** * Check if an event listener is added * @method has * @param {String} type * @param {Function} listener * @return {Boolean} */ has: function ( type, listener ) { if ( this._listeners === undefined ) return false; var listeners = this._listeners; if(listener){ if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) { return true; } } else { if ( listeners[ type ] !== undefined ) { return true; } } return false; }, /** * Remove an event listener * @method off * @param {String} type * @param {Function} listener * @return {EventEmitter} The self object, for chainability. */ off: function ( type, listener ) { if ( this._listeners === undefined ) return this; var listeners = this._listeners; var index = listeners[ type ].indexOf( listener ); if ( index !== - 1 ) { listeners[ type ].splice( index, 1 ); } return this; }, /** * Emit an event. * @method emit * @param {Object} event * @param {String} event.type * @return {EventEmitter} The self object, for chainability. */ emit: function ( event ) { if ( this._listeners === undefined ) return this; var listeners = this._listeners; var listenerArray = listeners[ event.type ]; if ( listenerArray !== undefined ) { event.target = this; for ( var i = 0, l = listenerArray.length; i < l; i ++ ) { var listener = listenerArray[ i ]; listener.call( listener.context, event ); } } return this; } }; },{}],27:[function(require,module,exports){ var Material = require('./Material'); var Equation = require('../equations/Equation'); module.exports = ContactMaterial; /** * Defines what happens when two materials meet, such as what friction coefficient to use. You can also set other things such as restitution, surface velocity and constraint parameters. * @class ContactMaterial * @constructor * @param {Material} materialA * @param {Material} materialB * @param {Object} [options] * @param {Number} [options.friction=0.3] Friction coefficient. * @param {Number} [options.restitution=0] Restitution coefficient aka "bounciness". * @param {Number} [options.stiffness] ContactEquation stiffness. * @param {Number} [options.relaxation] ContactEquation relaxation. * @param {Number} [options.frictionStiffness] FrictionEquation stiffness. * @param {Number} [options.frictionRelaxation] FrictionEquation relaxation. * @param {Number} [options.surfaceVelocity=0] Surface velocity. * @author schteppe */ function ContactMaterial(materialA, materialB, options){ options = options || {}; if(!(materialA instanceof Material) || !(materialB instanceof Material)) throw new Error("First two arguments must be Material instances."); /** * The contact material identifier * @property id * @type {Number} */ this.id = ContactMaterial.idCounter++; /** * First material participating in the contact material * @property materialA * @type {Material} */ this.materialA = materialA; /** * Second material participating in the contact material * @property materialB * @type {Material} */ this.materialB = materialB; /** * Friction to use in the contact of these two materials * @property friction * @type {Number} */ this.friction = typeof(options.friction) !== "undefined" ? Number(options.friction) : 0.3; /** * Restitution to use in the contact of these two materials * @property restitution * @type {Number} */ this.restitution = typeof(options.restitution) !== "undefined" ? Number(options.restitution) : 0.0; /** * Stiffness of the resulting ContactEquation that this ContactMaterial generate * @property stiffness * @type {Number} */ this.stiffness = typeof(options.stiffness) !== "undefined" ? Number(options.stiffness) : Equation.DEFAULT_STIFFNESS; /** * Relaxation of the resulting ContactEquation that this ContactMaterial generate * @property relaxation * @type {Number} */ this.relaxation = typeof(options.relaxation) !== "undefined" ? Number(options.relaxation) : Equation.DEFAULT_RELAXATION; /** * Stiffness of the resulting FrictionEquation that this ContactMaterial generate * @property frictionStiffness * @type {Number} */ this.frictionStiffness = typeof(options.frictionStiffness) !== "undefined" ? Number(options.frictionStiffness) : Equation.DEFAULT_STIFFNESS; /** * Relaxation of the resulting FrictionEquation that this ContactMaterial generate * @property frictionRelaxation * @type {Number} */ this.frictionRelaxation = typeof(options.frictionRelaxation) !== "undefined" ? Number(options.frictionRelaxation) : Equation.DEFAULT_RELAXATION; /** * Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. * @property {Number} surfaceVelocity */ this.surfaceVelocity = typeof(options.surfaceVelocity) !== "undefined" ? Number(options.surfaceVelocity) : 0; } ContactMaterial.idCounter = 0; },{"../equations/Equation":22,"./Material":28}],28:[function(require,module,exports){ module.exports = Material; /** * Defines a physics material. * @class Material * @constructor * @param string name * @author schteppe */ function Material(){ /** * The material identifier * @property id * @type {Number} */ this.id = Material.idCounter++; }; Material.idCounter = 0; },{}],29:[function(require,module,exports){ /* PolyK library url: http://polyk.ivank.net Released under MIT licence. Copyright (c) 2012 Ivan Kuckir Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var PolyK = {}; /* Is Polygon self-intersecting? O(n^2) */ /* PolyK.IsSimple = function(p) { var n = p.length>>1; if(n<4) return true; var a1 = new PolyK._P(), a2 = new PolyK._P(); var b1 = new PolyK._P(), b2 = new PolyK._P(); var c = new PolyK._P(); for(var i=0; i<n; i++) { a1.x = p[2*i ]; a1.y = p[2*i+1]; if(i==n-1) { a2.x = p[0 ]; a2.y = p[1 ]; } else { a2.x = p[2*i+2]; a2.y = p[2*i+3]; } for(var j=0; j<n; j++) { if(Math.abs(i-j) < 2) continue; if(j==n-1 && i==0) continue; if(i==n-1 && j==0) continue; b1.x = p[2*j ]; b1.y = p[2*j+1]; if(j==n-1) { b2.x = p[0 ]; b2.y = p[1 ]; } else { b2.x = p[2*j+2]; b2.y = p[2*j+3]; } if(PolyK._GetLineIntersection(a1,a2,b1,b2,c) != null) return false; } } return true; } PolyK.IsConvex = function(p) { if(p.length<6) return true; var l = p.length - 4; for(var i=0; i<l; i+=2) if(!PolyK._convex(p[i], p[i+1], p[i+2], p[i+3], p[i+4], p[i+5])) return false; if(!PolyK._convex(p[l ], p[l+1], p[l+2], p[l+3], p[0], p[1])) return false; if(!PolyK._convex(p[l+2], p[l+3], p[0 ], p[1 ], p[2], p[3])) return false; return true; } */ PolyK.GetArea = function(p) { if(p.length <6) return 0; var l = p.length - 2; var sum = 0; for(var i=0; i<l; i+=2) sum += (p[i+2]-p[i]) * (p[i+1]+p[i+3]); sum += (p[0]-p[l]) * (p[l+1]+p[1]); return - sum * 0.5; } /* PolyK.GetAABB = function(p) { var minx = Infinity; var miny = Infinity; var maxx = -minx; var maxy = -miny; for(var i=0; i<p.length; i+=2) { minx = Math.min(minx, p[i ]); maxx = Math.max(maxx, p[i ]); miny = Math.min(miny, p[i+1]); maxy = Math.max(maxy, p[i+1]); } return {x:minx, y:miny, width:maxx-minx, height:maxy-miny}; } */ PolyK.Triangulate = function(p) { var n = p.length>>1; if(n<3) return []; var tgs = []; var avl = []; for(var i=0; i<n; i++) avl.push(i); var i = 0; var al = n; while(al > 3) { var i0 = avl[(i+0)%al]; var i1 = avl[(i+1)%al]; var i2 = avl[(i+2)%al]; var ax = p[2*i0], ay = p[2*i0+1]; var bx = p[2*i1], by = p[2*i1+1]; var cx = p[2*i2], cy = p[2*i2+1]; var earFound = false; if(PolyK._convex(ax, ay, bx, by, cx, cy)) { earFound = true; for(var j=0; j<al; j++) { var vi = avl[j]; if(vi==i0 || vi==i1 || vi==i2) continue; if(PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) {earFound = false; break;} } } if(earFound) { tgs.push(i0, i1, i2); avl.splice((i+1)%al, 1); al--; i= 0; } else if(i++ > 3*al) break; // no convex angles :( } tgs.push(avl[0], avl[1], avl[2]); return tgs; } /* PolyK.ContainsPoint = function(p, px, py) { var n = p.length>>1; var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py; var depth = 0; for(var i=0; i<n; i++) { ax = bx; ay = by; bx = p[2*i ] - px; by = p[2*i+1] - py; if(ay< 0 && by< 0) continue; // both "up" or both "donw" if(ay>=0 && by>=0) continue; // both "up" or both "donw" if(ax< 0 && bx< 0) continue; var lx = ax + (bx-ax)*(-ay)/(by-ay); if(lx>0) depth++; } return (depth & 1) == 1; } PolyK.Slice = function(p, ax, ay, bx, by) { if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)]; var a = new PolyK._P(ax, ay); var b = new PolyK._P(bx, by); var iscs = []; // intersections var ps = []; // points for(var i=0; i<p.length; i+=2) ps.push(new PolyK._P(p[i], p[i+1])); for(var i=0; i<ps.length; i++) { var isc = new PolyK._P(0,0); isc = PolyK._GetLineIntersection(a, b, ps[i], ps[(i+1)%ps.length], isc); if(isc) { isc.flag = true; iscs.push(isc); ps.splice(i+1,0,isc); i++; } } if(iscs.length == 0) return [p.slice(0)]; var comp = function(u,v) {return PolyK._P.dist(a,u) - PolyK._P.dist(a,v); } iscs.sort(comp); var pgs = []; var dir = 0; while(iscs.length > 0) { var n = ps.length; var i0 = iscs[0]; var i1 = iscs[1]; var ind0 = ps.indexOf(i0); var ind1 = ps.indexOf(i1); var solved = false; if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; else { i0 = iscs[1]; i1 = iscs[0]; ind0 = ps.indexOf(i0); ind1 = ps.indexOf(i1); if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true; } if(solved) { dir--; var pgn = PolyK._getPoints(ps, ind0, ind1); pgs.push(pgn); ps = PolyK._getPoints(ps, ind1, ind0); i0.flag = i1.flag = false; iscs.splice(0,2); if(iscs.length == 0) pgs.push(ps); } else { dir++; iscs.reverse(); } if(dir>1) break; } var result = []; for(var i=0; i<pgs.length; i++) { var pg = pgs[i]; var npg = []; for(var j=0; j<pg.length; j++) npg.push(pg[j].x, pg[j].y); result.push(npg); } return result; } PolyK.Raycast = function(p, x, y, dx, dy, isc) { var l = p.length - 2; var tp = PolyK._tp; var a1 = tp[0], a2 = tp[1], b1 = tp[2], b2 = tp[3], c = tp[4]; a1.x = x; a1.y = y; a2.x = x+dx; a2.y = y+dy; if(isc==null) isc = {dist:0, edge:0, norm:{x:0, y:0}, refl:{x:0, y:0}}; isc.dist = Infinity; for(var i=0; i<l; i+=2) { b1.x = p[i ]; b1.y = p[i+1]; b2.x = p[i+2]; b2.y = p[i+3]; var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c); if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, i/2, isc); } b1.x = b2.x; b1.y = b2.y; b2.x = p[0]; b2.y = p[1]; var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c); if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, p.length/2, isc); return (isc.dist != Infinity) ? isc : null; } PolyK.ClosestEdge = function(p, x, y, isc) { var l = p.length - 2; var tp = PolyK._tp; var a1 = tp[0], b1 = tp[2], b2 = tp[3], c = tp[4]; a1.x = x; a1.y = y; if(isc==null) isc = {dist:0, edge:0, point:{x:0, y:0}, norm:{x:0, y:0}}; isc.dist = Infinity; for(var i=0; i<l; i+=2) { b1.x = p[i ]; b1.y = p[i+1]; b2.x = p[i+2]; b2.y = p[i+3]; PolyK._pointLineDist(a1, b1, b2, i>>1, isc); } b1.x = b2.x; b1.y = b2.y; b2.x = p[0]; b2.y = p[1]; PolyK._pointLineDist(a1, b1, b2, l>>1, isc); var idst = 1/isc.dist; isc.norm.x = (x-isc.point.x)*idst; isc.norm.y = (y-isc.point.y)*idst; return isc; } PolyK._pointLineDist = function(p, a, b, edge, isc) { var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y; var A = x - x1; var B = y - y1; var C = x2 - x1; var D = y2 - y1; var dot = A * C + B * D; var len_sq = C * C + D * D; var param = dot / len_sq; var xx, yy; if (param < 0 || (x1 == x2 && y1 == y2)) { xx = x1; yy = y1; } else if (param > 1) { xx = x2; yy = y2; } else { xx = x1 + param * C; yy = y1 + param * D; } var dx = x - xx; var dy = y - yy; var dst = Math.sqrt(dx * dx + dy * dy); if(dst<isc.dist) { isc.dist = dst; isc.edge = edge; isc.point.x = xx; isc.point.y = yy; } } PolyK._updateISC = function(dx, dy, a1, b1, b2, c, edge, isc) { var nrl = PolyK._P.dist(a1, c); if(nrl<isc.dist) { var ibl = 1/PolyK._P.dist(b1, b2); var nx = -(b2.y-b1.y)*ibl; var ny = (b2.x-b1.x)*ibl; var ddot = 2*(dx*nx+dy*ny); isc.dist = nrl; isc.norm.x = nx; isc.norm.y = ny; isc.refl.x = -ddot*nx+dx; isc.refl.y = -ddot*ny+dy; isc.edge = edge; } } PolyK._getPoints = function(ps, ind0, ind1) { var n = ps.length; var nps = []; if(ind1<ind0) ind1 += n; for(var i=ind0; i<= ind1; i++) nps.push(ps[i%n]); return nps; } PolyK._firstWithFlag = function(ps, ind) { var n = ps.length; while(true) { ind = (ind+1)%n; if(ps[ind].flag) return ind; } } */ PolyK._PointInTriangle = function(px, py, ax, ay, bx, by, cx, cy) { var v0x = cx-ax; var v0y = cy-ay; var v1x = bx-ax; var v1y = by-ay; var v2x = px-ax; var v2y = py-ay; var dot00 = v0x*v0x+v0y*v0y; var dot01 = v0x*v1x+v0y*v1y; var dot02 = v0x*v2x+v0y*v2y; var dot11 = v1x*v1x+v1y*v1y; var dot12 = v1x*v2x+v1y*v2y; var invDenom = 1 / (dot00 * dot11 - dot01 * dot01); var u = (dot11 * dot02 - dot01 * dot12) * invDenom; var v = (dot00 * dot12 - dot01 * dot02) * invDenom; // Check if point is in triangle return (u >= 0) && (v >= 0) && (u + v < 1); } /* PolyK._RayLineIntersection = function(a1, a2, b1, b2, c) { var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); var day = (a1.y-a2.y), dby = (b1.y-b2.y); var Den = dax*dby - day*dbx; if (Den == 0) return null; // parallel var A = (a1.x * a2.y - a1.y * a2.x); var B = (b1.x * b2.y - b1.y * b2.x); var I = c; var iDen = 1/Den; I.x = ( A*dbx - dax*B ) * iDen; I.y = ( A*dby - day*B ) * iDen; if(!PolyK._InRect(I, b1, b2)) return null; if((day>0 && I.y>a1.y) || (day<0 && I.y<a1.y)) return null; if((dax>0 && I.x>a1.x) || (dax<0 && I.x<a1.x)) return null; return I; } PolyK._GetLineIntersection = function(a1, a2, b1, b2, c) { var dax = (a1.x-a2.x), dbx = (b1.x-b2.x); var day = (a1.y-a2.y), dby = (b1.y-b2.y); var Den = dax*dby - day*dbx; if (Den == 0) return null; // parallel var A = (a1.x * a2.y - a1.y * a2.x); var B = (b1.x * b2.y - b1.y * b2.x); var I = c; I.x = ( A*dbx - dax*B ) / Den; I.y = ( A*dby - day*B ) / Den; if(PolyK._InRect(I, a1, a2) && PolyK._InRect(I, b1, b2)) return I; return null; } PolyK._InRect = function(a, b, c) { if (b.x == c.x) return (a.y>=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y)); if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x)); if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x) && a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y)) return true; return false; } */ PolyK._convex = function(ax, ay, bx, by, cx, cy) { return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0; } /* PolyK._P = function(x,y) { this.x = x; this.y = y; this.flag = false; } PolyK._P.prototype.toString = function() { return "Point ["+this.x+", "+this.y+"]"; } PolyK._P.dist = function(a,b) { var dx = b.x-a.x; var dy = b.y-a.y; return Math.sqrt(dx*dx + dy*dy); } PolyK._tp = []; for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0)); */ module.exports = PolyK; },{}],30:[function(require,module,exports){ /** * The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net for full doc. * @class vec2 */ var vec2 = require('../../build/vec2').vec2; /** * Make a cross product and only return the z component * @method crossLength * @static * @param {Float32Array} a * @param {Float32Array} b * @return {Number} */ vec2.crossLength = function(a,b){ return a[0] * b[1] - a[1] * b[0]; }; /** * Cross product between a vector and the Z component of a vector * @method crossVZ * @static * @param {Float32Array} out * @param {Float32Array} vec * @param {Number} zcomp * @return {Number} */ vec2.crossVZ = function(out, vec, zcomp){ vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Cross product between a vector and the Z component of a vector * @method crossZV * @static * @param {Float32Array} out * @param {Number} zcomp * @param {Float32Array} vec * @return {Number} */ vec2.crossZV = function(out, zcomp, vec){ vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule vec2.scale(out,out,zcomp); // Scale with z return out; }; /** * Rotate a vector by an angle * @method rotate * @static * @param {Float32Array} out * @param {Float32Array} a * @param {Number} angle */ vec2.rotate = function(out,a,angle){ var c = Math.cos(angle), s = Math.sin(angle), x = a[0], y = a[1]; out[0] = c*x -s*y; out[1] = s*x +c*y; }; /** * Rotate a vector 90 degrees clockwise * @method rotate90cw * @static * @param {Float32Array} out * @param {Float32Array} a * @param {Number} angle */ vec2.rotate90cw = function(out, a) { out[0] = a[1]; out[1] = -a[0]; }; /** * Transform a point position to local frame. * @method toLocalFrame * @param {Array} out * @param {Array} worldPoint * @param {Array} framePosition * @param {Number} frameAngle */ vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){ vec2.copy(out, worldPoint); vec2.sub(out, out, framePosition); vec2.rotate(out, out, -frameAngle); }; /** * Transform a point position to global frame. * @method toGlobalFrame * @param {Array} out * @param {Array} localPoint * @param {Array} framePosition * @param {Number} frameAngle */ vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){ vec2.copy(out, localPoint); vec2.rotate(out, out, frameAngle); vec2.add(out, out, framePosition); }; /** * Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php * @method centroid * @static * @param {Float32Array} out * @param {Float32Array} a * @param {Float32Array} b * @param {Float32Array} c * @return {Float32Array} The out object */ vec2.centroid = function(out, a, b, c){ vec2.add(out, a, b); vec2.add(out, out, c); vec2.scale(out, out, 1/3); return out; }; // Export everything module.exports = vec2; },{"../../build/vec2":1}],31:[function(require,module,exports){ var vec2 = require('../math/vec2') , decomp = require('poly-decomp') , Convex = require('../shapes/Convex') , AABB = require('../collision/AABB') , EventEmitter = require('../events/EventEmitter') module.exports = Body; /** * A rigid body. Has got a center of mass, position, velocity and a number of * shapes that are used for collisions. * * @class Body * @constructor * @extends EventEmitter * @param {Object} [options] * @param {Number} [options.mass=0] A number >= 0. If zero, the .motionState will be set to Body.STATIC. * @param {Array} [options.position] * @param {Array} [options.velocity] * @param {Number} [options.angle=0] * @param {Number} [options.angularVelocity=0] * @param {Array} [options.force] * @param {Number} [options.angularForce=0] * @param {Number} [options.fixedRotation=false] */ function Body(options){ options = options || {}; EventEmitter.call(this); /** * The body identifyer * @property id * @type {Number} */ this.id = ++Body._idCounter; /** * The world that this body is added to. This property is set to NULL if the body is not added to any world. * @property world * @type {World} */ this.world = null; /** * The shapes of the body. The local transform of the shape in .shapes[i] is * defined by .shapeOffsets[i] and .shapeAngles[i]. * * @property shapes * @type {Array} */ this.shapes = []; /** * The local shape offsets, relative to the body center of mass. This is an * array of Array. * @property shapeOffsets * @type {Array} */ this.shapeOffsets = []; /** * The body-local shape angle transforms. This is an array of numbers (angles). * @property shapeAngles * @type {Array} */ this.shapeAngles = []; /** * The mass of the body. * @property mass * @type {number} */ this.mass = options.mass || 0; /** * The inverse mass of the body. * @property invMass * @type {number} */ this.invMass = 0; /** * The inertia of the body around the Z axis. * @property inertia * @type {number} */ this.inertia = 0; /** * The inverse inertia of the body. * @property invInertia * @type {number} */ this.invInertia = 0; /** * Set to true if you want to fix the rotation of the body. * @property fixedRotation * @type {Boolean} */ this.fixedRotation = !!options.fixedRotation || false; /** * The position of the body * @property position * @type {Array} */ this.position = vec2.fromValues(0,0); if(options.position){ vec2.copy(this.position, options.position); } /** * The interpolated position of the body. * @property interpolatedPosition * @type {Array} */ this.interpolatedPosition = vec2.fromValues(0,0); /** * The interpolated angle of the body. * @property interpolatedAngle * @type {Number} */ this.interpolatedAngle = 0; /** * The previous position of the body. * @property previousPosition * @type {Array} */ this.previousPosition = vec2.fromValues(0,0); /** * The previous angle of the body. * @property previousAngle * @type {Number} */ this.previousAngle = 0; /** * The velocity of the body * @property velocity * @type {Array} */ this.velocity = vec2.fromValues(0,0); if(options.velocity){ vec2.copy(this.velocity, options.velocity); } /** * Constraint velocity that was added to the body during the last step. * @property vlambda * @type {Array} */ this.vlambda = vec2.fromValues(0,0); /** * Angular constraint velocity that was added to the body during last step. * @property wlambda * @type {Array} */ this.wlambda = 0; /** * The angle of the body, in radians. * @property angle * @type {number} * @example * // The angle property is not normalized to the interval 0 to 2*pi, it can be any value. * // If you need a value between 0 and 2*pi, use the following function to normalize it. * function normalizeAngle(angle){ * angle = angle % (2*Math.PI); * if(angle < 0){ * angle += (2*Math.PI); * } * return angle; * } */ this.angle = options.angle || 0; /** * The angular velocity of the body, in radians per second. * @property angularVelocity * @type {number} */ this.angularVelocity = options.angularVelocity || 0; /** * The force acting on the body. Since the body force (and {{#crossLink "Body/angularForce:property"}}{{/crossLink}}) will be zeroed after each step, so you need to set the force before each step. * @property force * @type {Array} * * @example * // This produces a forcefield of 1 Newton in the positive x direction. * for(var i=0; i<numSteps; i++){ * body.force[0] = 1; * world.step(1/60); * } * * @example * // This will apply a rotational force on the body * for(var i=0; i<numSteps; i++){ * body.angularForce = -3; * world.step(1/60); * } */ this.force = vec2.create(); if(options.force) vec2.copy(this.force, options.force); /** * The angular force acting on the body. See {{#crossLink "Body/force:property"}}{{/crossLink}}. * @property angularForce * @type {number} */ this.angularForce = options.angularForce || 0; /** * The linear damping acting on the body in the velocity direction. Should be a value between 0 and 1. * @property damping * @type {Number} * @default 0.1 */ this.damping = typeof(options.damping)=="number" ? options.damping : 0.1; /** * The angular force acting on the body. Should be a value between 0 and 1. * @property angularDamping * @type {Number} * @default 0.1 */ this.angularDamping = typeof(options.angularDamping)=="number" ? options.angularDamping : 0.1; /** * The type of motion this body has. Should be one of: {{#crossLink "Body/STATIC:property"}}Body.STATIC{{/crossLink}}, {{#crossLink "Body/DYNAMIC:property"}}Body.DYNAMIC{{/crossLink}} and {{#crossLink "Body/KINEMATIC:property"}}Body.KINEMATIC{{/crossLink}}. * * * Static bodies do not move, and they do not respond to forces or collision. * * Dynamic bodies body can move and respond to collisions and forces. * * Kinematic bodies only moves according to its .velocity, and does not respond to collisions or force. * * @property motionState * @type {number} * * @example * // This body will move and interact with other bodies * var dynamicBody = new Body({ * mass : 1 // If mass is nonzero, the body becomes dynamic automatically * }); * dynamicBody.motionState == Body.DYNAMIC // true * * @example * // This body will not move at all * var staticBody = new Body({ * mass : 0 // Will make the body static * }); * staticBody.motionState == Body.STATIC // true * * @example * // This body will only move if you change its velocity * var kinematicBody = new Body(); * kinematicBody.motionState = Body.KINEMATIC; */ this.motionState = this.mass === 0 ? Body.STATIC : Body.DYNAMIC; /** * Bounding circle radius. * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; /** * Bounding box of this body. * @property aabb * @type {AABB} */ this.aabb = new AABB(); /** * Indicates if the AABB needs update. Update it with {{#crossLink "Body/updateAABB:method"}}.updateAABB(){{/crossLink}}. * @property aabbNeedsUpdate * @type {Boolean} * @see updateAABB * * @example * // Force update the AABB * body.aabbNeedsUpdate = true; * body.updateAABB(); * console.log(body.aabbNeedsUpdate); // false */ this.aabbNeedsUpdate = true; /** * If true, the body will automatically fall to sleep. Note that you need to enable sleeping in the {{#crossLink "World"}}{{/crossLink}} before anything will happen. * @property allowSleep * @type {Boolean} * @default true */ this.allowSleep = true; this.wantsToSleep = false; /** * One of {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}}, {{#crossLink "Body/SLEEPY:property"}}Body.SLEEPY{{/crossLink}} and {{#crossLink "Body/SLEEPING:property"}}Body.SLEEPING{{/crossLink}}. * * The body is initially Body.AWAKE. If its velocity norm is below .sleepSpeedLimit, the sleepState will become Body.SLEEPY. If the body continues to be Body.SLEEPY for .sleepTimeLimit seconds, it will fall asleep (Body.SLEEPY). * * @property sleepState * @type {Number} * @default Body.AWAKE */ this.sleepState = Body.AWAKE; /** * If the speed (the norm of the velocity) is smaller than this value, the body is considered sleepy. * @property sleepSpeedLimit * @type {Number} * @default 0.2 */ this.sleepSpeedLimit = 0.2; /** * If the body has been sleepy for this sleepTimeLimit seconds, it is considered sleeping. * @property sleepTimeLimit * @type {Number} * @default 1 */ this.sleepTimeLimit = 1; /** * Gravity scaling factor. If you want the body to ignore gravity, set this to zero. If you want to reverse gravity, set it to -1. * @property {Number} gravityScale * @default 1 */ this.gravityScale = 1; /** * The last time when the body went to SLEEPY state. * @property {Number} timeLastSleepy * @private */ this.timeLastSleepy = 0; this.concavePath = null; this.lastDampingScale = 1; this.lastAngularDampingScale = 1; this.lastDampingTimeStep = -1; this._wakeUpAfterNarrowphase = false; this.updateMassProperties(); } Body.prototype = new EventEmitter(); Body._idCounter = 0; /** * Set the total density of the body * @method setDensity */ Body.prototype.setDensity = function(density) { var totalArea = this.getArea(); this.mass = totalArea * density; this.updateMassProperties(); }; /** * Get the total area of all shapes in the body * @method getArea * @return {Number} */ Body.prototype.getArea = function() { var totalArea = 0; for(var i=0; i<this.shapes.length; i++){ totalArea += this.shapes[i].area; } return totalArea; }; var shapeAABB = new AABB(), tmp = vec2.create(); /** * Updates the AABB of the Body * @method updateAABB */ Body.prototype.updateAABB = function() { var shapes = this.shapes, shapeOffsets = this.shapeOffsets, shapeAngles = this.shapeAngles, N = shapes.length; for(var i=0; i!==N; i++){ var shape = shapes[i], offset = tmp, angle = shapeAngles[i] + this.angle; // Get shape world offset vec2.rotate(offset,shapeOffsets[i],this.angle); vec2.add(offset,offset,this.position); // Get shape AABB shape.computeAABB(shapeAABB,offset,angle); if(i===0) this.aabb.copy(shapeAABB); else this.aabb.extend(shapeAABB); } this.aabbNeedsUpdate = false; }; /** * Update the bounding radius of the body. Should be done if any of the shapes * are changed. * @method updateBoundingRadius */ Body.prototype.updateBoundingRadius = function(){ var shapes = this.shapes, shapeOffsets = this.shapeOffsets, N = shapes.length, radius = 0; for(var i=0; i!==N; i++){ var shape = shapes[i], offset = vec2.length(shapeOffsets[i]), r = shape.boundingRadius; if(offset + r > radius){ radius = offset + r; } } this.boundingRadius = radius; }; /** * Add a shape to the body. You can pass a local transform when adding a shape, * so that the shape gets an offset and angle relative to the body center of mass. * Will automatically update the mass properties and bounding radius. * * @method addShape * @param {Shape} shape * @param {Array} [offset] Local body offset of the shape. * @param {Number} [angle] Local body angle. * * @example * var body = new Body(), * shape = new Circle(); * * // Add the shape to the body, positioned in the center * body.addShape(shape); * * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local x-axis. * body.addShape(shape,[1,0]); * * // Add another shape to the body, positioned 1 unit length from the body center of mass along the local y-axis, and rotated 90 degrees CCW. * body.addShape(shape,[0,1],Math.PI/2); */ Body.prototype.addShape = function(shape,offset,angle){ angle = angle || 0.0; // Copy the offset vector if(offset){ offset = vec2.fromValues(offset[0],offset[1]); } else { offset = vec2.fromValues(0,0); } this.shapes .push(shape); this.shapeOffsets.push(offset); this.shapeAngles .push(angle); this.updateMassProperties(); this.updateBoundingRadius(); this.aabbNeedsUpdate = true; }; /** * Remove a shape * @method removeShape * @param {Shape} shape * @return {Boolean} True if the shape was found and removed, else false. */ Body.prototype.removeShape = function(shape){ var idx = this.shapes.indexOf(shape); if(idx !== -1){ this.shapes.splice(idx,1); this.shapeOffsets.splice(idx,1); this.shapeAngles.splice(idx,1); this.aabbNeedsUpdate = true; return true; } else { return false; } }; /** * Updates .inertia, .invMass, .invInertia for this Body. Should be called when * changing the structure or mass of the Body. * * @method updateMassProperties * * @example * body.mass += 1; * body.updateMassProperties(); */ Body.prototype.updateMassProperties = function(){ if(this.motionState === Body.STATIC || this.motionState === Body.KINEMATIC){ this.mass = Number.MAX_VALUE; this.invMass = 0; this.inertia = Number.MAX_VALUE; this.invInertia = 0; } else { var shapes = this.shapes, N = shapes.length, m = this.mass / N, I = 0; if(!this.fixedRotation){ for(var i=0; i<N; i++){ var shape = shapes[i], r2 = vec2.squaredLength(this.shapeOffsets[i]), Icm = shape.computeMomentOfInertia(m); I += Icm + m*r2; } this.inertia = I; this.invInertia = I>0 ? 1/I : 0; } else { this.inertia = Number.MAX_VALUE; this.invInertia = 0; } // Inverse mass properties are easy this.invMass = 1/this.mass;// > 0 ? 1/this.mass : 0; } }; var Body_applyForce_r = vec2.create(); /** * Apply force to a world point. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. * @method applyForce * @param {Array} force The force to add. * @param {Array} worldPoint A world point to apply the force on. */ Body.prototype.applyForce = function(force,worldPoint){ // Compute point position relative to the body center var r = Body_applyForce_r; vec2.sub(r,worldPoint,this.position); // Add linear force vec2.add(this.force,this.force,force); // Compute produced rotational force var rotForce = vec2.crossLength(r,force); // Add rotational force this.angularForce += rotForce; }; /** * Transform a world point to local body frame. * @method toLocalFrame * @param {Array} out The vector to store the result in * @param {Array} worldPoint The input world vector */ Body.prototype.toLocalFrame = function(out, worldPoint){ vec2.toLocalFrame(out, worldPoint, this.position, this.angle); }; /** * Transform a local point to world frame. * @method toWorldFrame * @param {Array} out The vector to store the result in * @param {Array} localPoint The input local vector */ Body.prototype.toWorldFrame = function(out, localPoint){ vec2.toGlobalFrame(out, localPoint, this.position, this.angle); }; /** * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. * @method fromPolygon * @param {Array} path An array of 2d vectors, e.g. [[0,0],[0,1],...] that resembles a concave or convex polygon. The shape must be simple and without holes. * @param {Object} [options] * @param {Boolean} [options.optimalDecomp=false] Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {Boolean} [options.skipSimpleCheck=false] Set to true if you already know that the path is not intersecting itself. * @param {Boolean|Number} [options.removeCollinearPoints=false] Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @return {Boolean} True on success, else false. */ Body.prototype.fromPolygon = function(path,options){ options = options || {}; // Remove all shapes for(var i=this.shapes.length; i>=0; --i) this.removeShape(this.shapes[i]); var p = new decomp.Polygon(); p.vertices = path; // Make it counter-clockwise p.makeCCW(); if(typeof(options.removeCollinearPoints)=="number"){ p.removeCollinearPoints(options.removeCollinearPoints); } // Check if any line segment intersects the path itself if(typeof(options.skipSimpleCheck) == "undefined"){ if(!p.isSimple()) return false; } // Save this path for later this.concavePath = p.vertices.slice(0); for(var i=0; i<this.concavePath.length; i++){ var v = [0,0]; vec2.copy(v,this.concavePath[i]); this.concavePath[i] = v; } // Slow or fast decomp? var convexes; if(options.optimalDecomp) convexes = p.decomp(); else convexes = p.quickDecomp(); var cm = vec2.create(); // Add convexes for(var i=0; i!==convexes.length; i++){ // Create convex var c = new Convex(convexes[i].vertices); // Move all vertices so its center of mass is in the local center of the convex for(var j=0; j!==c.vertices.length; j++){ var v = c.vertices[j]; vec2.sub(v,v,c.centerOfMass); } vec2.scale(cm,c.centerOfMass,1); c.updateTriangles(); c.updateCenterOfMass(); c.updateBoundingRadius(); // Add the shape this.addShape(c,cm); } this.adjustCenterOfMass(); this.aabbNeedsUpdate = true; return true; }; var adjustCenterOfMass_tmp1 = vec2.fromValues(0,0), adjustCenterOfMass_tmp2 = vec2.fromValues(0,0), adjustCenterOfMass_tmp3 = vec2.fromValues(0,0), adjustCenterOfMass_tmp4 = vec2.fromValues(0,0); /** * Moves the shape offsets so their center of mass becomes the body center of mass. * @method adjustCenterOfMass */ Body.prototype.adjustCenterOfMass = function(){ var offset_times_area = adjustCenterOfMass_tmp2, sum = adjustCenterOfMass_tmp3, cm = adjustCenterOfMass_tmp4, totalArea = 0; vec2.set(sum,0,0); for(var i=0; i!==this.shapes.length; i++){ var s = this.shapes[i], offset = this.shapeOffsets[i]; vec2.scale(offset_times_area,offset,s.area); vec2.add(sum,sum,offset_times_area); totalArea += s.area; } vec2.scale(cm,sum,1/totalArea); // Now move all shapes for(var i=0; i!==this.shapes.length; i++){ var s = this.shapes[i], offset = this.shapeOffsets[i]; // Offset may be undefined. Fix that. if(!offset){ offset = this.shapeOffsets[i] = vec2.create(); } vec2.sub(offset,offset,cm); } // Move the body position too vec2.add(this.position,this.position,cm); // And concave path for(var i=0; this.concavePath && i<this.concavePath.length; i++){ vec2.sub(this.concavePath[i], this.concavePath[i], cm); } this.updateMassProperties(); this.updateBoundingRadius(); }; /** * Sets the force on the body to zero. * @method setZeroForce */ Body.prototype.setZeroForce = function(){ vec2.set(this.force,0.0,0.0); this.angularForce = 0.0; }; Body.prototype.resetConstraintVelocity = function(){ var b = this, vlambda = b.vlambda; vec2.set(vlambda,0,0); b.wlambda = 0; }; Body.prototype.addConstraintVelocity = function(){ var b = this, v = b.velocity; vec2.add( v, v, b.vlambda); b.angularVelocity += b.wlambda; }; /** * Apply damping, see <a href="http://code.google.com/p/bullet/issues/detail?id=74">this</a> for details. * @method applyDamping * @param {number} dt Current time step */ Body.prototype.applyDamping = function(dt){ if(this.motionState === Body.DYNAMIC){ // Only for dynamic bodies // Since Math.pow generates garbage we check if we can reuse the scaling coefficient from last step if(dt !== this.lastDampingTimeStep){ this.lastDampingScale = Math.pow(1.0 - this.damping,dt); this.lastAngularDampingScale = Math.pow(1.0 - this.angularDamping,dt); this.lastDampingTimeStep = dt; } var v = this.velocity; vec2.scale(v,v,this.lastDampingScale); this.angularVelocity *= this.lastAngularDampingScale; } }; /** * Wake the body up. Normally you should not need this, as the body is automatically awoken at events such as collisions. * Sets the sleepState to {{#crossLink "Body/AWAKE:property"}}Body.AWAKE{{/crossLink}} and emits the wakeUp event if the body wasn't awake before. * @method wakeUp */ Body.prototype.wakeUp = function(){ var s = this.sleepState; this.sleepState = Body.AWAKE; this.idleTime = 0; if(s !== Body.AWAKE){ this.emit(Body.wakeUpEvent); } }; /** * Force body sleep * @method sleep */ Body.prototype.sleep = function(){ this.sleepState = Body.SLEEPING; this.angularVelocity = 0; this.angularForce = 0; vec2.set(this.velocity,0,0); vec2.set(this.force,0,0); this.emit(Body.sleepEvent); }; //var velo2 = vec2.create(); /** * @method sleepTick * @param float time The world time in seconds * @brief Called every timestep to update internal sleep timer and change sleep state if needed. */ Body.prototype.sleepTick = function(time, dontSleep, dt){ if(!this.allowSleep || this.motionState === Body.SLEEPING){ return; } this.wantsToSleep = false; var sleepState = this.sleepState, speedSquared = vec2.squaredLength(this.velocity) + Math.pow(this.angularVelocity,2), speedLimitSquared = Math.pow(this.sleepSpeedLimit,2); // Add to idle time if(speedSquared >= speedLimitSquared){ this.idleTime = 0; this.sleepState = Body.AWAKE; } else { this.idleTime += dt; this.sleepState = Body.SLEEPY; } if(this.idleTime > this.sleepTimeLimit){ if(!dontSleep){ this.sleep(); } else { this.wantsToSleep = true; } } /* if(sleepState===Body.AWAKE && speedSquared < speedLimitSquared){ this.sleepState = Body.SLEEPY; // Sleepy this.timeLastSleepy = time; this.emit(Body.sleepyEvent); } else if(sleepState===Body.SLEEPY && speedSquared >= speedLimitSquared){ this.wakeUp(); // Wake up } else if(sleepState===Body.SLEEPY && (time - this.timeLastSleepy ) > this.sleepTimeLimit){ this.wantsToSleep = true; if(!dontSleep){ this.sleep(); } } */ }; Body.prototype.getVelocityFromPosition = function(store, timeStep){ store = store || vec2.create(); vec2.sub(store, this.position, this.previousPosition); vec2.scale(store, store, 1/timeStep); return store; }; Body.prototype.getAngularVelocityFromPosition = function(timeStep){ return (this.angle - this.previousAngle) / timeStep; }; /** * @event sleepy */ Body.sleepyEvent = { type: "sleepy" }; /** * @event sleep */ Body.sleepEvent = { type: "sleep" }; /** * @event wakeup */ Body.wakeUpEvent = { type: "wakeup" }; /** * Dynamic body. * @property DYNAMIC * @type {Number} * @static */ Body.DYNAMIC = 1; /** * Static body. * @property STATIC * @type {Number} * @static */ Body.STATIC = 2; /** * Kinematic body. * @property KINEMATIC * @type {Number} * @static */ Body.KINEMATIC = 4; /** * @property AWAKE * @type {Number} * @static */ Body.AWAKE = 0; /** * @property SLEEPY * @type {Number} * @static */ Body.SLEEPY = 1; /** * @property SLEEPING * @type {Number} * @static */ Body.SLEEPING = 2; },{"../collision/AABB":8,"../events/EventEmitter":26,"../math/vec2":30,"../shapes/Convex":36,"poly-decomp":6}],32:[function(require,module,exports){ var vec2 = require('../math/vec2'); var Utils = require('../utils/Utils'); module.exports = Spring; /** * A spring, connecting two bodies. The Spring explicitly adds force and angularForce to the bodies and does therefore not put load on the solver. * * @class Spring * @constructor * @param {Body} bodyA * @param {Body} bodyB * @param {Object} [options] * @param {number} [options.restLength=1] A number > 0. Default: 1 * @param {number} [options.stiffness=100] Spring constant (see Hookes Law). A number >= 0. * @param {number} [options.damping=1] A number >= 0. Default: 1 * @param {Array} [options.localAnchorA] Where to hook the spring to body A, in local body coordinates. Defaults to the body center. * @param {Array} [options.localAnchorB] * @param {Array} [options.worldAnchorA] Where to hook the spring to body A, in world coordinates. Overrides the option "localAnchorA" if given. * @param {Array} [options.worldAnchorB] */ function Spring(bodyA,bodyB,options){ options = Utils.defaults(options,{ restLength: 1, stiffness: 100, damping: 1, localAnchorA: [0,0], localAnchorB: [0,0], }); /** * Rest length of the spring. * @property restLength * @type {number} */ this.restLength = options.restLength; /** * Stiffness of the spring. * @property stiffness * @type {number} */ this.stiffness = options.stiffness; /** * Damping of the spring. * @property damping * @type {number} */ this.damping = options.damping; /** * First connected body. * @property bodyA * @type {Body} */ this.bodyA = bodyA; /** * Second connected body. * @property bodyB * @type {Body} */ this.bodyB = bodyB; /** * Anchor for bodyA in local bodyA coordinates. * @property localAnchorA * @type {Array} */ this.localAnchorA = vec2.create(); vec2.copy(this.localAnchorA, options.localAnchorA); /** * Anchor for bodyB in local bodyB coordinates. * @property localAnchorB * @type {Array} */ this.localAnchorB = vec2.create(); vec2.copy(this.localAnchorB, options.localAnchorB); if(options.worldAnchorA){ this.setWorldAnchorA(options.worldAnchorA); } if(options.worldAnchorB){ this.setWorldAnchorB(options.worldAnchorB); } } /** * Set the anchor point on body A, using world coordinates. * @method setWorldAnchorA * @param {Array} worldAnchorA */ Spring.prototype.setWorldAnchorA = function(worldAnchorA){ this.bodyA.toLocalFrame(this.localAnchorA, worldAnchorA); }; /** * Set the anchor point on body B, using world coordinates. * @method setWorldAnchorB * @param {Array} worldAnchorB */ Spring.prototype.setWorldAnchorB = function(worldAnchorB){ this.bodyB.toLocalFrame(this.localAnchorB, worldAnchorB); }; /** * Get the anchor point on body A, in world coordinates. * @method getWorldAnchorA * @param {Array} result The vector to store the result in. */ Spring.prototype.getWorldAnchorA = function(result){ this.bodyA.toWorldFrame(result, this.localAnchorA); }; /** * Get the anchor point on body B, in world coordinates. * @method getWorldAnchorB * @param {Array} result The vector to store the result in. */ Spring.prototype.getWorldAnchorB = function(result){ this.bodyB.toWorldFrame(result, this.localAnchorB); }; var applyForce_r = vec2.create(), applyForce_r_unit = vec2.create(), applyForce_u = vec2.create(), applyForce_f = vec2.create(), applyForce_worldAnchorA = vec2.create(), applyForce_worldAnchorB = vec2.create(), applyForce_ri = vec2.create(), applyForce_rj = vec2.create(), applyForce_tmp = vec2.create(); /** * Apply the spring force to the connected bodies. * @method applyForce */ Spring.prototype.applyForce = function(){ var k = this.stiffness, d = this.damping, l = this.restLength, bodyA = this.bodyA, bodyB = this.bodyB, r = applyForce_r, r_unit = applyForce_r_unit, u = applyForce_u, f = applyForce_f, tmp = applyForce_tmp; var worldAnchorA = applyForce_worldAnchorA, worldAnchorB = applyForce_worldAnchorB, ri = applyForce_ri, rj = applyForce_rj; // Get world anchors this.getWorldAnchorA(worldAnchorA); this.getWorldAnchorB(worldAnchorB); // Get offset points vec2.sub(ri, worldAnchorA, bodyA.position); vec2.sub(rj, worldAnchorB, bodyB.position); // Compute distance vector between world anchor points vec2.sub(r, worldAnchorB, worldAnchorA); var rlen = vec2.len(r); vec2.normalize(r_unit,r); //console.log(rlen) //console.log("A",vec2.str(worldAnchorA),"B",vec2.str(worldAnchorB)) // Compute relative velocity of the anchor points, u vec2.sub(u, bodyB.velocity, bodyA.velocity); vec2.crossZV(tmp, bodyB.angularVelocity, rj); vec2.add(u, u, tmp); vec2.crossZV(tmp, bodyA.angularVelocity, ri); vec2.sub(u, u, tmp); // F = - k * ( x - L ) - D * ( u ) vec2.scale(f, r_unit, -k*(rlen-l) - d*vec2.dot(u,r_unit)); // Add forces to bodies vec2.sub( bodyA.force, bodyA.force, f); vec2.add( bodyB.force, bodyB.force, f); // Angular force var ri_x_f = vec2.crossLength(ri, f); var rj_x_f = vec2.crossLength(rj, f); bodyA.angularForce -= ri_x_f; bodyB.angularForce += rj_x_f; }; },{"../math/vec2":30,"../utils/Utils":47}],33:[function(require,module,exports){ // Export p2 classes module.exports = { AABB : require('./collision/AABB'), AngleLockEquation : require('./equations/AngleLockEquation'), Body : require('./objects/Body'), Broadphase : require('./collision/Broadphase'), Capsule : require('./shapes/Capsule'), Circle : require('./shapes/Circle'), Constraint : require('./constraints/Constraint'), ContactEquation : require('./equations/ContactEquation'), ContactMaterial : require('./material/ContactMaterial'), Convex : require('./shapes/Convex'), DistanceConstraint : require('./constraints/DistanceConstraint'), Equation : require('./equations/Equation'), EventEmitter : require('./events/EventEmitter'), FrictionEquation : require('./equations/FrictionEquation'), GearConstraint : require('./constraints/GearConstraint'), GridBroadphase : require('./collision/GridBroadphase'), GSSolver : require('./solver/GSSolver'), Heightfield : require('./shapes/Heightfield'), Line : require('./shapes/Line'), LockConstraint : require('./constraints/LockConstraint'), Material : require('./material/Material'), Narrowphase : require('./collision/Narrowphase'), NaiveBroadphase : require('./collision/NaiveBroadphase'), Particle : require('./shapes/Particle'), Plane : require('./shapes/Plane'), RevoluteConstraint : require('./constraints/RevoluteConstraint'), PrismaticConstraint : require('./constraints/PrismaticConstraint'), Rectangle : require('./shapes/Rectangle'), RotationalVelocityEquation : require('./equations/RotationalVelocityEquation'), SAPBroadphase : require('./collision/SAPBroadphase'), Shape : require('./shapes/Shape'), Solver : require('./solver/Solver'), Spring : require('./objects/Spring'), Utils : require('./utils/Utils'), World : require('./world/World'), vec2 : require('./math/vec2'), version : require('../package.json').version, }; },{"../package.json":7,"./collision/AABB":8,"./collision/Broadphase":9,"./collision/GridBroadphase":10,"./collision/NaiveBroadphase":11,"./collision/Narrowphase":12,"./collision/SAPBroadphase":13,"./constraints/Constraint":14,"./constraints/DistanceConstraint":15,"./constraints/GearConstraint":16,"./constraints/LockConstraint":17,"./constraints/PrismaticConstraint":18,"./constraints/RevoluteConstraint":19,"./equations/AngleLockEquation":20,"./equations/ContactEquation":21,"./equations/Equation":22,"./equations/FrictionEquation":23,"./equations/RotationalVelocityEquation":25,"./events/EventEmitter":26,"./material/ContactMaterial":27,"./material/Material":28,"./math/vec2":30,"./objects/Body":31,"./objects/Spring":32,"./shapes/Capsule":34,"./shapes/Circle":35,"./shapes/Convex":36,"./shapes/Heightfield":37,"./shapes/Line":38,"./shapes/Particle":39,"./shapes/Plane":40,"./shapes/Rectangle":41,"./shapes/Shape":42,"./solver/GSSolver":43,"./solver/Solver":44,"./utils/Utils":47,"./world/World":51}],34:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2'); module.exports = Capsule; /** * Capsule shape class. * @class Capsule * @constructor * @extends Shape * @param {Number} [length] The distance between the end points * @param {Number} [radius] Radius of the capsule */ function Capsule(length, radius){ /** * The distance between the end points. * @property {Number} length */ this.length = length || 1; /** * The radius of the capsule. * @property {Number} radius */ this.radius = radius || 1; Shape.call(this,Shape.CAPSULE); } Capsule.prototype = new Shape(); /** * Compute the mass moment of inertia of the Capsule. * @method conputeMomentOfInertia * @param {Number} mass * @return {Number} * @todo */ Capsule.prototype.computeMomentOfInertia = function(mass){ // Approximate with rectangle var r = this.radius, w = this.length + r, // 2*r is too much, 0 is too little h = r*2; return mass * (h*h + w*w) / 12; }; /** * @method updateBoundingRadius */ Capsule.prototype.updateBoundingRadius = function(){ this.boundingRadius = this.radius + this.length/2; }; /** * @method updateArea */ Capsule.prototype.updateArea = function(){ this.area = Math.PI * this.radius * this.radius + this.radius * 2 * this.length; }; var r = vec2.create(); /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Capsule.prototype.computeAABB = function(out, position, angle){ var radius = this.radius; // Compute center position of one of the the circles, world oriented, but with local offset vec2.set(r,this.length,0); vec2.rotate(r,r,angle); // Get bounds vec2.set(out.upperBound, Math.max(r[0]+radius, -r[0]+radius), Math.max(r[1]+radius, -r[1]+radius)); vec2.set(out.lowerBound, Math.min(r[0]-radius, -r[0]-radius), Math.min(r[1]-radius, -r[1]-radius)); // Add offset vec2.add(out.lowerBound, out.lowerBound, position); vec2.add(out.upperBound, out.upperBound, position); }; },{"../math/vec2":30,"./Shape":42}],35:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2') module.exports = Circle; /** * Circle shape class. * @class Circle * @extends Shape * @constructor * @param {number} [radius=1] The radius of this circle */ function Circle(radius){ /** * The radius of the circle. * @property radius * @type {number} */ this.radius = radius || 1; Shape.call(this,Shape.CIRCLE); }; Circle.prototype = new Shape(); /** * @method computeMomentOfInertia * @param {Number} mass * @return {Number} */ Circle.prototype.computeMomentOfInertia = function(mass){ var r = this.radius; return mass * r * r / 2; }; /** * @method updateBoundingRadius * @return {Number} */ Circle.prototype.updateBoundingRadius = function(){ this.boundingRadius = this.radius; }; /** * @method updateArea * @return {Number} */ Circle.prototype.updateArea = function(){ this.area = Math.PI * this.radius * this.radius; }; /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Circle.prototype.computeAABB = function(out, position, angle){ var r = this.radius; vec2.set(out.upperBound, r, r); vec2.set(out.lowerBound, -r, -r); if(position){ vec2.add(out.lowerBound, out.lowerBound, position); vec2.add(out.upperBound, out.upperBound, position); } }; },{"../math/vec2":30,"./Shape":42}],36:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2') , polyk = require('../math/polyk') , decomp = require('poly-decomp') module.exports = Convex; /** * Convex shape class. * @class Convex * @constructor * @extends Shape * @param {Array} vertices An array of Float32Array vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction. */ function Convex(vertices){ /** * Vertices defined in the local frame. * @property vertices * @type {Array} */ this.vertices = []; // Copy the verts for(var i=0; i<vertices.length; i++){ var v = vec2.create(); vec2.copy(v,vertices[i]); this.vertices.push(v); } /** * The center of mass of the Convex * @property centerOfMass * @type {Float32Array} */ this.centerOfMass = vec2.fromValues(0,0); /** * Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices. * @property triangles * @type {Array} */ this.triangles = []; if(this.vertices.length){ this.updateTriangles(); this.updateCenterOfMass(); } /** * The bounding radius of the convex * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; Shape.call(this,Shape.CONVEX); this.updateBoundingRadius(); this.updateArea(); if(this.area < 0) throw new Error("Convex vertices must be given in conter-clockwise winding."); }; Convex.prototype = new Shape(); /** * Update the .triangles property * @method updateTriangles */ Convex.prototype.updateTriangles = function(){ this.triangles.length = 0; // Rewrite on polyk notation, array of numbers var polykVerts = []; for(var i=0; i<this.vertices.length; i++){ var v = this.vertices[i]; polykVerts.push(v[0],v[1]); } // Triangulate var triangles = polyk.Triangulate(polykVerts); // Loop over all triangles, add their inertia contributions to I for(var i=0; i<triangles.length; i+=3){ var id1 = triangles[i], id2 = triangles[i+1], id3 = triangles[i+2]; // Add to triangles this.triangles.push([id1,id2,id3]); } }; var updateCenterOfMass_centroid = vec2.create(), updateCenterOfMass_centroid_times_mass = vec2.create(), updateCenterOfMass_a = vec2.create(), updateCenterOfMass_b = vec2.create(), updateCenterOfMass_c = vec2.create(), updateCenterOfMass_ac = vec2.create(), updateCenterOfMass_ca = vec2.create(), updateCenterOfMass_cb = vec2.create(), updateCenterOfMass_n = vec2.create(); /** * Update the .centerOfMass property. * @method updateCenterOfMass */ Convex.prototype.updateCenterOfMass = function(){ var triangles = this.triangles, verts = this.vertices, cm = this.centerOfMass, centroid = updateCenterOfMass_centroid, n = updateCenterOfMass_n, a = updateCenterOfMass_a, b = updateCenterOfMass_b, c = updateCenterOfMass_c, ac = updateCenterOfMass_ac, ca = updateCenterOfMass_ca, cb = updateCenterOfMass_cb, centroid_times_mass = updateCenterOfMass_centroid_times_mass; vec2.set(cm,0,0); var totalArea = 0; for(var i=0; i!==triangles.length; i++){ var t = triangles[i], a = verts[t[0]], b = verts[t[1]], c = verts[t[2]]; vec2.centroid(centroid,a,b,c); // Get mass for the triangle (density=1 in this case) // http://math.stackexchange.com/questions/80198/area-of-triangle-via-vectors var m = Convex.triangleArea(a,b,c) totalArea += m; // Add to center of mass vec2.scale(centroid_times_mass, centroid, m); vec2.add(cm, cm, centroid_times_mass); } vec2.scale(cm,cm,1/totalArea); }; /** * Compute the mass moment of inertia of the Convex. * @method computeMomentOfInertia * @param {Number} mass * @return {Number} * @see http://www.gamedev.net/topic/342822-moment-of-inertia-of-a-polygon-2d/ */ Convex.prototype.computeMomentOfInertia = function(mass){ var denom = 0.0, numer = 0.0, N = this.vertices.length; for(var j = N-1, i = 0; i < N; j = i, i ++){ var p0 = this.vertices[j]; var p1 = this.vertices[i]; var a = Math.abs(vec2.crossLength(p0,p1)); var b = vec2.dot(p1,p1) + vec2.dot(p1,p0) + vec2.dot(p0,p0); denom += a * b; numer += a; } return (mass / 6.0) * (denom / numer); }; /** * Updates the .boundingRadius property * @method updateBoundingRadius */ Convex.prototype.updateBoundingRadius = function(){ var verts = this.vertices, r2 = 0; for(var i=0; i!==verts.length; i++){ var l2 = vec2.squaredLength(verts[i]); if(l2 > r2) r2 = l2; } this.boundingRadius = Math.sqrt(r2); }; /** * Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative. * @static * @method triangleArea * @param {Array} a * @param {Array} b * @param {Array} c * @return {Number} */ Convex.triangleArea = function(a,b,c){ return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5; } /** * Update the .area * @method updateArea */ Convex.prototype.updateArea = function(){ this.updateTriangles(); this.area = 0; var triangles = this.triangles, verts = this.vertices; for(var i=0; i!==triangles.length; i++){ var t = triangles[i], a = verts[t[0]], b = verts[t[1]], c = verts[t[2]]; // Get mass for the triangle (density=1 in this case) var m = Convex.triangleArea(a,b,c); this.area += m; } }; /** * @method computeAABB * @param {AABB} out * @param {Array} position * @param {Number} angle */ Convex.prototype.computeAABB = function(out, position, angle){ out.setFromPoints(this.vertices,position,angle); }; },{"../math/polyk":29,"../math/vec2":30,"./Shape":42,"poly-decomp":6}],37:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2') , Utils = require('../utils/Utils'); module.exports = Heightfield; /** * Heightfield shape class. Height data is given as an array. These data points are spread out evenly with a distance "elementWidth". * @class Heightfield * @extends Shape * @constructor * @param {Array} data * @param {Number} maxValue * @param {Number} elementWidth * @todo Should take maxValue as an option and also be able to compute it itself if not given. * @todo Should be possible to use along all axes, not just y */ function Heightfield(data, options){ options = Utils.defaults(options, { maxValue : null, minValue : null, elementWidth : 0.1 }); if(options.minValue === null || options.maxValue === null){ options.maxValue = data[0]; options.minValue = data[0]; for(var i=0; i !== data.length; i++){ var v = data[i]; if(v > options.maxValue){ options.maxValue = v; } if(v < options.minValue){ options.minValue = v; } } } /** * An array of numbers, or height values, that are spread out along the x axis. * @property {array} data */ this.data = data; /** * Max value of the data * @property {number} maxValue */ this.maxValue = options.maxValue; /** * Max value of the data * @property {number} minValue */ this.minValue = options.minValue; /** * The width of each element * @property {number} elementWidth */ this.elementWidth = options.elementWidth; Shape.call(this,Shape.HEIGHTFIELD); } Heightfield.prototype = new Shape(); /** * @method computeMomentOfInertia * @param {Number} mass * @return {Number} */ Heightfield.prototype.computeMomentOfInertia = function(mass){ return Number.MAX_VALUE; }; Heightfield.prototype.updateBoundingRadius = function(){ this.boundingRadius = Number.MAX_VALUE; }; Heightfield.prototype.updateArea = function(){ var data = this.data, area = 0; for(var i=0; i<data.length-1; i++){ area += (data[i]+data[i+1]) / 2 * this.elementWidth; } this.area = area; }; /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Heightfield.prototype.computeAABB = function(out, position, angle){ // Use the max data rectangle out.upperBound[0] = this.elementWidth * this.data.length + position[0]; out.upperBound[1] = this.maxValue + position[1]; out.lowerBound[0] = position[0]; out.lowerBound[1] = -Number.MAX_VALUE; // Infinity }; },{"../math/vec2":30,"../utils/Utils":47,"./Shape":42}],38:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2') module.exports = Line; /** * Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. * @class Line * @param {Number} length The total length of the line * @extends Shape * @constructor */ function Line(length){ /** * Length of this line * @property length * @type {Number} */ this.length = length || 1; Shape.call(this,Shape.LINE); } Line.prototype = new Shape(); Line.prototype.computeMomentOfInertia = function(mass){ return mass * Math.pow(this.length,2) / 12; }; Line.prototype.updateBoundingRadius = function(){ this.boundingRadius = this.length/2; }; var points = [vec2.create(),vec2.create()]; /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Line.prototype.computeAABB = function(out, position, angle){ var l = this.length; vec2.set(points[0], -l/2, 0); vec2.set(points[1], l/2, 0); out.setFromPoints(points,position,angle); }; },{"../math/vec2":30,"./Shape":42}],39:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2') module.exports = Particle; /** * Particle shape class. * @class Particle * @constructor * @extends Shape */ function Particle(){ Shape.call(this,Shape.PARTICLE); }; Particle.prototype = new Shape(); Particle.prototype.computeMomentOfInertia = function(mass){ return 0; // Can't rotate a particle }; Particle.prototype.updateBoundingRadius = function(){ this.boundingRadius = 0; }; /** * @method computeAABB * @param {AABB} out * @param {Array} position * @param {Number} angle */ Particle.prototype.computeAABB = function(out, position, angle){ var l = this.length; vec2.copy(out.lowerBound, position); vec2.copy(out.upperBound, position); }; },{"../math/vec2":30,"./Shape":42}],40:[function(require,module,exports){ var Shape = require('./Shape') , vec2 = require('../math/vec2') , Utils = require('../utils/Utils') module.exports = Plane; /** * Plane shape class. The plane is facing in the Y direction. * @class Plane * @extends Shape * @constructor */ function Plane(){ Shape.call(this,Shape.PLANE); }; Plane.prototype = new Shape(); /** * Compute moment of inertia * @method computeMomentOfInertia */ Plane.prototype.computeMomentOfInertia = function(mass){ return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here }; /** * Update the bounding radius * @method updateBoundingRadius */ Plane.prototype.updateBoundingRadius = function(){ this.boundingRadius = Number.MAX_VALUE; }; /** * @method computeAABB * @param {AABB} out * @param {Array} position * @param {Number} angle */ Plane.prototype.computeAABB = function(out, position, angle){ var a = 0, set = vec2.set; if(typeof(angle) == "number") a = angle % (2*Math.PI); if(a == 0){ // y goes from -inf to 0 set(out.lowerBound, -Number.MAX_VALUE, -Number.MAX_VALUE); set(out.upperBound, Number.MAX_VALUE, 0); } else if(a == Math.PI / 2){ // x goes from 0 to inf set(out.lowerBound, 0, -Number.MAX_VALUE); set(out.upperBound, Number.MAX_VALUE, Number.MAX_VALUE); } else if(a == Math.PI){ // y goes from 0 to inf set(out.lowerBound, -Number.MAX_VALUE, 0); set(out.upperBound, Number.MAX_VALUE, Number.MAX_VALUE); } else if(a == 3*Math.PI/2){ // x goes from -inf to 0 set(out.lowerBound, -Number.MAX_VALUE, -Number.MAX_VALUE); set(out.upperBound, 0, Number.MAX_VALUE); } else { // Set max bounds set(out.lowerBound, -Number.MAX_VALUE, -Number.MAX_VALUE); set(out.upperBound, Number.MAX_VALUE, Number.MAX_VALUE); } vec2.add(out.lowerBound, out.lowerBound, position); vec2.add(out.upperBound, out.upperBound, position); }; Plane.prototype.updateArea = function(){ this.area = Number.MAX_VALUE; }; },{"../math/vec2":30,"../utils/Utils":47,"./Shape":42}],41:[function(require,module,exports){ var vec2 = require('../math/vec2') , Shape = require('./Shape') , Convex = require('./Convex'); module.exports = Rectangle; /** * Rectangle shape class. * @class Rectangle * @constructor * @param {Number} width Width * @param {Number} height Height * @extends Convex */ function Rectangle(width, height){ width = width || 1; height = height || 1; var verts = [ vec2.fromValues(-width/2, -height/2), vec2.fromValues( width/2, -height/2), vec2.fromValues( width/2, height/2), vec2.fromValues(-width/2, height/2)]; /** * Total width of the rectangle * @property width * @type {Number} */ this.width = width; /** * Total height of the rectangle * @property height * @type {Number} */ this.height = height; Convex.call(this,verts); this.type = Shape.RECTANGLE; } Rectangle.prototype = new Convex([]); /** * Compute moment of inertia * @method computeMomentOfInertia * @param {Number} mass * @return {Number} */ Rectangle.prototype.computeMomentOfInertia = function(mass){ var w = this.width, h = this.height; return mass * (h*h + w*w) / 12; }; /** * Update the bounding radius * @method updateBoundingRadius */ Rectangle.prototype.updateBoundingRadius = function(){ var w = this.width, h = this.height; this.boundingRadius = Math.sqrt(w*w + h*h) / 2; }; var corner1 = vec2.create(), corner2 = vec2.create(), corner3 = vec2.create(), corner4 = vec2.create(); /** * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Rectangle.prototype.computeAABB = function(out, position, angle){ out.setFromPoints(this.vertices,position,angle); }; Rectangle.prototype.updateArea = function(){ this.area = this.width * this.height; }; },{"../math/vec2":30,"./Convex":36,"./Shape":42}],42:[function(require,module,exports){ module.exports = Shape; /** * Base class for shapes. * @class Shape * @constructor * @param {Number} type */ function Shape(type){ /** * The type of the shape. One of: * * * {{#crossLink "Shape/CIRCLE:property"}}Shape.CIRCLE{{/crossLink}} * * {{#crossLink "Shape/PARTICLE:property"}}Shape.PARTICLE{{/crossLink}} * * {{#crossLink "Shape/PLANE:property"}}Shape.PLANE{{/crossLink}} * * {{#crossLink "Shape/CONVEX:property"}}Shape.CONVEX{{/crossLink}} * * {{#crossLink "Shape/LINE:property"}}Shape.LINE{{/crossLink}} * * {{#crossLink "Shape/RECTANGLE:property"}}Shape.RECTANGLE{{/crossLink}} * * {{#crossLink "Shape/CAPSULE:property"}}Shape.CAPSULE{{/crossLink}} * * {{#crossLink "Shape/HEIGHTFIELD:property"}}Shape.HEIGHTFIELD{{/crossLink}} * * @property {number} type */ this.type = type; /** * Shape object identifier. * @type {Number} * @property id */ this.id = Shape.idCounter++; /** * Bounding circle radius of this shape * @property boundingRadius * @type {Number} */ this.boundingRadius = 0; /** * Collision group that this shape belongs to (bit mask). See <a href="http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/">this tutorial</a>. * @property collisionGroup * @type {Number} * @example * // Setup bits for each available group * var PLAYER = Math.pow(2,0), * ENEMY = Math.pow(2,1), * GROUND = Math.pow(2,2) * * // Put shapes into their groups * player1Shape.collisionGroup = PLAYER; * player2Shape.collisionGroup = PLAYER; * enemyShape .collisionGroup = ENEMY; * groundShape .collisionGroup = GROUND; * * // Assign groups that each shape collide with. * // Note that the players can collide with ground and enemies, but not with other players. * player1Shape.collisionMask = ENEMY | GROUND; * player2Shape.collisionMask = ENEMY | GROUND; * enemyShape .collisionMask = PLAYER | GROUND; * groundShape .collisionMask = PLAYER | ENEMY; * * @example * // How collision check is done * if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){ * // The shapes will collide * } */ this.collisionGroup = 1; /** * Collision mask of this shape. See .collisionGroup. * @property collisionMask * @type {Number} */ this.collisionMask = 1; if(type) this.updateBoundingRadius(); /** * Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead. * @property material * @type {Material} */ this.material = null; /** * Area of this shape. * @property area * @type {Number} */ this.area = 0; /** * Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts. * @property {Boolean} sensor */ this.sensor = false; this.updateArea(); }; Shape.idCounter = 0; /** * @static * @property {Number} CIRCLE */ Shape.CIRCLE = 1; /** * @static * @property {Number} PARTICLE */ Shape.PARTICLE = 2; /** * @static * @property {Number} PLANE */ Shape.PLANE = 4; /** * @static * @property {Number} CONVEX */ Shape.CONVEX = 8; /** * @static * @property {Number} LINE */ Shape.LINE = 16; /** * @static * @property {Number} RECTANGLE */ Shape.RECTANGLE = 32; /** * @static * @property {Number} CAPSULE */ Shape.CAPSULE = 64; /** * @static * @property {Number} HEIGHTFIELD */ Shape.HEIGHTFIELD = 128; /** * Should return the moment of inertia around the Z axis of the body given the total mass. See <a href="http://en.wikipedia.org/wiki/List_of_moments_of_inertia">Wikipedia's list of moments of inertia</a>. * @method computeMomentOfInertia * @param {Number} mass * @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0. */ Shape.prototype.computeMomentOfInertia = function(mass){ throw new Error("Shape.computeMomentOfInertia is not implemented in this Shape..."); }; /** * Returns the bounding circle radius of this shape. * @method updateBoundingRadius * @return {Number} */ Shape.prototype.updateBoundingRadius = function(){ throw new Error("Shape.updateBoundingRadius is not implemented in this Shape..."); }; /** * Update the .area property of the shape. * @method updateArea */ Shape.prototype.updateArea = function(){ // To be implemented in all subclasses }; /** * Compute the world axis-aligned bounding box (AABB) of this shape. * @method computeAABB * @param {AABB} out The resulting AABB. * @param {Array} position * @param {Number} angle */ Shape.prototype.computeAABB = function(out, position, angle){ // To be implemented in each subclass }; },{}],43:[function(require,module,exports){ var vec2 = require('../math/vec2') , Solver = require('./Solver') , Utils = require('../utils/Utils') , FrictionEquation = require('../equations/FrictionEquation'); module.exports = GSSolver; /** * Iterative Gauss-Seidel constraint equation solver. * * @class GSSolver * @constructor * @extends Solver * @param {Object} [options] * @param {Number} [options.iterations=10] * @param {Number} [options.tolerance=0] */ function GSSolver(options){ Solver.call(this,options,Solver.GS); options = options || {}; /** * The number of iterations to do when solving. More gives better results, but is more expensive. * @property iterations * @type {Number} */ this.iterations = options.iterations || 10; /** * The error tolerance, per constraint. If the total error is below this limit, the solver will stop iterating. Set to zero for as good solution as possible, but to something larger than zero to make computations faster. * @property tolerance * @type {Number} */ this.tolerance = options.tolerance || 1e-10; this.arrayStep = 30; this.lambda = new Utils.ARRAY_TYPE(this.arrayStep); this.Bs = new Utils.ARRAY_TYPE(this.arrayStep); this.invCs = new Utils.ARRAY_TYPE(this.arrayStep); /** * Set to true to set all right hand side terms to zero when solving. Can be handy for a few applications. * @property useZeroRHS * @type {Boolean} */ this.useZeroRHS = false; /** * Number of solver iterations that are done to approximate normal forces. When these iterations are done, friction force will be computed from the contact normal forces. These friction forces will override any other friction forces set from the World for example. * The solver will use less iterations if the solution is below the .tolerance. * @property frictionIterations * @type {Number} */ this.frictionIterations = 0; /** * The number of iterations that were made during the last solve. If .tolerance is zero, this value will always be equal to .iterations, but if .tolerance is larger than zero, and the solver can quit early, then this number will be somewhere between 1 and .iterations. * @property {Number} usedIterations */ this.usedIterations = 0; } GSSolver.prototype = new Solver(); function setArrayZero(array){ var l = array.length; while(l--){ array[l] = +0.0; } } /** * Solve the system of equations * @method solve * @param {Number} h Time step * @param {World} world World to solve */ GSSolver.prototype.solve = function(h, world){ this.sortEquations(); var iter = 0, maxIter = this.iterations, maxFrictionIter = this.frictionIterations, equations = this.equations, Neq = equations.length, tolSquared = Math.pow(this.tolerance*Neq, 2), bodies = world.bodies, Nbodies = world.bodies.length, add = vec2.add, set = vec2.set, useZeroRHS = this.useZeroRHS, lambda = this.lambda; this.usedIterations = 0; // Things that does not change during iteration can be computed once if(lambda.length < Neq){ lambda = this.lambda = new Utils.ARRAY_TYPE(Neq + this.arrayStep); this.Bs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); this.invCs = new Utils.ARRAY_TYPE(Neq + this.arrayStep); } setArrayZero(lambda); var invCs = this.invCs, Bs = this.Bs, lambda = this.lambda; for(var i=0; i!==equations.length; i++){ var c = equations[i]; if(c.timeStep !== h || c.needsUpdate){ c.timeStep = h; c.update(); } Bs[i] = c.computeB(c.a,c.b,h); invCs[i] = c.computeInvC(c.epsilon); } var q, B, c, deltalambdaTot,i,j; if(Neq !== 0){ // Reset vlambda for(i=0; i!==Nbodies; i++){ bodies[i].resetConstraintVelocity(); } if(maxFrictionIter){ // Iterate over contact equations to get normal forces for(iter=0; iter!==maxFrictionIter; iter++){ // Accumulate the total error for each iteration. deltalambdaTot = 0.0; for(j=0; j!==Neq; j++){ c = equations[j]; if(c instanceof FrictionEquation){ //continue; } var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); deltalambdaTot += Math.abs(deltalambda); } this.usedIterations++; // If the total error is small enough - stop iterate if(deltalambdaTot*deltalambdaTot <= tolSquared){ break; } } GSSolver.updateMultipliers(equations, lambda, 1/h); // Set computed friction force for(j=0; j!==Neq; j++){ var eq = equations[j]; if(eq instanceof FrictionEquation){ var f = eq.contactEquation.multiplier * eq.frictionCoefficient; eq.maxForce = f; eq.minForce = -f; } } } // Iterate over all equations for(iter=0; iter!==maxIter; iter++){ // Accumulate the total error for each iteration. deltalambdaTot = 0.0; for(j=0; j!==Neq; j++){ c = equations[j]; var deltalambda = GSSolver.iterateEquation(j,c,c.epsilon,Bs,invCs,lambda,useZeroRHS,h,iter); deltalambdaTot += Math.abs(deltalambda); } this.usedIterations++; // If the total error is small enough - stop iterate if(deltalambdaTot*deltalambdaTot <= tolSquared){ break; } } // Add result to velocity for(i=0; i!==Nbodies; i++){ bodies[i].addConstraintVelocity(); } GSSolver.updateMultipliers(equations, lambda, 1/h); } }; // Sets the .multiplier property of each equation GSSolver.updateMultipliers = function(equations, lambda, invDt){ // Set the .multiplier property of each equation var l = equations.length; while(l--){ equations[l].multiplier = lambda[l] * invDt; } }; GSSolver.iterateEquation = function(j,eq,eps,Bs,invCs,lambda,useZeroRHS,dt,iter){ // Compute iteration var B = Bs[j], invC = invCs[j], lambdaj = lambda[j], GWlambda = eq.computeGWlambda(); var maxForce = eq.maxForce, minForce = eq.minForce; if(useZeroRHS){ B = 0; } var deltalambda = invC * ( B - GWlambda - eps * lambdaj ); // Clamp if we are not within the min/max interval var lambdaj_plus_deltalambda = lambdaj + deltalambda; if(lambdaj_plus_deltalambda < minForce*dt){ deltalambda = minForce*dt - lambdaj; } else if(lambdaj_plus_deltalambda > maxForce*dt){ deltalambda = maxForce*dt - lambdaj; } lambda[j] += deltalambda; eq.addToWlambda(deltalambda); return deltalambda; }; },{"../equations/FrictionEquation":23,"../math/vec2":30,"../utils/Utils":47,"./Solver":44}],44:[function(require,module,exports){ var Utils = require('../utils/Utils') , EventEmitter = require('../events/EventEmitter') module.exports = Solver; /** * Base class for constraint solvers. * @class Solver * @constructor * @extends EventEmitter */ function Solver(options,type){ options = options || {}; EventEmitter.call(this); this.type = type; /** * Current equations in the solver. * * @property equations * @type {Array} */ this.equations = []; /** * Function that is used to sort all equations before each solve. * @property equationSortFunction * @type {function|boolean} */ this.equationSortFunction = options.equationSortFunction || false; } Solver.prototype = new EventEmitter(); /** * Method to be implemented in each subclass * @method solve * @param {Number} dt * @param {World} world */ Solver.prototype.solve = function(dt,world){ throw new Error("Solver.solve should be implemented by subclasses!"); }; var mockWorld = {bodies:[]}; /** * Solves all constraints in an island. * @method solveIsland * @param {Number} dt * @param {Island} island */ Solver.prototype.solveIsland = function(dt,island){ this.removeAllEquations(); if(island.equations.length){ // Add equations to solver this.addEquations(island.equations); mockWorld.bodies.length = 0; island.getBodies(mockWorld.bodies); // Solve if(mockWorld.bodies.length){ this.solve(dt,mockWorld); } } }; /** * Sort all equations using the .equationSortFunction. Should be called by subclasses before solving. * @method sortEquations */ Solver.prototype.sortEquations = function(){ if(this.equationSortFunction){ this.equations.sort(this.equationSortFunction); } }; /** * Add an equation to be solved. * * @method addEquation * @param {Equation} eq */ Solver.prototype.addEquation = function(eq){ if(eq.enabled){ this.equations.push(eq); } }; /** * Add equations. Same as .addEquation, but this time the argument is an array of Equations * * @method addEquations * @param {Array} eqs */ Solver.prototype.addEquations = function(eqs){ //Utils.appendArray(this.equations,eqs); for(var i=0, N=eqs.length; i!==N; i++){ var eq = eqs[i]; if(eq.enabled){ this.equations.push(eq); } } }; /** * Remove an equation. * * @method removeEquation * @param {Equation} eq */ Solver.prototype.removeEquation = function(eq){ var i = this.equations.indexOf(eq); if(i !== -1){ this.equations.splice(i,1); } }; /** * Remove all currently added equations. * * @method removeAllEquations */ Solver.prototype.removeAllEquations = function(){ this.equations.length=0; }; Solver.GS = 1; Solver.ISLAND = 2; },{"../events/EventEmitter":26,"../utils/Utils":47}],45:[function(require,module,exports){ var TupleDictionary = require('./TupleDictionary'); var Utils = require('./Utils'); module.exports = OverlapKeeper; /** * Keeps track of overlaps in the current state and the last step state. * @class OverlapKeeper * @constructor */ function OverlapKeeper() { this.overlappingLastState = new TupleDictionary(); this.overlappingCurrentState = new TupleDictionary(); this.recordPool = []; this.tmpDict = new TupleDictionary(); this.tmpArray1 = []; } /** * @method tick */ OverlapKeeper.prototype.tick = function() { var last = this.overlappingLastState; var current = this.overlappingCurrentState; // Save old objects into pool var l = current.keys.length; while(l--){ var key = current.keys[l]; this.recordPool.push(current.getByKey(key)); } // Clear last object last.reset(); // Transfer from new object to old last.copy(current); // Clear current object current.reset(); }; /** * @method setOverlapping */ OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) { var last = this.overlappingLastState; var current = this.overlappingCurrentState; // Store current contact state if(!current.get(shapeA.id, shapeB.id)){ var data; if(this.recordPool.length){ data = this.recordPool.pop(); } else { data = new OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB); } current.set(shapeA.id, shapeB.id, data); } }; OverlapKeeper.prototype.getNewOverlaps = function(result){ return this.getDiff(this.overlappingLastState, this.overlappingCurrentState, result); }; OverlapKeeper.prototype.getEndOverlaps = function(result){ return this.getDiff(this.overlappingCurrentState, this.overlappingLastState, result); }; OverlapKeeper.prototype.getDiff = function(dictA, dictB, result){ var result = result || []; var last = dictA; var current = dictB; result.length = 0; var l = current.keys.length; while(l--){ var key = current.keys[l]; var data = current.data[key]; if(!data){ throw new Error('Key '+key+' had no data!'); } var lastData = last.data[key]; if(!lastData){ // Not overlapping in last state, but in current. result.push(data); } } return result; }; OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){ var idA = shapeA.id|0, idB = shapeB.id|0; return !!!this.overlappingLastState.get(idA, idB) && !!this.overlappingCurrentState.get(idA, idB); }; OverlapKeeper.prototype.getNewBodyOverlaps = function(result){ this.tmpArray1.length = 0; var overlaps = this.getNewOverlaps(this.tmpArray1); return this.getBodyDiff(overlaps, result); }; OverlapKeeper.prototype.getEndBodyOverlaps = function(result){ this.tmpArray1.length = 0; var overlaps = this.getEndOverlaps(this.tmpArray1); return this.getBodyDiff(overlaps, result); }; OverlapKeeper.prototype.getBodyDiff = function(overlaps, result){ result = result || []; var accumulator = this.tmpDict; var l = overlaps.length; while(l--){ var data = overlaps[l]; // Since we use body id's for the accumulator, these will be a subset of the original one accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data); } l = accumulator.keys.length; while(l--){ var data = accumulator.keys[l]; result.push(data.bodyA, data.bodyB); } accumulator.reset(); return result; }; /** * Overlap data container for the OverlapKeeper * @param {Body} bodyA * @param {Shape} shapeA * @param {Body} bodyB * @param {Shape} shapeB [description] */ function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){ /** * @property {Shape} shapeA */ this.shapeA = shapeA; /** * @property {Shape} shapeB */ this.shapeB = shapeB; /** * @property {Body} bodyA */ this.bodyA = bodyA; /** * @property {Body} bodyB */ this.bodyB = bodyB; } OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){ OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB); }; },{"./TupleDictionary":46,"./Utils":47}],46:[function(require,module,exports){ var Utils = require('./Utils'); module.exports = TupleDictionary; /** * @class TupleDictionary * @constructor */ function TupleDictionary() { /** * The data storage * @property data * @type {Array} */ this.data = []; /** * Keys that are currently used. * @type {Array} */ this.keys = []; } /** * Generate a key given two integers * @param {number} i * @param {number} j * @return {string} */ TupleDictionary.prototype.getKey = function(id1, id2) { id1 = id1|0; id2 = id2|0; if ( (id1|0) === (id2|0) ){ return -1; } // valid for values < 2^16 return ((id1|0) > (id2|0) ? (id1 << 16) | (id2 & 0xFFFF) : (id2 << 16) | (id1 & 0xFFFF))|0 ; }; /** * @method getByKey * @param {Number} key * @return {Object} */ TupleDictionary.prototype.getByKey = function(key) { key = key|0; return this.data[key]; }; /** * @method get * @param {Number} i * @param {Number} j * @return {Number} */ TupleDictionary.prototype.get = function(i, j) { i = i|0; j = j|0; var key = this.getKey(i, j)|0; return this.data[key]; }; /** * @method set * @param {Number} i * @param {Number} j * @param {Number} value */ TupleDictionary.prototype.set = function(i, j, value) { if(!value){ throw new Error("No data!"); } i = i|0; j = j|0; var key = this.getKey(i, j)|0; // Check if key already exists if(!this.get(i, j)){ this.keys.push(key); } this.data[key] = value; return key; }; /** * @method reset */ TupleDictionary.prototype.reset = function() { var data = this.data, keys = this.keys; var l = keys.length|0; while(l--){ var key = keys[l]|0; data[key] = undefined; } keys.length = 0; }; /** * @method copy */ TupleDictionary.prototype.copy = function(dict) { this.reset(); Utils.appendArray(this.keys, dict.keys); var l = dict.keys.length|0; while(l--){ var key = dict.keys[l]|0; this.data[key] = dict.data[key]; } }; },{"./Utils":47}],47:[function(require,module,exports){ module.exports = Utils; /** * Misc utility functions * @class Utils * @constructor */ function Utils(){}; /** * Append the values in array b to the array a. See <a href="http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array/1374131#1374131">this</a> for an explanation. * @method appendArray * @static * @param {Array} a * @param {Array} b */ Utils.appendArray = function(a,b){ if (b.length < 150000) { a.push.apply(a, b); } else { for (var i = 0, len = b.length; i !== len; ++i) { a.push(b[i]); } } }; /** * Garbage free Array.splice(). Does not allocate a new array. * @method splice * @static * @param {Array} array * @param {Number} index * @param {Number} howmany */ Utils.splice = function(array,index,howmany){ howmany = howmany || 1; for (var i=index, len=array.length-howmany; i < len; i++){ array[i] = array[i + howmany]; } array.length = len; }; /** * The array type to use for internal numeric computations. * @type {Array} * @static * @property ARRAY_TYPE */ Utils.ARRAY_TYPE = window.Float32Array || Array; /** * Extend an object with the properties of another * @static * @method extend * @param {object} a * @param {object} b */ Utils.extend = function(a,b){ for(var key in b){ a[key] = b[key]; } }; /** * Extend an object with the properties of another * @static * @method extend * @param {object} a * @param {object} b */ Utils.defaults = function(options, defaults){ options = options || {}; for(var key in defaults){ if(!(key in options)){ options[key] = defaults[key]; } } return options; }; },{}],48:[function(require,module,exports){ var Body = require('../objects/Body'); module.exports = Island; /** * An island of bodies connected with equations. * @class Island * @constructor */ function Island(){ /** * Current equations in this island. * @property equations * @type {Array} */ this.equations = []; /** * Current bodies in this island. * @property bodies * @type {Array} */ this.bodies = []; } /** * Clean this island from bodies and equations. * @method reset */ Island.prototype.reset = function(){ this.equations.length = this.bodies.length = 0; }; var bodyIds = []; /** * Get all unique bodies in this island. * @method getBodies * @return {Array} An array of Body */ Island.prototype.getBodies = function(result){ var bodies = result || [], eqs = this.equations; bodyIds.length = 0; for(var i=0; i!==eqs.length; i++){ var eq = eqs[i]; if(bodyIds.indexOf(eq.bodyA.id)===-1){ bodies.push(eq.bodyA); bodyIds.push(eq.bodyA.id); } if(bodyIds.indexOf(eq.bodyB.id)===-1){ bodies.push(eq.bodyB); bodyIds.push(eq.bodyB.id); } } return bodies; }; /** * Check if the entire island wants to sleep. * @method wantsToSleep * @return {Boolean} */ Island.prototype.wantsToSleep = function(){ for(var i=0; i<this.bodies.length; i++){ var b = this.bodies[i]; if(b.motionState === Body.DYNAMIC && !b.wantsToSleep){ return false; } } return true; }; /** * Make all bodies in the island sleep. * @method sleep */ Island.prototype.sleep = function(){ for(var i=0; i<this.bodies.length; i++){ var b = this.bodies[i]; b.sleep(); } return true; }; },{"../objects/Body":31}],49:[function(require,module,exports){ var vec2 = require('../math/vec2') , Island = require('./Island') , IslandNode = require('./IslandNode') , Body = require('../objects/Body') module.exports = IslandManager; /** * Splits the system of bodies and equations into independent islands * * @class IslandManager * @constructor * @param {Object} [options] * @extends Solver */ function IslandManager(options){ // Pooling of node objects saves some GC load this._nodePool = []; this._islandPool = []; /** * The equations to split. Manually fill this array before running .split(). * @property {Array} equations */ this.equations = []; /** * The resulting {{#crossLink "Island"}}{{/crossLink}}s. * @property {Array} islands */ this.islands = []; /** * The resulting graph nodes. * @property {Array} nodes */ this.nodes = []; /** * The node queue, used when traversing the graph of nodes. * @private * @property {Array} queue */ this.queue = []; } /** * Get an unvisited node from a list of nodes. * @static * @method getUnvisitedNode * @param {Array} nodes * @return {IslandNode|boolean} The node if found, else false. */ IslandManager.getUnvisitedNode = function(nodes){ var Nnodes = nodes.length; for(var i=0; i!==Nnodes; i++){ var node = nodes[i]; if(!node.visited && node.body.motionState === Body.DYNAMIC){ return node; } } return false; }; /** * Visit a node. * @method visit * @param {IslandNode} node * @param {Array} bds * @param {Array} eqs */ IslandManager.prototype.visit = function (node,bds,eqs){ bds.push(node.body); var Neqs = node.equations.length; for(var i=0; i!==Neqs; i++){ var eq = node.equations[i]; if(eqs.indexOf(eq) === -1){ // Already added? eqs.push(eq); } } }; /** * Runs the search algorithm, starting at a root node. The resulting bodies and equations will be stored in the provided arrays. * @method bfs * @param {IslandNode} root The node to start from * @param {Array} bds An array to append resulting Bodies to. * @param {Array} eqs An array to append resulting Equations to. */ IslandManager.prototype.bfs = function(root,bds,eqs){ // Reset the visit queue var queue = this.queue; queue.length = 0; // Add root node to queue queue.push(root); root.visited = true; this.visit(root,bds,eqs); // Process all queued nodes while(queue.length) { // Get next node in the queue var node = queue.pop(); // Visit unvisited neighboring nodes var child; while((child = IslandManager.getUnvisitedNode(node.neighbors))) { child.visited = true; this.visit(child,bds,eqs); // Only visit the children of this node if it's dynamic if(child.body.motionState === Body.DYNAMIC){ queue.push(child); } } } }; /** * Split the world into independent islands. The result is stored in .islands. * @method split * @param {World} world * @return {Array} The generated islands */ IslandManager.prototype.split = function(world){ var bodies = world.bodies, nodes = this.nodes, equations = this.equations; // Move old nodes to the node pool while(nodes.length){ this._nodePool.push(nodes.pop()); } // Create needed nodes, reuse if possible for(var i=0; i!==bodies.length; i++){ if(this._nodePool.length){ var node = this._nodePool.pop(); node.reset(); node.body = bodies[i]; nodes.push(node); } else { nodes.push(new IslandNode(bodies[i])); } } // Add connectivity data. Each equation connects 2 bodies. for(var k=0; k!==equations.length; k++){ var eq=equations[k], i=bodies.indexOf(eq.bodyA), j=bodies.indexOf(eq.bodyB), ni=nodes[i], nj=nodes[j]; ni.neighbors.push(nj); nj.neighbors.push(ni); ni.equations.push(eq); nj.equations.push(eq); } // Move old islands to the island pool var islands = this.islands; while(islands.length){ var island = islands.pop(); island.reset(); this._islandPool.push(island); } // Get islands var child; while((child = IslandManager.getUnvisitedNode(nodes))){ // Create new island var island = this._islandPool.length ? this._islandPool.pop() : new Island(); // Get all equations and bodies in this island this.bfs(child, island.bodies, island.equations); islands.push(island); } return islands; }; },{"../math/vec2":30,"../objects/Body":31,"./Island":48,"./IslandNode":50}],50:[function(require,module,exports){ module.exports = IslandNode; /** * Holds a body and keeps track of some additional properties needed for graph traversal. * @class IslandNode * @constructor * @param {Body} body */ function IslandNode(body){ /** * The body that is contained in this node. * @property {Body} */ this.body = body; /** * Neighboring IslandNodes * @property {Array} neighbors */ this.neighbors = []; /** * Equations connected to this node. * @property {Array} equations */ this.equations = []; /** * If this node was visiting during the graph traversal. * @property visited * @type {Boolean} */ this.visited = false; } /** * Clean this node from bodies and equations. * @method reset */ IslandNode.prototype.reset = function(){ this.equations.length = 0; this.neighbors.length = 0; this.visited = false; this.body = null; }; },{}],51:[function(require,module,exports){ var GSSolver = require('../solver/GSSolver') , Solver = require('../solver/Solver') , NaiveBroadphase = require('../collision/NaiveBroadphase') , vec2 = require('../math/vec2') , Circle = require('../shapes/Circle') , Rectangle = require('../shapes/Rectangle') , Convex = require('../shapes/Convex') , Line = require('../shapes/Line') , Plane = require('../shapes/Plane') , Capsule = require('../shapes/Capsule') , Particle = require('../shapes/Particle') , EventEmitter = require('../events/EventEmitter') , Body = require('../objects/Body') , Shape = require('../shapes/Shape') , Spring = require('../objects/Spring') , Material = require('../material/Material') , ContactMaterial = require('../material/ContactMaterial') , DistanceConstraint = require('../constraints/DistanceConstraint') , Constraint = require('../constraints/Constraint') , LockConstraint = require('../constraints/LockConstraint') , RevoluteConstraint = require('../constraints/RevoluteConstraint') , PrismaticConstraint = require('../constraints/PrismaticConstraint') , GearConstraint = require('../constraints/GearConstraint') , pkg = require('../../package.json') , Broadphase = require('../collision/Broadphase') , SAPBroadphase = require('../collision/SAPBroadphase') , Narrowphase = require('../collision/Narrowphase') , Utils = require('../utils/Utils') , OverlapKeeper = require('../utils/OverlapKeeper') , IslandManager = require('./IslandManager') module.exports = World; if(typeof performance === 'undefined'){ performance = {}; } if(!performance.now){ var nowOffset = Date.now(); if (performance.timing && performance.timing.navigationStart){ nowOffset = performance.timing.navigationStart; } performance.now = function(){ return Date.now() - nowOffset; }; } /** * The dynamics world, where all bodies and constraints lives. * * @class World * @constructor * @param {Object} [options] * @param {Solver} [options.solver] Defaults to GSSolver. * @param {Array} [options.gravity] Defaults to [0,-9.78] * @param {Broadphase} [options.broadphase] Defaults to NaiveBroadphase * @param {Boolean} [options.islandSplit=false] * @param {Boolean} [options.doProfiling=false] * @extends EventEmitter */ function World(options){ EventEmitter.apply(this); options = options || {}; /** * All springs in the world. To add a spring to the world, use {{#crossLink "World/addSpring:method"}}{{/crossLink}}. * * @property springs * @type {Array} */ this.springs = []; /** * All bodies in the world. To add a body to the world, use {{#crossLink "World/addBody:method"}}{{/crossLink}}. * @property {Array} bodies */ this.bodies = []; /** * Disabled body collision pairs. See {{#crossLink "World/disableBodyCollision:method"}}. * @private * @property {Array} disabledBodyCollisionPairs */ this.disabledBodyCollisionPairs = []; /** * The solver used to satisfy constraints and contacts. Default is {{#crossLink "GSSolver"}}{{/crossLink}}. * @property {Solver} solver */ this.solver = options.solver || new GSSolver(); /** * The narrowphase to use to generate contacts. * * @property narrowphase * @type {Narrowphase} */ this.narrowphase = new Narrowphase(this); /** * The island manager of this world. * @property {IslandManager} islandManager */ this.islandManager = new IslandManager(); /** * Gravity in the world. This is applied on all bodies in the beginning of each step(). * * @property gravity * @type {Array} */ this.gravity = vec2.fromValues(0, -9.78); if(options.gravity){ vec2.copy(this.gravity, options.gravity); } /** * Gravity to use when approximating the friction max force (mu*mass*gravity). * @property {Number} frictionGravity */ this.frictionGravity = vec2.length(this.gravity) || 10; /** * Set to true if you want .frictionGravity to be automatically set to the length of .gravity. * @property {Boolean} useWorldGravityAsFrictionGravity */ this.useWorldGravityAsFrictionGravity = true; /** * If the length of .gravity is zero, and .useWorldGravityAsFrictionGravity=true, then switch to using .frictionGravity for friction instead. This fallback is useful for gravityless games. * @property {Boolean} useFrictionGravityOnZeroGravity */ this.useFrictionGravityOnZeroGravity = true; /** * Whether to do timing measurements during the step() or not. * * @property doPofiling * @type {Boolean} */ this.doProfiling = options.doProfiling || false; /** * How many millisecconds the last step() took. This is updated each step if .doProfiling is set to true. * * @property lastStepTime * @type {Number} */ this.lastStepTime = 0.0; /** * The broadphase algorithm to use. * * @property broadphase * @type {Broadphase} */ this.broadphase = options.broadphase || new NaiveBroadphase(); this.broadphase.setWorld(this); /** * User-added constraints. * * @property constraints * @type {Array} */ this.constraints = []; /** * Dummy default material in the world, used in .defaultContactMaterial * @property {Material} defaultMaterial */ this.defaultMaterial = new Material(); /** * The default contact material to use, if no contact material was set for the colliding materials. * @property {ContactMaterial} defaultContactMaterial */ this.defaultContactMaterial = new ContactMaterial(this.defaultMaterial,this.defaultMaterial); /** * For keeping track of what time step size we used last step * @property lastTimeStep * @type {Number} */ this.lastTimeStep = 1/60; /** * Enable to automatically apply spring forces each step. * @property applySpringForces * @type {Boolean} */ this.applySpringForces = true; /** * Enable to automatically apply body damping each step. * @property applyDamping * @type {Boolean} */ this.applyDamping = true; /** * Enable to automatically apply gravity each step. * @property applyGravity * @type {Boolean} */ this.applyGravity = true; /** * Enable/disable constraint solving in each step. * @property solveConstraints * @type {Boolean} */ this.solveConstraints = true; /** * The ContactMaterials added to the World. * @property contactMaterials * @type {Array} */ this.contactMaterials = []; /** * World time. * @property time * @type {Number} */ this.time = 0.0; /** * Is true during the step(). * @property {Boolean} stepping */ this.stepping = false; /** * Bodies that are scheduled to be removed at the end of the step. * @property {Array} bodiesToBeRemoved * @private */ this.bodiesToBeRemoved = []; this.fixedStepTime = 0.0; /** * Whether to enable island splitting. Island splitting can be an advantage for many things, including solver performance. See {{#crossLink "IslandManager"}}{{/crossLink}}. * @property {Boolean} islandSplit */ this.islandSplit = typeof(options.islandSplit)!=="undefined" ? !!options.islandSplit : false; /** * Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. * @property emitImpactEvent * @type {Boolean} */ this.emitImpactEvent = true; // Id counters this._constraintIdCounter = 0; this._bodyIdCounter = 0; /** * Fired after the step(). * @event postStep */ this.postStepEvent = { type : "postStep", }; /** * Fired when a body is added to the world. * @event addBody * @param {Body} body */ this.addBodyEvent = { type : "addBody", body : null }; /** * Fired when a body is removed from the world. * @event removeBody * @param {Body} body */ this.removeBodyEvent = { type : "removeBody", body : null }; /** * Fired when a spring is added to the world. * @event addSpring * @param {Spring} spring */ this.addSpringEvent = { type : "addSpring", spring : null, }; /** * Fired when a first contact is created between two bodies. This event is fired after the step has been done. * @event impact * @param {Body} bodyA * @param {Body} bodyB */ this.impactEvent = { type: "impact", bodyA : null, bodyB : null, shapeA : null, shapeB : null, contactEquation : null, }; /** * Fired after the Broadphase has collected collision pairs in the world. * Inside the event handler, you can modify the pairs array as you like, to * prevent collisions between objects that you don't want. * @event postBroadphase * @param {Array} pairs An array of collision pairs. If this array is [body1,body2,body3,body4], then the body pairs 1,2 and 3,4 would advance to narrowphase. */ this.postBroadphaseEvent = { type:"postBroadphase", pairs:null, }; /** * Enable / disable automatic body sleeping. Sleeping can improve performance. You might need to {{#crossLink "Body/wakeUp:method"}}wake up{{/crossLink}} the bodies if they fall asleep when they shouldn't. If you want to enable sleeping in the world, but want to disable it for a particular body, see {{#crossLink "Body/allowSleep:property"}}Body.allowSleep{{/crossLink}}. * @property allowSleep * @type {Boolean} */ this.enableBodySleeping = false; /** * Enable or disable island sleeping. Note that you must enable {{#crossLink "World/islandSplit:property"}}.islandSplit{{/crossLink}} for this to work. * @property {Boolean} enableIslandSleeping */ this.enableIslandSleeping = false; /** * Fired when two shapes starts start to overlap. Fired in the narrowphase, during step. * @event beginContact * @param {Shape} shapeA * @param {Shape} shapeB * @param {Body} bodyA * @param {Body} bodyB * @param {Array} contactEquations */ this.beginContactEvent = { type:"beginContact", shapeA : null, shapeB : null, bodyA : null, bodyB : null, contactEquations : [], }; /** * Fired when two shapes stop overlapping, after the narrowphase (during step). * @event endContact * @param {Shape} shapeA * @param {Shape} shapeB * @param {Body} bodyA * @param {Body} bodyB * @param {Array} contactEquations */ this.endContactEvent = { type:"endContact", shapeA : null, shapeB : null, bodyA : null, bodyB : null, }; /** * Fired just before equations are added to the solver to be solved. Can be used to control what equations goes into the solver. * @event preSolve * @param {Array} contactEquations An array of contacts to be solved. * @param {Array} frictionEquations An array of friction equations to be solved. */ this.preSolveEvent = { type:"preSolve", contactEquations:null, frictionEquations:null, }; // For keeping track of overlapping shapes this.overlappingShapesLastState = { keys:[] }; this.overlappingShapesCurrentState = { keys:[] }; this.overlapKeeper = new OverlapKeeper(); } World.prototype = new Object(EventEmitter.prototype); /** * Add a constraint to the simulation. * * @method addConstraint * @param {Constraint} c */ World.prototype.addConstraint = function(c){ this.constraints.push(c); }; /** * Add a ContactMaterial to the simulation. * @method addContactMaterial * @param {ContactMaterial} contactMaterial */ World.prototype.addContactMaterial = function(contactMaterial){ this.contactMaterials.push(contactMaterial); }; /** * Removes a contact material * * @method removeContactMaterial * @param {ContactMaterial} cm */ World.prototype.removeContactMaterial = function(cm){ var idx = this.contactMaterials.indexOf(cm); if(idx!==-1){ Utils.splice(this.contactMaterials,idx,1); } }; /** * Get a contact material given two materials * @method getContactMaterial * @param {Material} materialA * @param {Material} materialB * @return {ContactMaterial} The matching ContactMaterial, or false on fail. * @todo Use faster hash map to lookup from material id's */ World.prototype.getContactMaterial = function(materialA,materialB){ var cmats = this.contactMaterials; for(var i=0, N=cmats.length; i!==N; i++){ var cm = cmats[i]; if( (cm.materialA === materialA) && (cm.materialB === materialB) || (cm.materialA === materialB) && (cm.materialB === materialA) ){ return cm; } } return false; }; /** * Removes a constraint * * @method removeConstraint * @param {Constraint} c */ World.prototype.removeConstraint = function(c){ var idx = this.constraints.indexOf(c); if(idx!==-1){ Utils.splice(this.constraints,idx,1); } }; var step_r = vec2.create(), step_runit = vec2.create(), step_u = vec2.create(), step_f = vec2.create(), step_fhMinv = vec2.create(), step_velodt = vec2.create(), step_mg = vec2.create(), xiw = vec2.fromValues(0,0), xjw = vec2.fromValues(0,0), zero = vec2.fromValues(0,0), interpvelo = vec2.fromValues(0,0); /** * Step the physics world forward in time. * * There are two modes. The simple mode is fixed timestepping without interpolation. In this case you only use the first argument. The second case uses interpolation. In that you also provide the time since the function was last used, as well as the maximum fixed timesteps to take. * * @method step * @param {Number} dt The fixed time step size to use. * @param {Number} [timeSinceLastCalled=0] The time elapsed since the function was last called. * @param {Number} [maxSubSteps=10] Maximum number of fixed steps to take per function call. * * @example * // fixed timestepping without interpolation * var world = new World(); * world.step(0.01); * * @see http://bulletphysics.org/mediawiki-1.5.8/index.php/Stepping_The_World */ World.prototype.step = function(dt,timeSinceLastCalled,maxSubSteps){ maxSubSteps = maxSubSteps || 10; timeSinceLastCalled = timeSinceLastCalled || 0; if(timeSinceLastCalled === 0){ // Fixed, simple stepping this.internalStep(dt); // Increment time this.time += dt; } else { // Compute the number of fixed steps we should have taken since the last step var internalSteps = Math.floor( (this.time+timeSinceLastCalled) / dt) - Math.floor(this.time / dt); internalSteps = Math.min(internalSteps,maxSubSteps); // Do some fixed steps to catch up for(var i=0; i!==internalSteps; i++){ this.internalStep(dt); } // Increment internal clock this.time += timeSinceLastCalled; // Compute "Left over" time step var h = this.time % dt; var h_div_dt = h/dt; for(var j=0; j!==this.bodies.length; j++){ var b = this.bodies[j]; if(b.motionState !== Body.STATIC && b.sleepState !== Body.SLEEPING){ // Interpolate vec2.sub(interpvelo, b.position, b.previousPosition); vec2.scale(interpvelo, interpvelo, h_div_dt); vec2.add(b.interpolatedPosition, b.position, interpvelo); b.interpolatedAngle = b.angle + (b.angle - b.previousAngle) * h_div_dt; } else { // For static bodies, just copy. Who else will do it? vec2.copy(b.interpolatedPosition, b.position); b.interpolatedAngle = b.angle; } } } }; var endOverlaps = []; /** * Make a fixed step. * @method internalStep * @param {number} dt * @private */ World.prototype.internalStep = function(dt){ this.stepping = true; var that = this, doProfiling = this.doProfiling, Nsprings = this.springs.length, springs = this.springs, bodies = this.bodies, g = this.gravity, solver = this.solver, Nbodies = this.bodies.length, broadphase = this.broadphase, np = this.narrowphase, constraints = this.constraints, t0, t1, fhMinv = step_fhMinv, velodt = step_velodt, mg = step_mg, scale = vec2.scale, add = vec2.add, rotate = vec2.rotate, islandManager = this.islandManager; this.lastTimeStep = dt; if(doProfiling){ t0 = performance.now(); } // Update approximate friction gravity. if(this.useWorldGravityAsFrictionGravity){ var gravityLen = vec2.length(this.gravity); if(gravityLen === 0 && this.useFrictionGravityOnZeroGravity){ // Leave friction gravity as it is. } else { // Nonzero gravity. Use it. this.frictionGravity = gravityLen; } } // Add gravity to bodies if(this.applyGravity){ for(var i=0; i!==Nbodies; i++){ var b = bodies[i], fi = b.force; if(b.motionState !== Body.DYNAMIC || b.sleepState === Body.SLEEPING){ continue; } vec2.scale(mg,g,b.mass*b.gravityScale); // F=m*g add(fi,fi,mg); } } // Add spring forces if(this.applySpringForces){ for(var i=0; i!==Nsprings; i++){ var s = springs[i]; s.applyForce(); } } if(this.applyDamping){ for(var i=0; i!==Nbodies; i++){ var b = bodies[i]; if(b.motionState === Body.DYNAMIC){ b.applyDamping(dt); } } } // Broadphase var result = broadphase.getCollisionPairs(this); // Remove ignored collision pairs var ignoredPairs = this.disabledBodyCollisionPairs; for(var i=ignoredPairs.length-2; i>=0; i-=2){ for(var j=result.length-2; j>=0; j-=2){ if( (ignoredPairs[i] === result[j] && ignoredPairs[i+1] === result[j+1]) || (ignoredPairs[i+1] === result[j] && ignoredPairs[i] === result[j+1])){ result.splice(j,2); } } } // Remove constrained pairs with collideConnected == false var Nconstraints = constraints.length; for(i=0; i!==Nconstraints; i++){ var c = constraints[i]; if(!c.collideConnected){ for(var j=result.length-2; j>=0; j-=2){ if( (c.bodyA === result[j] && c.bodyB === result[j+1]) || (c.bodyB === result[j] && c.bodyA === result[j+1])){ result.splice(j,2); } } } } // postBroadphase event this.postBroadphaseEvent.pairs = result; this.emit(this.postBroadphaseEvent); // Narrowphase np.reset(this); for(var i=0, Nresults=result.length; i!==Nresults; i+=2){ var bi = result[i], bj = result[i+1]; // Loop over all shapes of body i for(var k=0, Nshapesi=bi.shapes.length; k!==Nshapesi; k++){ var si = bi.shapes[k], xi = bi.shapeOffsets[k], ai = bi.shapeAngles[k]; // All shapes of body j for(var l=0, Nshapesj=bj.shapes.length; l!==Nshapesj; l++){ var sj = bj.shapes[l], xj = bj.shapeOffsets[l], aj = bj.shapeAngles[l]; var cm = this.defaultContactMaterial; if(si.material && sj.material){ var tmp = this.getContactMaterial(si.material,sj.material); if(tmp){ cm = tmp; } } this.runNarrowphase(np,bi,si,xi,ai,bj,sj,xj,aj,cm,this.frictionGravity); } } } // Wake up bodies for(var i=0; i!==Nbodies; i++){ var body = bodies[i]; if(body._wakeUpAfterNarrowphase){ body.wakeUp(); body._wakeUpAfterNarrowphase = false; } } // Emit end overlap events if(this.has('endContact')){ this.overlapKeeper.getEndOverlaps(endOverlaps); var e = this.endContactEvent; var l = endOverlaps.length; while(l--){ var data = endOverlaps[l]; e.shapeA = data.shapeA; e.shapeB = data.shapeB; e.bodyA = data.bodyA; e.bodyB = data.bodyA; this.emit(e); } } this.overlapKeeper.tick(); var preSolveEvent = this.preSolveEvent; preSolveEvent.contactEquations = np.contactEquations; preSolveEvent.frictionEquations = np.frictionEquations; this.emit(preSolveEvent); // update constraint equations var Nconstraints = constraints.length; for(i=0; i!==Nconstraints; i++){ constraints[i].update(); } if(np.contactEquations.length || np.frictionEquations.length || constraints.length){ if(this.islandSplit){ // Split into islands islandManager.equations.length = 0; Utils.appendArray(islandManager.equations, np.contactEquations); Utils.appendArray(islandManager.equations, np.frictionEquations); for(i=0; i!==Nconstraints; i++){ Utils.appendArray(islandManager.equations, constraints[i].equations); } islandManager.split(this); for(var i=0; i!==islandManager.islands.length; i++){ var island = islandManager.islands[i]; if(island.equations.length){ solver.solveIsland(dt,island); } } } else { // Add contact equations to solver solver.addEquations(np.contactEquations); solver.addEquations(np.frictionEquations); // Add user-defined constraint equations for(i=0; i!==Nconstraints; i++){ solver.addEquations(constraints[i].equations); } if(this.solveConstraints){ solver.solve(dt,this); } solver.removeAllEquations(); } } // Step forward for(var i=0; i!==Nbodies; i++){ var body = bodies[i]; if(body.sleepState !== Body.SLEEPING && body.motionState !== Body.STATIC){ World.integrateBody(body,dt); } } // Reset force for(var i=0; i!==Nbodies; i++){ bodies[i].setZeroForce(); } if(doProfiling){ t1 = performance.now(); that.lastStepTime = t1-t0; } // Emit impact event if(this.emitImpactEvent && this.has('impact')){ var ev = this.impactEvent; for(var i=0; i!==np.contactEquations.length; i++){ var eq = np.contactEquations[i]; if(eq.firstImpact){ ev.bodyA = eq.bodyA; ev.bodyB = eq.bodyB; ev.shapeA = eq.shapeA; ev.shapeB = eq.shapeB; ev.contactEquation = eq; this.emit(ev); } } } // Sleeping update if(this.enableBodySleeping){ for(i=0; i!==Nbodies; i++){ bodies[i].sleepTick(this.time, false, dt); } } else if(this.enableIslandSleeping && this.islandSplit){ // Tell all bodies to sleep tick but dont sleep yet for(i=0; i!==Nbodies; i++){ bodies[i].sleepTick(this.time, true, dt); } // Sleep islands for(var i=0; i<this.islandManager.islands.length; i++){ var island = this.islandManager.islands[i]; if(island.wantsToSleep()){ island.sleep(); } } } this.stepping = false; // Remove bodies that are scheduled for removal if(this.bodiesToBeRemoved.length){ for(var i=0; i!==this.bodiesToBeRemoved.length; i++){ this.removeBody(this.bodiesToBeRemoved[i]); } this.bodiesToBeRemoved.length = 0; } this.emit(this.postStepEvent); }; var ib_fhMinv = vec2.create(); var ib_velodt = vec2.create(); /** * Move a body forward in time. * @static * @method integrateBody * @param {Body} body * @param {Number} dt * @todo Move to Body.prototype? */ World.integrateBody = function(body,dt){ var minv = body.invMass, f = body.force, pos = body.position, velo = body.velocity; // Save old position vec2.copy(body.previousPosition, body.position); body.previousAngle = body.angle; // Angular step if(!body.fixedRotation){ body.angularVelocity += body.angularForce * body.invInertia * dt; body.angle += body.angularVelocity * dt; } // Linear step vec2.scale(ib_fhMinv,f,dt*minv); vec2.add(velo,ib_fhMinv,velo); vec2.scale(ib_velodt,velo,dt); vec2.add(pos,pos,ib_velodt); body.aabbNeedsUpdate = true; }; /** * Runs narrowphase for the shape pair i and j. * @method runNarrowphase * @param {Narrowphase} np * @param {Body} bi * @param {Shape} si * @param {Array} xi * @param {Number} ai * @param {Body} bj * @param {Shape} sj * @param {Array} xj * @param {Number} aj * @param {Number} mu */ World.prototype.runNarrowphase = function(np,bi,si,xi,ai,bj,sj,xj,aj,cm,glen){ // Check collision groups and masks if(!((si.collisionGroup & sj.collisionMask) !== 0 && (sj.collisionGroup & si.collisionMask) !== 0)){ return; } // Get world position and angle of each shape vec2.rotate(xiw, xi, bi.angle); vec2.rotate(xjw, xj, bj.angle); vec2.add(xiw, xiw, bi.position); vec2.add(xjw, xjw, bj.position); var aiw = ai + bi.angle; var ajw = aj + bj.angle; np.enableFriction = cm.friction > 0; np.frictionCoefficient = cm.friction; var reducedMass; if(bi.motionState === Body.STATIC || bi.motionState === Body.KINEMATIC){ reducedMass = bj.mass; } else if(bj.motionState === Body.STATIC || bj.motionState === Body.KINEMATIC){ reducedMass = bi.mass; } else { reducedMass = (bi.mass*bj.mass)/(bi.mass+bj.mass); } np.slipForce = cm.friction*glen*reducedMass; np.restitution = cm.restitution; np.surfaceVelocity = cm.surfaceVelocity; np.frictionStiffness = cm.frictionStiffness; np.frictionRelaxation = cm.frictionRelaxation; np.stiffness = cm.stiffness; np.relaxation = cm.relaxation; var resolver = np[si.type | sj.type], numContacts = 0; if (resolver) { var sensor = si.sensor || sj.sensor; var numFrictionBefore = np.frictionEquations.length; if (si.type < sj.type) { numContacts = resolver.call(np, bi,si,xiw,aiw, bj,sj,xjw,ajw, sensor); } else { numContacts = resolver.call(np, bj,sj,xjw,ajw, bi,si,xiw,aiw, sensor); } var numFrictionEquations = np.frictionEquations.length - numFrictionBefore; if(numContacts){ if( bi.allowSleep && bi.motionState === Body.DYNAMIC && bi.sleepState === Body.SLEEPING && bj.sleepState === Body.AWAKE && bj.motionState !== Body.STATIC ){ var speedSquaredB = vec2.squaredLength(bj.velocity) + Math.pow(bj.angularVelocity,2); var speedLimitSquaredB = Math.pow(bj.sleepSpeedLimit,2); if(speedSquaredB >= speedLimitSquaredB*2){ bi._wakeUpAfterNarrowphase = true; } } if( bj.allowSleep && bj.motionState === Body.DYNAMIC && bj.sleepState === Body.SLEEPING && bi.sleepState === Body.AWAKE && bi.motionState !== Body.STATIC ){ var speedSquaredA = vec2.squaredLength(bi.velocity) + Math.pow(bi.angularVelocity,2); var speedLimitSquaredA = Math.pow(bi.sleepSpeedLimit,2); if(speedSquaredA >= speedLimitSquaredA*2){ bj._wakeUpAfterNarrowphase = true; } } this.overlapKeeper.setOverlapping(bi, si, bj, sj); if(this.has('beginContact') && this.overlapKeeper.isNewOverlap(si, sj)){ // Report new shape overlap var e = this.beginContactEvent; e.shapeA = si; e.shapeB = sj; e.bodyA = bi; e.bodyB = bj; // Reset contact equations e.contactEquations.length = 0; if(typeof(numContacts)==="number"){ for(var i=np.contactEquations.length-numContacts; i<np.contactEquations.length; i++){ e.contactEquations.push(np.contactEquations[i]); } } this.emit(e); } // divide the max friction force by the number of contacts if(typeof(numContacts)==="number" && numFrictionEquations > 1){ // Why divide by 1? for(var i=np.frictionEquations.length-numFrictionEquations; i<np.frictionEquations.length; i++){ var f = np.frictionEquations[i]; f.setSlipForce(f.getSlipForce() / numFrictionEquations); } } } } }; /** * Add a spring to the simulation * * @method addSpring * @param {Spring} s */ World.prototype.addSpring = function(s){ this.springs.push(s); this.addSpringEvent.spring = s; this.emit(this.addSpringEvent); }; /** * Remove a spring * * @method removeSpring * @param {Spring} s */ World.prototype.removeSpring = function(s){ var idx = this.springs.indexOf(s); if(idx===-1){ Utils.splice(this.springs,idx,1); } }; /** * Add a body to the simulation * * @method addBody * @param {Body} body * * @example * var world = new World(), * body = new Body(); * world.addBody(body); * @todo What if this is done during step? */ World.prototype.addBody = function(body){ if(this.bodies.indexOf(body) === -1){ this.bodies.push(body); body.world = this; this.addBodyEvent.body = body; this.emit(this.addBodyEvent); } }; /** * Remove a body from the simulation. If this method is called during step(), the body removal is scheduled to after the step. * * @method removeBody * @param {Body} body */ World.prototype.removeBody = function(body){ if(this.stepping){ this.bodiesToBeRemoved.push(body); } else { body.world = null; var idx = this.bodies.indexOf(body); if(idx!==-1){ Utils.splice(this.bodies,idx,1); this.removeBodyEvent.body = body; body.resetConstraintVelocity(); this.emit(this.removeBodyEvent); } } }; /** * Get a body by its id. * @method getBodyById * @return {Body|Boolean} The body, or false if it was not found. */ World.prototype.getBodyById = function(id){ var bodies = this.bodies; for(var i=0; i<bodies.length; i++){ var b = bodies[i]; if(b.id === id){ return b; } } return false; }; /** * Disable collision between two bodies * @method disableCollision * @param {Body} bodyA * @param {Body} bodyB */ World.prototype.disableBodyCollision = function(bodyA,bodyB){ this.disabledBodyCollisionPairs.push(bodyA,bodyB); }; /** * Enable collisions between the given two bodies * @method enableCollision * @param {Body} bodyA * @param {Body} bodyB */ World.prototype.enableBodyCollision = function(bodyA,bodyB){ var pairs = this.disabledBodyCollisionPairs; for(var i=0; i<pairs.length; i+=2){ if((pairs[i] === bodyA && pairs[i+1] === bodyB) || (pairs[i+1] === bodyA && pairs[i] === bodyB)){ pairs.splice(i,2); return; } } }; function v2a(v){ if(!v) return v; return [v[0],v[1]]; } function extend(a,b){ for(var key in b) a[key] = b[key]; } function contactMaterialToJSON(cm){ return { id : cm.id, materialA : cm.materialA.id, materialB : cm.materialB.id, friction : cm.friction, restitution : cm.restitution, stiffness : cm.stiffness, relaxation : cm.relaxation, frictionStiffness : cm.frictionStiffness, frictionRelaxation : cm.frictionRelaxation, }; } /** * Convert the world to a JSON-serializable Object. * * @method toJSON * @return {Object} * @deprecated Should use Serializer instead. */ World.prototype.toJSON = function(){ var world = this; var json = { p2 : pkg.version, bodies : [], springs : [], solver : {}, gravity : v2a(world.gravity), broadphase : {}, distanceConstraints : [], revoluteConstraints : [], prismaticConstraints : [], lockConstraints : [], gearConstraints : [], contactMaterials : [], materials : [], defaultContactMaterial : contactMaterialToJSON(world.defaultContactMaterial), islandSplit : world.islandSplit, enableIslandSleeping : world.enableIslandSleeping, enableBodySleeping : world.enableBodySleeping, }; // Solver var js = json.solver, s = world.solver; if(s.type === Solver.GS){ js.type = "GSSolver"; js.iterations = s.iterations; } // Broadphase var jb = json.broadphase, wb = world.broadphase; if(wb.type === Broadphase.NAIVE){ jb.type = "NaiveBroadphase"; } else if(wb.type === Broadphase.SAP) { jb.type = "SAPBroadphase"; //jb.axisIndex = wb.axisIndex; } else { console.error("Broadphase not supported: "+wb.type); } // Serialize springs for(var i=0; i!==world.springs.length; i++){ var s = world.springs[i]; json.springs.push({ bodyA : world.bodies.indexOf(s.bodyA), bodyB : world.bodies.indexOf(s.bodyB), stiffness : s.stiffness, damping : s.damping, restLength : s.restLength, localAnchorA : v2a(s.localAnchorA), localAnchorB : v2a(s.localAnchorB), }); } // Serialize constraints for(var i=0; i<world.constraints.length; i++){ var c = world.constraints[i]; var jc = { bodyA : world.bodies.indexOf(c.bodyA), bodyB : world.bodies.indexOf(c.bodyB), collideConnected : c.collideConnected }; switch(c.type){ case Constraint.DISTANCE: extend(jc,{ distance : c.distance, maxForce : c.getMaxForce(), }); json.distanceConstraints.push(jc); break; case Constraint.REVOLUTE: extend(jc,{ pivotA : v2a(c.pivotA), pivotB : v2a(c.pivotB), maxForce : c.maxForce, motorSpeed : c.getMotorSpeed() || 0, motorEnabled : !!c.getMotorSpeed(), lowerLimit : c.lowerLimit, lowerLimitEnabled : c.lowerLimitEnabled, upperLimit : c.upperLimit, upperLimitEnabled : c.upperLimitEnabled, }); json.revoluteConstraints.push(jc); break; case Constraint.PRISMATIC: extend(jc,{ localAxisA : v2a(c.localAxisA), localAnchorA : v2a(c.localAnchorA), localAnchorB : v2a(c.localAnchorB), maxForce : c.maxForce, upperLimitEnabled : c.upperLimitEnabled, lowerLimitEnabled : c.lowerLimitEnabled, upperLimit : c.upperLimit, lowerLimit : c.lowerLimit, motorEnabled : c.motorEnabled, motorSpeed : c.motorSpeed, }); json.prismaticConstraints.push(jc); break; case Constraint.LOCK: extend(jc,{ localOffsetB : v2a(c.localOffsetB), localAngleB : c.localAngleB, maxForce : c.getMaxForce(), }); json.lockConstraints.push(jc); break; case Constraint.GEAR: extend(jc,{ angle : c.angle, ratio : c.ratio, maxForce : c.maxForce || 1e6, // correct? }); json.gearConstraints.push(jc); break; default: console.error("Constraint not supported yet: ",c.type); break; } } // Serialize bodies for(var i=0; i!==world.bodies.length; i++){ var b = world.bodies[i], ss = b.shapes, jsonBody = { id : b.id, mass : b.mass, angle : b.angle, position : v2a(b.position), velocity : v2a(b.velocity), angularVelocity : b.angularVelocity, force : v2a(b.force), motionState : b.motionState, fixedRotation : b.fixedRotation, circleShapes : [], planeShapes : [], particleShapes : [], lineShapes : [], rectangleShapes : [], convexShapes : [], capsuleShapes : [], }; if(b.concavePath){ jsonBody.concavePath = b.concavePath; } for(var j=0; j<ss.length; j++){ var s = ss[j], jsonShape = {}; jsonShape.offset = v2a(b.shapeOffsets[j]); jsonShape.angle = b.shapeAngles[j]; jsonShape.collisionGroup = s.collisionGroup; jsonShape.collisionMask = s.collisionMask; jsonShape.material = s.material ? s.material.id : null; // Check type switch(s.type){ case Shape.CIRCLE: extend(jsonShape,{ radius : s.radius, }); jsonBody.circleShapes.push(jsonShape); break; case Shape.PLANE: jsonBody.planeShapes.push(jsonShape); break; case Shape.PARTICLE: jsonBody.particleShapes.push(jsonShape); break; case Shape.LINE: jsonShape.length = s.length; jsonBody.lineShapes.push(jsonShape); break; case Shape.RECTANGLE: extend(jsonShape,{ width : s.width, height : s.height }); jsonBody.rectangleShapes.push(jsonShape); break; case Shape.CONVEX: var verts = []; for(var k=0; k<s.vertices.length; k++){ verts.push(v2a(s.vertices[k])); } extend(jsonShape,{ vertices : verts }); jsonBody.convexShapes.push(jsonShape); break; case Shape.CAPSULE: extend(jsonShape,{ length : s.length, radius : s.radius }); jsonBody.capsuleShapes.push(jsonShape); break; default: console.error("Shape type not supported yet!"); break; } } json.bodies.push(jsonBody); } // Serialize contactmaterials for(var i=0; i<world.contactMaterials.length; i++){ var cm = world.contactMaterials[i]; json.contactMaterials.push(contactMaterialToJSON(cm)); } // Serialize materials var mats = {}; // Get unique materials first for(var i=0; i<world.contactMaterials.length; i++){ var cm = world.contactMaterials[i]; mats[cm.materialA.id+''] = cm.materialA; mats[cm.materialB.id+''] = cm.materialB; } for(var matId in mats){ var m = mats[parseInt(matId)]; json.materials.push({ id : m.id, }); } return json; }; /** * Load a scene from a serialized state in JSON format. * * @method fromJSON * @param {Object} json * @return {Boolean} True on success, else false. */ World.prototype.fromJSON = function(json){ this.clear(); if(!json.p2){ return false; } var w = this; // Set gravity vec2.copy(w.gravity, json.gravity); w.islandSplit = json.islandSplit; w.enableIslandSleeping = json.enableIslandSleeping; w.enableBodySleeping = json.enableBodySleeping; // Set solver switch(json.solver.type){ case "GSSolver": var js = json.solver, s = new GSSolver(); w.solver = s; s.iterations = js.iterations; break; default: throw new Error("Solver type not recognized: "+json.solver.type); } // Broadphase switch(json.broadphase.type){ case "NaiveBroadphase": w.broadphase = new NaiveBroadphase(); break; case "SAPBroadphase": w.broadphase = new SAPBroadphase(); break; } w.broadphase.setWorld(w); var bodies = w.bodies; // Load materials var id2material = {}; for(var i=0; i!==json.materials.length; i++){ var jm = json.materials[i]; var m = new Material(); id2material[jm.id+""] = m; m.id = jm.id; } // Load default material w.defaultMaterial.id = json.defaultContactMaterial.materialA; // Load bodies for(var i=0; i!==json.bodies.length; i++){ var jb = json.bodies[i]; // Create body var b = new Body({ mass : jb.mass, position : jb.position, angle : jb.angle, velocity : jb.velocity, angularVelocity : jb.angularVelocity, force : jb.force, fixedRotation : jb.fixedRotation, }); b.id = jb.id; b.motionState = jb.motionState; // Circle for(var j=0; j<jb.circleShapes.length; j++){ var s = jb.circleShapes[j]; addShape(b, new Circle(s.radius), s); } // Plane for(var j=0; j<jb.planeShapes.length; j++){ var s = jb.planeShapes[j]; addShape(b, new Plane(), s); } // Particle for(var j=0; j<jb.particleShapes.length; j++){ var s = jb.particleShapes[j]; addShape(b, new Particle(), s); } // Line for(var j=0; j<jb.lineShapes.length; j++){ var s = jb.lineShapes[j]; addShape(b, new Line(s.length), s); } // Rectangle for(var j=0; j<jb.rectangleShapes.length; j++){ var s = jb.rectangleShapes[j]; addShape(b, new Rectangle(s.width,s.height), s); } // Convex for(var j=0; j<jb.convexShapes.length; j++){ var s = jb.convexShapes[j]; addShape(b, new Convex(s.vertices), s); } // Capsule for(var j=0; j<jb.capsuleShapes.length; j++){ var s = jb.capsuleShapes[j]; addShape(b, new Capsule(s.length, s.radius), s); } function addShape(body, shape, shapeJSON){ shape.collisionMask = shapeJSON.collisionMask; shape.collisionGroup = shapeJSON.collisionGroup; if(shapeJSON.material){ shape.material = id2material[shapeJSON.material+""]; } body.addShape(shape, shapeJSON.offset, shapeJSON.angle); } if(jb.concavePath){ b.concavePath = jb.concavePath; } w.addBody(b); } // Load springs for(var i=0; i<json.springs.length; i++){ var js = json.springs[i]; var bodyA = bodies[js.bodyA], bodyB = bodies[js.bodyB]; if(!bodyA){ this.error = "instance.springs["+i+"] references instance.body["+js.bodyA+"], which does not exist."; return false; } if(!bodyB){ this.error = "instance.springs["+i+"] references instance.body["+js.bodyB+"], which does not exist."; return false; } var s = new Spring(bodyA, bodyB, { stiffness : js.stiffness, damping : js.damping, restLength : js.restLength, localAnchorA : js.localAnchorA, localAnchorB : js.localAnchorB, }); w.addSpring(s); } // Load contact materials for(var i=0; i<json.contactMaterials.length; i++){ var jm = json.contactMaterials[i], matA = id2material[jm.materialA+""], matB = id2material[jm.materialB+""]; if(!matA){ this.error = "Reference to material id "+jm.materialA+": material not found"; return false; } if(!matB){ this.error = "Reference to material id "+jm.materialB+": material not found"; return false; } var cm = new ContactMaterial(matA, matB, { friction : jm.friction, restitution : jm.restitution, stiffness : jm.stiffness, relaxation : jm.relaxation, frictionStiffness : jm.frictionStiffness, frictionRelaxation : jm.frictionRelaxation, }); cm.id = jm.id; w.addContactMaterial(cm); } // Load default contact material var jm = json.defaultContactMaterial, matA = w.defaultMaterial, matB = w.defaultMaterial; var cm = new ContactMaterial(matA, matB, { friction : jm.friction, restitution : jm.restitution, stiffness : jm.stiffness, relaxation : jm.relaxation, frictionStiffness : jm.frictionStiffness, frictionRelaxation : jm.frictionRelaxation, }); cm.id = jm.id; w.defaultContactMaterial = cm; // DistanceConstraint for(var i=0; i<json.distanceConstraints.length; i++){ var c = json.distanceConstraints[i]; w.addConstraint(new DistanceConstraint( bodies[c.bodyA], bodies[c.bodyB], c.distance, { maxForce:c.maxForce, collideConnected:c.collideConnected })); } // RevoluteConstraint for(var i=0; i<json.revoluteConstraints.length; i++){ var c = json.revoluteConstraints[i]; var revolute = new RevoluteConstraint(bodies[c.bodyA], c.pivotA, bodies[c.bodyB], c.pivotB, { maxForce: c.maxForce, collideConnected: c.collideConnected }); if(c.motorEnabled){ revolute.enableMotor(); } revolute.setMotorSpeed(c.motorSpeed); revolute.lowerLimit = c.lowerLimit; revolute.upperLimit = c.upperLimit; revolute.lowerLimitEnabled = c.lowerLimitEnabled; revolute.upperLimitEnabled = c.upperLimitEnabled; w.addConstraint(revolute); } // PrismaticConstraint for(var i=0; i<json.prismaticConstraints.length; i++){ var c = json.prismaticConstraints[i], p = new PrismaticConstraint(bodies[c.bodyA], bodies[c.bodyB], { maxForce : c.maxForce, localAxisA : c.localAxisA, localAnchorA : c.localAnchorA, localAnchorB : c.localAnchorB, collideConnected: c.collideConnected }); p.motorSpeed = c.motorSpeed; w.addConstraint(p); } // LockConstraint for(var i=0; i<json.lockConstraints.length; i++){ var c = json.lockConstraints[i]; w.addConstraint(new LockConstraint(bodies[c.bodyA], bodies[c.bodyB], { maxForce : c.maxForce, localOffsetB : c.localOffsetB, localAngleB : c.localAngleB, collideConnected: c.collideConnected })); } // GearConstraint for(var i=0; i<json.gearConstraints.length; i++){ var c = json.gearConstraints[i]; w.addConstraint(new GearConstraint(bodies[c.bodyA], bodies[c.bodyB], { maxForce : c.maxForce, angle : c.angle, ratio : c.ratio, collideConnected: c.collideConnected })); } return true; }; /** * Resets the World, removes all bodies, constraints and springs. * * @method clear */ World.prototype.clear = function(){ this.time = 0; this.fixedStepTime = 0; // Remove all solver equations if(this.solver && this.solver.equations.length){ this.solver.removeAllEquations(); } // Remove all constraints var cs = this.constraints; for(var i=cs.length-1; i>=0; i--){ this.removeConstraint(cs[i]); } // Remove all bodies var bodies = this.bodies; for(var i=bodies.length-1; i>=0; i--){ this.removeBody(bodies[i]); } // Remove all springs var springs = this.springs; for(var i=springs.length-1; i>=0; i--){ this.removeSpring(springs[i]); } // Remove all contact materials var cms = this.contactMaterials; for(var i=cms.length-1; i>=0; i--){ this.removeContactMaterial(cms[i]); } World.apply(this); }; /** * Get a copy of this World instance * @method clone * @return {World} */ World.prototype.clone = function(){ var world = new World(); world.fromJSON(this.toJSON()); return world; }; var hitTest_tmp1 = vec2.create(), hitTest_zero = vec2.fromValues(0,0), hitTest_tmp2 = vec2.fromValues(0,0); /** * Test if a world point overlaps bodies * @method hitTest * @param {Array} worldPoint Point to use for intersection tests * @param {Array} bodies A list of objects to check for intersection * @param {Number} precision Used for matching against particles and lines. Adds some margin to these infinitesimal objects. * @return {Array} Array of bodies that overlap the point */ World.prototype.hitTest = function(worldPoint,bodies,precision){ precision = precision || 0; // Create a dummy particle body with a particle shape to test against the bodies var pb = new Body({ position:worldPoint }), ps = new Particle(), px = worldPoint, pa = 0, x = hitTest_tmp1, zero = hitTest_zero, tmp = hitTest_tmp2; pb.addShape(ps); var n = this.narrowphase, result = []; // Check bodies for(var i=0, N=bodies.length; i!==N; i++){ var b = bodies[i]; for(var j=0, NS=b.shapes.length; j!==NS; j++){ var s = b.shapes[j], offset = b.shapeOffsets[j] || zero, angle = b.shapeAngles[j] || 0.0; // Get shape world position + angle vec2.rotate(x, offset, b.angle); vec2.add(x, x, b.position); var a = angle + b.angle; if( (s instanceof Circle && n.circleParticle (b,s,x,a, pb,ps,px,pa, true)) || (s instanceof Convex && n.particleConvex (pb,ps,px,pa, b,s,x,a, true)) || (s instanceof Plane && n.particlePlane (pb,ps,px,pa, b,s,x,a, true)) || (s instanceof Capsule && n.particleCapsule (pb,ps,px,pa, b,s,x,a, true)) || (s instanceof Particle && vec2.squaredLength(vec2.sub(tmp,x,worldPoint)) < precision*precision) ){ result.push(b); } } } return result; }; /** * Sets the Equation parameters for all constraints and contact materials. * @method setGlobalEquationParameters * @param {object} [parameters] * @param {Number} [parameters.relaxation] * @param {Number} [parameters.stiffness] */ World.prototype.setGlobalEquationParameters = function(parameters){ parameters = parameters || {}; // Set for all constraints for(var i=0; i !== this.constraints.length; i++){ var c = this.constraints[i]; for(var j=0; j !== c.equations.length; j++){ var eq = c.equations[j]; if(typeof(parameters.stiffness) !== "undefined"){ eq.stiffness = parameters.stiffness; } if(typeof(parameters.relaxation) !== "undefined"){ eq.relaxation = parameters.relaxation; } eq.needsUpdate = true; } } // Set for all contact materials for(var i=0; i !== this.contactMaterials.length; i++){ var c = this.contactMaterials[i]; if(typeof(parameters.stiffness) !== "undefined"){ c.stiffness = parameters.stiffness; c.frictionStiffness = parameters.stiffness; } if(typeof(parameters.relaxation) !== "undefined"){ c.relaxation = parameters.relaxation; c.frictionRelaxation = parameters.relaxation; } } // Set for default contact material var c = this.defaultContactMaterial; if(typeof(parameters.stiffness) !== "undefined"){ c.stiffness = parameters.stiffness; c.frictionStiffness = parameters.stiffness; } if(typeof(parameters.relaxation) !== "undefined"){ c.relaxation = parameters.relaxation; c.frictionRelaxation = parameters.relaxation; } }; /** * Set the stiffness for all equations and contact materials. * @method setGlobalStiffness * @param {Number} stiffness */ World.prototype.setGlobalStiffness = function(stiffness){ this.setGlobalEquationParameters({ stiffness: stiffness }); }; /** * Set the relaxation for all equations and contact materials. * @method setGlobalRelaxation * @param {Number} relaxation */ World.prototype.setGlobalRelaxation = function(relaxation){ this.setGlobalEquationParameters({ relaxation: relaxation }); }; },{"../../package.json":7,"../collision/Broadphase":9,"../collision/NaiveBroadphase":11,"../collision/Narrowphase":12,"../collision/SAPBroadphase":13,"../constraints/Constraint":14,"../constraints/DistanceConstraint":15,"../constraints/GearConstraint":16,"../constraints/LockConstraint":17,"../constraints/PrismaticConstraint":18,"../constraints/RevoluteConstraint":19,"../events/EventEmitter":26,"../material/ContactMaterial":27,"../material/Material":28,"../math/vec2":30,"../objects/Body":31,"../objects/Spring":32,"../shapes/Capsule":34,"../shapes/Circle":35,"../shapes/Convex":36,"../shapes/Line":38,"../shapes/Particle":39,"../shapes/Plane":40,"../shapes/Rectangle":41,"../shapes/Shape":42,"../solver/GSSolver":43,"../solver/Solver":44,"../utils/OverlapKeeper":45,"../utils/Utils":47,"./IslandManager":49}]},{},[33]) (33) }); ;; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ // Add an extra properties to p2 that we need p2.Body.prototype.parent = null; p2.Spring.prototype.parent = null; /** * @class Phaser.Physics.P2 * @classdesc Physics World Constructor * @constructor * @param {Phaser.Game} game - Reference to the current game instance. * @param {object} [config] - Physics configuration object passed in from the game constructor. */ Phaser.Physics.P2 = function (game, config) { /** * @property {Phaser.Game} game - Local reference to game. */ this.game = game; if (typeof config === 'undefined' || !config.hasOwnProperty('gravity') || !config.hasOwnProperty('broadphase')) { config = { gravity: [0, 0], broadphase: new p2.SAPBroadphase() }; } /** * @property {p2.World} world - The p2 World in which the simulation is run. * @protected */ this.world = new p2.World(config); /** * @property {number} frameRate - The frame rate the world will be stepped at. Defaults to 1 / 60, but you can change here. Also see useElapsedTime property. * @default */ this.frameRate = 1 / 60; /** * @property {boolean} useElapsedTime - If true the frameRate value will be ignored and instead p2 will step with the value of Game.Time.physicsElapsed, which is a delta time value. * @default */ this.useElapsedTime = false; /** * @property {boolean} paused - The paused state of the P2 World. * @default */ this.paused = false; /** * @property {array<Phaser.Physics.P2.Material>} materials - A local array of all created Materials. * @protected */ this.materials = []; /** * @property {Phaser.Physics.P2.InversePointProxy} gravity - The gravity applied to all bodies each step. */ this.gravity = new Phaser.Physics.P2.InversePointProxy(this, this.world.gravity); /** * @property {object} walls - An object containing the 4 wall bodies that bound the physics world. */ this.walls = { left: null, right: null, top: null, bottom: null }; /** * @property {Phaser.Signal} onBodyAdded - Dispatched when a new Body is added to the World. */ this.onBodyAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onBodyRemoved - Dispatched when a Body is removed from the World. */ this.onBodyRemoved = new Phaser.Signal(); /** * @property {Phaser.Signal} onSpringAdded - Dispatched when a new Spring is added to the World. */ this.onSpringAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onSpringRemoved - Dispatched when a Spring is removed from the World. */ this.onSpringRemoved = new Phaser.Signal(); /** * @property {Phaser.Signal} onConstraintAdded - Dispatched when a new Constraint is added to the World. */ this.onConstraintAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onConstraintRemoved - Dispatched when a Constraint is removed from the World. */ this.onConstraintRemoved = new Phaser.Signal(); /** * @property {Phaser.Signal} onContactMaterialAdded - Dispatched when a new ContactMaterial is added to the World. */ this.onContactMaterialAdded = new Phaser.Signal(); /** * @property {Phaser.Signal} onContactMaterialRemoved - Dispatched when a ContactMaterial is removed from the World. */ this.onContactMaterialRemoved = new Phaser.Signal(); /** * @property {function} postBroadphaseCallback - A postBroadphase callback. */ this.postBroadphaseCallback = null; /** * @property {object} callbackContext - The context under which the callbacks are fired. */ this.callbackContext = null; /** * @property {Phaser.Signal} onBeginContact - Dispatched when a first contact is created between two bodies. This event is fired before the step has been done. */ this.onBeginContact = new Phaser.Signal(); /** * @property {Phaser.Signal} onEndContact - Dispatched when final contact occurs between two bodies. This event is fired before the step has been done. */ this.onEndContact = new Phaser.Signal(); // Pixel to meter function overrides if (config.hasOwnProperty('mpx') && config.hasOwnProperty('pxm') && config.hasOwnProperty('mpxi') && config.hasOwnProperty('pxmi')) { this.mpx = config.mpx; this.mpxi = config.mpxi; this.pxm = config.pxm; this.pxmi = config.pxmi; } // Hook into the World events this.world.on("beginContact", this.beginContactHandler, this); this.world.on("endContact", this.endContactHandler, this); /** * @property {array} collisionGroups - An array containing the collision groups that have been defined in the World. */ this.collisionGroups = []; /** * @property {Phaser.Physics.P2.CollisionGroup} nothingCollisionGroup - A default collision group. */ this.nothingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(1); /** * @property {Phaser.Physics.P2.CollisionGroup} boundsCollisionGroup - A default collision group. */ this.boundsCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2); /** * @property {Phaser.Physics.P2.CollisionGroup} everythingCollisionGroup - A default collision group. */ this.everythingCollisionGroup = new Phaser.Physics.P2.CollisionGroup(2147483648); /** * @property {array} boundsCollidesWith - An array of the bodies the world bounds collides with. */ this.boundsCollidesWith = []; /** * @property {array} _toRemove - Internal var used to hold references to bodies to remove from the world on the next step. * @private */ this._toRemove = []; /** * @property {number} _collisionGroupID - Internal var. * @private */ this._collisionGroupID = 2; // By default we want everything colliding with everything this.setBoundsToWorld(true, true, true, true, false); }; Phaser.Physics.P2.prototype = { /** * This will add a P2 Physics body into the removal list for the next step. * * @method Phaser.Physics.P2#removeBodyNextStep * @param {Phaser.Physics.P2.Body} body - The body to remove at the start of the next step. */ removeBodyNextStep: function (body) { this._toRemove.push(body); }, /** * Called at the start of the core update loop. Purges flagged bodies from the world. * * @method Phaser.Physics.P2#preUpdate */ preUpdate: function () { var i = this._toRemove.length; while (i--) { this.removeBody(this._toRemove[i]); } this._toRemove.length = 0; }, /** * This will create a P2 Physics body on the given game object or array of game objects. * A game object can only have 1 physics body active at any one time, and it can't be changed until the object is destroyed. * Note: When the game object is enabled for P2 physics it has its anchor x/y set to 0.5 so it becomes centered. * * @method Phaser.Physics.P2#enable * @param {object|array|Phaser.Group} object - The game object to create the physics body on. Can also be an array or Group of objects, a body will be created on every child that has a `body` property. * @param {boolean} [debug=false] - Create a debug object to go with this body? * @param {boolean} [children=true] - Should a body be created on all children of this object? If true it will recurse down the display list as far as it can go. */ enable: function (object, debug, children) { if (typeof debug === 'undefined') { debug = false; } if (typeof children === 'undefined') { children = true; } var i = 1; if (Array.isArray(object)) { i = object.length; while (i--) { if (object[i] instanceof Phaser.Group) { // If it's a Group then we do it on the children regardless this.enable(object[i].children, debug, children); } else { this.enableBody(object[i], debug); if (children && object[i].hasOwnProperty('children') && object[i].children.length > 0) { this.enable(object[i], debug, true); } } } } else { if (object instanceof Phaser.Group) { // If it's a Group then we do it on the children regardless this.enable(object.children, debug, children); } else { this.enableBody(object, debug); if (children && object.hasOwnProperty('children') && object.children.length > 0) { this.enable(object.children, debug, true); } } } }, /** * Creates a P2 Physics body on the given game object. * A game object can only have 1 physics body active at any one time, and it can't be changed until the body is nulled. * * @method Phaser.Physics.P2#enableBody * @param {object} object - The game object to create the physics body on. A body will only be created if this object has a null `body` property. * @param {boolean} debug - Create a debug object to go with this body? */ enableBody: function (object, debug) { if (object.hasOwnProperty('body') && object.body === null) { object.body = new Phaser.Physics.P2.Body(this.game, object, object.x, object.y, 1); object.body.debug = debug; object.anchor.set(0.5); } }, /** * Impact event handling is disabled by default. Enable it before any impact events will be dispatched. * In a busy world hundreds of impact events can be generated every step, so only enable this if you cannot do what you need via beginContact or collision masks. * * @method Phaser.Physics.P2#setImpactEvents * @param {boolean} state - Set to true to enable impact events, or false to disable. */ setImpactEvents: function (state) { if (state) { this.world.on("impact", this.impactHandler, this); } else { this.world.off("impact", this.impactHandler, this); } }, /** * Sets a callback to be fired after the Broadphase has collected collision pairs in the world. * Just because a pair exists it doesn't mean they *will* collide, just that they potentially could do. * If your calback returns `false` the pair will be removed from the narrowphase. This will stop them testing for collision this step. * Returning `true` from the callback will ensure they are checked in the narrowphase. * * @method Phaser.Physics.P2#setPostBroadphaseCallback * @param {function} callback - The callback that will receive the postBroadphase event data. It must return a boolean. Set to null to disable an existing callback. * @param {object} context - The context under which the callback will be fired. */ setPostBroadphaseCallback: function (callback, context) { this.postBroadphaseCallback = callback; this.callbackContext = context; if (callback !== null) { this.world.on("postBroadphase", this.postBroadphaseHandler, this); } else { this.world.off("postBroadphase", this.postBroadphaseHandler, this); } }, /** * Internal handler for the postBroadphase event. * * @method Phaser.Physics.P2#postBroadphaseHandler * @private * @param {object} event - The event data. */ postBroadphaseHandler: function (event) { if (this.postBroadphaseCallback) { var i = event.pairs.length; while (i -= 2) { if (event.pairs[i].parent && event.pairs[i+1].parent && !this.postBroadphaseCallback.call(this.callbackContext, event.pairs[i].parent, event.pairs[i+1].parent)) { event.pairs.splice(i, 2); } } } }, /** * Handles a p2 impact event. * * @method Phaser.Physics.P2#impactHandler * @private * @param {object} event - The event data. */ impactHandler: function (event) { if (event.bodyA.parent && event.bodyB.parent) { // Body vs. Body callbacks var a = event.bodyA.parent; var b = event.bodyB.parent; if (a._bodyCallbacks[event.bodyB.id]) { a._bodyCallbacks[event.bodyB.id].call(a._bodyCallbackContext[event.bodyB.id], a, b, event.shapeA, event.shapeB); } if (b._bodyCallbacks[event.bodyA.id]) { b._bodyCallbacks[event.bodyA.id].call(b._bodyCallbackContext[event.bodyA.id], b, a, event.shapeB, event.shapeA); } // Body vs. Group callbacks if (a._groupCallbacks[event.shapeB.collisionGroup]) { a._groupCallbacks[event.shapeB.collisionGroup].call(a._groupCallbackContext[event.shapeB.collisionGroup], a, b, event.shapeA, event.shapeB); } if (b._groupCallbacks[event.shapeA.collisionGroup]) { b._groupCallbacks[event.shapeA.collisionGroup].call(b._groupCallbackContext[event.shapeA.collisionGroup], b, a, event.shapeB, event.shapeA); } } }, /** * Handles a p2 begin contact event. * * @method Phaser.Physics.P2#beginContactHandler * @param {object} event - The event data. */ beginContactHandler: function (event) { this.onBeginContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB, event.contactEquations); if (event.bodyA.parent) { event.bodyA.parent.onBeginContact.dispatch(event.bodyB.parent, event.shapeA, event.shapeB, event.contactEquations); } if (event.bodyB.parent) { event.bodyB.parent.onBeginContact.dispatch(event.bodyA.parent, event.shapeB, event.shapeA, event.contactEquations); } }, /** * Handles a p2 end contact event. * * @method Phaser.Physics.P2#endContactHandler * @param {object} event - The event data. */ endContactHandler: function (event) { this.onEndContact.dispatch(event.bodyA, event.bodyB, event.shapeA, event.shapeB); if (event.bodyA.parent) { event.bodyA.parent.onEndContact.dispatch(event.bodyB.parent, event.shapeA, event.shapeB); } if (event.bodyB.parent) { event.bodyB.parent.onEndContact.dispatch(event.bodyA.parent, event.shapeB, event.shapeA); } }, /** * Sets the bounds of the Physics world to match the Game.World dimensions. * You can optionally set which 'walls' to create: left, right, top or bottom. * * @method Phaser.Physics#setBoundsToWorld * @param {boolean} [left=true] - If true will create the left bounds wall. * @param {boolean} [right=true] - If true will create the right bounds wall. * @param {boolean} [top=true] - If true will create the top bounds wall. * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. */ setBoundsToWorld: function (left, right, top, bottom, setCollisionGroup) { this.setBounds(this.game.world.bounds.x, this.game.world.bounds.y, this.game.world.bounds.width, this.game.world.bounds.height, left, right, top, bottom, setCollisionGroup); }, /** * Sets the given material against the 4 bounds of this World. * * @method Phaser.Physics#setWorldMaterial * @param {Phaser.Physics.P2.Material} material - The material to set. * @param {boolean} [left=true] - If true will set the material on the left bounds wall. * @param {boolean} [right=true] - If true will set the material on the right bounds wall. * @param {boolean} [top=true] - If true will set the material on the top bounds wall. * @param {boolean} [bottom=true] - If true will set the material on the bottom bounds wall. */ setWorldMaterial: function (material, left, right, top, bottom) { if (typeof left === 'undefined') { left = true; } if (typeof right === 'undefined') { right = true; } if (typeof top === 'undefined') { top = true; } if (typeof bottom === 'undefined') { bottom = true; } if (left && this.walls.left) { this.walls.left.shapes[0].material = material; } if (right && this.walls.right) { this.walls.right.shapes[0].material = material; } if (top && this.walls.top) { this.walls.top.shapes[0].material = material; } if (bottom && this.walls.bottom) { this.walls.bottom.shapes[0].material = material; } }, /** * By default the World will be set to collide everything with everything. The bounds of the world is a Body with 4 shapes, one for each face. * If you start to use your own collision groups then your objects will no longer collide with the bounds. * To fix this you need to adjust the bounds to use its own collision group first BEFORE changing your Sprites collision group. * * @method Phaser.Physics.P2#updateBoundsCollisionGroup * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. */ updateBoundsCollisionGroup: function (setCollisionGroup) { var mask = this.everythingCollisionGroup.mask; if (typeof setCollisionGroup === 'undefined') { mask = this.boundsCollisionGroup.mask; } if (this.walls.left) { this.walls.left.shapes[0].collisionGroup = mask; } if (this.walls.right) { this.walls.right.shapes[0].collisionGroup = mask; } if (this.walls.top) { this.walls.top.shapes[0].collisionGroup = mask; } if (this.walls.bottom) { this.walls.bottom.shapes[0].collisionGroup = mask; } }, /** * Sets the bounds of the Physics world to match the given world pixel dimensions. * You can optionally set which 'walls' to create: left, right, top or bottom. * * @method Phaser.Physics.P2#setBounds * @param {number} x - The x coordinate of the top-left corner of the bounds. * @param {number} y - The y coordinate of the top-left corner of the bounds. * @param {number} width - The width of the bounds. * @param {number} height - The height of the bounds. * @param {boolean} [left=true] - If true will create the left bounds wall. * @param {boolean} [right=true] - If true will create the right bounds wall. * @param {boolean} [top=true] - If true will create the top bounds wall. * @param {boolean} [bottom=true] - If true will create the bottom bounds wall. * @param {boolean} [setCollisionGroup=true] - If true the Bounds will be set to use its own Collision Group. */ setBounds: function (x, y, width, height, left, right, top, bottom, setCollisionGroup) { if (typeof left === 'undefined') { left = true; } if (typeof right === 'undefined') { right = true; } if (typeof top === 'undefined') { top = true; } if (typeof bottom === 'undefined') { bottom = true; } if (typeof setCollisionGroup === 'undefined') { setCollisionGroup = true; } if (this.walls.left) { this.world.removeBody(this.walls.left); } if (this.walls.right) { this.world.removeBody(this.walls.right); } if (this.walls.top) { this.world.removeBody(this.walls.top); } if (this.walls.bottom) { this.world.removeBody(this.walls.bottom); } if (left) { this.walls.left = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: 1.5707963267948966 }); this.walls.left.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.left.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.left); } if (right) { this.walls.right = new p2.Body({ mass: 0, position: [ this.pxmi(x + width), this.pxmi(y) ], angle: -1.5707963267948966 }); this.walls.right.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.right.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.right); } if (top) { this.walls.top = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y) ], angle: -3.141592653589793 }); this.walls.top.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.top.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.top); } if (bottom) { this.walls.bottom = new p2.Body({ mass: 0, position: [ this.pxmi(x), this.pxmi(y + height) ] }); this.walls.bottom.addShape(new p2.Plane()); if (setCollisionGroup) { this.walls.bottom.shapes[0].collisionGroup = this.boundsCollisionGroup.mask; } this.world.addBody(this.walls.bottom); } }, /** * Pauses the P2 World independent of the game pause state. * * @method Phaser.Physics.P2#pause */ pause: function() { this.paused = true; }, /** * Resumes a paused P2 World. * * @method Phaser.Physics.P2#resume */ resume: function() { this.paused = false; }, /** * Internal P2 update loop. * * @method Phaser.Physics.P2#update */ update: function () { // Do nothing when the pysics engine was paused before if (this.paused) { return; } if (this.useElapsedTime) { this.world.step(this.game.time.physicsElapsed); } else { this.world.step(this.frameRate); } }, /** * Clears all bodies from the simulation, resets callbacks and resets the collision bitmask. * * @method Phaser.Physics.P2#clear */ clear: function () { this.world.clear(); this.world.off("beginContact", this.beginContactHandler, this); this.world.off("endContact", this.endContactHandler, this); this.postBroadphaseCallback = null; this.callbackContext = null; this.impactCallback = null; this.collisionGroups = []; this._toRemove = []; this._collisionGroupID = 2; this.boundsCollidesWith = []; }, /** * Clears all bodies from the simulation and unlinks World from Game. Should only be called on game shutdown. Call `clear` on a State change. * * @method Phaser.Physics.P2#destroy */ destroy: function () { this.clear(); this.game = null; }, /** * Add a body to the world. * * @method Phaser.Physics.P2#addBody * @param {Phaser.Physics.P2.Body} body - The Body to add to the World. * @return {boolean} True if the Body was added successfully, otherwise false. */ addBody: function (body) { if (body.data.world) { return false; } else { this.world.addBody(body.data); this.onBodyAdded.dispatch(body); return true; } }, /** * Removes a body from the world. This will silently fail if the body wasn't part of the world to begin with. * * @method Phaser.Physics.P2#removeBody * @param {Phaser.Physics.P2.Body} body - The Body to remove from the World. * @return {Phaser.Physics.P2.Body} The Body that was removed. */ removeBody: function (body) { if (body.data.world == this.world) { this.world.removeBody(body.data); this.onBodyRemoved.dispatch(body); } return body; }, /** * Adds a Spring to the world. * * @method Phaser.Physics.P2#addSpring * @param {Phaser.Physics.P2.Spring} spring - The Spring to add to the World. * @return {Phaser.Physics.P2.Spring} The Spring that was added. */ addSpring: function (spring) { this.world.addSpring(spring); this.onSpringAdded.dispatch(spring); return spring; }, /** * Removes a Spring from the world. * * @method Phaser.Physics.P2#removeSpring * @param {Phaser.Physics.P2.Spring} spring - The Spring to remove from the World. * @return {Phaser.Physics.P2.Spring} The Spring that was removed. */ removeSpring: function (spring) { this.world.removeSpring(spring); this.onSpringRemoved.dispatch(spring); return spring; }, /** * Creates a constraint that tries to keep the distance between two bodies constant. * * @method Phaser.Physics.P2#createDistanceConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} distance - The distance to keep between the bodies. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.DistanceConstraint} The constraint */ createDistanceConstraint: function (bodyA, bodyB, distance, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.DistanceConstraint(this, bodyA, bodyB, distance, maxForce)); } }, /** * Creates a constraint that tries to keep the distance between two bodies constant. * * @method Phaser.Physics.P2#createGearConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} [angle=0] - The relative angle * @param {number} [ratio=1] - The gear ratio. * @return {Phaser.Physics.P2.GearConstraint} The constraint */ createGearConstraint: function (bodyA, bodyB, angle, ratio) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.GearConstraint(this, bodyA, bodyB, angle, ratio)); } }, /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * The pivot points are given in world (pixel) coordinates. * * @method Phaser.Physics.P2#createRevoluteConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.RevoluteConstraint} The constraint */ createRevoluteConstraint: function (bodyA, pivotA, bodyB, pivotB, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.RevoluteConstraint(this, bodyA, pivotA, bodyB, pivotB, maxForce)); } }, /** * Locks the relative position between two bodies. * * @method Phaser.Physics.P2#createLockConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.LockConstraint} The constraint */ createLockConstraint: function (bodyA, bodyB, offset, angle, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.LockConstraint(this, bodyA, bodyB, offset, angle, maxForce)); } }, /** * Constraint that only allows bodies to move along a line, relative to each other. * See http://www.iforce2d.net/b2dtut/joints-prismatic * * @method Phaser.Physics.P2#createPrismaticConstraint * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. * @return {Phaser.Physics.P2.PrismaticConstraint} The constraint */ createPrismaticConstraint: function (bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Constraint, invalid body objects given'); } else { return this.addConstraint(new Phaser.Physics.P2.PrismaticConstraint(this, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce)); } }, /** * Adds a Constraint to the world. * * @method Phaser.Physics.P2#addConstraint * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to add to the World. * @return {Phaser.Physics.P2.Constraint} The Constraint that was added. */ addConstraint: function (constraint) { this.world.addConstraint(constraint); this.onConstraintAdded.dispatch(constraint); return constraint; }, /** * Removes a Constraint from the world. * * @method Phaser.Physics.P2#removeConstraint * @param {Phaser.Physics.P2.Constraint} constraint - The Constraint to be removed from the World. * @return {Phaser.Physics.P2.Constraint} The Constraint that was removed. */ removeConstraint: function (constraint) { this.world.removeConstraint(constraint); this.onConstraintRemoved.dispatch(constraint); return constraint; }, /** * Adds a Contact Material to the world. * * @method Phaser.Physics.P2#addContactMaterial * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be added to the World. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was added. */ addContactMaterial: function (material) { this.world.addContactMaterial(material); this.onContactMaterialAdded.dispatch(material); return material; }, /** * Removes a Contact Material from the world. * * @method Phaser.Physics.P2#removeContactMaterial * @param {Phaser.Physics.P2.ContactMaterial} material - The Contact Material to be removed from the World. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was removed. */ removeContactMaterial: function (material) { this.world.removeContactMaterial(material); this.onContactMaterialRemoved.dispatch(material); return material; }, /** * Gets a Contact Material based on the two given Materials. * * @method Phaser.Physics.P2#getContactMaterial * @param {Phaser.Physics.P2.Material} materialA - The first Material to search for. * @param {Phaser.Physics.P2.Material} materialB - The second Material to search for. * @return {Phaser.Physics.P2.ContactMaterial|boolean} The Contact Material or false if none was found matching the Materials given. */ getContactMaterial: function (materialA, materialB) { return this.world.getContactMaterial(materialA, materialB); }, /** * Sets the given Material against all Shapes owned by all the Bodies in the given array. * * @method Phaser.Physics.P2#setMaterial * @param {Phaser.Physics.P2.Material} material - The Material to be applied to the given Bodies. * @param {array<Phaser.Physics.P2.Body>} bodies - An Array of Body objects that the given Material will be set on. */ setMaterial: function (material, bodies) { var i = bodies.length; while (i--) { bodies[i].setMaterial(material); } }, /** * Creates a Material. Materials are applied to Shapes owned by a Body and can be set with Body.setMaterial(). * Materials are a way to control what happens when Shapes collide. Combine unique Materials together to create Contact Materials. * Contact Materials have properties such as friction and restitution that allow for fine-grained collision control between different Materials. * * @method Phaser.Physics.P2#createMaterial * @param {string} [name] - Optional name of the Material. Each Material has a unique ID but string names are handy for debugging. * @param {Phaser.Physics.P2.Body} [body] - Optional Body. If given it will assign the newly created Material to the Body shapes. * @return {Phaser.Physics.P2.Material} The Material that was created. This is also stored in Phaser.Physics.P2.materials. */ createMaterial: function (name, body) { name = name || ''; var material = new Phaser.Physics.P2.Material(name); this.materials.push(material); if (typeof body !== 'undefined') { body.setMaterial(material); } return material; }, /** * Creates a Contact Material from the two given Materials. You can then edit the properties of the Contact Material directly. * * @method Phaser.Physics.P2#createContactMaterial * @param {Phaser.Physics.P2.Material} [materialA] - The first Material to create the ContactMaterial from. If undefined it will create a new Material object first. * @param {Phaser.Physics.P2.Material} [materialB] - The second Material to create the ContactMaterial from. If undefined it will create a new Material object first. * @param {object} [options] - Material options object. * @return {Phaser.Physics.P2.ContactMaterial} The Contact Material that was created. */ createContactMaterial: function (materialA, materialB, options) { if (typeof materialA === 'undefined') { materialA = this.createMaterial(); } if (typeof materialB === 'undefined') { materialB = this.createMaterial(); } var contact = new Phaser.Physics.P2.ContactMaterial(materialA, materialB, options); return this.addContactMaterial(contact); }, /** * Populates and returns an array with references to of all current Bodies in the world. * * @method Phaser.Physics.P2#getBodies * @return {array<Phaser.Physics.P2.Body>} An array containing all current Bodies in the world. */ getBodies: function () { var output = []; var i = this.world.bodies.length; while (i--) { output.push(this.world.bodies[i].parent); } return output; }, /** * Checks the given object to see if it has a p2.Body and if so returns it. * * @method Phaser.Physics.P2#getBody * @param {object} object - The object to check for a p2.Body on. * @return {p2.Body} The p2.Body, or null if not found. */ getBody: function (object) { if (object instanceof p2.Body) { // Native p2 body return object; } else if (object instanceof Phaser.Physics.P2.Body) { // Phaser P2 Body return object.data; } else if (object['body'] && object['body'].type === Phaser.Physics.P2JS) { // Sprite, TileSprite, etc return object.body.data; } return null; }, /** * Populates and returns an array of all current Springs in the world. * * @method Phaser.Physics.P2#getSprings * @return {array<Phaser.Physics.P2.Spring>} An array containing all current Springs in the world. */ getSprings: function () { var output = []; var i = this.world.springs.length; while (i--) { output.push(this.world.springs[i].parent); } return output; }, /** * Populates and returns an array of all current Constraints in the world. * * @method Phaser.Physics.P2#getConstraints * @return {array<Phaser.Physics.P2.Constraint>} An array containing all current Constraints in the world. */ getConstraints: function () { var output = []; var i = this.world.constraints.length; while (i--) { output.push(this.world.constraints[i].parent); } return output; }, /** * Test if a world point overlaps bodies. You will get an array of actual P2 bodies back. You can find out which Sprite a Body belongs to * (if any) by checking the Body.parent.sprite property. Body.parent is a Phaser.Physics.P2.Body property. * * @method Phaser.Physics.P2#hitTest * @param {Phaser.Point} worldPoint - Point to use for intersection tests. The points values must be in world (pixel) coordinates. * @param {Array<Phaser.Physics.P2.Body|Phaser.Sprite|p2.Body>} [bodies] - A list of objects to check for intersection. If not given it will check Phaser.Physics.P2.world.bodies (i.e. all world bodies) * @param {number} [precision=5] - Used for matching against particles and lines. Adds some margin to these infinitesimal objects. * @param {boolean} [filterStatic=false] - If true all Static objects will be removed from the results array. * @return {Array} Array of bodies that overlap the point. */ hitTest: function (worldPoint, bodies, precision, filterStatic) { if (typeof bodies === 'undefined') { bodies = this.world.bodies; } if (typeof precision === 'undefined') { precision = 5; } if (typeof filterStatic === 'undefined') { filterStatic = false; } var physicsPosition = [ this.pxmi(worldPoint.x), this.pxmi(worldPoint.y) ]; var query = []; var i = bodies.length; while (i--) { if (bodies[i] instanceof Phaser.Physics.P2.Body && !(filterStatic && bodies[i].data.motionState === p2.Body.STATIC)) { query.push(bodies[i].data); } else if (bodies[i] instanceof p2.Body && bodies[i].parent && !(filterStatic && bodies[i].motionState === p2.Body.STATIC)) { query.push(bodies[i]); } else if (bodies[i] instanceof Phaser.Sprite && bodies[i].hasOwnProperty('body') && !(filterStatic && bodies[i].body.data.motionState === p2.Body.STATIC)) { query.push(bodies[i].body.data); } } return this.world.hitTest(physicsPosition, query, precision); }, /** * Converts the current world into a JSON object. * * @method Phaser.Physics.P2#toJSON * @return {object} A JSON representation of the world. */ toJSON: function () { return this.world.toJSON(); }, /** * Creates a new Collision Group and optionally applies it to the given object. * Collision Groups are handled using bitmasks, therefore you have a fixed limit you can create before you need to re-use older groups. * * @method Phaser.Physics.P2#createCollisionGroup * @param {Phaser.Group|Phaser.Sprite} [object] - An optional Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. */ createCollisionGroup: function (object) { var bitmask = Math.pow(2, this._collisionGroupID); if (this.walls.left) { this.walls.left.shapes[0].collisionMask = this.walls.left.shapes[0].collisionMask | bitmask; } if (this.walls.right) { this.walls.right.shapes[0].collisionMask = this.walls.right.shapes[0].collisionMask | bitmask; } if (this.walls.top) { this.walls.top.shapes[0].collisionMask = this.walls.top.shapes[0].collisionMask | bitmask; } if (this.walls.bottom) { this.walls.bottom.shapes[0].collisionMask = this.walls.bottom.shapes[0].collisionMask | bitmask; } this._collisionGroupID++; var group = new Phaser.Physics.P2.CollisionGroup(bitmask); this.collisionGroups.push(group); if (object) { this.setCollisionGroup(object, group); } return group; }, /** * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. * Note that this resets the collisionMask and any previously set groups. See Body.collides() for appending them. * * @method Phaser.Physics.P2y#setCollisionGroup * @param {Phaser.Group|Phaser.Sprite} object - A Sprite or Group to apply the Collision Group to. If a Group is given it will be applied to all top-level children. * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. */ setCollisionGroup: function (object, group) { if (object instanceof Phaser.Group) { for (var i = 0; i < object.total; i++) { if (object.children[i]['body'] && object.children[i]['body'].type === Phaser.Physics.P2JS) { object.children[i].body.setCollisionGroup(group); } } } else { object.body.setCollisionGroup(group); } }, /** * Creates a spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. * * @method Phaser.Physics.P2#createSpring * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyA - First connected body. * @param {Phaser.Sprite|Phaser.Physics.P2.Body|p2.Body} bodyB - Second connected body. * @param {number} [restLength=1] - Rest length of the spring. A number > 0. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. * @param {number} [damping=1] - Damping of the spring. A number >= 0. * @param {number} [restLength=1] - Rest length of the spring. A number > 0. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. * @param {number} [damping=1] - Damping of the spring. A number >= 0. * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array by 2 elements, x and y, i.e: [32, 32]. * @return {Phaser.Physics.P2.Spring} The spring */ createSpring: function (bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { bodyA = this.getBody(bodyA); bodyB = this.getBody(bodyB); if (!bodyA || !bodyB) { console.warn('Cannot create Spring, invalid body objects given'); } else { return this.addSpring(new Phaser.Physics.P2.Spring(this, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB)); } }, /** * Creates a new Body and adds it to the World. * * @method Phaser.Physics.P2#createBody * @param {number} x - The x coordinate of Body. * @param {number} y - The y coordinate of Body. * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). * @param {object} options - An object containing the build options: * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. * @return {Phaser.Physics.P2.Body} The body */ createBody: function (x, y, mass, addToWorld, options, data) { if (typeof addToWorld === 'undefined') { addToWorld = false; } var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); if (data) { var result = body.addPolygon(options, data); if (!result) { return false; } } if (addToWorld) { this.world.addBody(body.data); } return body; }, /** * Creates a new Particle and adds it to the World. * * @method Phaser.Physics.P2#createParticle * @param {number} x - The x coordinate of Body. * @param {number} y - The y coordinate of Body. * @param {number} mass - The mass of the Body. A mass of 0 means a 'static' Body is created. * @param {boolean} [addToWorld=false] - Automatically add this Body to the world? (usually false as it won't have any shapes on construction). * @param {object} options - An object containing the build options: * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. */ createParticle: function (x, y, mass, addToWorld, options, data) { if (typeof addToWorld === 'undefined') { addToWorld = false; } var body = new Phaser.Physics.P2.Body(this.game, null, x, y, mass); if (data) { var result = body.addPolygon(options, data); if (!result) { return false; } } if (addToWorld) { this.world.addBody(body.data); } return body; }, /** * Converts all of the polylines objects inside a Tiled ObjectGroup into physics bodies that are added to the world. * Note that the polylines must be created in such a way that they can withstand polygon decomposition. * * @method Phaser.Physics.P2#convertCollisionObjects * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world. * @return {array} An array of the Phaser.Physics.Body objects that have been created. */ convertCollisionObjects: function (map, layer, addToWorld) { if (typeof addToWorld === 'undefined') { addToWorld = true; } var output = []; for (var i = 0, len = map.collision[layer].length; i < len; i++) { // name: json.layers[i].objects[v].name, // x: json.layers[i].objects[v].x, // y: json.layers[i].objects[v].y, // width: json.layers[i].objects[v].width, // height: json.layers[i].objects[v].height, // visible: json.layers[i].objects[v].visible, // properties: json.layers[i].objects[v].properties, // polyline: json.layers[i].objects[v].polyline var object = map.collision[layer][i]; var body = this.createBody(object.x, object.y, 0, addToWorld, {}, object.polyline); if (body) { output.push(body); } } return output; }, /** * Clears all physics bodies from the given TilemapLayer that were created with `World.convertTilemap`. * * @method Phaser.Physics.P2#clearTilemapLayerBodies * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. */ clearTilemapLayerBodies: function (map, layer) { layer = map.getLayer(layer); var i = map.layers[layer].bodies.length; while (i--) { map.layers[layer].bodies[i].destroy(); } map.layers[layer].bodies.length = 0; }, /** * Goes through all tiles in the given Tilemap and TilemapLayer and converts those set to collide into physics bodies. * Only call this *after* you have specified all of the tiles you wish to collide with calls like Tilemap.setCollisionBetween, etc. * Every time you call this method it will destroy any previously created bodies and remove them from the world. * Therefore understand it's a very expensive operation and not to be done in a core game update loop. * * @method Phaser.Physics.P2#convertTilemap * @param {Phaser.Tilemap} map - The Tilemap to get the map data from. * @param {number|string|Phaser.TilemapLayer} [layer] - The layer to operate on. If not given will default to map.currentLayer. * @param {boolean} [addToWorld=true] - If true it will automatically add each body to the world, otherwise it's up to you to do so. * @param {boolean} [optimize=true] - If true adjacent colliding tiles will be combined into a single body to save processing. However it means you cannot perform specific Tile to Body collision responses. * @return {array} An array of the Phaser.Physics.P2.Body objects that were created. */ convertTilemap: function (map, layer, addToWorld, optimize) { layer = map.getLayer(layer); if (typeof addToWorld === 'undefined') { addToWorld = true; } if (typeof optimize === 'undefined') { optimize = true; } // If the bodies array is already populated we need to nuke it this.clearTilemapLayerBodies(map, layer); var width = 0; var sx = 0; var sy = 0; for (var y = 0, h = map.layers[layer].height; y < h; y++) { width = 0; for (var x = 0, w = map.layers[layer].width; x < w; x++) { var tile = map.layers[layer].data[y][x]; if (tile && tile.index > -1 && tile.collides) { if (optimize) { var right = map.getTileRight(layer, x, y); if (width === 0) { sx = tile.x * tile.width; sy = tile.y * tile.height; width = tile.width; } if (right && right.collides) { width += tile.width; } else { var body = this.createBody(sx, sy, 0, false); body.addRectangle(width, tile.height, width / 2, tile.height / 2, 0); if (addToWorld) { this.addBody(body); } map.layers[layer].bodies.push(body); width = 0; } } else { var body = this.createBody(tile.x * tile.width, tile.y * tile.height, 0, false); body.addRectangle(tile.width, tile.height, tile.width / 2, tile.height / 2, 0); if (addToWorld) { this.addBody(body); } map.layers[layer].bodies.push(body); } } } } return map.layers[layer].bodies; }, /** * Convert p2 physics value (meters) to pixel scale. * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#mpx * @param {number} v - The value to convert. * @return {number} The scaled value. */ mpx: function (v) { return v *= 20; }, /** * Convert pixel value to p2 physics scale (meters). * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#pxm * @param {number} v - The value to convert. * @return {number} The scaled value. */ pxm: function (v) { return v * 0.05; }, /** * Convert p2 physics value (meters) to pixel scale and inverses it. * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#mpxi * @param {number} v - The value to convert. * @return {number} The scaled value. */ mpxi: function (v) { return v *= -20; }, /** * Convert pixel value to p2 physics scale (meters) and inverses it. * By default Phaser uses a scale of 20px per meter. * If you need to modify this you can over-ride these functions via the Physics Configuration object. * * @method Phaser.Physics.P2#pxmi * @param {number} v - The value to convert. * @return {number} The scaled value. */ pxmi: function (v) { return v * -0.05; } }; /** * @name Phaser.Physics.P2#friction * @property {number} friction - Friction between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. */ Object.defineProperty(Phaser.Physics.P2.prototype, "friction", { get: function () { return this.world.defaultContactMaterial.friction; }, set: function (value) { this.world.defaultContactMaterial.friction = value; } }); /** * @name Phaser.Physics.P2#defaultFriction * @property {number} defaultFriction - DEPRECATED: Use World.friction instead. */ Object.defineProperty(Phaser.Physics.P2.prototype, "defaultFriction", { get: function () { return this.world.defaultContactMaterial.friction; }, set: function (value) { this.world.defaultContactMaterial.friction = value; } }); /** * @name Phaser.Physics.P2#restitution * @property {number} restitution - Default coefficient of restitution between colliding bodies. This value is used if no matching ContactMaterial is found for a Material pair. */ Object.defineProperty(Phaser.Physics.P2.prototype, "restitution", { get: function () { return this.world.defaultContactMaterial.restitution; }, set: function (value) { this.world.defaultContactMaterial.restitution = value; } }); /** * @name Phaser.Physics.P2#defaultRestitution * @property {number} defaultRestitution - DEPRECATED: Use World.restitution instead. */ Object.defineProperty(Phaser.Physics.P2.prototype, "defaultRestitution", { get: function () { return this.world.defaultContactMaterial.restitution; }, set: function (value) { this.world.defaultContactMaterial.restitution = value; } }); /** * @name Phaser.Physics.P2#contactMaterial * @property {p2.ContactMaterial} contactMaterial - The default Contact Material being used by the World. */ Object.defineProperty(Phaser.Physics.P2.prototype, "contactMaterial", { get: function () { return this.world.defaultContactMaterial; }, set: function (value) { this.world.defaultContactMaterial = value; } }); /** * @name Phaser.Physics.P2#applySpringForces * @property {boolean} applySpringForces - Enable to automatically apply spring forces each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "applySpringForces", { get: function () { return this.world.applySpringForces; }, set: function (value) { this.world.applySpringForces = value; } }); /** * @name Phaser.Physics.P2#applyDamping * @property {boolean} applyDamping - Enable to automatically apply body damping each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "applyDamping", { get: function () { return this.world.applyDamping; }, set: function (value) { this.world.applyDamping = value; } }); /** * @name Phaser.Physics.P2#applyGravity * @property {boolean} applyGravity - Enable to automatically apply gravity each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "applyGravity", { get: function () { return this.world.applyGravity; }, set: function (value) { this.world.applyGravity = value; } }); /** * @name Phaser.Physics.P2#solveConstraints * @property {boolean} solveConstraints - Enable/disable constraint solving in each step. */ Object.defineProperty(Phaser.Physics.P2.prototype, "solveConstraints", { get: function () { return this.world.solveConstraints; }, set: function (value) { this.world.solveConstraints = value; } }); /** * @name Phaser.Physics.P2#time * @property {boolean} time - The World time. * @readonly */ Object.defineProperty(Phaser.Physics.P2.prototype, "time", { get: function () { return this.world.time; } }); /** * @name Phaser.Physics.P2#emitImpactEvent * @property {boolean} emitImpactEvent - Set to true if you want to the world to emit the "impact" event. Turning this off could improve performance. */ Object.defineProperty(Phaser.Physics.P2.prototype, "emitImpactEvent", { get: function () { return this.world.emitImpactEvent; }, set: function (value) { this.world.emitImpactEvent = value; } }); /** * @name Phaser.Physics.P2#enableBodySleeping * @property {boolean} enableBodySleeping - Enable / disable automatic body sleeping. */ Object.defineProperty(Phaser.Physics.P2.prototype, "enableBodySleeping", { get: function () { return this.world.enableBodySleeping; }, set: function (value) { this.world.enableBodySleeping = value; } }); /** * @name Phaser.Physics.P2#total * @property {number} total - The total number of bodies in the world. * @readonly */ Object.defineProperty(Phaser.Physics.P2.prototype, "total", { get: function () { return this.world.bodies.length; } }); /* jshint noarg: false */ /** * @author Georgios Kaleadis https://github.com/georgiee * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Allow to access a list of created fixture (coming from Body#addPhaserPolygon) * which itself parse the input from PhysicsEditor with the custom phaser exporter. * You can access fixtures of a Body by a group index or even by providing a fixture Key. * You can set the fixture key and also the group index for a fixture in PhysicsEditor. * This gives you the power to create a complex body built of many fixtures and modify them * during runtime (to remove parts, set masks, categories & sensor properties) * * @class Phaser.Physics.P2.FixtureList * @classdesc Collection for generated P2 fixtures * @constructor * @param {Array} list - A list of fixtures (from Phaser.Physics.P2.Body#addPhaserPolygon) */ Phaser.Physics.P2.FixtureList = function (list) { if (!Array.isArray(list)) { list = [list]; } this.rawList = list; this.init(); this.parse(this.rawList); }; Phaser.Physics.P2.FixtureList.prototype = { /** * @method Phaser.Physics.P2.FixtureList#init */ init: function () { /** * @property {object} namedFixtures - Collect all fixtures with a key * @private */ this.namedFixtures = {}; /** * @property {Array} groupedFixtures - Collect all given fixtures per group index. Notice: Every fixture with a key also belongs to a group * @private */ this.groupedFixtures = []; /** * @property {Array} allFixtures - This is a list of everything in this collection * @private */ this.allFixtures = []; }, /** * @method Phaser.Physics.P2.FixtureList#setCategory * @param {number} bit - The bit to set as the collision group. * @param {string} fixtureKey - Only apply to the fixture with the given key. */ setCategory: function (bit, fixtureKey) { var setter = function(fixture) { fixture.collisionGroup = bit; }; this.getFixtures(fixtureKey).forEach(setter); }, /** * @method Phaser.Physics.P2.FixtureList#setMask * @param {number} bit - The bit to set as the collision mask * @param {string} fixtureKey - Only apply to the fixture with the given key */ setMask: function (bit, fixtureKey) { var setter = function(fixture) { fixture.collisionMask = bit; }; this.getFixtures(fixtureKey).forEach(setter); }, /** * @method Phaser.Physics.P2.FixtureList#setSensor * @param {boolean} value - sensor true or false * @param {string} fixtureKey - Only apply to the fixture with the given key */ setSensor: function (value, fixtureKey) { var setter = function(fixture) { fixture.sensor = value; }; this.getFixtures(fixtureKey).forEach(setter); }, /** * @method Phaser.Physics.P2.FixtureList#setMaterial * @param {Object} material - The contact material for a fixture * @param {string} fixtureKey - Only apply to the fixture with the given key */ setMaterial: function (material, fixtureKey) { var setter = function(fixture) { fixture.material = material; }; this.getFixtures(fixtureKey).forEach(setter); }, /** * Accessor to get either a list of specified fixtures by key or the whole fixture list * * @method Phaser.Physics.P2.FixtureList#getFixtures * @param {array} keys - A list of fixture keys */ getFixtures: function (keys) { var fixtures = []; if (keys) { if (!(keys instanceof Array)) { keys = [keys]; } var self = this; keys.forEach(function(key) { if (self.namedFixtures[key]) { fixtures.push(self.namedFixtures[key]); } }); return this.flatten(fixtures); } else { return this.allFixtures; } }, /** * Accessor to get either a single fixture by its key. * * @method Phaser.Physics.P2.FixtureList#getFixtureByKey * @param {string} key - The key of the fixture. */ getFixtureByKey: function (key) { return this.namedFixtures[key]; }, /** * Accessor to get a group of fixtures by its group index. * * @method Phaser.Physics.P2.FixtureList#getGroup * @param {number} groupID - The group index. */ getGroup: function (groupID) { return this.groupedFixtures[groupID]; }, /** * Parser for the output of Phaser.Physics.P2.Body#addPhaserPolygon * * @method Phaser.Physics.P2.FixtureList#parse */ parse: function () { var key, value, _ref, _results; _ref = this.rawList; _results = []; for (key in _ref) { value = _ref[key]; if (!isNaN(key - 0)) { this.groupedFixtures[key] = this.groupedFixtures[key] || []; this.groupedFixtures[key] = this.groupedFixtures[key].concat(value); } else { this.namedFixtures[key] = this.flatten(value); } _results.push(this.allFixtures = this.flatten(this.groupedFixtures)); } }, /** * A helper to flatten arrays. This is very useful as the fixtures are nested from time to time due to the way P2 creates and splits polygons. * * @method Phaser.Physics.P2.FixtureList#flatten * @param {array} array - The array to flatten. Notice: This will happen recursive not shallow. */ flatten: function (array) { var result, self; result = []; self = arguments.callee; array.forEach(function(item) { return Array.prototype.push.apply(result, (Array.isArray(item) ? self(item) : [item])); }); return result; } }; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * A PointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays. * * @class Phaser.Physics.P2.PointProxy * @classdesc PointProxy * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {any} destination - The object to bind to. */ Phaser.Physics.P2.PointProxy = function (world, destination) { this.world = world; this.destination = destination; }; Phaser.Physics.P2.PointProxy.prototype.constructor = Phaser.Physics.P2.PointProxy; /** * @name Phaser.Physics.P2.PointProxy#x * @property {number} x - The x property of this PointProxy. */ Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "x", { get: function () { return this.destination[0]; }, set: function (value) { this.destination[0] = this.world.pxm(value); } }); /** * @name Phaser.Physics.P2.PointProxy#y * @property {number} y - The y property of this PointProxy. */ Object.defineProperty(Phaser.Physics.P2.PointProxy.prototype, "y", { get: function () { return this.destination[1]; }, set: function (value) { this.destination[1] = this.world.pxm(value); } }); /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * A InversePointProxy is an internal class that allows for direct getter/setter style property access to Arrays and TypedArrays but inverses the values on set. * * @class Phaser.Physics.P2.InversePointProxy * @classdesc InversePointProxy * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {any} destination - The object to bind to. */ Phaser.Physics.P2.InversePointProxy = function (world, destination) { this.world = world; this.destination = destination; }; Phaser.Physics.P2.InversePointProxy.prototype.constructor = Phaser.Physics.P2.InversePointProxy; /** * @name Phaser.Physics.P2.InversePointProxy#x * @property {number} x - The x property of this InversePointProxy. */ Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "x", { get: function () { return this.destination[0]; }, set: function (value) { this.destination[0] = this.world.pxm(-value); } }); /** * @name Phaser.Physics.P2.InversePointProxy#y * @property {number} y - The y property of this InversePointProxy. */ Object.defineProperty(Phaser.Physics.P2.InversePointProxy.prototype, "y", { get: function () { return this.destination[1]; }, set: function (value) { this.destination[1] = this.world.pxm(-value); } }); /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * The Physics Body is typically linked to a single Sprite and defines properties that determine how the physics body is simulated. * These properties affect how the body reacts to forces, what forces it generates on itself (to simulate friction), and how it reacts to collisions in the scene. * In most cases, the properties are used to simulate physical effects. Each body also has its own property values that determine exactly how it reacts to forces and collisions in the scene. * By default a single Rectangle shape is added to the Body that matches the dimensions of the parent Sprite. See addShape, removeShape, clearShapes to add extra shapes around the Body. * Note: When bound to a Sprite to avoid single-pixel jitters on mobile devices we strongly recommend using Sprite sizes that are even on both axis, i.e. 128x128 not 127x127. * Note: When a game object is given a P2 body it has its anchor x/y set to 0.5, so it becomes centered. * * @class Phaser.Physics.P2.Body * @classdesc Physics Body Constructor * @constructor * @param {Phaser.Game} game - Game reference to the currently running game. * @param {Phaser.Sprite} [sprite] - The Sprite object this physics body belongs to. * @param {number} [x=0] - The x coordinate of this Body. * @param {number} [y=0] - The y coordinate of this Body. * @param {number} [mass=1] - The default mass of this Body (0 = static). */ Phaser.Physics.P2.Body = function (game, sprite, x, y, mass) { sprite = sprite || null; x = x || 0; y = y || 0; if (typeof mass === 'undefined') { mass = 1; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = game; /** * @property {Phaser.Physics.P2} world - Local reference to the P2 World. */ this.world = game.physics.p2; /** * @property {Phaser.Sprite} sprite - Reference to the parent Sprite. */ this.sprite = sprite; /** * @property {number} type - The type of physics system this body belongs to. */ this.type = Phaser.Physics.P2JS; /** * @property {Phaser.Point} offset - The offset of the Physics Body from the Sprite x/y position. */ this.offset = new Phaser.Point(); /** * @property {p2.Body} data - The p2 Body data. * @protected */ this.data = new p2.Body({ position: [ this.world.pxmi(x), this.world.pxmi(y) ], mass: mass }); this.data.parent = this; /** * @property {Phaser.InversePointProxy} velocity - The velocity of the body. Set velocity.x to a negative value to move to the left, position to the right. velocity.y negative values move up, positive move down. */ this.velocity = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.velocity); /** * @property {Phaser.InversePointProxy} force - The force applied to the body. */ this.force = new Phaser.Physics.P2.InversePointProxy(this.world, this.data.force); /** * @property {Phaser.Point} gravity - A locally applied gravity force to the Body. Applied directly before the world step. NOTE: Not currently implemented. */ this.gravity = new Phaser.Point(); /** * Dispatched when a first contact is created between shapes in two bodies. This event is fired during the step, so collision has already taken place. * The event will be sent 4 parameters: The body it is in contact with, the shape from this body that caused the contact, the shape from the contact body and the contact equation data array. * @property {Phaser.Signal} onBeginContact */ this.onBeginContact = new Phaser.Signal(); /** * Dispatched when contact ends between shapes in two bodies. This event is fired during the step, so collision has already taken place. * The event will be sent 3 parameters: The body it is in contact with, the shape from this body that caused the contact and the shape from the contact body. * @property {Phaser.Signal} onEndContact */ this.onEndContact = new Phaser.Signal(); /** * @property {array} collidesWith - Array of CollisionGroups that this Bodies shapes collide with. */ this.collidesWith = []; /** * @property {boolean} removeNextStep - To avoid deleting this body during a physics step, and causing all kinds of problems, set removeNextStep to true to have it removed in the next preUpdate. */ this.removeNextStep = false; /** * @property {Phaser.Physics.P2.BodyDebug} debugBody - Reference to the debug body. */ this.debugBody = null; /** * @property {boolean} _collideWorldBounds - Internal var that determines if this Body collides with the world bounds or not. * @private */ this._collideWorldBounds = true; /** * @property {object} _bodyCallbacks - Array of Body callbacks. * @private */ this._bodyCallbacks = {}; /** * @property {object} _bodyCallbackContext - Array of Body callback contexts. * @private */ this._bodyCallbackContext = {}; /** * @property {object} _groupCallbacks - Array of Group callbacks. * @private */ this._groupCallbacks = {}; /** * @property {object} _bodyCallbackContext - Array of Grouo callback contexts. * @private */ this._groupCallbackContext = {}; // Set-up the default shape if (sprite) { this.setRectangleFromSprite(sprite); if (sprite.exists) { this.game.physics.p2.addBody(this); } } }; Phaser.Physics.P2.Body.prototype = { /** * Sets a callback to be fired any time a shape in this Body impacts with a shape in the given Body. The impact test is performed against body.id values. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. * * @method Phaser.Physics.P2.Body#createBodyCallback * @param {Phaser.Sprite|Phaser.TileSprite|Phaser.Physics.P2.Body|p2.Body} object - The object to send impact events for. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. * @param {object} callbackContext - The context under which the callback will fire. */ createBodyCallback: function (object, callback, callbackContext) { var id = -1; if (object['id']) { id = object.id; } else if (object['body']) { id = object.body.id; } if (id > -1) { if (callback === null) { delete (this._bodyCallbacks[id]); delete (this._bodyCallbackContext[id]); } else { this._bodyCallbacks[id] = callback; this._bodyCallbackContext[id] = callbackContext; } } }, /** * Sets a callback to be fired any time this Body impacts with the given Group. The impact test is performed against shape.collisionGroup values. * The callback will be sent 4 parameters: This body, the body that impacted, the Shape in this body and the shape in the impacting body. * This callback will only fire if this Body has been assigned a collision group. * Note that the impact event happens after collision resolution, so it cannot be used to prevent a collision from happening. * It also happens mid-step. So do not destroy a Body during this callback, instead set safeDestroy to true so it will be killed on the next preUpdate. * * @method Phaser.Physics.P2.Body#createGroupCallback * @param {Phaser.Physics.CollisionGroup} group - The Group to send impact events for. * @param {function} callback - The callback to fire on impact. Set to null to clear a previously set callback. * @param {object} callbackContext - The context under which the callback will fire. */ createGroupCallback: function (group, callback, callbackContext) { if (callback === null) { delete (this._groupCallbacks[group.mask]); delete (this._groupCallbacksContext[group.mask]); } else { this._groupCallbacks[group.mask] = callback; this._groupCallbackContext[group.mask] = callbackContext; } }, /** * Gets the collision bitmask from the groups this body collides with. * * @method Phaser.Physics.P2.Body#getCollisionMask * @return {number} The bitmask. */ getCollisionMask: function () { var mask = 0; if (this._collideWorldBounds) { mask = this.game.physics.p2.boundsCollisionGroup.mask; } for (var i = 0; i < this.collidesWith.length; i++) { mask = mask | this.collidesWith[i].mask; } return mask; }, /** * Updates the collisionMask. * * @method Phaser.Physics.P2.Body#updateCollisionMask * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. */ updateCollisionMask: function (shape) { var mask = this.getCollisionMask(); if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionMask = mask; } } else { shape.collisionMask = mask; } }, /** * Sets the given CollisionGroup to be the collision group for all shapes in this Body, unless a shape is specified. * This also resets the collisionMask. * * @method Phaser.Physics.P2.Body#setCollisionGroup * @param {Phaser.Physics.CollisionGroup} group - The Collision Group that this Bodies shapes will use. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision group will be added to all Shapes in this Body. */ setCollisionGroup: function (group, shape) { var mask = this.getCollisionMask(); if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionGroup = group.mask; this.data.shapes[i].collisionMask = mask; } } else { shape.collisionGroup = group.mask; shape.collisionMask = mask; } }, /** * Clears the collision data from the shapes in this Body. Optionally clears Group and/or Mask. * * @method Phaser.Physics.P2.Body#clearCollision * @param {boolean} [clearGroup=true] - Clear the collisionGroup value from the shape/s? * @param {boolean} [clearMask=true] - Clear the collisionMask value from the shape/s? * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision data will be cleared from all Shapes in this Body. */ clearCollision: function (clearGroup, clearMask, shape) { if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { if (clearGroup) { this.data.shapes[i].collisionGroup = null; } if (clearMask) { this.data.shapes[i].collisionMask = null; } } } else { if (clearGroup) { shape.collisionGroup = null; } if (clearMask) { shape.collisionMask = null; } } if (clearGroup) { this.collidesWith.length = 0; } }, /** * Adds the given CollisionGroup, or array of CollisionGroups, to the list of groups that this body will collide with and updates the collision masks. * * @method Phaser.Physics.P2.Body#collides * @param {Phaser.Physics.CollisionGroup|array} group - The Collision Group or Array of Collision Groups that this Bodies shapes will collide with. * @param {function} [callback] - Optional callback that will be triggered when this Body impacts with the given Group. * @param {object} [callbackContext] - The context under which the callback will be called. * @param {p2.Shape} [shape] - An optional Shape. If not provided the collision mask will be added to all Shapes in this Body. */ collides: function (group, callback, callbackContext, shape) { if (Array.isArray(group)) { for (var i = 0; i < group.length; i++) { if (this.collidesWith.indexOf(group[i]) === -1) { this.collidesWith.push(group[i]); if (callback) { this.createGroupCallback(group[i], callback, callbackContext); } } } } else { if (this.collidesWith.indexOf(group) === -1) { this.collidesWith.push(group); if (callback) { this.createGroupCallback(group, callback, callbackContext); } } } var mask = this.getCollisionMask(); if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].collisionMask = mask; } } else { shape.collisionMask = mask; } }, /** * Moves the shape offsets so their center of mass becomes the body center of mass. * * @method Phaser.Physics.P2.Body#adjustCenterOfMass */ adjustCenterOfMass: function () { this.data.adjustCenterOfMass(); }, /** * Apply damping, see http://code.google.com/p/bullet/issues/detail?id=74 for details. * * @method Phaser.Physics.P2.Body#applyDamping * @param {number} dt - Current time step. */ applyDamping: function (dt) { this.data.applyDamping(dt); }, /** * Apply force to a world point. This could for example be a point on the RigidBody surface. Applying force this way will add to Body.force and Body.angularForce. * * @method Phaser.Physics.P2.Body#applyForce * @param {Float32Array|Array} force - The force vector to add. * @param {number} worldX - The world x point to apply the force on. * @param {number} worldY - The world y point to apply the force on. */ applyForce: function (force, worldX, worldY) { this.data.applyForce(force, [this.world.pxmi(worldX), this.world.pxmi(worldY)]); }, /** * Sets the force on the body to zero. * * @method Phaser.Physics.P2.Body#setZeroForce */ setZeroForce: function () { this.data.setZeroForce(); }, /** * If this Body is dynamic then this will zero its angular velocity. * * @method Phaser.Physics.P2.Body#setZeroRotation */ setZeroRotation: function () { this.data.angularVelocity = 0; }, /** * If this Body is dynamic then this will zero its velocity on both axis. * * @method Phaser.Physics.P2.Body#setZeroVelocity */ setZeroVelocity: function () { this.data.velocity[0] = 0; this.data.velocity[1] = 0; }, /** * Sets the Body damping and angularDamping to zero. * * @method Phaser.Physics.P2.Body#setZeroDamping */ setZeroDamping: function () { this.data.damping = 0; this.data.angularDamping = 0; }, /** * Transform a world point to local body frame. * * @method Phaser.Physics.P2.Body#toLocalFrame * @param {Float32Array|Array} out - The vector to store the result in. * @param {Float32Array|Array} worldPoint - The input world vector. */ toLocalFrame: function (out, worldPoint) { return this.data.toLocalFrame(out, worldPoint); }, /** * Transform a local point to world frame. * * @method Phaser.Physics.P2.Body#toWorldFrame * @param {Array} out - The vector to store the result in. * @param {Array} localPoint - The input local vector. */ toWorldFrame: function (out, localPoint) { return this.data.toWorldFrame(out, localPoint); }, /** * This will rotate the Body by the given speed to the left (counter-clockwise). * * @method Phaser.Physics.P2.Body#rotateLeft * @param {number} speed - The speed at which it should rotate. */ rotateLeft: function (speed) { this.data.angularVelocity = this.world.pxm(-speed); }, /** * This will rotate the Body by the given speed to the left (clockwise). * * @method Phaser.Physics.P2.Body#rotateRight * @param {number} speed - The speed at which it should rotate. */ rotateRight: function (speed) { this.data.angularVelocity = this.world.pxm(speed); }, /** * Moves the Body forwards based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveForward * @param {number} speed - The speed at which it should move forwards. */ moveForward: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.velocity[0] = magnitude * Math.cos(angle); this.data.velocity[1] = magnitude * Math.sin(angle); }, /** * Moves the Body backwards based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveBackward * @param {number} speed - The speed at which it should move backwards. */ moveBackward: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.velocity[0] = -(magnitude * Math.cos(angle)); this.data.velocity[1] = -(magnitude * Math.sin(angle)); }, /** * Applies a force to the Body that causes it to 'thrust' forwards, based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#thrust * @param {number} speed - The speed at which it should thrust. */ thrust: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.force[0] += magnitude * Math.cos(angle); this.data.force[1] += magnitude * Math.sin(angle); }, /** * Applies a force to the Body that causes it to 'thrust' backwards (in reverse), based on its current angle and the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#reverse * @param {number} speed - The speed at which it should reverse. */ reverse: function (speed) { var magnitude = this.world.pxmi(-speed); var angle = this.data.angle + Math.PI / 2; this.data.force[0] -= magnitude * Math.cos(angle); this.data.force[1] -= magnitude * Math.sin(angle); }, /** * If this Body is dynamic then this will move it to the left by setting its x velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveLeft * @param {number} speed - The speed at which it should move to the left, in pixels per second. */ moveLeft: function (speed) { this.data.velocity[0] = this.world.pxmi(-speed); }, /** * If this Body is dynamic then this will move it to the right by setting its x velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveRight * @param {number} speed - The speed at which it should move to the right, in pixels per second. */ moveRight: function (speed) { this.data.velocity[0] = this.world.pxmi(speed); }, /** * If this Body is dynamic then this will move it up by setting its y velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveUp * @param {number} speed - The speed at which it should move up, in pixels per second. */ moveUp: function (speed) { this.data.velocity[1] = this.world.pxmi(-speed); }, /** * If this Body is dynamic then this will move it down by setting its y velocity to the given speed. * The speed is represented in pixels per second. So a value of 100 would move 100 pixels in 1 second (1000ms). * * @method Phaser.Physics.P2.Body#moveDown * @param {number} speed - The speed at which it should move down, in pixels per second. */ moveDown: function (speed) { this.data.velocity[1] = this.world.pxmi(speed); }, /** * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. * * @method Phaser.Physics.P2.Body#preUpdate * @protected */ preUpdate: function () { if (this.removeNextStep) { this.removeFromWorld(); this.removeNextStep = false; } }, /** * Internal method. This is called directly before the sprites are sent to the renderer and after the update function has finished. * * @method Phaser.Physics.P2.Body#postUpdate * @protected */ postUpdate: function () { this.sprite.x = this.world.mpxi(this.data.position[0]); this.sprite.y = this.world.mpxi(this.data.position[1]); if (!this.fixedRotation) { this.sprite.rotation = this.data.angle; } }, /** * Resets the Body force, velocity (linear and angular) and rotation. Optionally resets damping and mass. * * @method Phaser.Physics.P2.Body#reset * @param {number} x - The new x position of the Body. * @param {number} y - The new x position of the Body. * @param {boolean} [resetDamping=false] - Resets the linear and angular damping. * @param {boolean} [resetMass=false] - Sets the Body mass back to 1. */ reset: function (x, y, resetDamping, resetMass) { if (typeof resetDamping === 'undefined') { resetDamping = false; } if (typeof resetMass === 'undefined') { resetMass = false; } this.setZeroForce(); this.setZeroVelocity(); this.setZeroRotation(); if (resetDamping) { this.setZeroDamping(); } if (resetMass) { this.mass = 1; } this.x = x; this.y = y; }, /** * Adds this physics body to the world. * * @method Phaser.Physics.P2.Body#addToWorld */ addToWorld: function () { if (this.game.physics.p2._toRemove) { for (var i = 0; i < this.game.physics.p2._toRemove.length; i++) { if (this.game.physics.p2._toRemove[i] === this) { this.game.physics.p2._toRemove.splice(i, 1); } } } if (this.data.world !== this.game.physics.p2.world) { this.game.physics.p2.addBody(this); } }, /** * Removes this physics body from the world. * * @method Phaser.Physics.P2.Body#removeFromWorld */ removeFromWorld: function () { if (this.data.world === this.game.physics.p2.world) { this.game.physics.p2.removeBodyNextStep(this); } }, /** * Destroys this Body and all references it holds to other objects. * * @method Phaser.Physics.P2.Body#destroy */ destroy: function () { this.removeFromWorld(); this.clearShapes(); this._bodyCallbacks = {}; this._bodyCallbackContext = {}; this._groupCallbacks = {}; this._groupCallbackContext = {}; if (this.debugBody) { this.debugBody.destroy(); } this.debugBody = null; this.sprite = null; }, /** * Removes all Shapes from this Body. * * @method Phaser.Physics.P2.Body#clearShapes */ clearShapes: function () { var i = this.data.shapes.length; while (i--) { this.data.removeShape(this.data.shapes[i]); } this.shapeChanged(); }, /** * Add a shape to the body. You can pass a local transform when adding a shape, so that the shape gets an offset and an angle relative to the body center of mass. * Will automatically update the mass properties and bounding radius. * * @method Phaser.Physics.P2.Body#addShape * @param {p2.Shape} shape - The shape to add to the body. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Shape} The shape that was added to the body. */ addShape: function (shape, offsetX, offsetY, rotation) { if (typeof offsetX === 'undefined') { offsetX = 0; } if (typeof offsetY === 'undefined') { offsetY = 0; } if (typeof rotation === 'undefined') { rotation = 0; } this.data.addShape(shape, [this.world.pxmi(offsetX), this.world.pxmi(offsetY)], rotation); this.shapeChanged(); return shape; }, /** * Adds a Circle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addCircle * @param {number} radius - The radius of this circle (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Circle} The Circle shape that was added to the Body. */ addCircle: function (radius, offsetX, offsetY, rotation) { var shape = new p2.Circle(this.world.pxm(radius)); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Rectangle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addRectangle * @param {number} width - The width of the rectangle in pixels. * @param {number} height - The height of the rectangle in pixels. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ addRectangle: function (width, height, offsetX, offsetY, rotation) { var shape = new p2.Rectangle(this.world.pxm(width), this.world.pxm(height)); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Plane shape to this Body. The plane is facing in the Y direction. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addPlane * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Plane} The Plane shape that was added to the Body. */ addPlane: function (offsetX, offsetY, rotation) { var shape = new p2.Plane(); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Particle shape to this Body. You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addParticle * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Particle} The Particle shape that was added to the Body. */ addParticle: function (offsetX, offsetY, rotation) { var shape = new p2.Particle(); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Line shape to this Body. * The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0]. * You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addLine * @param {number} length - The length of this line (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Line} The Line shape that was added to the Body. */ addLine: function (length, offsetX, offsetY, rotation) { var shape = new p2.Line(this.world.pxm(length)); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Adds a Capsule shape to this Body. * You can control the offset from the center of the body and the rotation. * * @method Phaser.Physics.P2.Body#addCapsule * @param {number} length - The distance between the end points in pixels. * @param {number} radius - Radius of the capsule in radians. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Capsule} The Capsule shape that was added to the Body. */ addCapsule: function (length, radius, offsetX, offsetY, rotation) { var shape = new p2.Capsule(this.world.pxm(length), radius); return this.addShape(shape, offsetX, offsetY, rotation); }, /** * Reads a polygon shape path, and assembles convex shapes from that and puts them at proper offset points. The shape must be simple and without holes. * This function expects the x.y values to be given in pixels. If you want to provide them at p2 world scales then call Body.data.fromPolygon directly. * * @method Phaser.Physics.P2.Body#addPolygon * @param {object} options - An object containing the build options: * @param {boolean} [options.optimalDecomp=false] - Set to true if you need optimal decomposition. Warning: very slow for polygons with more than 10 vertices. * @param {boolean} [options.skipSimpleCheck=false] - Set to true if you already know that the path is not intersecting itself. * @param {boolean|number} [options.removeCollinearPoints=false] - Set to a number (angle threshold value) to remove collinear points, or false to keep all points. * @param {(number[]|...number)} points - An array of 2d vectors that form the convex or concave polygon. * Either [[0,0], [0,1],...] or a flat array of numbers that will be interpreted as [x,y, x,y, ...], * or the arguments passed can be flat x,y values e.g. `setPolygon(options, x,y, x,y, x,y, ...)` where `x` and `y` are numbers. * @return {boolean} True on success, else false. */ addPolygon: function (options, points) { options = options || {}; if (!Array.isArray(points)) { points = Array.prototype.slice.call(arguments, 1); } var path = []; // Did they pass in a single array of points? if (points.length === 1 && Array.isArray(points[0])) { path = points[0].slice(0); } else if (Array.isArray(points[0])) { path = points[0].slice(0); } else if (typeof points[0] === 'number') { // We've a list of numbers for (var i = 0, len = points.length; i < len; i += 2) { path.push([points[i], points[i + 1]]); } } // top and tail var idx = path.length - 1; if (path[idx][0] === path[0][0] && path[idx][1] === path[0][1]) { path.pop(); } // Now process them into p2 values for (var p = 0; p < path.length; p++) { path[p][0] = this.world.pxmi(path[p][0]); path[p][1] = this.world.pxmi(path[p][1]); } var result = this.data.fromPolygon(path, options); this.shapeChanged(); return result; }, /** * Remove a shape from the body. Will automatically update the mass properties and bounding radius. * * @method Phaser.Physics.P2.Body#removeShape * @param {p2.Circle|p2.Rectangle|p2.Plane|p2.Line|p2.Particle} shape - The shape to remove from the body. * @return {boolean} True if the shape was found and removed, else false. */ removeShape: function (shape) { var result = this.data.removeShape(shape); this.shapeChanged(); return result; }, /** * Clears any previously set shapes. Then creates a new Circle shape and adds it to this Body. * * @method Phaser.Physics.P2.Body#setCircle * @param {number} radius - The radius of this circle (in pixels) * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. */ setCircle: function (radius, offsetX, offsetY, rotation) { this.clearShapes(); return this.addCircle(radius, offsetX, offsetY, rotation); }, /** * Clears any previously set shapes. The creates a new Rectangle shape at the given size and offset, and adds it to this Body. * If you wish to create a Rectangle to match the size of a Sprite or Image see Body.setRectangleFromSprite. * * @method Phaser.Physics.P2.Body#setRectangle * @param {number} [width=16] - The width of the rectangle in pixels. * @param {number} [height=16] - The height of the rectangle in pixels. * @param {number} [offsetX=0] - Local horizontal offset of the shape relative to the body center of mass. * @param {number} [offsetY=0] - Local vertical offset of the shape relative to the body center of mass. * @param {number} [rotation=0] - Local rotation of the shape relative to the body center of mass, specified in radians. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ setRectangle: function (width, height, offsetX, offsetY, rotation) { if (typeof width === 'undefined') { width = 16; } if (typeof height === 'undefined') { height = 16; } this.clearShapes(); return this.addRectangle(width, height, offsetX, offsetY, rotation); }, /** * Clears any previously set shapes. * Then creates a Rectangle shape sized to match the dimensions and orientation of the Sprite given. * If no Sprite is given it defaults to using the parent of this Body. * * @method Phaser.Physics.P2.Body#setRectangleFromSprite * @param {Phaser.Sprite|Phaser.Image} [sprite] - The Sprite on which the Rectangle will get its dimensions. * @return {p2.Rectangle} The Rectangle shape that was added to the Body. */ setRectangleFromSprite: function (sprite) { if (typeof sprite === 'undefined') { sprite = this.sprite; } this.clearShapes(); return this.addRectangle(sprite.width, sprite.height, 0, 0, sprite.rotation); }, /** * Adds the given Material to all Shapes that belong to this Body. * If you only wish to apply it to a specific Shape in this Body then provide that as the 2nd parameter. * * @method Phaser.Physics.P2.Body#setMaterial * @param {Phaser.Physics.P2.Material} material - The Material that will be applied. * @param {p2.Shape} [shape] - An optional Shape. If not provided the Material will be added to all Shapes in this Body. */ setMaterial: function (material, shape) { if (typeof shape === 'undefined') { for (var i = this.data.shapes.length - 1; i >= 0; i--) { this.data.shapes[i].material = material; } } else { shape.material = material; } }, /** * Updates the debug draw if any body shapes change. * * @method Phaser.Physics.P2.Body#shapeChanged */ shapeChanged: function() { if (this.debugBody) { this.debugBody.draw(); } }, /** * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. * The shape data format is based on the custom phaser export in. * * @method Phaser.Physics.P2.Body#addPhaserPolygon * @param {string} key - The key of the Physics Data file as stored in Game.Cache. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. */ addPhaserPolygon: function (key, object) { var data = this.game.cache.getPhysicsData(key, object); var createdFixtures = []; // Cycle through the fixtures for (var i = 0; i < data.length; i++) { var fixtureData = data[i]; var shapesOfFixture = this.addFixture(fixtureData); // Always add to a group createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group] || []; createdFixtures[fixtureData.filter.group] = createdFixtures[fixtureData.filter.group].concat(shapesOfFixture); // if (unique) fixture key is provided if (fixtureData.fixtureKey) { createdFixtures[fixtureData.fixtureKey] = shapesOfFixture; } } this.data.aabbNeedsUpdate = true; this.shapeChanged(); return createdFixtures; }, /** * Add a polygon fixture. This is used during #loadPolygon. * * @method Phaser.Physics.P2.Body#addFixture * @param {string} fixtureData - The data for the fixture. It contains: isSensor, filter (collision) and the actual polygon shapes. * @return {array} An array containing the generated shapes for the given polygon. */ addFixture: function (fixtureData) { var generatedShapes = []; if (fixtureData.circle) { var shape = new p2.Circle(this.world.pxm(fixtureData.circle.radius)); shape.collisionGroup = fixtureData.filter.categoryBits; shape.collisionMask = fixtureData.filter.maskBits; shape.sensor = fixtureData.isSensor; var offset = p2.vec2.create(); offset[0] = this.world.pxmi(fixtureData.circle.position[0] - this.sprite.width/2); offset[1] = this.world.pxmi(fixtureData.circle.position[1] - this.sprite.height/2); this.data.addShape(shape, offset); generatedShapes.push(shape); } else { var polygons = fixtureData.polygons; var cm = p2.vec2.create(); for (var i = 0; i < polygons.length; i++) { var shapes = polygons[i]; var vertices = []; for (var s = 0; s < shapes.length; s += 2) { vertices.push([ this.world.pxmi(shapes[s]), this.world.pxmi(shapes[s + 1]) ]); } var shape = new p2.Convex(vertices); // Move all vertices so its center of mass is in the local center of the convex for (var j = 0; j !== shape.vertices.length; j++) { var v = shape.vertices[j]; p2.vec2.sub(v, v, shape.centerOfMass); } p2.vec2.scale(cm, shape.centerOfMass, 1); cm[0] -= this.world.pxmi(this.sprite.width / 2); cm[1] -= this.world.pxmi(this.sprite.height / 2); shape.updateTriangles(); shape.updateCenterOfMass(); shape.updateBoundingRadius(); shape.collisionGroup = fixtureData.filter.categoryBits; shape.collisionMask = fixtureData.filter.maskBits; shape.sensor = fixtureData.isSensor; this.data.addShape(shape, cm); generatedShapes.push(shape); } } return generatedShapes; }, /** * Reads the shape data from a physics data file stored in the Game.Cache and adds it as a polygon to this Body. * * @method Phaser.Physics.P2.Body#loadPolygon * @param {string} key - The key of the Physics Data file as stored in Game.Cache. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. * @return {boolean} True on success, else false. */ loadPolygon: function (key, object) { var data = this.game.cache.getPhysicsData(key, object); // We've multiple Convex shapes, they should be CCW automatically var cm = p2.vec2.create(); for (var i = 0; i < data.length; i++) { var vertices = []; for (var s = 0; s < data[i].shape.length; s += 2) { vertices.push([ this.world.pxmi(data[i].shape[s]), this.world.pxmi(data[i].shape[s + 1]) ]); } var c = new p2.Convex(vertices); // Move all vertices so its center of mass is in the local center of the convex for (var j = 0; j !== c.vertices.length; j++) { var v = c.vertices[j]; p2.vec2.sub(v, v, c.centerOfMass); } p2.vec2.scale(cm, c.centerOfMass, 1); cm[0] -= this.world.pxmi(this.sprite.width / 2); cm[1] -= this.world.pxmi(this.sprite.height / 2); c.updateTriangles(); c.updateCenterOfMass(); c.updateBoundingRadius(); this.data.addShape(c, cm); } this.data.aabbNeedsUpdate = true; this.shapeChanged(); return true; }, /** * DEPRECATED: This method will soon be removed from the API. Please avoid using. * Reads the physics data from a physics data file stored in the Game.Cache. * It will add the shape data to this Body, as well as set the density (mass). * * @method Phaser.Physics.P2.Body#loadData * @param {string} key - The key of the Physics Data file as stored in Game.Cache. * @param {string} object - The key of the object within the Physics data file that you wish to load the shape data from. * @return {boolean} True on success, else false. */ loadData: function (key, object) { var data = this.game.cache.getPhysicsData(key, object); if (data && data.shape) { this.mass = data.density; return this.loadPolygon(key, object); } } }; Phaser.Physics.P2.Body.prototype.constructor = Phaser.Physics.P2.Body; /** * Dynamic body. * @property DYNAMIC * @type {Number} * @static */ Phaser.Physics.P2.Body.DYNAMIC = 1; /** * Static body. * @property STATIC * @type {Number} * @static */ Phaser.Physics.P2.Body.STATIC = 2; /** * Kinematic body. * @property KINEMATIC * @type {Number} * @static */ Phaser.Physics.P2.Body.KINEMATIC = 4; /** * @name Phaser.Physics.P2.Body#static * @property {boolean} static - Returns true if the Body is static. Setting Body.static to 'false' will make it dynamic. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "static", { get: function () { return (this.data.motionState === Phaser.Physics.P2.Body.STATIC); }, set: function (value) { if (value && this.data.motionState !== Phaser.Physics.P2.Body.STATIC) { this.data.motionState = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } else if (!value && this.data.motionState === Phaser.Physics.P2.Body.STATIC) { this.data.motionState = Phaser.Physics.P2.Body.DYNAMIC; if (this.mass === 0) { this.mass = 1; } } } }); /** * @name Phaser.Physics.P2.Body#dynamic * @property {boolean} dynamic - Returns true if the Body is dynamic. Setting Body.dynamic to 'false' will make it static. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "dynamic", { get: function () { return (this.data.motionState === Phaser.Physics.P2.Body.DYNAMIC); }, set: function (value) { if (value && this.data.motionState !== Phaser.Physics.P2.Body.DYNAMIC) { this.data.motionState = Phaser.Physics.P2.Body.DYNAMIC; if (this.mass === 0) { this.mass = 1; } } else if (!value && this.data.motionState === Phaser.Physics.P2.Body.DYNAMIC) { this.data.motionState = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } } }); /** * @name Phaser.Physics.P2.Body#kinematic * @property {boolean} kinematic - Returns true if the Body is kinematic. Setting Body.kinematic to 'false' will make it static. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "kinematic", { get: function () { return (this.data.motionState === Phaser.Physics.P2.Body.KINEMATIC); }, set: function (value) { if (value && this.data.motionState !== Phaser.Physics.P2.Body.KINEMATIC) { this.data.motionState = Phaser.Physics.P2.Body.KINEMATIC; this.mass = 4; } else if (!value && this.data.motionState === Phaser.Physics.P2.Body.KINEMATIC) { this.data.motionState = Phaser.Physics.P2.Body.STATIC; this.mass = 0; } } }); /** * @name Phaser.Physics.P2.Body#allowSleep * @property {boolean} allowSleep - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "allowSleep", { get: function () { return this.data.allowSleep; }, set: function (value) { if (value !== this.data.allowSleep) { this.data.allowSleep = value; } } }); /** * The angle of the Body in degrees from its original orientation. Values from 0 to 180 represent clockwise rotation; values from 0 to -180 represent counterclockwise rotation. * Values outside this range are added to or subtracted from 360 to obtain a value within the range. For example, the statement Body.angle = 450 is the same as Body.angle = 90. * If you wish to work in radians instead of degrees use the property Body.rotation instead. Working in radians is faster as it doesn't have to convert values. * * @name Phaser.Physics.P2.Body#angle * @property {number} angle - The angle of this Body in degrees. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angle", { get: function() { return Phaser.Math.wrapAngle(Phaser.Math.radToDeg(this.data.angle)); }, set: function(value) { this.data.angle = Phaser.Math.degToRad(Phaser.Math.wrapAngle(value)); } }); /** * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. * @name Phaser.Physics.P2.Body#angularDamping * @property {number} angularDamping - The angular damping acting acting on the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularDamping", { get: function () { return this.data.angularDamping; }, set: function (value) { this.data.angularDamping = value; } }); /** * @name Phaser.Physics.P2.Body#angularForce * @property {number} angularForce - The angular force acting on the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularForce", { get: function () { return this.data.angularForce; }, set: function (value) { this.data.angularForce = value; } }); /** * @name Phaser.Physics.P2.Body#angularVelocity * @property {number} angularVelocity - The angular velocity of the body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "angularVelocity", { get: function () { return this.data.angularVelocity; }, set: function (value) { this.data.angularVelocity = value; } }); /** * Damping is specified as a value between 0 and 1, which is the proportion of velocity lost per second. * @name Phaser.Physics.P2.Body#damping * @property {number} damping - The linear damping acting on the body in the velocity direction. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "damping", { get: function () { return this.data.damping; }, set: function (value) { this.data.damping = value; } }); /** * @name Phaser.Physics.P2.Body#fixedRotation * @property {boolean} fixedRotation - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "fixedRotation", { get: function () { return this.data.fixedRotation; }, set: function (value) { if (value !== this.data.fixedRotation) { this.data.fixedRotation = value; } } }); /** * @name Phaser.Physics.P2.Body#inertia * @property {number} inertia - The inertia of the body around the Z axis.. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "inertia", { get: function () { return this.data.inertia; }, set: function (value) { this.data.inertia = value; } }); /** * @name Phaser.Physics.P2.Body#mass * @property {number} mass - */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "mass", { get: function () { return this.data.mass; }, set: function (value) { if (value !== this.data.mass) { this.data.mass = value; this.data.updateMassProperties(); } } }); /** * @name Phaser.Physics.P2.Body#motionState * @property {number} motionState - The type of motion this body has. Should be one of: Body.STATIC (the body does not move), Body.DYNAMIC (body can move and respond to collisions) and Body.KINEMATIC (only moves according to its .velocity). */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "motionState", { get: function () { return this.data.motionState; }, set: function (value) { if (value !== this.data.motionState) { this.data.motionState = value; } } }); /** * The angle of the Body in radians. * If you wish to work in degrees instead of radians use the Body.angle property instead. Working in radians is faster as it doesn't have to convert values. * * @name Phaser.Physics.P2.Body#rotation * @property {number} rotation - The angle of this Body in radians. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "rotation", { get: function() { return this.data.angle; }, set: function(value) { this.data.angle = value; } }); /** * @name Phaser.Physics.P2.Body#sleepSpeedLimit * @property {number} sleepSpeedLimit - . */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "sleepSpeedLimit", { get: function () { return this.data.sleepSpeedLimit; }, set: function (value) { this.data.sleepSpeedLimit = value; } }); /** * @name Phaser.Physics.P2.Body#x * @property {number} x - The x coordinate of this Body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "x", { get: function () { return this.world.mpxi(this.data.position[0]); }, set: function (value) { this.data.position[0] = this.world.pxmi(value); } }); /** * @name Phaser.Physics.P2.Body#y * @property {number} y - The y coordinate of this Body. */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "y", { get: function () { return this.world.mpxi(this.data.position[1]); }, set: function (value) { this.data.position[1] = this.world.pxmi(value); } }); /** * @name Phaser.Physics.P2.Body#id * @property {number} id - The Body ID. Each Body that has been added to the World has a unique ID. * @readonly */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "id", { get: function () { return this.data.id; } }); /** * @name Phaser.Physics.P2.Body#debug * @property {boolean} debug - Enable or disable debug drawing of this body */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "debug", { get: function () { return (this.debugBody !== null); }, set: function (value) { if (value && !this.debugBody) { // This will be added to the global space this.debugBody = new Phaser.Physics.P2.BodyDebug(this.game, this.data); } else if (!value && this.debugBody) { this.debugBody.destroy(); this.debugBody = null; } } }); /** * A Body can be set to collide against the World bounds automatically if this is set to true. Otherwise it will leave the World. * Note that this only applies if your World has bounds! The response to the collision should be managed via CollisionMaterials. * * @name Phaser.Physics.P2.Body#collideWorldBounds * @property {boolean} collideWorldBounds - Should the Body collide with the World bounds? */ Object.defineProperty(Phaser.Physics.P2.Body.prototype, "collideWorldBounds", { get: function () { return this._collideWorldBounds; }, set: function (value) { if (value && !this._collideWorldBounds) { this._collideWorldBounds = true; this.updateCollisionMask(); } else if (!value && this._collideWorldBounds) { this._collideWorldBounds = false; this.updateCollisionMask(); } } }); /** * @author George https://github.com/georgiee * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Draws a P2 Body to a Graphics instance for visual debugging. * Needless to say, for every body you enable debug drawing on, you are adding processor and graphical overhead. * So use sparingly and rarely (if ever) in production code. * * @class Phaser.Physics.P2.BodyDebug * @classdesc Physics Body Debug Constructor * @constructor * @extends Phaser.Group * @param {Phaser.Game} game - Game reference to the currently running game. * @param {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. * @param {object} settings - Settings object. */ Phaser.Physics.P2.BodyDebug = function(game, body, settings) { Phaser.Group.call(this, game); /** * @property {object} defaultSettings - Default debug settings. * @private */ var defaultSettings = { pixelsPerLengthUnit: 20, debugPolygons: false, lineWidth: 1, alpha: 0.5 }; this.settings = Phaser.Utils.extend(defaultSettings, settings); /** * @property {number} ppu - Pixels per Length Unit. */ this.ppu = this.settings.pixelsPerLengthUnit; this.ppu = -1 * this.ppu; /** * @property {Phaser.Physics.P2.Body} body - The P2 Body to display debug data for. */ this.body = body; /** * @property {Phaser.Graphics} canvas - The canvas to render the debug info to. */ this.canvas = new Phaser.Graphics(game); this.canvas.alpha = this.settings.alpha; this.add(this.canvas); this.draw(); }; Phaser.Physics.P2.BodyDebug.prototype = Object.create(Phaser.Group.prototype); Phaser.Physics.P2.BodyDebug.prototype.constructor = Phaser.Physics.P2.BodyDebug; Phaser.Utils.extend(Phaser.Physics.P2.BodyDebug.prototype, { /** * Core update. * * @method Phaser.Physics.P2.BodyDebug#update */ update: function() { this.updateSpriteTransform(); }, /** * Core update. * * @method Phaser.Physics.P2.BodyDebug#updateSpriteTransform */ updateSpriteTransform: function() { this.position.x = this.body.position[0] * this.ppu; this.position.y = this.body.position[1] * this.ppu; return this.rotation = this.body.angle; }, /** * Draws the P2 shapes to the Graphics object. * * @method Phaser.Physics.P2.BodyDebug#draw */ draw: function() { var angle, child, color, i, j, lineColor, lw, obj, offset, sprite, v, verts, vrot, _j, _ref1; obj = this.body; sprite = this.canvas; sprite.clear(); color = parseInt(this.randomPastelHex(), 16); lineColor = 0xff0000; lw = this.lineWidth; if (obj instanceof p2.Body && obj.shapes.length) { var l = obj.shapes.length; i = 0; while (i !== l) { child = obj.shapes[i]; offset = obj.shapeOffsets[i]; angle = obj.shapeAngles[i]; offset = offset || 0; angle = angle || 0; if (child instanceof p2.Circle) { this.drawCircle(sprite, offset[0] * this.ppu, offset[1] * this.ppu, angle, child.radius * this.ppu, color, lw); } else if (child instanceof p2.Convex) { verts = []; vrot = p2.vec2.create(); for (j = _j = 0, _ref1 = child.vertices.length; 0 <= _ref1 ? _j < _ref1 : _j > _ref1; j = 0 <= _ref1 ? ++_j : --_j) { v = child.vertices[j]; p2.vec2.rotate(vrot, v, angle); verts.push([(vrot[0] + offset[0]) * this.ppu, -(vrot[1] + offset[1]) * this.ppu]); } this.drawConvex(sprite, verts, child.triangles, lineColor, color, lw, this.settings.debugPolygons, [offset[0] * this.ppu, -offset[1] * this.ppu]); } else if (child instanceof p2.Plane) { this.drawPlane(sprite, offset[0] * this.ppu, -offset[1] * this.ppu, color, lineColor, lw * 5, lw * 10, lw * 10, this.ppu * 100, angle); } else if (child instanceof p2.Line) { this.drawLine(sprite, child.length * this.ppu, lineColor, lw); } else if (child instanceof p2.Rectangle) { this.drawRectangle(sprite, offset[0] * this.ppu, -offset[1] * this.ppu, angle, child.width * this.ppu, child.height * this.ppu, lineColor, color, lw); } i++; } } }, /** * Draws the P2 shapes to the Graphics object. * * @method Phaser.Physics.P2.BodyDebug#draw */ drawRectangle: function(g, x, y, angle, w, h, color, fillColor, lineWidth) { if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0x000000; } g.lineStyle(lineWidth, color, 1); g.beginFill(fillColor); g.drawRect(x - w / 2, y - h / 2, w, h); }, /** * Draws a P2 Circle shape. * * @method Phaser.Physics.P2.BodyDebug#drawCircle */ drawCircle: function(g, x, y, angle, radius, color, lineWidth) { if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0xffffff; } g.lineStyle(lineWidth, 0x000000, 1); g.beginFill(color, 1.0); g.drawCircle(x, y, -radius); g.endFill(); g.moveTo(x, y); g.lineTo(x + radius * Math.cos(-angle), y + radius * Math.sin(-angle)); }, /** * Draws a P2 Line shape. * * @method Phaser.Physics.P2.BodyDebug#drawCircle */ drawLine: function(g, len, color, lineWidth) { if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0x000000; } g.lineStyle(lineWidth * 5, color, 1); g.moveTo(-len / 2, 0); g.lineTo(len / 2, 0); }, /** * Draws a P2 Convex shape. * * @method Phaser.Physics.P2.BodyDebug#drawConvex */ drawConvex: function(g, verts, triangles, color, fillColor, lineWidth, debug, offset) { var colors, i, v, v0, v1, x, x0, x1, y, y0, y1; if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0x000000; } if (!debug) { g.lineStyle(lineWidth, color, 1); g.beginFill(fillColor); i = 0; while (i !== verts.length) { v = verts[i]; x = v[0]; y = v[1]; if (i === 0) { g.moveTo(x, -y); } else { g.lineTo(x, -y); } i++; } g.endFill(); if (verts.length > 2) { g.moveTo(verts[verts.length - 1][0], -verts[verts.length - 1][1]); return g.lineTo(verts[0][0], -verts[0][1]); } } else { colors = [0xff0000, 0x00ff00, 0x0000ff]; i = 0; while (i !== verts.length + 1) { v0 = verts[i % verts.length]; v1 = verts[(i + 1) % verts.length]; x0 = v0[0]; y0 = v0[1]; x1 = v1[0]; y1 = v1[1]; g.lineStyle(lineWidth, colors[i % colors.length], 1); g.moveTo(x0, -y0); g.lineTo(x1, -y1); g.drawCircle(x0, -y0, lineWidth * 2); i++; } g.lineStyle(lineWidth, 0x000000, 1); return g.drawCircle(offset[0], offset[1], lineWidth * 2); } }, /** * Draws a P2 Path. * * @method Phaser.Physics.P2.BodyDebug#drawPath */ drawPath: function(g, path, color, fillColor, lineWidth) { var area, i, lastx, lasty, p1x, p1y, p2x, p2y, p3x, p3y, v, x, y; if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0x000000; } g.lineStyle(lineWidth, color, 1); if (typeof fillColor === "number") { g.beginFill(fillColor); } lastx = null; lasty = null; i = 0; while (i < path.length) { v = path[i]; x = v[0]; y = v[1]; if (x !== lastx || y !== lasty) { if (i === 0) { g.moveTo(x, y); } else { p1x = lastx; p1y = lasty; p2x = x; p2y = y; p3x = path[(i + 1) % path.length][0]; p3y = path[(i + 1) % path.length][1]; area = ((p2x - p1x) * (p3y - p1y)) - ((p3x - p1x) * (p2y - p1y)); if (area !== 0) { g.lineTo(x, y); } } lastx = x; lasty = y; } i++; } if (typeof fillColor === "number") { g.endFill(); } if (path.length > 2 && typeof fillColor === "number") { g.moveTo(path[path.length - 1][0], path[path.length - 1][1]); g.lineTo(path[0][0], path[0][1]); } }, /** * Draws a P2 Plane shape. * * @method Phaser.Physics.P2.BodyDebug#drawPlane */ drawPlane: function(g, x0, x1, color, lineColor, lineWidth, diagMargin, diagSize, maxLength, angle) { var max, xd, yd; if (typeof lineWidth === 'undefined') { lineWidth = 1; } if (typeof color === 'undefined') { color = 0xffffff; } g.lineStyle(lineWidth, lineColor, 11); g.beginFill(color); max = maxLength; g.moveTo(x0, -x1); xd = x0 + Math.cos(angle) * this.game.width; yd = x1 + Math.sin(angle) * this.game.height; g.lineTo(xd, -yd); g.moveTo(x0, -x1); xd = x0 + Math.cos(angle) * -this.game.width; yd = x1 + Math.sin(angle) * -this.game.height; g.lineTo(xd, -yd); }, /** * Picks a random pastel color. * * @method Phaser.Physics.P2.BodyDebug#randomPastelHex */ randomPastelHex: function() { var blue, green, mix, red; mix = [255, 255, 255]; red = Math.floor(Math.random() * 256); green = Math.floor(Math.random() * 256); blue = Math.floor(Math.random() * 256); red = Math.floor((red + 3 * mix[0]) / 4); green = Math.floor((green + 3 * mix[1]) / 4); blue = Math.floor((blue + 3 * mix[2]) / 4); return this.rgbToHex(red, green, blue); }, /** * Converts from RGB to Hex. * * @method Phaser.Physics.P2.BodyDebug#rgbToHex */ rgbToHex: function(r, g, b) { return this.componentToHex(r) + this.componentToHex(g) + this.componentToHex(b); }, /** * Component to hex conversion. * * @method Phaser.Physics.P2.BodyDebug#componentToHex */ componentToHex: function(c) { var hex; hex = c.toString(16); if (hex.len === 2) { return hex; } else { return hex + '0'; } } }); /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Creates a spring, connecting two bodies. A spring can have a resting length, a stiffness and damping. * * @class Phaser.Physics.P2.Spring * @classdesc Physics Spring Constructor * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {number} [restLength=1] - Rest length of the spring. A number > 0. * @param {number} [stiffness=100] - Stiffness of the spring. A number >= 0. * @param {number} [damping=1] - Damping of the spring. A number >= 0. * @param {Array} [worldA] - Where to hook the spring to body A in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [worldB] - Where to hook the spring to body B in world coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [localA] - Where to hook the spring to body A in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [localB] - Where to hook the spring to body B in local body coordinates. This value is an array with 2 elements matching x and y, i.e: [32, 32]. */ Phaser.Physics.P2.Spring = function (world, bodyA, bodyB, restLength, stiffness, damping, worldA, worldB, localA, localB) { /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; if (typeof restLength === 'undefined') { restLength = 1; } if (typeof stiffness === 'undefined') { stiffness = 100; } if (typeof damping === 'undefined') { damping = 1; } restLength = world.pxm(restLength); var options = { restLength: restLength, stiffness: stiffness, damping: damping }; if (typeof worldA !== 'undefined' && worldA !== null) { options.worldAnchorA = [ world.pxm(worldA[0]), world.pxm(worldA[1]) ]; } if (typeof worldB !== 'undefined' && worldB !== null) { options.worldAnchorB = [ world.pxm(worldB[0]), world.pxm(worldB[1]) ]; } if (typeof localA !== 'undefined' && localA !== null) { options.localAnchorA = [ world.pxm(localA[0]), world.pxm(localA[1]) ]; } if (typeof localB !== 'undefined' && localB !== null) { options.localAnchorB = [ world.pxm(localB[0]), world.pxm(localB[1]) ]; } p2.Spring.call(this, bodyA, bodyB, options); }; Phaser.Physics.P2.Spring.prototype = Object.create(p2.Spring.prototype); Phaser.Physics.P2.Spring.prototype.constructor = Phaser.Physics.P2.Spring; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * \o/ ~ "Because I'm a Material girl" * * @class Phaser.Physics.P2.Material * @classdesc Physics Material Constructor * @constructor */ Phaser.Physics.P2.Material = function (name) { /** * @property {string} name - The user defined name given to this Material. * @default */ this.name = name; p2.Material.call(this); }; Phaser.Physics.P2.Material.prototype = Object.create(p2.Material.prototype); Phaser.Physics.P2.Material.prototype.constructor = Phaser.Physics.P2.Material; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Defines a physics material * * @class Phaser.Physics.P2.ContactMaterial * @classdesc Physics ContactMaterial Constructor * @constructor * @param {Phaser.Physics.P2.Material} materialA * @param {Phaser.Physics.P2.Material} materialB * @param {object} [options] */ Phaser.Physics.P2.ContactMaterial = function (materialA, materialB, options) { /** * @property {number} id - The contact material identifier. */ /** * @property {Phaser.Physics.P2.Material} materialA - First material participating in the contact material. */ /** * @property {Phaser.Physics.P2.Material} materialB - First second participating in the contact material. */ /** * @property {number} [friction=0.3] - Friction to use in the contact of these two materials. */ /** * @property {number} [restitution=0.0] - Restitution to use in the contact of these two materials. */ /** * @property {number} [stiffness=1e7] - Stiffness of the resulting ContactEquation that this ContactMaterial generate. */ /** * @property {number} [relaxation=3] - Relaxation of the resulting ContactEquation that this ContactMaterial generate. */ /** * @property {number} [frictionStiffness=1e7] - Stiffness of the resulting FrictionEquation that this ContactMaterial generate. */ /** * @property {number} [frictionRelaxation=3] - Relaxation of the resulting FrictionEquation that this ContactMaterial generate. */ /** * @property {number} [surfaceVelocity=0] - Will add surface velocity to this material. If bodyA rests on top if bodyB, and the surface velocity is positive, bodyA will slide to the right. */ p2.ContactMaterial.call(this, materialA, materialB, options); }; Phaser.Physics.P2.ContactMaterial.prototype = Object.create(p2.ContactMaterial.prototype); Phaser.Physics.P2.ContactMaterial.prototype.constructor = Phaser.Physics.P2.ContactMaterial; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Collision Group * * @class Phaser.Physics.P2.CollisionGroup * @classdesc Physics Collision Group Constructor * @constructor */ Phaser.Physics.P2.CollisionGroup = function (bitmask) { /** * @property {number} mask - The CollisionGroup bitmask. */ this.mask = bitmask; }; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * A constraint that tries to keep the distance between two bodies constant. * * @class Phaser.Physics.P2.DistanceConstraint * @classdesc Physics DistanceConstraint Constructor * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {number} distance - The distance to keep between the bodies. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. */ Phaser.Physics.P2.DistanceConstraint = function (world, bodyA, bodyB, distance, maxForce) { if (typeof distance === 'undefined') { distance = 100; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; distance = world.pxm(distance); p2.DistanceConstraint.call(this, bodyA, bodyB, distance, {maxForce: maxForce}); }; Phaser.Physics.P2.DistanceConstraint.prototype = Object.create(p2.DistanceConstraint.prototype); Phaser.Physics.P2.DistanceConstraint.prototype.constructor = Phaser.Physics.P2.DistanceConstraint; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * * @class Phaser.Physics.P2.GearConstraint * @classdesc Physics GearConstraint Constructor * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {number} [angle=0] - The relative angle * @param {number} [ratio=1] - The gear ratio. */ Phaser.Physics.P2.GearConstraint = function (world, bodyA, bodyB, angle, ratio) { if (typeof angle === 'undefined') { angle = 0; } if (typeof ratio === 'undefined') { ratio = 1; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; var options = { angle: angle, ratio: ratio }; p2.GearConstraint.call(this, bodyA, bodyB, options); }; Phaser.Physics.P2.GearConstraint.prototype = Object.create(p2.GearConstraint.prototype); Phaser.Physics.P2.GearConstraint.prototype.constructor = Phaser.Physics.P2.GearConstraint; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Locks the relative position between two bodies. * * @class Phaser.Physics.P2.LockConstraint * @classdesc Physics LockConstraint Constructor * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {Array} [offset] - The offset of bodyB in bodyA's frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [angle=0] - The angle of bodyB in bodyA's frame. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. */ Phaser.Physics.P2.LockConstraint = function (world, bodyA, bodyB, offset, angle, maxForce) { if (typeof offset === 'undefined') { offset = [0, 0]; } if (typeof angle === 'undefined') { angle = 0; } if (typeof maxForce === 'undefined') { maxForce = Number.MAX_VALUE; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; offset = [ world.pxm(offset[0]), world.pxm(offset[1]) ]; var options = { localOffsetB: offset, localAngleB: angle, maxForce: maxForce }; p2.LockConstraint.call(this, bodyA, bodyB, options); }; Phaser.Physics.P2.LockConstraint.prototype = Object.create(p2.LockConstraint.prototype); Phaser.Physics.P2.LockConstraint.prototype.constructor = Phaser.Physics.P2.LockConstraint; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * * @class Phaser.Physics.P2.PrismaticConstraint * @classdesc Physics PrismaticConstraint Constructor * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {p2.Body} bodyB - Second connected body. * @param {boolean} [lockRotation=true] - If set to false, bodyB will be free to rotate around its anchor point. * @param {Array} [anchorA] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [anchorB] - Body A's anchor point, defined in its own local frame. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {Array} [axis] - An axis, defined in body A frame, that body B's anchor point may slide along. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce] - The maximum force that should be applied to constrain the bodies. */ Phaser.Physics.P2.PrismaticConstraint = function (world, bodyA, bodyB, lockRotation, anchorA, anchorB, axis, maxForce) { if (typeof lockRotation === 'undefined') { lockRotation = true; } if (typeof anchorA === 'undefined') { anchorA = [0, 0]; } if (typeof anchorB === 'undefined') { anchorB = [0, 0]; } if (typeof axis === 'undefined') { axis = [0, 0]; } if (typeof maxForce === 'undefined') { maxForce = Number.MAX_VALUE; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; anchorA = [ world.pxmi(anchorA[0]), world.pxmi(anchorA[1]) ]; anchorB = [ world.pxmi(anchorB[0]), world.pxmi(anchorB[1]) ]; var options = { localAnchorA: anchorA, localAnchorB: anchorB, localAxisA: axis, maxForce: maxForce, disableRotationalLock: !lockRotation }; p2.PrismaticConstraint.call(this, bodyA, bodyB, options); }; Phaser.Physics.P2.PrismaticConstraint.prototype = Object.create(p2.PrismaticConstraint.prototype); Phaser.Physics.P2.PrismaticConstraint.prototype.constructor = Phaser.Physics.P2.PrismaticConstraint; /** * @author Richard Davey <[email protected]> * @copyright 2014 Photon Storm Ltd. * @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License} */ /** * Connects two bodies at given offset points, letting them rotate relative to each other around this point. * The pivot points are given in world (pixel) coordinates. * * @class Phaser.Physics.P2.RevoluteConstraint * @classdesc Physics RevoluteConstraint Constructor * @constructor * @param {Phaser.Physics.P2} world - A reference to the P2 World. * @param {p2.Body} bodyA - First connected body. * @param {Float32Array} pivotA - The point relative to the center of mass of bodyA which bodyA is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {p2.Body} bodyB - Second connected body. * @param {Float32Array} pivotB - The point relative to the center of mass of bodyB which bodyB is constrained to. The value is an array with 2 elements matching x and y, i.e: [32, 32]. * @param {number} [maxForce=0] - The maximum force that should be applied to constrain the bodies. */ Phaser.Physics.P2.RevoluteConstraint = function (world, bodyA, pivotA, bodyB, pivotB, maxForce) { if (typeof maxForce === 'undefined') { maxForce = Number.MAX_VALUE; } /** * @property {Phaser.Game} game - Local reference to game. */ this.game = world.game; /** * @property {Phaser.Physics.P2} world - Local reference to P2 World. */ this.world = world; pivotA = [ world.pxmi(pivotA[0]), world.pxmi(pivotA[1]) ]; pivotB = [ world.pxmi(pivotB[0]), world.pxmi(pivotB[1]) ]; p2.RevoluteConstraint.call(this, bodyA, pivotA, bodyB, pivotB, {maxForce: maxForce}); }; Phaser.Physics.P2.RevoluteConstraint.prototype = Object.create(p2.RevoluteConstraint.prototype); Phaser.Physics.P2.RevoluteConstraint.prototype.constructor = Phaser.Physics.P2.RevoluteConstraint;
node_modules/react-onsenui/test/speedDialItem-test.js
epgui/FEECUM-cordova
/* global describe it assert */ import React from 'react'; import ReactDOM from 'react-dom'; import {SpeedDialItem} from '../dist/react-onsenui.js'; import TestUtils from 'react/lib/ReactTestUtils'; import rendersToComponent from './testUtil.js'; describe('SpeedDialItem', function() { rendersToComponent( <SpeedDialItem />, 'ons-speed-dial-item' ); });
files/rxjs/2.4.10/rx.lite.extras.js
firulais/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (factory) { 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; } // Because of build optimizers if (typeof define === 'function' && define.amd) { define(['rx-lite'], function (Rx, exports) { return factory(root, exports, Rx); }); } else if (typeof module === 'object' && module && module.exports === freeExports) { module.exports = factory(root, module.exports, require('rx-lite')); } else { root.Rx = factory(root, {}, root.Rx); } }.call(this, function (root, exp, Rx, undefined) { // References var Observable = Rx.Observable, observableProto = Observable.prototype, observableNever = Observable.never, observableThrow = Observable.throwException, AnonymousObservable = Rx.AnonymousObservable, AnonymousObserver = Rx.AnonymousObserver, notificationCreateOnNext = Rx.Notification.createOnNext, notificationCreateOnError = Rx.Notification.createOnError, notificationCreateOnCompleted = Rx.Notification.createOnCompleted, Observer = Rx.Observer, Subject = Rx.Subject, internals = Rx.internals, helpers = Rx.helpers, ScheduledObserver = internals.ScheduledObserver, SerialDisposable = Rx.SerialDisposable, SingleAssignmentDisposable = Rx.SingleAssignmentDisposable, CompositeDisposable = Rx.CompositeDisposable, RefCountDisposable = Rx.RefCountDisposable, disposableEmpty = Rx.Disposable.empty, immediateScheduler = Rx.Scheduler.immediate, defaultKeySerializer = helpers.defaultKeySerializer, addRef = Rx.internals.addRef, identity = helpers.identity, isPromise = helpers.isPromise, inherits = internals.inherits, bindCallback = internals.bindCallback, noop = helpers.noop, isScheduler = helpers.isScheduler, observableFromPromise = Observable.fromPromise, ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError; function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * 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) { var handlerFunc = bindCallback(handler, thisArg, 1); return new AnonymousObserver(function (x) { return handlerFunc(notificationCreateOnNext(x)); }, function (e) { return handlerFunc(notificationCreateOnError(e)); }, function () { return handlerFunc(notificationCreateOnCompleted()); }); }; /** * 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 () { var source = this; return new AnonymousObserver( function (x) { source.onNext(x); }, function (e) { source.onError(e); }, function () { source.onCompleted(); } ); }; /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (o) { var first = true; return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); hasResult && (result = resultSelector(state)); } catch (e) { o.onError(e); return; } if (hasResult) { o.onNext(result); self(state); } else { o.onCompleted(); } }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; return Rx; }));
ajax/libs/material-ui/5.0.0-alpha.32/legacy/Container/Container.min.js
cdnjs/cdnjs
import _objectWithoutProperties from"@babel/runtime/helpers/esm/objectWithoutProperties";import _defineProperty from"@babel/runtime/helpers/esm/defineProperty";import _extends from"@babel/runtime/helpers/esm/extends";import*as React from"react";import PropTypes from"prop-types";import clsx from"clsx";import{unstable_composeClasses as composeClasses}from"@material-ui/unstyled";import useThemeProps from"../styles/useThemeProps";import experimentalStyled from"../styles/experimentalStyled";import{getContainerUtilityClass}from"./containerClasses";import capitalize from"../utils/capitalize";import{jsx as _jsx}from"react/jsx-runtime";var useUtilityClasses=function(e){var t=e.classes,s=e.fixed,o=e.disableGutters,e=e.maxWidth,o={root:["root",e&&"maxWidth".concat(capitalize(String(e))),s&&"fixed",o&&"disableGutters"]};return composeClasses(o,getContainerUtilityClass,t)},ContainerRoot=experimentalStyled("div",{},{name:"MuiContainer",slot:"Root",overridesResolver:function(e,t){e=e.styleProps;return _extends({},t.root,t["maxWidth".concat(capitalize(String(e.maxWidth)))],e.fixed&&t.fixed,e.disableGutters&&t.disableGutters)}})(function(e){var t=e.theme,e=e.styleProps;return _extends({width:"100%",marginLeft:"auto",boxSizing:"border-box",marginRight:"auto",display:"block"},!e.disableGutters&&_defineProperty({paddingLeft:t.spacing(2),paddingRight:t.spacing(2)},t.breakpoints.up("sm"),{paddingLeft:t.spacing(3),paddingRight:t.spacing(3)}))},function(e){var o=e.theme;return e.styleProps.fixed&&Object.keys(o.breakpoints.values).reduce(function(e,t){var s=o.breakpoints.values[t];return 0!==s&&(e[o.breakpoints.up(t)]={maxWidth:"".concat(s).concat(o.breakpoints.unit)}),e},{})},function(e){var t=e.theme,e=e.styleProps;return _extends({},"xs"===e.maxWidth&&_defineProperty({},t.breakpoints.up("xs"),{maxWidth:Math.max(t.breakpoints.values.xs,444)}),e.maxWidth&&"xs"!==e.maxWidth&&_defineProperty({},t.breakpoints.up(e.maxWidth),{maxWidth:"".concat(t.breakpoints.values[e.maxWidth]).concat(t.breakpoints.unit)}))}),Container=React.forwardRef(function(e,t){var s=useThemeProps({props:e,name:"MuiContainer"}),o=s.className,r=s.component,i=void 0===r?"div":r,a=s.disableGutters,n=void 0!==a&&a,e=s.fixed,r=void 0!==e&&e,a=s.maxWidth,e=void 0===a?"lg":a,a=_objectWithoutProperties(s,["className","component","disableGutters","fixed","maxWidth"]),r=_extends({},s,{component:i,disableGutters:n,fixed:r,maxWidth:e}),e=useUtilityClasses(r);return _jsx(ContainerRoot,_extends({as:i,styleProps:r,className:clsx(e.root,o),ref:t},a))});"production"!==process.env.NODE_ENV&&(Container.propTypes={children:PropTypes.node,classes:PropTypes.object,className:PropTypes.string,component:PropTypes.elementType,disableGutters:PropTypes.bool,fixed:PropTypes.bool,maxWidth:PropTypes.oneOf(["lg","md","sm","xl","xs",!1]),sx:PropTypes.object});export default Container;
ajax/libs/aui/5.2-m6/js/aui-dependencies.js
szimek/cdnjs
/*! AUI Flat Pack - version 5.2-m6 - generated 2013-05-29 03:12:37 -0400 */ /* * jQuery JavaScript Library v1.8.3 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: Tue Nov 13 2012 08:20:33 GMT-0500 (Eastern Standard Time) */ (function(a2,aB){var w,af,o=a2.document,aI=a2.location,d=a2.navigator,bg=a2.jQuery,I=a2.$,am=Array.prototype.push,a4=Array.prototype.slice,aK=Array.prototype.indexOf,z=Object.prototype.toString,V=Object.prototype.hasOwnProperty,aO=String.prototype.trim,bG=function(e,bZ){return new bG.fn.init(e,bZ,w)},bx=/[\-+]?(?:\d*\.|)\d+(?:[eE][\-+]?\d+|)/.source,aa=/\S/,aV=/\s+/,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,bo=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,a=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,bf=/^[\],:{}\s]*$/,bi=/(?:^|:|,)(?:\s*\[)+/g,bD=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,a0=/"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g,bP=/^-ms-/,aU=/-([\da-z])/gi,N=function(e,bZ){return(bZ+"").toUpperCase()},aF=function(){if(o.addEventListener){o.removeEventListener("DOMContentLoaded",aF,false);bG.ready()}else{if(o.readyState==="complete"){o.detachEvent("onreadystatechange",aF);bG.ready()}}},Z={};bG.fn=bG.prototype={constructor:bG,init:function(e,b2,b1){var b0,b3,bZ,b4;if(!e){return this}if(e.nodeType){this.context=this[0]=e;this.length=1;return this}if(typeof e==="string"){if(e.charAt(0)==="<"&&e.charAt(e.length-1)===">"&&e.length>=3){b0=[null,e,null]}else{b0=bo.exec(e)}if(b0&&(b0[1]||!b2)){if(b0[1]){b2=b2 instanceof bG?b2[0]:b2;b4=(b2&&b2.nodeType?b2.ownerDocument||b2:o);e=bG.parseHTML(b0[1],b4,true);if(a.test(b0[1])&&bG.isPlainObject(b2)){this.attr.call(e,b2,true)}return bG.merge(this,e)}else{b3=o.getElementById(b0[2]);if(b3&&b3.parentNode){if(b3.id!==b0[2]){return b1.find(e)}this.length=1;this[0]=b3}this.context=o;this.selector=e;return this}}else{if(!b2||b2.jquery){return(b2||b1).find(e)}else{return this.constructor(b2).find(e)}}}else{if(bG.isFunction(e)){return b1.ready(e)}}if(e.selector!==aB){this.selector=e.selector;this.context=e.context}return bG.makeArray(e,this)},selector:"",jquery:"1.8.3",length:0,size:function(){return this.length},toArray:function(){return a4.call(this)},get:function(e){return e==null?this.toArray():(e<0?this[this.length+e]:this[e])},pushStack:function(bZ,b1,e){var b0=bG.merge(this.constructor(),bZ);b0.prevObject=this;b0.context=this.context;if(b1==="find"){b0.selector=this.selector+(this.selector?" ":"")+e}else{if(b1){b0.selector=this.selector+"."+b1+"("+e+")"}}return b0},each:function(bZ,e){return bG.each(this,bZ,e)},ready:function(e){bG.ready.promise().done(e);return this},eq:function(e){e=+e;return e===-1?this.slice(e):this.slice(e,e+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(a4.apply(this,arguments),"slice",a4.call(arguments).join(","))},map:function(e){return this.pushStack(bG.map(this,function(b0,bZ){return e.call(b0,bZ,b0)}))},end:function(){return this.prevObject||this.constructor(null)},push:am,sort:[].sort,splice:[].splice};bG.fn.init.prototype=bG.fn;bG.extend=bG.fn.extend=function(){var b7,b0,e,bZ,b4,b5,b3=arguments[0]||{},b2=1,b1=arguments.length,b6=false;if(typeof b3==="boolean"){b6=b3;b3=arguments[1]||{};b2=2}if(typeof b3!=="object"&&!bG.isFunction(b3)){b3={}}if(b1===b2){b3=this;--b2}for(;b2<b1;b2++){if((b7=arguments[b2])!=null){for(b0 in b7){e=b3[b0];bZ=b7[b0];if(b3===bZ){continue}if(b6&&bZ&&(bG.isPlainObject(bZ)||(b4=bG.isArray(bZ)))){if(b4){b4=false;b5=e&&bG.isArray(e)?e:[]}else{b5=e&&bG.isPlainObject(e)?e:{}}b3[b0]=bG.extend(b6,b5,bZ)}else{if(bZ!==aB){b3[b0]=bZ}}}}}return b3};bG.extend({noConflict:function(e){if(a2.$===bG){a2.$=I}if(e&&a2.jQuery===bG){a2.jQuery=bg}return bG},isReady:false,readyWait:1,holdReady:function(e){if(e){bG.readyWait++}else{bG.ready(true)}},ready:function(e){if(e===true?--bG.readyWait:bG.isReady){return}if(!o.body){return setTimeout(bG.ready,1)}bG.isReady=true;if(e!==true&&--bG.readyWait>0){return}af.resolveWith(o,[bG]);if(bG.fn.trigger){bG(o).trigger("ready").off("ready")}},isFunction:function(e){return bG.type(e)==="function"},isArray:Array.isArray||function(e){return bG.type(e)==="array"},isWindow:function(e){return e!=null&&e==e.window},isNumeric:function(e){return !isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return e==null?String(e):Z[z.call(e)]||"object"},isPlainObject:function(b1){if(!b1||bG.type(b1)!=="object"||b1.nodeType||bG.isWindow(b1)){return false}try{if(b1.constructor&&!V.call(b1,"constructor")&&!V.call(b1.constructor.prototype,"isPrototypeOf")){return false}}catch(b0){return false}var bZ;for(bZ in b1){}return bZ===aB||V.call(b1,bZ)},isEmptyObject:function(bZ){var e;for(e in bZ){return false}return true},error:function(e){throw new Error(e)},parseHTML:function(b1,b0,e){var bZ;if(!b1||typeof b1!=="string"){return null}if(typeof b0==="boolean"){e=b0;b0=0}b0=b0||o;if((bZ=a.exec(b1))){return[b0.createElement(bZ[1])]}bZ=bG.buildFragment([b1],b0,e?null:[]);return bG.merge([],(bZ.cacheable?bG.clone(bZ.fragment):bZ.fragment).childNodes)},parseJSON:function(e){if(!e||typeof e!=="string"){return null}e=bG.trim(e);if(a2.JSON&&a2.JSON.parse){return a2.JSON.parse(e)}if(bf.test(e.replace(bD,"@").replace(a0,"]").replace(bi,""))){return(new Function("return "+e))()}bG.error("Invalid JSON: "+e)},parseXML:function(b1){var bZ,b0;if(!b1||typeof b1!=="string"){return null}try{if(a2.DOMParser){b0=new DOMParser();bZ=b0.parseFromString(b1,"text/xml")}else{bZ=new ActiveXObject("Microsoft.XMLDOM");bZ.async="false";bZ.loadXML(b1)}}catch(b2){bZ=aB}if(!bZ||!bZ.documentElement||bZ.getElementsByTagName("parsererror").length){bG.error("Invalid XML: "+b1)}return bZ},noop:function(){},globalEval:function(e){if(e&&aa.test(e)){(a2.execScript||function(bZ){a2["eval"].call(a2,bZ)})(e)}},camelCase:function(e){return e.replace(bP,"ms-").replace(aU,N)},nodeName:function(bZ,e){return bZ.nodeName&&bZ.nodeName.toLowerCase()===e.toLowerCase()},each:function(b3,b4,b0){var bZ,b1=0,b2=b3.length,e=b2===aB||bG.isFunction(b3);if(b0){if(e){for(bZ in b3){if(b4.apply(b3[bZ],b0)===false){break}}}else{for(;b1<b2;){if(b4.apply(b3[b1++],b0)===false){break}}}}else{if(e){for(bZ in b3){if(b4.call(b3[bZ],bZ,b3[bZ])===false){break}}}else{for(;b1<b2;){if(b4.call(b3[b1],b1,b3[b1++])===false){break}}}}return b3},trim:aO&&!aO.call("\uFEFF\xA0")?function(e){return e==null?"":aO.call(e)}:function(e){return e==null?"":(e+"").replace(C,"")},makeArray:function(e,b0){var b1,bZ=b0||[];if(e!=null){b1=bG.type(e);if(e.length==null||b1==="string"||b1==="function"||b1==="regexp"||bG.isWindow(e)){am.call(bZ,e)}else{bG.merge(bZ,e)}}return bZ},inArray:function(b1,bZ,b0){var e;if(bZ){if(aK){return aK.call(bZ,b1,b0)}e=bZ.length;b0=b0?b0<0?Math.max(0,e+b0):b0:0;for(;b0<e;b0++){if(b0 in bZ&&bZ[b0]===b1){return b0}}}return -1},merge:function(b2,b0){var e=b0.length,b1=b2.length,bZ=0;if(typeof e==="number"){for(;bZ<e;bZ++){b2[b1++]=b0[bZ]}}else{while(b0[bZ]!==aB){b2[b1++]=b0[bZ++]}}b2.length=b1;return b2},grep:function(bZ,b4,e){var b3,b0=[],b1=0,b2=bZ.length;e=!!e;for(;b1<b2;b1++){b3=!!b4(bZ[b1],b1);if(e!==b3){b0.push(bZ[b1])}}return b0},map:function(e,b5,b6){var b3,b4,b2=[],b0=0,bZ=e.length,b1=e instanceof bG||bZ!==aB&&typeof bZ==="number"&&((bZ>0&&e[0]&&e[bZ-1])||bZ===0||bG.isArray(e));if(b1){for(;b0<bZ;b0++){b3=b5(e[b0],b0,b6);if(b3!=null){b2[b2.length]=b3}}}else{for(b4 in e){b3=b5(e[b4],b4,b6);if(b3!=null){b2[b2.length]=b3}}}return b2.concat.apply([],b2)},guid:1,proxy:function(b2,b1){var b0,e,bZ;if(typeof b1==="string"){b0=b2[b1];b1=b2;b2=b0}if(!bG.isFunction(b2)){return aB}e=a4.call(arguments,2);bZ=function(){return b2.apply(b1,e.concat(a4.call(arguments)))};bZ.guid=b2.guid=b2.guid||bG.guid++;return bZ},access:function(e,b4,b7,b5,b2,b8,b6){var b0,b3=b7==null,b1=0,bZ=e.length;if(b7&&typeof b7==="object"){for(b1 in b7){bG.access(e,b4,b1,b7[b1],1,b8,b5)}b2=1}else{if(b5!==aB){b0=b6===aB&&bG.isFunction(b5);if(b3){if(b0){b0=b4;b4=function(ca,b9,cb){return b0.call(bG(ca),cb)}}else{b4.call(e,b5);b4=null}}if(b4){for(;b1<bZ;b1++){b4(e[b1],b7,b0?b5.call(e[b1],b1,b4(e[b1],b7)):b5,b6)}}b2=1}}return b2?e:b3?b4.call(e):bZ?b4(e[0],b7):b8},now:function(){return(new Date()).getTime()}});bG.ready.promise=function(b2){if(!af){af=bG.Deferred();if(o.readyState==="complete"){setTimeout(bG.ready,1)}else{if(o.addEventListener){o.addEventListener("DOMContentLoaded",aF,false);a2.addEventListener("load",bG.ready,false)}else{o.attachEvent("onreadystatechange",aF);a2.attachEvent("onload",bG.ready);var b1=false;try{b1=a2.frameElement==null&&o.documentElement}catch(b0){}if(b1&&b1.doScroll){(function bZ(){if(!bG.isReady){try{b1.doScroll("left")}catch(b3){return setTimeout(bZ,50)}bG.ready()}})()}}}}return af.promise(b2)};bG.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(bZ,e){Z["[object "+e+"]"]=e.toLowerCase()});w=bG(o);var bU={};function ac(bZ){var e=bU[bZ]={};bG.each(bZ.split(aV),function(b1,b0){e[b0]=true});return e}bG.Callbacks=function(b8){b8=typeof b8==="string"?(bU[b8]||ac(b8)):bG.extend({},b8);var b1,e,b2,b0,b3,b4,b5=[],b6=!b8.once&&[],bZ=function(b9){b1=b8.memory&&b9;e=true;b4=b0||0;b0=0;b3=b5.length;b2=true;for(;b5&&b4<b3;b4++){if(b5[b4].apply(b9[0],b9[1])===false&&b8.stopOnFalse){b1=false;break}}b2=false;if(b5){if(b6){if(b6.length){bZ(b6.shift())}}else{if(b1){b5=[]}else{b7.disable()}}}},b7={add:function(){if(b5){var ca=b5.length;(function b9(cb){bG.each(cb,function(cd,cc){var ce=bG.type(cc);if(ce==="function"){if(!b8.unique||!b7.has(cc)){b5.push(cc)}}else{if(cc&&cc.length&&ce!=="string"){b9(cc)}}})})(arguments);if(b2){b3=b5.length}else{if(b1){b0=ca;bZ(b1)}}}return this},remove:function(){if(b5){bG.each(arguments,function(cb,b9){var ca;while((ca=bG.inArray(b9,b5,ca))>-1){b5.splice(ca,1);if(b2){if(ca<=b3){b3--}if(ca<=b4){b4--}}}})}return this},has:function(b9){return bG.inArray(b9,b5)>-1},empty:function(){b5=[];return this},disable:function(){b5=b6=b1=aB;return this},disabled:function(){return !b5},lock:function(){b6=aB;if(!b1){b7.disable()}return this},locked:function(){return !b6},fireWith:function(ca,b9){b9=b9||[];b9=[ca,b9.slice?b9.slice():b9];if(b5&&(!e||b6)){if(b2){b6.push(b9)}else{bZ(b9)}}return this},fire:function(){b7.fireWith(this,arguments);return this},fired:function(){return !!e}};return b7};bG.extend({Deferred:function(b0){var bZ=[["resolve","done",bG.Callbacks("once memory"),"resolved"],["reject","fail",bG.Callbacks("once memory"),"rejected"],["notify","progress",bG.Callbacks("memory")]],b1="pending",b2={state:function(){return b1},always:function(){e.done(arguments).fail(arguments);return this},then:function(){var b3=arguments;return bG.Deferred(function(b4){bG.each(bZ,function(b6,b5){var b8=b5[0],b7=b3[b6];e[b5[1]](bG.isFunction(b7)?function(){var b9=b7.apply(this,arguments);if(b9&&bG.isFunction(b9.promise)){b9.promise().done(b4.resolve).fail(b4.reject).progress(b4.notify)}else{b4[b8+"With"](this===e?b4:this,[b9])}}:b4[b8])});b3=null}).promise()},promise:function(b3){return b3!=null?bG.extend(b3,b2):b2}},e={};b2.pipe=b2.then;bG.each(bZ,function(b4,b3){var b6=b3[2],b5=b3[3];b2[b3[1]]=b6.add;if(b5){b6.add(function(){b1=b5},bZ[b4^1][2].disable,bZ[2][2].lock)}e[b3[0]]=b6.fire;e[b3[0]+"With"]=b6.fireWith});b2.promise(e);if(b0){b0.call(e,e)}return e},when:function(b2){var b0=0,b4=a4.call(arguments),e=b4.length,bZ=e!==1||(b2&&bG.isFunction(b2.promise))?e:0,b7=bZ===1?b2:bG.Deferred(),b1=function(b9,ca,b8){return function(cb){ca[b9]=this;b8[b9]=arguments.length>1?a4.call(arguments):cb;if(b8===b6){b7.notifyWith(ca,b8)}else{if(!(--bZ)){b7.resolveWith(ca,b8)}}}},b6,b3,b5;if(e>1){b6=new Array(e);b3=new Array(e);b5=new Array(e);for(;b0<e;b0++){if(b4[b0]&&bG.isFunction(b4[b0].promise)){b4[b0].promise().done(b1(b0,b5,b4)).fail(b7.reject).progress(b1(b0,b3,b6))}else{--bZ}}}if(!bZ){b7.resolveWith(b5,b4)}return b7.promise()}});bG.support=(function(){var cb,ca,b8,b9,b2,b7,b6,b4,b3,b1,bZ,b0=o.createElement("div");b0.setAttribute("className","t");b0.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";ca=b0.getElementsByTagName("*");b8=b0.getElementsByTagName("a")[0];if(!ca||!b8||!ca.length){return{}}b9=o.createElement("select");b2=b9.appendChild(o.createElement("option"));b7=b0.getElementsByTagName("input")[0];b8.style.cssText="top:1px;float:left;opacity:.5";cb={leadingWhitespace:(b0.firstChild.nodeType===3),tbody:!b0.getElementsByTagName("tbody").length,htmlSerialize:!!b0.getElementsByTagName("link").length,style:/top/.test(b8.getAttribute("style")),hrefNormalized:(b8.getAttribute("href")==="/a"),opacity:/^0.5/.test(b8.style.opacity),cssFloat:!!b8.style.cssFloat,checkOn:(b7.value==="on"),optSelected:b2.selected,getSetAttribute:b0.className!=="t",enctype:!!o.createElement("form").enctype,html5Clone:o.createElement("nav").cloneNode(true).outerHTML!=="<:nav></:nav>",boxModel:(o.compatMode==="CSS1Compat"),submitBubbles:true,changeBubbles:true,focusinBubbles:false,deleteExpando:true,noCloneEvent:true,inlineBlockNeedsLayout:false,shrinkWrapBlocks:false,reliableMarginRight:true,boxSizingReliable:true,pixelPosition:false};b7.checked=true;cb.noCloneChecked=b7.cloneNode(true).checked;b9.disabled=true;cb.optDisabled=!b2.disabled;try{delete b0.test}catch(b5){cb.deleteExpando=false}if(!b0.addEventListener&&b0.attachEvent&&b0.fireEvent){b0.attachEvent("onclick",bZ=function(){cb.noCloneEvent=false});b0.cloneNode(true).fireEvent("onclick");b0.detachEvent("onclick",bZ)}b7=o.createElement("input");b7.value="t";b7.setAttribute("type","radio");cb.radioValue=b7.value==="t";b7.setAttribute("checked","checked");b7.setAttribute("name","t");b0.appendChild(b7);b6=o.createDocumentFragment();b6.appendChild(b0.lastChild);cb.checkClone=b6.cloneNode(true).cloneNode(true).lastChild.checked;cb.appendChecked=b7.checked;b6.removeChild(b7);b6.appendChild(b0);if(b0.attachEvent){for(b3 in {submit:true,change:true,focusin:true}){b4="on"+b3;b1=(b4 in b0);if(!b1){b0.setAttribute(b4,"return;");b1=(typeof b0[b4]==="function")}cb[b3+"Bubbles"]=b1}}bG(function(){var cc,cg,ce,cf,cd="padding:0;margin:0;border:0;display:block;overflow:hidden;",e=o.getElementsByTagName("body")[0];if(!e){return}cc=o.createElement("div");cc.style.cssText="visibility:hidden;border:0;width:0;height:0;position:static;top:0;margin-top:1px";e.insertBefore(cc,e.firstChild);cg=o.createElement("div");cc.appendChild(cg);cg.innerHTML="<table><tr><td></td><td>t</td></tr></table>";ce=cg.getElementsByTagName("td");ce[0].style.cssText="padding:0;margin:0;border:0;display:none";b1=(ce[0].offsetHeight===0);ce[0].style.display="";ce[1].style.display="none";cb.reliableHiddenOffsets=b1&&(ce[0].offsetHeight===0);cg.innerHTML="";cg.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%;";cb.boxSizing=(cg.offsetWidth===4);cb.doesNotIncludeMarginInBodyOffset=(e.offsetTop!==1);if(a2.getComputedStyle){cb.pixelPosition=(a2.getComputedStyle(cg,null)||{}).top!=="1%";cb.boxSizingReliable=(a2.getComputedStyle(cg,null)||{width:"4px"}).width==="4px";cf=o.createElement("div");cf.style.cssText=cg.style.cssText=cd;cf.style.marginRight=cf.style.width="0";cg.style.width="1px";cg.appendChild(cf);cb.reliableMarginRight=!parseFloat((a2.getComputedStyle(cf,null)||{}).marginRight)}if(typeof cg.style.zoom!=="undefined"){cg.innerHTML="";cg.style.cssText=cd+"width:1px;padding:1px;display:inline;zoom:1";cb.inlineBlockNeedsLayout=(cg.offsetWidth===3);cg.style.display="block";cg.style.overflow="visible";cg.innerHTML="<div></div>";cg.firstChild.style.width="5px";cb.shrinkWrapBlocks=(cg.offsetWidth!==3);cc.style.zoom=1}e.removeChild(cc);cc=cg=ce=cf=null});b6.removeChild(b0);ca=b8=b9=b2=b7=b6=b0=null;return cb})();var bt=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,aL=/([A-Z])/g;bG.extend({cache:{},deletedIds:[],uuid:0,expando:"jQuery"+(bG.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:true,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:true},hasData:function(e){e=e.nodeType?bG.cache[e[bG.expando]]:e[bG.expando];return !!e&&!O(e)},data:function(b1,bZ,b3,b2){if(!bG.acceptData(b1)){return}var b4,b6,b7=bG.expando,b5=typeof bZ==="string",b8=b1.nodeType,e=b8?bG.cache:b1,b0=b8?b1[b7]:b1[b7]&&b7;if((!b0||!e[b0]||(!b2&&!e[b0].data))&&b5&&b3===aB){return}if(!b0){if(b8){b1[b7]=b0=bG.deletedIds.pop()||bG.guid++}else{b0=b7}}if(!e[b0]){e[b0]={};if(!b8){e[b0].toJSON=bG.noop}}if(typeof bZ==="object"||typeof bZ==="function"){if(b2){e[b0]=bG.extend(e[b0],bZ)}else{e[b0].data=bG.extend(e[b0].data,bZ)}}b4=e[b0];if(!b2){if(!b4.data){b4.data={}}b4=b4.data}if(b3!==aB){b4[bG.camelCase(bZ)]=b3}if(b5){b6=b4[bZ];if(b6==null){b6=b4[bG.camelCase(bZ)]}}else{b6=b4}return b6},removeData:function(b1,bZ,b2){if(!bG.acceptData(b1)){return}var b5,b4,b3,b6=b1.nodeType,e=b6?bG.cache:b1,b0=b6?b1[bG.expando]:bG.expando;if(!e[b0]){return}if(bZ){b5=b2?e[b0]:e[b0].data;if(b5){if(!bG.isArray(bZ)){if(bZ in b5){bZ=[bZ]}else{bZ=bG.camelCase(bZ);if(bZ in b5){bZ=[bZ]}else{bZ=bZ.split(" ")}}}for(b4=0,b3=bZ.length;b4<b3;b4++){delete b5[bZ[b4]]}if(!(b2?O:bG.isEmptyObject)(b5)){return}}}if(!b2){delete e[b0].data;if(!O(e[b0])){return}}if(b6){bG.cleanData([b1],true)}else{if(bG.support.deleteExpando||e!=e.window){delete e[b0]}else{e[b0]=null}}},_data:function(bZ,e,b0){return bG.data(bZ,e,b0,true)},acceptData:function(bZ){var e=bZ.nodeName&&bG.noData[bZ.nodeName.toLowerCase()];return !e||e!==true&&bZ.getAttribute("classid")===e}});bG.fn.extend({data:function(b7,b6){var b2,bZ,b5,e,b1,b0=this[0],b4=0,b3=null;if(b7===aB){if(this.length){b3=bG.data(b0);if(b0.nodeType===1&&!bG._data(b0,"parsedAttrs")){b5=b0.attributes;for(b1=b5.length;b4<b1;b4++){e=b5[b4].name;if(!e.indexOf("data-")){e=bG.camelCase(e.substring(5));bv(b0,e,b3[e])}}bG._data(b0,"parsedAttrs",true)}}return b3}if(typeof b7==="object"){return this.each(function(){bG.data(this,b7)})}b2=b7.split(".",2);b2[1]=b2[1]?"."+b2[1]:"";bZ=b2[1]+"!";return bG.access(this,function(b8){if(b8===aB){b3=this.triggerHandler("getData"+bZ,[b2[0]]);if(b3===aB&&b0){b3=bG.data(b0,b7);b3=bv(b0,b7,b3)}return b3===aB&&b2[1]?this.data(b2[0]):b3}b2[1]=b8;this.each(function(){var b9=bG(this);b9.triggerHandler("setData"+bZ,b2);bG.data(this,b7,b8);b9.triggerHandler("changeData"+bZ,b2)})},null,b6,arguments.length>1,null,false)},removeData:function(e){return this.each(function(){bG.removeData(this,e)})}});function bv(b1,b0,b2){if(b2===aB&&b1.nodeType===1){var bZ="data-"+b0.replace(aL,"-$1").toLowerCase();b2=b1.getAttribute(bZ);if(typeof b2==="string"){try{b2=b2==="true"?true:b2==="false"?false:b2==="null"?null:+b2+""===b2?+b2:bt.test(b2)?bG.parseJSON(b2):b2}catch(b3){}bG.data(b1,b0,b2)}else{b2=aB}}return b2}function O(bZ){var e;for(e in bZ){if(e==="data"&&bG.isEmptyObject(bZ[e])){continue}if(e!=="toJSON"){return false}}return true}bG.extend({queue:function(b0,bZ,b1){var e;if(b0){bZ=(bZ||"fx")+"queue";e=bG._data(b0,bZ);if(b1){if(!e||bG.isArray(b1)){e=bG._data(b0,bZ,bG.makeArray(b1))}else{e.push(b1)}}return e||[]}},dequeue:function(b3,b2){b2=b2||"fx";var bZ=bG.queue(b3,b2),b4=bZ.length,b1=bZ.shift(),e=bG._queueHooks(b3,b2),b0=function(){bG.dequeue(b3,b2)};if(b1==="inprogress"){b1=bZ.shift();b4--}if(b1){if(b2==="fx"){bZ.unshift("inprogress")}delete e.stop;b1.call(b3,b0,e)}if(!b4&&e){e.empty.fire()}},_queueHooks:function(b0,bZ){var e=bZ+"queueHooks";return bG._data(b0,e)||bG._data(b0,e,{empty:bG.Callbacks("once memory").add(function(){bG.removeData(b0,bZ+"queue",true);bG.removeData(b0,e,true)})})}});bG.fn.extend({queue:function(e,bZ){var b0=2;if(typeof e!=="string"){bZ=e;e="fx";b0--}if(arguments.length<b0){return bG.queue(this[0],e)}return bZ===aB?this:this.each(function(){var b1=bG.queue(this,e,bZ);bG._queueHooks(this,e);if(e==="fx"&&b1[0]!=="inprogress"){bG.dequeue(this,e)}})},dequeue:function(e){return this.each(function(){bG.dequeue(this,e)})},delay:function(bZ,e){bZ=bG.fx?bG.fx.speeds[bZ]||bZ:bZ;e=e||"fx";return this.queue(e,function(b1,b0){var b2=setTimeout(b1,bZ);b0.stop=function(){clearTimeout(b2)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(b0,b4){var bZ,b1=1,b5=bG.Deferred(),b3=this,e=this.length,b2=function(){if(!(--b1)){b5.resolveWith(b3,[b3])}};if(typeof b0!=="string"){b4=b0;b0=aB}b0=b0||"fx";while(e--){bZ=bG._data(b3[e],b0+"queueHooks");if(bZ&&bZ.empty){b1++;bZ.empty.add(b2)}}b2();return b5.promise(b4)}});var a7,bV,n,bJ=/[\t\r\n]/g,ai=/\r/g,j=/^(?:button|input)$/i,aA=/^(?:button|input|object|select|textarea)$/i,D=/^a(?:rea|)$/i,M=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,bL=bG.support.getSetAttribute;bG.fn.extend({attr:function(e,bZ){return bG.access(this,bG.attr,e,bZ,arguments.length>1)},removeAttr:function(e){return this.each(function(){bG.removeAttr(this,e)})},prop:function(e,bZ){return bG.access(this,bG.prop,e,bZ,arguments.length>1)},removeProp:function(e){e=bG.propFix[e]||e;return this.each(function(){try{this[e]=aB;delete this[e]}catch(bZ){}})},addClass:function(b2){var b4,b0,bZ,b1,b3,b5,e;if(bG.isFunction(b2)){return this.each(function(b6){bG(this).addClass(b2.call(this,b6,this.className))})}if(b2&&typeof b2==="string"){b4=b2.split(aV);for(b0=0,bZ=this.length;b0<bZ;b0++){b1=this[b0];if(b1.nodeType===1){if(!b1.className&&b4.length===1){b1.className=b2}else{b3=" "+b1.className+" ";for(b5=0,e=b4.length;b5<e;b5++){if(b3.indexOf(" "+b4[b5]+" ")<0){b3+=b4[b5]+" "}}b1.className=bG.trim(b3)}}}}return this},removeClass:function(b4){var b1,b2,b3,b5,bZ,b0,e;if(bG.isFunction(b4)){return this.each(function(b6){bG(this).removeClass(b4.call(this,b6,this.className))})}if((b4&&typeof b4==="string")||b4===aB){b1=(b4||"").split(aV);for(b0=0,e=this.length;b0<e;b0++){b3=this[b0];if(b3.nodeType===1&&b3.className){b2=(" "+b3.className+" ").replace(bJ," ");for(b5=0,bZ=b1.length;b5<bZ;b5++){while(b2.indexOf(" "+b1[b5]+" ")>=0){b2=b2.replace(" "+b1[b5]+" "," ")}}b3.className=b4?bG.trim(b2):""}}}return this},toggleClass:function(b1,bZ){var b0=typeof b1,e=typeof bZ==="boolean";if(bG.isFunction(b1)){return this.each(function(b2){bG(this).toggleClass(b1.call(this,b2,this.className,bZ),bZ)})}return this.each(function(){if(b0==="string"){var b4,b3=0,b2=bG(this),b5=bZ,b6=b1.split(aV);while((b4=b6[b3++])){b5=e?b5:!b2.hasClass(b4);b2[b5?"addClass":"removeClass"](b4)}}else{if(b0==="undefined"||b0==="boolean"){if(this.className){bG._data(this,"__className__",this.className)}this.className=this.className||b1===false?"":bG._data(this,"__className__")||""}}})},hasClass:function(e){var b1=" "+e+" ",b0=0,bZ=this.length;for(;b0<bZ;b0++){if(this[b0].nodeType===1&&(" "+this[b0].className+" ").replace(bJ," ").indexOf(b1)>=0){return true}}return false},val:function(b1){var e,bZ,b2,b0=this[0];if(!arguments.length){if(b0){e=bG.valHooks[b0.type]||bG.valHooks[b0.nodeName.toLowerCase()];if(e&&"get" in e&&(bZ=e.get(b0,"value"))!==aB){return bZ}bZ=b0.value;return typeof bZ==="string"?bZ.replace(ai,""):bZ==null?"":bZ}return}b2=bG.isFunction(b1);return this.each(function(b4){var b5,b3=bG(this);if(this.nodeType!==1){return}if(b2){b5=b1.call(this,b4,b3.val())}else{b5=b1}if(b5==null){b5=""}else{if(typeof b5==="number"){b5+=""}else{if(bG.isArray(b5)){b5=bG.map(b5,function(b6){return b6==null?"":b6+""})}}}e=bG.valHooks[this.type]||bG.valHooks[this.nodeName.toLowerCase()];if(!e||!("set" in e)||e.set(this,b5,"value")===aB){this.value=b5}})}});bG.extend({valHooks:{option:{get:function(e){var bZ=e.attributes.value;return !bZ||bZ.specified?e.value:e.text}},select:{get:function(e){var b4,b0,b6=e.options,b2=e.selectedIndex,b1=e.type==="select-one"||b2<0,b5=b1?null:[],b3=b1?b2+1:b6.length,bZ=b2<0?b3:b1?b2:0;for(;bZ<b3;bZ++){b0=b6[bZ];if((b0.selected||bZ===b2)&&(bG.support.optDisabled?!b0.disabled:b0.getAttribute("disabled")===null)&&(!b0.parentNode.disabled||!bG.nodeName(b0.parentNode,"optgroup"))){b4=bG(b0).val();if(b1){return b4}b5.push(b4)}}return b5},set:function(bZ,b0){var e=bG.makeArray(b0);bG(bZ).find("option").each(function(){this.selected=bG.inArray(bG(this).val(),e)>=0});if(!e.length){bZ.selectedIndex=-1}return e}}},attrFn:{},attr:function(b4,b1,b5,b3){var b0,e,b2,bZ=b4.nodeType;if(!b4||bZ===3||bZ===8||bZ===2){return}if(b3&&bG.isFunction(bG.fn[b1])){return bG(b4)[b1](b5)}if(typeof b4.getAttribute==="undefined"){return bG.prop(b4,b1,b5)}b2=bZ!==1||!bG.isXMLDoc(b4);if(b2){b1=b1.toLowerCase();e=bG.attrHooks[b1]||(M.test(b1)?bV:a7)}if(b5!==aB){if(b5===null){bG.removeAttr(b4,b1);return}else{if(e&&"set" in e&&b2&&(b0=e.set(b4,b5,b1))!==aB){return b0}else{b4.setAttribute(b1,b5+"");return b5}}}else{if(e&&"get" in e&&b2&&(b0=e.get(b4,b1))!==null){return b0}else{b0=b4.getAttribute(b1);return b0===null?aB:b0}}},removeAttr:function(b1,b3){var b2,b4,bZ,e,b0=0;if(b3&&b1.nodeType===1){b4=b3.split(aV);for(;b0<b4.length;b0++){bZ=b4[b0];if(bZ){b2=bG.propFix[bZ]||bZ;e=M.test(bZ);if(!e){bG.attr(b1,bZ,"")}b1.removeAttribute(bL?bZ:b2);if(e&&b2 in b1){b1[b2]=false}}}}},attrHooks:{type:{set:function(e,bZ){if(j.test(e.nodeName)&&e.parentNode){bG.error("type property can't be changed")}else{if(!bG.support.radioValue&&bZ==="radio"&&bG.nodeName(e,"input")){var b0=e.value;e.setAttribute("type",bZ);if(b0){e.value=b0}return bZ}}}},value:{get:function(bZ,e){if(a7&&bG.nodeName(bZ,"button")){return a7.get(bZ,e)}return e in bZ?bZ.value:null},set:function(bZ,b0,e){if(a7&&bG.nodeName(bZ,"button")){return a7.set(bZ,b0,e)}bZ.value=b0}}},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(b3,b1,b4){var b0,e,b2,bZ=b3.nodeType;if(!b3||bZ===3||bZ===8||bZ===2){return}b2=bZ!==1||!bG.isXMLDoc(b3);if(b2){b1=bG.propFix[b1]||b1;e=bG.propHooks[b1]}if(b4!==aB){if(e&&"set" in e&&(b0=e.set(b3,b4,b1))!==aB){return b0}else{return(b3[b1]=b4)}}else{if(e&&"get" in e&&(b0=e.get(b3,b1))!==null){return b0}else{return b3[b1]}}},propHooks:{tabIndex:{get:function(bZ){var e=bZ.getAttributeNode("tabindex");return e&&e.specified?parseInt(e.value,10):aA.test(bZ.nodeName)||D.test(bZ.nodeName)&&bZ.href?0:aB}}}});bV={get:function(bZ,e){var b1,b0=bG.prop(bZ,e);return b0===true||typeof b0!=="boolean"&&(b1=bZ.getAttributeNode(e))&&b1.nodeValue!==false?e.toLowerCase():aB},set:function(bZ,b1,e){var b0;if(b1===false){bG.removeAttr(bZ,e)}else{b0=bG.propFix[e]||e;if(b0 in bZ){bZ[b0]=true}bZ.setAttribute(e,e.toLowerCase())}return e}};if(!bL){n={name:true,id:true,coords:true};a7=bG.valHooks.button={get:function(b0,bZ){var e;e=b0.getAttributeNode(bZ);return e&&(n[bZ]?e.value!=="":e.specified)?e.value:aB},set:function(b0,b1,bZ){var e=b0.getAttributeNode(bZ);if(!e){e=o.createAttribute(bZ);b0.setAttributeNode(e)}return(e.value=b1+"")}};bG.each(["width","height"],function(bZ,e){bG.attrHooks[e]=bG.extend(bG.attrHooks[e],{set:function(b0,b1){if(b1===""){b0.setAttribute(e,"auto");return b1}}})});bG.attrHooks.contenteditable={get:a7.get,set:function(bZ,b0,e){if(b0===""){b0="false"}a7.set(bZ,b0,e)}}}if(!bG.support.hrefNormalized){bG.each(["href","src","width","height"],function(bZ,e){bG.attrHooks[e]=bG.extend(bG.attrHooks[e],{get:function(b1){var b0=b1.getAttribute(e,2);return b0===null?aB:b0}})})}if(!bG.support.style){bG.attrHooks.style={get:function(e){return e.style.cssText.toLowerCase()||aB},set:function(e,bZ){return(e.style.cssText=bZ+"")}}}if(!bG.support.optSelected){bG.propHooks.selected=bG.extend(bG.propHooks.selected,{get:function(bZ){var e=bZ.parentNode;if(e){e.selectedIndex;if(e.parentNode){e.parentNode.selectedIndex}}return null}})}if(!bG.support.enctype){bG.propFix.enctype="encoding"}if(!bG.support.checkOn){bG.each(["radio","checkbox"],function(){bG.valHooks[this]={get:function(e){return e.getAttribute("value")===null?"on":e.value}}})}bG.each(["radio","checkbox"],function(){bG.valHooks[this]=bG.extend(bG.valHooks[this],{set:function(e,bZ){if(bG.isArray(bZ)){return(e.checked=bG.inArray(bG(e).val(),bZ)>=0)}}})});var bE=/^(?:textarea|input|select)$/i,br=/^([^\.]*|)(?:\.(.+)|)$/,ba=/(?:^|\s)hover(\.\S+|)\b/,a3=/^key/,bK=/^(?:mouse|contextmenu)|click/,by=/^(?:focusinfocus|focusoutblur)$/,aq=function(e){return bG.event.special.hover?e:e.replace(ba,"mouseenter$1 mouseleave$1")};bG.event={add:function(b1,b5,cc,b3,b2){var b6,b4,cd,cb,ca,b8,e,b9,bZ,b0,b7;if(b1.nodeType===3||b1.nodeType===8||!b5||!cc||!(b6=bG._data(b1))){return}if(cc.handler){bZ=cc;cc=bZ.handler;b2=bZ.selector}if(!cc.guid){cc.guid=bG.guid++}cd=b6.events;if(!cd){b6.events=cd={}}b4=b6.handle;if(!b4){b6.handle=b4=function(ce){return typeof bG!=="undefined"&&(!ce||bG.event.triggered!==ce.type)?bG.event.dispatch.apply(b4.elem,arguments):aB};b4.elem=b1}b5=bG.trim(aq(b5)).split(" ");for(cb=0;cb<b5.length;cb++){ca=br.exec(b5[cb])||[];b8=ca[1];e=(ca[2]||"").split(".").sort();b7=bG.event.special[b8]||{};b8=(b2?b7.delegateType:b7.bindType)||b8;b7=bG.event.special[b8]||{};b9=bG.extend({type:b8,origType:ca[1],data:b3,handler:cc,guid:cc.guid,selector:b2,needsContext:b2&&bG.expr.match.needsContext.test(b2),namespace:e.join(".")},bZ);b0=cd[b8];if(!b0){b0=cd[b8]=[];b0.delegateCount=0;if(!b7.setup||b7.setup.call(b1,b3,e,b4)===false){if(b1.addEventListener){b1.addEventListener(b8,b4,false)}else{if(b1.attachEvent){b1.attachEvent("on"+b8,b4)}}}}if(b7.add){b7.add.call(b1,b9);if(!b9.handler.guid){b9.handler.guid=cc.guid}}if(b2){b0.splice(b0.delegateCount++,0,b9)}else{b0.push(b9)}bG.event.global[b8]=true}b1=null},global:{},remove:function(b1,b6,cc,b2,b5){var cd,ce,b9,b0,bZ,b3,b4,cb,b8,e,ca,b7=bG.hasData(b1)&&bG._data(b1);if(!b7||!(cb=b7.events)){return}b6=bG.trim(aq(b6||"")).split(" ");for(cd=0;cd<b6.length;cd++){ce=br.exec(b6[cd])||[];b9=b0=ce[1];bZ=ce[2];if(!b9){for(b9 in cb){bG.event.remove(b1,b9+b6[cd],cc,b2,true)}continue}b8=bG.event.special[b9]||{};b9=(b2?b8.delegateType:b8.bindType)||b9;e=cb[b9]||[];b3=e.length;bZ=bZ?new RegExp("(^|\\.)"+bZ.split(".").sort().join("\\.(?:.*\\.|)")+"(\\.|$)"):null;for(b4=0;b4<e.length;b4++){ca=e[b4];if((b5||b0===ca.origType)&&(!cc||cc.guid===ca.guid)&&(!bZ||bZ.test(ca.namespace))&&(!b2||b2===ca.selector||b2==="**"&&ca.selector)){e.splice(b4--,1);if(ca.selector){e.delegateCount--}if(b8.remove){b8.remove.call(b1,ca)}}}if(e.length===0&&b3!==e.length){if(!b8.teardown||b8.teardown.call(b1,bZ,b7.handle)===false){bG.removeEvent(b1,b9,b7.handle)}delete cb[b9]}}if(bG.isEmptyObject(cb)){delete b7.handle;bG.removeData(b1,"events",true)}},customEvent:{getData:true,setData:true,changeData:true},trigger:function(bZ,b6,b4,cd){if(b4&&(b4.nodeType===3||b4.nodeType===8)){return}var e,b1,b7,cb,b3,b2,b9,b8,b5,cc,ca=bZ.type||bZ,b0=[];if(by.test(ca+bG.event.triggered)){return}if(ca.indexOf("!")>=0){ca=ca.slice(0,-1);b1=true}if(ca.indexOf(".")>=0){b0=ca.split(".");ca=b0.shift();b0.sort()}if((!b4||bG.event.customEvent[ca])&&!bG.event.global[ca]){return}bZ=typeof bZ==="object"?bZ[bG.expando]?bZ:new bG.Event(ca,bZ):new bG.Event(ca);bZ.type=ca;bZ.isTrigger=true;bZ.exclusive=b1;bZ.namespace=b0.join(".");bZ.namespace_re=bZ.namespace?new RegExp("(^|\\.)"+b0.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;b2=ca.indexOf(":")<0?"on"+ca:"";if(!b4){e=bG.cache;for(b7 in e){if(e[b7].events&&e[b7].events[ca]){bG.event.trigger(bZ,b6,e[b7].handle.elem,true)}}return}bZ.result=aB;if(!bZ.target){bZ.target=b4}b6=b6!=null?bG.makeArray(b6):[];b6.unshift(bZ);b9=bG.event.special[ca]||{};if(b9.trigger&&b9.trigger.apply(b4,b6)===false){return}b5=[[b4,b9.bindType||ca]];if(!cd&&!b9.noBubble&&!bG.isWindow(b4)){cc=b9.delegateType||ca;cb=by.test(cc+ca)?b4:b4.parentNode;for(b3=b4;cb;cb=cb.parentNode){b5.push([cb,cc]);b3=cb}if(b3===(b4.ownerDocument||o)){b5.push([b3.defaultView||b3.parentWindow||a2,cc])}}for(b7=0;b7<b5.length&&!bZ.isPropagationStopped();b7++){cb=b5[b7][0];bZ.type=b5[b7][1];b8=(bG._data(cb,"events")||{})[bZ.type]&&bG._data(cb,"handle");if(b8){b8.apply(cb,b6)}b8=b2&&cb[b2];if(b8&&bG.acceptData(cb)&&b8.apply&&b8.apply(cb,b6)===false){bZ.preventDefault()}}bZ.type=ca;if(!cd&&!bZ.isDefaultPrevented()){if((!b9._default||b9._default.apply(b4.ownerDocument,b6)===false)&&!(ca==="click"&&bG.nodeName(b4,"a"))&&bG.acceptData(b4)){if(b2&&b4[ca]&&((ca!=="focus"&&ca!=="blur")||bZ.target.offsetWidth!==0)&&!bG.isWindow(b4)){b3=b4[b2];if(b3){b4[b2]=null}bG.event.triggered=ca;b4[ca]();bG.event.triggered=aB;if(b3){b4[b2]=b3}}}}return bZ.result},dispatch:function(e){e=bG.event.fix(e||a2.event);var b5,b4,ce,b8,b7,bZ,b6,cc,b1,cd,b2=((bG._data(this,"events")||{})[e.type]||[]),b3=b2.delegateCount,ca=a4.call(arguments),b0=!e.exclusive&&!e.namespace,b9=bG.event.special[e.type]||{},cb=[];ca[0]=e;e.delegateTarget=this;if(b9.preDispatch&&b9.preDispatch.call(this,e)===false){return}if(b3&&!(e.button&&e.type==="click")){for(ce=e.target;ce!=this;ce=ce.parentNode||this){if(ce.disabled!==true||e.type!=="click"){b7={};b6=[];for(b5=0;b5<b3;b5++){cc=b2[b5];b1=cc.selector;if(b7[b1]===aB){b7[b1]=cc.needsContext?bG(b1,this).index(ce)>=0:bG.find(b1,this,null,[ce]).length}if(b7[b1]){b6.push(cc)}}if(b6.length){cb.push({elem:ce,matches:b6})}}}}if(b2.length>b3){cb.push({elem:this,matches:b2.slice(b3)})}for(b5=0;b5<cb.length&&!e.isPropagationStopped();b5++){bZ=cb[b5];e.currentTarget=bZ.elem;for(b4=0;b4<bZ.matches.length&&!e.isImmediatePropagationStopped();b4++){cc=bZ.matches[b4];if(b0||(!e.namespace&&!cc.namespace)||e.namespace_re&&e.namespace_re.test(cc.namespace)){e.data=cc.data;e.handleObj=cc;b8=((bG.event.special[cc.origType]||{}).handle||cc.handler).apply(bZ.elem,ca);if(b8!==aB){e.result=b8;if(b8===false){e.preventDefault();e.stopPropagation()}}}}}if(b9.postDispatch){b9.postDispatch.call(this,e)}return e.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(bZ,e){if(bZ.which==null){bZ.which=e.charCode!=null?e.charCode:e.keyCode}return bZ}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(b1,b0){var b2,b3,e,bZ=b0.button,b4=b0.fromElement;if(b1.pageX==null&&b0.clientX!=null){b2=b1.target.ownerDocument||o;b3=b2.documentElement;e=b2.body;b1.pageX=b0.clientX+(b3&&b3.scrollLeft||e&&e.scrollLeft||0)-(b3&&b3.clientLeft||e&&e.clientLeft||0);b1.pageY=b0.clientY+(b3&&b3.scrollTop||e&&e.scrollTop||0)-(b3&&b3.clientTop||e&&e.clientTop||0)}if(!b1.relatedTarget&&b4){b1.relatedTarget=b4===b1.target?b0.toElement:b4}if(!b1.which&&bZ!==aB){b1.which=(bZ&1?1:(bZ&2?3:(bZ&4?2:0)))}return b1}},fix:function(b0){if(b0[bG.expando]){return b0}var bZ,b3,e=b0,b1=bG.event.fixHooks[b0.type]||{},b2=b1.props?this.props.concat(b1.props):this.props;b0=bG.Event(e);for(bZ=b2.length;bZ;){b3=b2[--bZ];b0[b3]=e[b3]}if(!b0.target){b0.target=e.srcElement||o}if(b0.target.nodeType===3){b0.target=b0.target.parentNode}b0.metaKey=!!b0.metaKey;return b1.filter?b1.filter(b0,e):b0},special:{load:{noBubble:true},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(b0,bZ,e){if(bG.isWindow(this)){this.onbeforeunload=e}},teardown:function(bZ,e){if(this.onbeforeunload===e){this.onbeforeunload=null}}}},simulate:function(b0,b2,b1,bZ){var b3=bG.extend(new bG.Event(),b1,{type:b0,isSimulated:true,originalEvent:{}});if(bZ){bG.event.trigger(b3,null,b2)}else{bG.event.dispatch.call(b2,b3)}if(b3.isDefaultPrevented()){b1.preventDefault()}}};bG.event.handle=bG.event.dispatch;bG.removeEvent=o.removeEventListener?function(bZ,e,b0){if(bZ.removeEventListener){bZ.removeEventListener(e,b0,false)}}:function(b0,bZ,b1){var e="on"+bZ;if(b0.detachEvent){if(typeof b0[e]==="undefined"){b0[e]=null}b0.detachEvent(e,b1)}};bG.Event=function(bZ,e){if(!(this instanceof bG.Event)){return new bG.Event(bZ,e)}if(bZ&&bZ.type){this.originalEvent=bZ;this.type=bZ.type;this.isDefaultPrevented=(bZ.defaultPrevented||bZ.returnValue===false||bZ.getPreventDefault&&bZ.getPreventDefault())?R:X}else{this.type=bZ}if(e){bG.extend(this,e)}this.timeStamp=bZ&&bZ.timeStamp||bG.now();this[bG.expando]=true};function X(){return false}function R(){return true}bG.Event.prototype={preventDefault:function(){this.isDefaultPrevented=R;var bZ=this.originalEvent;if(!bZ){return}if(bZ.preventDefault){bZ.preventDefault()}else{bZ.returnValue=false}},stopPropagation:function(){this.isPropagationStopped=R;var bZ=this.originalEvent;if(!bZ){return}if(bZ.stopPropagation){bZ.stopPropagation()}bZ.cancelBubble=true},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=R;this.stopPropagation()},isDefaultPrevented:X,isPropagationStopped:X,isImmediatePropagationStopped:X};bG.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(bZ,e){bG.event.special[bZ]={delegateType:e,bindType:e,handle:function(b3){var b1,b5=this,b4=b3.relatedTarget,b2=b3.handleObj,b0=b2.selector;if(!b4||(b4!==b5&&!bG.contains(b5,b4))){b3.type=b2.origType;b1=b2.handler.apply(this,arguments);b3.type=e}return b1}}});if(!bG.support.submitBubbles){bG.event.special.submit={setup:function(){if(bG.nodeName(this,"form")){return false}bG.event.add(this,"click._submit keypress._submit",function(b1){var b0=b1.target,bZ=bG.nodeName(b0,"input")||bG.nodeName(b0,"button")?b0.form:aB;if(bZ&&!bG._data(bZ,"_submit_attached")){bG.event.add(bZ,"submit._submit",function(e){e._submit_bubble=true});bG._data(bZ,"_submit_attached",true)}})},postDispatch:function(e){if(e._submit_bubble){delete e._submit_bubble;if(this.parentNode&&!e.isTrigger){bG.event.simulate("submit",this.parentNode,e,true)}}},teardown:function(){if(bG.nodeName(this,"form")){return false}bG.event.remove(this,"._submit")}}}if(!bG.support.changeBubbles){bG.event.special.change={setup:function(){if(bE.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio"){bG.event.add(this,"propertychange._change",function(e){if(e.originalEvent.propertyName==="checked"){this._just_changed=true}});bG.event.add(this,"click._change",function(e){if(this._just_changed&&!e.isTrigger){this._just_changed=false}bG.event.simulate("change",this,e,true)})}return false}bG.event.add(this,"beforeactivate._change",function(b0){var bZ=b0.target;if(bE.test(bZ.nodeName)&&!bG._data(bZ,"_change_attached")){bG.event.add(bZ,"change._change",function(e){if(this.parentNode&&!e.isSimulated&&!e.isTrigger){bG.event.simulate("change",this.parentNode,e,true)}});bG._data(bZ,"_change_attached",true)}})},handle:function(bZ){var e=bZ.target;if(this!==e||bZ.isSimulated||bZ.isTrigger||(e.type!=="radio"&&e.type!=="checkbox")){return bZ.handleObj.handler.apply(this,arguments)}},teardown:function(){bG.event.remove(this,"._change");return !bE.test(this.nodeName)}}}if(!bG.support.focusinBubbles){bG.each({focus:"focusin",blur:"focusout"},function(b1,e){var bZ=0,b0=function(b2){bG.event.simulate(e,b2.target,bG.event.fix(b2),true)};bG.event.special[e]={setup:function(){if(bZ++===0){o.addEventListener(b1,b0,true)}},teardown:function(){if(--bZ===0){o.removeEventListener(b1,b0,true)}}}})}bG.fn.extend({on:function(b0,e,b3,b2,bZ){var b4,b1;if(typeof b0==="object"){if(typeof e!=="string"){b3=b3||e;e=aB}for(b1 in b0){this.on(b1,e,b3,b0[b1],bZ)}return this}if(b3==null&&b2==null){b2=e;b3=e=aB}else{if(b2==null){if(typeof e==="string"){b2=b3;b3=aB}else{b2=b3;b3=e;e=aB}}}if(b2===false){b2=X}else{if(!b2){return this}}if(bZ===1){b4=b2;b2=function(b5){bG().off(b5);return b4.apply(this,arguments)};b2.guid=b4.guid||(b4.guid=bG.guid++)}return this.each(function(){bG.event.add(this,b0,b2,b3,e)})},one:function(bZ,e,b1,b0){return this.on(bZ,e,b1,b0,1)},off:function(b0,e,b2){var bZ,b1;if(b0&&b0.preventDefault&&b0.handleObj){bZ=b0.handleObj;bG(b0.delegateTarget).off(bZ.namespace?bZ.origType+"."+bZ.namespace:bZ.origType,bZ.selector,bZ.handler);return this}if(typeof b0==="object"){for(b1 in b0){this.off(b1,e,b0[b1])}return this}if(e===false||typeof e==="function"){b2=e;e=aB}if(b2===false){b2=X}return this.each(function(){bG.event.remove(this,b0,b2,e)})},bind:function(e,b0,bZ){return this.on(e,null,b0,bZ)},unbind:function(e,bZ){return this.off(e,null,bZ)},live:function(e,b0,bZ){bG(this.context).on(e,this.selector,b0,bZ);return this},die:function(e,bZ){bG(this.context).off(e,this.selector||"**",bZ);return this},delegate:function(e,bZ,b1,b0){return this.on(bZ,e,b1,b0)},undelegate:function(e,bZ,b0){return arguments.length===1?this.off(e,"**"):this.off(bZ,e||"**",b0)},trigger:function(e,bZ){return this.each(function(){bG.event.trigger(e,bZ,this)})},triggerHandler:function(e,bZ){if(this[0]){return bG.event.trigger(e,bZ,this[0],true)}},toggle:function(b1){var bZ=arguments,e=b1.guid||bG.guid++,b0=0,b2=function(b3){var b4=(bG._data(this,"lastToggle"+b1.guid)||0)%b0;bG._data(this,"lastToggle"+b1.guid,b4+1);b3.preventDefault();return bZ[b4].apply(this,arguments)||false};b2.guid=e;while(b0<bZ.length){bZ[b0++].guid=e}return this.click(b2)},hover:function(e,bZ){return this.mouseenter(e).mouseleave(bZ||e)}});bG.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(bZ,e){bG.fn[e]=function(b1,b0){if(b0==null){b0=b1;b1=null}return arguments.length>0?this.on(e,null,b1,b0):this.trigger(e)};if(a3.test(e)){bG.event.fixHooks[e]=bG.event.keyHooks}if(bK.test(e)){bG.event.fixHooks[e]=bG.event.mouseHooks}}); /* * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function(cS,ch){var cX,ca,cL,b0,cm,cA,cd,cg,cc,cJ,b9=true,cu="undefined",cZ=("sizcache"+Math.random()).replace(".",""),b4=String,b8=cS.document,cb=b8.documentElement,cr=0,cf=0,cE=[].pop,cW=[].push,cl=[].slice,co=[].indexOf||function(c8){var c7=0,e=this.length;for(;c7<e;c7++){if(this[c7]===c8){return c7}}return -1},c1=function(e,c7){e[cZ]=c7==null||c7;return e},c5=function(){var e={},c7=[];return c1(function(c8,c9){if(c7.push(c8)>cL.cacheLength){delete e[c7.shift()]}return(e[c8+" "]=c9)},e)},cU=c5(),cV=c5(),cn=c5(),cy="[\\x20\\t\\r\\n\\f]",ck="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",ci=ck.replace("w","w#"),c4="([*^$|!~]?=)",cP="\\["+cy+"*("+ck+")"+cy+"*(?:"+c4+cy+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+ci+")|)|)"+cy+"*\\]",c6=":("+ck+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+cP+")|[^:]|\\\\.)*|.*))\\)|)",cz=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+cy+"*((?:-\\d)?\\d*)"+cy+"*\\)|)(?=[^-]|$)",cT=new RegExp("^"+cy+"+|((?:^|[^\\\\])(?:\\\\.)*)"+cy+"+$","g"),b5=new RegExp("^"+cy+"*,"+cy+"*"),cH=new RegExp("^"+cy+"*([\\x20\\t\\r\\n\\f>+~])"+cy+"*"),cM=new RegExp(c6),cO=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,cD=/^:not/,cR=/[\x20\t\r\n\f]*[+~]/,c0=/:not\($/,cs=/h\d/i,cN=/input|select|textarea|button/i,ct=/\\(?!\\)/g,cG={ID:new RegExp("^#("+ck+")"),CLASS:new RegExp("^\\.("+ck+")"),NAME:new RegExp("^\\[name=['\"]?("+ck+")['\"]?\\]"),TAG:new RegExp("^("+ck.replace("w","w*")+")"),ATTR:new RegExp("^"+cP),PSEUDO:new RegExp("^"+c6),POS:new RegExp(cz,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+cy+"*(even|odd|(([+-]|)(\\d*)n|)"+cy+"*(?:([+-]|)"+cy+"*(\\d+)|))"+cy+"*\\)|)","i"),needsContext:new RegExp("^"+cy+"*[>+~]|"+cz,"i")},cK=function(c7){var c9=b8.createElement("div");try{return c7(c9)}catch(c8){return false}finally{c9=null}},b7=cK(function(e){e.appendChild(b8.createComment(""));return !e.getElementsByTagName("*").length}),cC=cK(function(e){e.innerHTML="<a href='#'></a>";return e.firstChild&&typeof e.firstChild.getAttribute!==cu&&e.firstChild.getAttribute("href")==="#"}),cq=cK(function(c7){c7.innerHTML="<select></select>";var e=typeof c7.lastChild.getAttribute("multiple");return e!=="boolean"&&e!=="string"}),cB=cK(function(e){e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>";if(!e.getElementsByClassName||!e.getElementsByClassName("e").length){return false}e.lastChild.className="e";return e.getElementsByClassName("e").length===2}),bZ=cK(function(c7){c7.id=cZ+0;c7.innerHTML="<a name='"+cZ+"'></a><div name='"+cZ+"'></div>";cb.insertBefore(c7,cb.firstChild);var e=b8.getElementsByName&&b8.getElementsByName(cZ).length===2+b8.getElementsByName(cZ+0).length;ca=!b8.getElementById(cZ);cb.removeChild(c7);return e});try{cl.call(cb.childNodes,0)[0].nodeType}catch(c3){cl=function(c7){var c8,e=[];for(;(c8=this[c7]);c7++){e.push(c8)}return e}}function cQ(c9,e,db,de){db=db||[];e=e||b8;var dc,c7,dd,c8,da=e.nodeType;if(!c9||typeof c9!=="string"){return db}if(da!==1&&da!==9){return[]}dd=cm(e);if(!dd&&!de){if((dc=cO.exec(c9))){if((c8=dc[1])){if(da===9){c7=e.getElementById(c8);if(c7&&c7.parentNode){if(c7.id===c8){db.push(c7);return db}}else{return db}}else{if(e.ownerDocument&&(c7=e.ownerDocument.getElementById(c8))&&cA(e,c7)&&c7.id===c8){db.push(c7);return db}}}else{if(dc[2]){cW.apply(db,cl.call(e.getElementsByTagName(c9),0));return db}else{if((c8=dc[3])&&cB&&e.getElementsByClassName){cW.apply(db,cl.call(e.getElementsByClassName(c8),0));return db}}}}}return cY(c9.replace(cT,"$1"),e,db,de,dd)}cQ.matches=function(c7,e){return cQ(c7,null,null,e)};cQ.matchesSelector=function(e,c7){return cQ(c7,null,null,[e]).length>0};function cI(e){return function(c8){var c7=c8.nodeName.toLowerCase();return c7==="input"&&c8.type===e}}function b3(e){return function(c8){var c7=c8.nodeName.toLowerCase();return(c7==="input"||c7==="button")&&c8.type===e}}function cF(e){return c1(function(c7){c7=+c7;return c1(function(c8,dc){var da,c9=e([],c8.length,c7),db=c9.length;while(db--){if(c8[(da=c9[db])]){c8[da]=!(dc[da]=c8[da])}}})})}b0=cQ.getText=function(da){var c9,c7="",c8=0,e=da.nodeType;if(e){if(e===1||e===9||e===11){if(typeof da.textContent==="string"){return da.textContent}else{for(da=da.firstChild;da;da=da.nextSibling){c7+=b0(da)}}}else{if(e===3||e===4){return da.nodeValue}}}else{for(;(c9=da[c8]);c8++){c7+=b0(c9)}}return c7};cm=cQ.isXML=function(e){var c7=e&&(e.ownerDocument||e).documentElement;return c7?c7.nodeName!=="HTML":false};cA=cQ.contains=cb.contains?function(c7,e){var c9=c7.nodeType===9?c7.documentElement:c7,c8=e&&e.parentNode;return c7===c8||!!(c8&&c8.nodeType===1&&c9.contains&&c9.contains(c8))}:cb.compareDocumentPosition?function(c7,e){return e&&!!(c7.compareDocumentPosition(e)&16)}:function(c7,e){while((e=e.parentNode)){if(e===c7){return true}}return false};cQ.attr=function(c8,c7){var c9,e=cm(c8);if(!e){c7=c7.toLowerCase()}if((c9=cL.attrHandle[c7])){return c9(c8)}if(e||cq){return c8.getAttribute(c7)}c9=c8.getAttributeNode(c7);return c9?typeof c8[c7]==="boolean"?c8[c7]?c7:null:c9.specified?c9.value:null:null};cL=cQ.selectors={cacheLength:50,createPseudo:c1,match:cG,attrHandle:cC?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},find:{ID:ca?function(c9,c8,c7){if(typeof c8.getElementById!==cu&&!c7){var e=c8.getElementById(c9);return e&&e.parentNode?[e]:[]}}:function(c9,c8,c7){if(typeof c8.getElementById!==cu&&!c7){var e=c8.getElementById(c9);return e?e.id===c9||typeof e.getAttributeNode!==cu&&e.getAttributeNode("id").value===c9?[e]:ch:[]}},TAG:b7?function(e,c7){if(typeof c7.getElementsByTagName!==cu){return c7.getElementsByTagName(e)}}:function(e,da){var c9=da.getElementsByTagName(e);if(e==="*"){var db,c8=[],c7=0;for(;(db=c9[c7]);c7++){if(db.nodeType===1){c8.push(db)}}return c8}return c9},NAME:bZ&&function(e,c7){if(typeof c7.getElementsByName!==cu){return c7.getElementsByName(name)}},CLASS:cB&&function(c8,c7,e){if(typeof c7.getElementsByClassName!==cu&&!e){return c7.getElementsByClassName(c8)}}},relative:{">":{dir:"parentNode",first:true}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:true},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){e[1]=e[1].replace(ct,"");e[3]=(e[4]||e[5]||"").replace(ct,"");if(e[2]==="~="){e[3]=" "+e[3]+" "}return e.slice(0,4)},CHILD:function(e){e[1]=e[1].toLowerCase();if(e[1]==="nth"){if(!e[2]){cQ.error(e[0])}e[3]=+(e[3]?e[4]+(e[5]||1):2*(e[2]==="even"||e[2]==="odd"));e[4]=+((e[6]+e[7])||e[2]==="odd")}else{if(e[2]){cQ.error(e[0])}}return e},PSEUDO:function(c7){var c8,e;if(cG.CHILD.test(c7[0])){return null}if(c7[3]){c7[2]=c7[3]}else{if((c8=c7[4])){if(cM.test(c8)&&(e=b1(c8,true))&&(e=c8.indexOf(")",c8.length-e)-c8.length)){c8=c8.slice(0,e);c7[0]=c7[0].slice(0,e)}c7[2]=c8}}return c7.slice(0,3)}},filter:{ID:ca?function(e){e=e.replace(ct,"");return function(c7){return c7.getAttribute("id")===e}}:function(e){e=e.replace(ct,"");return function(c8){var c7=typeof c8.getAttributeNode!==cu&&c8.getAttributeNode("id");return c7&&c7.value===e}},TAG:function(e){if(e==="*"){return function(){return true}}e=e.replace(ct,"").toLowerCase();return function(c7){return c7.nodeName&&c7.nodeName.toLowerCase()===e}},CLASS:function(e){var c7=cU[cZ][e+" "];return c7||(c7=new RegExp("(^|"+cy+")"+e+"("+cy+"|$)"))&&cU(e,function(c8){return c7.test(c8.className||(typeof c8.getAttribute!==cu&&c8.getAttribute("class"))||"")})},ATTR:function(c8,c7,e){return function(db,da){var c9=cQ.attr(db,c8);if(c9==null){return c7==="!="}if(!c7){return true}c9+="";return c7==="="?c9===e:c7==="!="?c9!==e:c7==="^="?e&&c9.indexOf(e)===0:c7==="*="?e&&c9.indexOf(e)>-1:c7==="$="?e&&c9.substr(c9.length-e.length)===e:c7==="~="?(" "+c9+" ").indexOf(e)>-1:c7==="|="?c9===e||c9.substr(0,e.length+1)===e+"-":false}},CHILD:function(e,c8,c9,c7){if(e==="nth"){return function(dc){var db,dd,da=dc.parentNode;if(c9===1&&c7===0){return true}if(da){dd=0;for(db=da.firstChild;db;db=db.nextSibling){if(db.nodeType===1){dd++;if(dc===db){break}}}}dd-=c7;return dd===c9||(dd%c9===0&&dd/c9>=0)}}return function(db){var da=db;switch(e){case"only":case"first":while((da=da.previousSibling)){if(da.nodeType===1){return false}}if(e==="first"){return true}da=db;case"last":while((da=da.nextSibling)){if(da.nodeType===1){return false}}return true}}},PSEUDO:function(c9,c8){var e,c7=cL.pseudos[c9]||cL.setFilters[c9.toLowerCase()]||cQ.error("unsupported pseudo: "+c9);if(c7[cZ]){return c7(c8)}if(c7.length>1){e=[c9,c9,"",c8];return cL.setFilters.hasOwnProperty(c9.toLowerCase())?c1(function(dc,de){var db,da=c7(dc,c8),dd=da.length;while(dd--){db=co.call(dc,da[dd]);dc[db]=!(de[db]=da[dd])}}):function(da){return c7(da,0,e)}}return c7}},pseudos:{not:c1(function(e){var c7=[],c8=[],c9=cd(e.replace(cT,"$1"));return c9[cZ]?c1(function(db,dg,de,dc){var df,da=c9(db,null,dc,[]),dd=db.length;while(dd--){if((df=da[dd])){db[dd]=!(dg[dd]=df)}}}):function(dc,db,da){c7[0]=dc;c9(c7,null,da,c8);return !c8.pop()}}),has:c1(function(e){return function(c7){return cQ(e,c7).length>0}}),contains:c1(function(e){return function(c7){return(c7.textContent||c7.innerText||b0(c7)).indexOf(e)>-1}}),enabled:function(e){return e.disabled===false},disabled:function(e){return e.disabled===true},checked:function(e){var c7=e.nodeName.toLowerCase();return(c7==="input"&&!!e.checked)||(c7==="option"&&!!e.selected)},selected:function(e){if(e.parentNode){e.parentNode.selectedIndex}return e.selected===true},parent:function(e){return !cL.pseudos.empty(e)},empty:function(c7){var e;c7=c7.firstChild;while(c7){if(c7.nodeName>"@"||(e=c7.nodeType)===3||e===4){return false}c7=c7.nextSibling}return true},header:function(e){return cs.test(e.nodeName)},text:function(c8){var c7,e;return c8.nodeName.toLowerCase()==="input"&&(c7=c8.type)==="text"&&((e=c8.getAttribute("type"))==null||e.toLowerCase()===c7)},radio:cI("radio"),checkbox:cI("checkbox"),file:cI("file"),password:cI("password"),image:cI("image"),submit:b3("submit"),reset:b3("reset"),button:function(c7){var e=c7.nodeName.toLowerCase();return e==="input"&&c7.type==="button"||e==="button"},input:function(e){return cN.test(e.nodeName)},focus:function(e){var c7=e.ownerDocument;return e===c7.activeElement&&(!c7.hasFocus||c7.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},active:function(e){return e===e.ownerDocument.activeElement},first:cF(function(){return[0]}),last:cF(function(e,c7){return[c7-1]}),eq:cF(function(e,c8,c7){return[c7<0?c7+c8:c7]}),even:cF(function(e,c8){for(var c7=0;c7<c8;c7+=2){e.push(c7)}return e}),odd:cF(function(e,c8){for(var c7=1;c7<c8;c7+=2){e.push(c7)}return e}),lt:cF(function(e,c9,c8){for(var c7=c8<0?c8+c9:c8;--c7>=0;){e.push(c7)}return e}),gt:cF(function(e,c9,c8){for(var c7=c8<0?c8+c9:c8;++c7<c9;){e.push(c7)}return e})}};function b2(c7,e,c8){if(c7===e){return c8}var c9=c7.nextSibling;while(c9){if(c9===e){return -1}c9=c9.nextSibling}return 1}cg=cb.compareDocumentPosition?function(c7,e){if(c7===e){cc=true;return 0}return(!c7.compareDocumentPosition||!e.compareDocumentPosition?c7.compareDocumentPosition:c7.compareDocumentPosition(e)&4)?-1:1}:function(de,dd){if(de===dd){cc=true;return 0}else{if(de.sourceIndex&&dd.sourceIndex){return de.sourceIndex-dd.sourceIndex}}var db,c7,c8=[],e=[],da=de.parentNode,dc=dd.parentNode,df=da;if(da===dc){return b2(de,dd)}else{if(!da){return -1}else{if(!dc){return 1}}}while(df){c8.unshift(df);df=df.parentNode}df=dc;while(df){e.unshift(df);df=df.parentNode}db=c8.length;c7=e.length;for(var c9=0;c9<db&&c9<c7;c9++){if(c8[c9]!==e[c9]){return b2(c8[c9],e[c9])}}return c9===db?b2(de,e[c9],-1):b2(c8[c9],dd,1)};[0,0].sort(cg);b9=!cc;cQ.uniqueSort=function(c8){var c9,da=[],c7=1,e=0;cc=b9;c8.sort(cg);if(cc){for(;(c9=c8[c7]);c7++){if(c9===c8[c7-1]){e=da.push(c7)}}while(e--){c8.splice(da[e],1)}}return c8};cQ.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)};function b1(da,df){var c7,db,dd,de,dc,c8,e,c9=cV[cZ][da+" "];if(c9){return df?0:c9.slice(0)}dc=da;c8=[];e=cL.preFilter;while(dc){if(!c7||(db=b5.exec(dc))){if(db){dc=dc.slice(db[0].length)||dc}c8.push(dd=[])}c7=false;if((db=cH.exec(dc))){dd.push(c7=new b4(db.shift()));dc=dc.slice(c7.length);c7.type=db[0].replace(cT," ")}for(de in cL.filter){if((db=cG[de].exec(dc))&&(!e[de]||(db=e[de](db)))){dd.push(c7=new b4(db.shift()));dc=dc.slice(c7.length);c7.type=de;c7.matches=db}}if(!c7){break}}return df?dc.length:dc?cQ.error(da):cV(da,c8).slice(0)}function cw(da,c8,c9){var e=c8.dir,db=c9&&c8.dir==="parentNode",c7=cf++;return c8.first?function(de,dd,dc){while((de=de[e])){if(db||de.nodeType===1){return da(de,dd,dc)}}}:function(df,de,dd){if(!dd){var dc,dg=cr+" "+c7+" ",dh=dg+cX;while((df=df[e])){if(db||df.nodeType===1){if((dc=df[cZ])===dh){return df.sizset}else{if(typeof dc==="string"&&dc.indexOf(dg)===0){if(df.sizset){return df}}else{df[cZ]=dh;if(da(df,de,dd)){df.sizset=true;return df}df.sizset=false}}}}}else{while((df=df[e])){if(db||df.nodeType===1){if(da(df,de,dd)){return df}}}}}}function ce(e){return e.length>1?function(da,c9,c7){var c8=e.length;while(c8--){if(!e[c8](da,c9,c7)){return false}}return true}:e[0]}function cv(e,c7,c8,c9,dc){var da,df=[],db=0,dd=e.length,de=c7!=null;for(;db<dd;db++){if((da=e[db])){if(!c8||c8(da,c9,dc)){df.push(da);if(de){c7.push(db)}}}}return df}function c2(c8,c7,da,c9,db,e){if(c9&&!c9[cZ]){c9=c2(c9)}if(db&&!db[cZ]){db=c2(db,e)}return c1(function(dm,dj,de,dl){var dp,dk,dg,df=[],dn=[],dd=dj.length,dc=dm||cp(c7||"*",de.nodeType?[de]:de,[]),dh=c8&&(dm||!c7)?cv(dc,df,c8,de,dl):dc,di=da?db||(dm?c8:dd||c9)?[]:dj:dh;if(da){da(dh,di,de,dl)}if(c9){dp=cv(di,dn);c9(dp,[],de,dl);dk=dp.length;while(dk--){if((dg=dp[dk])){di[dn[dk]]=!(dh[dn[dk]]=dg)}}}if(dm){if(db||c8){if(db){dp=[];dk=di.length;while(dk--){if((dg=di[dk])){dp.push((dh[dk]=dg))}}db(null,(di=[]),dp,dl)}dk=di.length;while(dk--){if((dg=di[dk])&&(dp=db?co.call(dm,dg):df[dk])>-1){dm[dp]=!(dj[dp]=dg)}}}}else{di=cv(di===dj?di.splice(dd,di.length):di);if(db){db(null,dj,di,dl)}else{cW.apply(dj,di)}}})}function cx(dc){var c7,da,c8,db=dc.length,df=cL.relative[dc[0].type],dg=df||cL.relative[" "],c9=df?1:0,dd=cw(function(dh){return dh===c7},dg,true),de=cw(function(dh){return co.call(c7,dh)>-1},dg,true),e=[function(dj,di,dh){return(!df&&(dh||di!==cJ))||((c7=di).nodeType?dd(dj,di,dh):de(dj,di,dh))}];for(;c9<db;c9++){if((da=cL.relative[dc[c9].type])){e=[cw(ce(e),da)]}else{da=cL.filter[dc[c9].type].apply(null,dc[c9].matches);if(da[cZ]){c8=++c9;for(;c8<db;c8++){if(cL.relative[dc[c8].type]){break}}return c2(c9>1&&ce(e),c9>1&&dc.slice(0,c9-1).join("").replace(cT,"$1"),da,c9<c8&&cx(dc.slice(c9,c8)),c8<db&&cx((dc=dc.slice(c8))),c8<db&&dc.join(""))}e.push(da)}}return ce(e)}function b6(c9,c8){var e=c8.length>0,da=c9.length>0,c7=function(dk,de,dj,di,dr){var df,dg,dl,dq=[],dp=0,dh="0",db=dk&&[],dm=dr!=null,dn=cJ,dd=dk||da&&cL.find.TAG("*",dr&&de.parentNode||de),dc=(cr+=dn==null?1:Math.E);if(dm){cJ=de!==b8&&de;cX=c7.el}for(;(df=dd[dh])!=null;dh++){if(da&&df){for(dg=0;(dl=c9[dg]);dg++){if(dl(df,de,dj)){di.push(df);break}}if(dm){cr=dc;cX=++c7.el}}if(e){if((df=!dl&&df)){dp--}if(dk){db.push(df)}}}dp+=dh;if(e&&dh!==dp){for(dg=0;(dl=c8[dg]);dg++){dl(db,dq,de,dj)}if(dk){if(dp>0){while(dh--){if(!(db[dh]||dq[dh])){dq[dh]=cE.call(di)}}}dq=cv(dq)}cW.apply(di,dq);if(dm&&!dk&&dq.length>0&&(dp+c8.length)>1){cQ.uniqueSort(di)}}if(dm){cr=dc;cJ=dn}return db};c7.el=0;return e?c1(c7):c7}cd=cQ.compile=function(e,db){var c8,c7=[],da=[],c9=cn[cZ][e+" "];if(!c9){if(!db){db=b1(e)}c8=db.length;while(c8--){c9=cx(db[c8]);if(c9[cZ]){c7.push(c9)}else{da.push(c9)}}c9=cn(e,b6(da,c7))}return c9};function cp(c7,da,c9){var c8=0,e=da.length;for(;c8<e;c8++){cQ(c7,da[c8],c9)}return c9}function cY(c8,e,da,de,dd){var db,dh,c7,dg,df,dc=b1(c8),c9=dc.length;if(!de){if(dc.length===1){dh=dc[0]=dc[0].slice(0);if(dh.length>2&&(c7=dh[0]).type==="ID"&&e.nodeType===9&&!dd&&cL.relative[dh[1].type]){e=cL.find.ID(c7.matches[0].replace(ct,""),e,dd)[0];if(!e){return da}c8=c8.slice(dh.shift().length)}for(db=cG.POS.test(c8)?-1:dh.length-1;db>=0;db--){c7=dh[db];if(cL.relative[(dg=c7.type)]){break}if((df=cL.find[dg])){if((de=df(c7.matches[0].replace(ct,""),cR.test(dh[0].type)&&e.parentNode||e,dd))){dh.splice(db,1);c8=de.length&&dh.join("");if(!c8){cW.apply(da,cl.call(de,0));return da}break}}}}}cd(c8,dc)(de,e,dd,da,cR.test(c8));return da}if(b8.querySelectorAll){(function(){var db,dc=cY,da=/'|\\/g,c8=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,c7=[":focus"],e=[":active"],c9=cb.matchesSelector||cb.mozMatchesSelector||cb.webkitMatchesSelector||cb.oMatchesSelector||cb.msMatchesSelector;cK(function(dd){dd.innerHTML="<select><option selected=''></option></select>";if(!dd.querySelectorAll("[selected]").length){c7.push("\\["+cy+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)")}if(!dd.querySelectorAll(":checked").length){c7.push(":checked")}});cK(function(dd){dd.innerHTML="<p test=''></p>";if(dd.querySelectorAll("[test^='']").length){c7.push("[*^$]="+cy+"*(?:\"\"|'')")}dd.innerHTML="<input type='hidden'/>";if(!dd.querySelectorAll(":enabled").length){c7.push(":enabled",":disabled")}});c7=new RegExp(c7.join("|"));cY=function(dj,de,dl,dp,dn){if(!dp&&!dn&&!c7.test(dj)){var dh,dm,dg=true,dd=cZ,df=de,dk=de.nodeType===9&&dj;if(de.nodeType===1&&de.nodeName.toLowerCase()!=="object"){dh=b1(dj);if((dg=de.getAttribute("id"))){dd=dg.replace(da,"\\$&")}else{de.setAttribute("id",dd)}dd="[id='"+dd+"'] ";dm=dh.length;while(dm--){dh[dm]=dd+dh[dm].join("")}df=cR.test(dj)&&de.parentNode||de;dk=dh.join(",")}if(dk){try{cW.apply(dl,cl.call(df.querySelectorAll(dk),0));return dl}catch(di){}finally{if(!dg){de.removeAttribute("id")}}}}return dc(dj,de,dl,dp,dn)};if(c9){cK(function(de){db=c9.call(de,"div");try{c9.call(de,"[test!='']:sizzle");e.push("!=",c6)}catch(dd){}});e=new RegExp(e.join("|"));cQ.matchesSelector=function(de,dg){dg=dg.replace(c8,"='$1']");if(!cm(de)&&!e.test(dg)&&!c7.test(dg)){try{var dd=c9.call(de,dg);if(dd||db||de.document&&de.document.nodeType!==11){return dd}}catch(df){}}return cQ(dg,null,null,[de]).length>0}}})()}cL.pseudos.nth=cL.pseudos.eq;function cj(){}cL.filters=cj.prototype=cL.pseudos;cL.setFilters=new cj();cQ.attr=bG.attr;bG.find=cQ;bG.expr=cQ.selectors;bG.expr[":"]=bG.expr.pseudos;bG.unique=cQ.uniqueSort;bG.text=cQ.getText;bG.isXMLDoc=cQ.isXML;bG.contains=cQ.contains})(a2);var ag=/Until$/,bq=/^(?:parents|prev(?:Until|All))/,al=/^.[^:#\[\.,]*$/,y=bG.expr.match.needsContext,bu={children:true,contents:true,next:true,prev:true};bG.fn.extend({find:function(e){var b2,bZ,b4,b5,b3,b1,b0=this;if(typeof e!=="string"){return bG(e).filter(function(){for(b2=0,bZ=b0.length;b2<bZ;b2++){if(bG.contains(b0[b2],this)){return true}}})}b1=this.pushStack("","find",e);for(b2=0,bZ=this.length;b2<bZ;b2++){b4=b1.length;bG.find(e,this[b2],b1);if(b2>0){for(b5=b4;b5<b1.length;b5++){for(b3=0;b3<b4;b3++){if(b1[b3]===b1[b5]){b1.splice(b5--,1);break}}}}}return b1},has:function(b1){var b0,bZ=bG(b1,this),e=bZ.length;return this.filter(function(){for(b0=0;b0<e;b0++){if(bG.contains(this,bZ[b0])){return true}}})},not:function(e){return this.pushStack(aM(this,e,false),"not",e)},filter:function(e){return this.pushStack(aM(this,e,true),"filter",e)},is:function(e){return !!e&&(typeof e==="string"?y.test(e)?bG(e,this.context).index(this[0])>=0:bG.filter(e,this).length>0:this.filter(e).length>0)},closest:function(b2,b1){var b3,b0=0,e=this.length,bZ=[],b4=y.test(b2)||typeof b2!=="string"?bG(b2,b1||this.context):0;for(;b0<e;b0++){b3=this[b0];while(b3&&b3.ownerDocument&&b3!==b1&&b3.nodeType!==11){if(b4?b4.index(b3)>-1:bG.find.matchesSelector(b3,b2)){bZ.push(b3);break}b3=b3.parentNode}}bZ=bZ.length>1?bG.unique(bZ):bZ;return this.pushStack(bZ,"closest",b2)},index:function(e){if(!e){return(this[0]&&this[0].parentNode)?this.prevAll().length:-1}if(typeof e==="string"){return bG.inArray(this[0],bG(e))}return bG.inArray(e.jquery?e[0]:e,this)},add:function(e,bZ){var b1=typeof e==="string"?bG(e,bZ):bG.makeArray(e&&e.nodeType?[e]:e),b0=bG.merge(this.get(),b1);return this.pushStack(aR(b1[0])||aR(b0[0])?b0:bG.unique(b0))},addBack:function(e){return this.add(e==null?this.prevObject:this.prevObject.filter(e))}});bG.fn.andSelf=bG.fn.addBack;function aR(e){return !e||!e.parentNode||e.parentNode.nodeType===11}function aY(bZ,e){do{bZ=bZ[e]}while(bZ&&bZ.nodeType!==1);return bZ}bG.each({parent:function(bZ){var e=bZ.parentNode;return e&&e.nodeType!==11?e:null},parents:function(e){return bG.dir(e,"parentNode")},parentsUntil:function(bZ,e,b0){return bG.dir(bZ,"parentNode",b0)},next:function(e){return aY(e,"nextSibling")},prev:function(e){return aY(e,"previousSibling")},nextAll:function(e){return bG.dir(e,"nextSibling")},prevAll:function(e){return bG.dir(e,"previousSibling")},nextUntil:function(bZ,e,b0){return bG.dir(bZ,"nextSibling",b0)},prevUntil:function(bZ,e,b0){return bG.dir(bZ,"previousSibling",b0)},siblings:function(e){return bG.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return bG.sibling(e.firstChild)},contents:function(e){return bG.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:bG.merge([],e.childNodes)}},function(e,bZ){bG.fn[e]=function(b2,b0){var b1=bG.map(this,bZ,b2);if(!ag.test(e)){b0=b2}if(b0&&typeof b0==="string"){b1=bG.filter(b0,b1)}b1=this.length>1&&!bu[e]?bG.unique(b1):b1;if(this.length>1&&bq.test(e)){b1=b1.reverse()}return this.pushStack(b1,e,a4.call(arguments).join(","))}});bG.extend({filter:function(b0,e,bZ){if(bZ){b0=":not("+b0+")"}return e.length===1?bG.find.matchesSelector(e[0],b0)?[e[0]]:[]:bG.find.matches(b0,e)},dir:function(b0,bZ,b2){var e=[],b1=b0[bZ];while(b1&&b1.nodeType!==9&&(b2===aB||b1.nodeType!==1||!bG(b1).is(b2))){if(b1.nodeType===1){e.push(b1)}b1=b1[bZ]}return e},sibling:function(b0,bZ){var e=[];for(;b0;b0=b0.nextSibling){if(b0.nodeType===1&&b0!==bZ){e.push(b0)}}return e}});function aM(b1,b0,e){b0=b0||0;if(bG.isFunction(b0)){return bG.grep(b1,function(b3,b2){var b4=!!b0.call(b3,b2,b3);return b4===e})}else{if(b0.nodeType){return bG.grep(b1,function(b3,b2){return(b3===b0)===e})}else{if(typeof b0==="string"){var bZ=bG.grep(b1,function(b2){return b2.nodeType===1});if(al.test(b0)){return bG.filter(b0,bZ,!e)}else{b0=bG.filter(b0,bZ)}}}}return bG.grep(b1,function(b3,b2){return(bG.inArray(b3,b0)>=0)===e})}function A(e){var b0=c.split("|"),bZ=e.createDocumentFragment();if(bZ.createElement){while(b0.length){bZ.createElement(b0.pop())}}return bZ}var c="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",av=/ jQuery\d+="(?:null|\d+)"/g,bY=/^\s+/,ay=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,p=/<([\w:]+)/,bT=/<tbody/i,J=/<|&#?\w+;/,aj=/<(?:script|style|link)/i,ap=/<(?:script|object|embed|option|style)/i,K=new RegExp("<(?:"+c+")[\\s/>]","i"),aE=/^(?:checkbox|radio)$/,bR=/checked\s*(?:[^=]|=\s*.checked.)/i,bw=/\/(java|ecma)script/i,aH=/^\s*<!(?:\[CDATA\[|\-\-)|[\]\-]{2}>\s*$/g,T={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,"",""]},aQ=A(o),l=aQ.appendChild(o.createElement("div"));T.optgroup=T.option;T.tbody=T.tfoot=T.colgroup=T.caption=T.thead;T.th=T.td;if(!bG.support.htmlSerialize){T._default=[1,"X<div>","</div>"]}bG.fn.extend({text:function(e){return bG.access(this,function(bZ){return bZ===aB?bG.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(bZ))},null,e,arguments.length)},wrapAll:function(e){if(bG.isFunction(e)){return this.each(function(b0){bG(this).wrapAll(e.call(this,b0))})}if(this[0]){var bZ=bG(e,this[0].ownerDocument).eq(0).clone(true);if(this[0].parentNode){bZ.insertBefore(this[0])}bZ.map(function(){var b0=this;while(b0.firstChild&&b0.firstChild.nodeType===1){b0=b0.firstChild}return b0}).append(this)}return this},wrapInner:function(e){if(bG.isFunction(e)){return this.each(function(bZ){bG(this).wrapInner(e.call(this,bZ))})}return this.each(function(){var bZ=bG(this),b0=bZ.contents();if(b0.length){b0.wrapAll(e)}else{bZ.append(e)}})},wrap:function(e){var bZ=bG.isFunction(e);return this.each(function(b0){bG(this).wrapAll(bZ?e.call(this,b0):e)})},unwrap:function(){return this.parent().each(function(){if(!bG.nodeName(this,"body")){bG(this).replaceWith(this.childNodes)}}).end()},append:function(){return this.domManip(arguments,true,function(e){if(this.nodeType===1||this.nodeType===11){this.appendChild(e)}})},prepend:function(){return this.domManip(arguments,true,function(e){if(this.nodeType===1||this.nodeType===11){this.insertBefore(e,this.firstChild)}})},before:function(){if(!aR(this[0])){return this.domManip(arguments,false,function(bZ){this.parentNode.insertBefore(bZ,this)})}if(arguments.length){var e=bG.clean(arguments);return this.pushStack(bG.merge(e,this),"before",this.selector)}},after:function(){if(!aR(this[0])){return this.domManip(arguments,false,function(bZ){this.parentNode.insertBefore(bZ,this.nextSibling)})}if(arguments.length){var e=bG.clean(arguments);return this.pushStack(bG.merge(this,e),"after",this.selector)}},remove:function(e,b1){var b0,bZ=0;for(;(b0=this[bZ])!=null;bZ++){if(!e||bG.filter(e,[b0]).length){if(!b1&&b0.nodeType===1){bG.cleanData(b0.getElementsByTagName("*"));bG.cleanData([b0])}if(b0.parentNode){b0.parentNode.removeChild(b0)}}}return this},empty:function(){var bZ,e=0;for(;(bZ=this[e])!=null;e++){if(bZ.nodeType===1){bG.cleanData(bZ.getElementsByTagName("*"))}while(bZ.firstChild){bZ.removeChild(bZ.firstChild)}}return this},clone:function(bZ,e){bZ=bZ==null?false:bZ;e=e==null?bZ:e;return this.map(function(){return bG.clone(this,bZ,e)})},html:function(e){return bG.access(this,function(b2){var b1=this[0]||{},b0=0,bZ=this.length;if(b2===aB){return b1.nodeType===1?b1.innerHTML.replace(av,""):aB}if(typeof b2==="string"&&!aj.test(b2)&&(bG.support.htmlSerialize||!K.test(b2))&&(bG.support.leadingWhitespace||!bY.test(b2))&&!T[(p.exec(b2)||["",""])[1].toLowerCase()]){b2=b2.replace(ay,"<$1></$2>");try{for(;b0<bZ;b0++){b1=this[b0]||{};if(b1.nodeType===1){bG.cleanData(b1.getElementsByTagName("*"));b1.innerHTML=b2}}b1=0}catch(b3){}}if(b1){this.empty().append(b2)}},null,e,arguments.length)},replaceWith:function(e){if(!aR(this[0])){if(bG.isFunction(e)){return this.each(function(b1){var b0=bG(this),bZ=b0.html();b0.replaceWith(e.call(this,b1,bZ))})}if(typeof e!=="string"){e=bG(e).detach()}return this.each(function(){var b0=this.nextSibling,bZ=this.parentNode;bG(this).remove();if(b0){bG(b0).before(e)}else{bG(bZ).append(e)}})}return this.length?this.pushStack(bG(bG.isFunction(e)?e():e),"replaceWith",e):this},detach:function(e){return this.remove(e,true)},domManip:function(b4,b8,b7){b4=[].concat.apply([],b4);var b0,b2,b3,b6,b1=0,b5=b4[0],bZ=[],e=this.length;if(!bG.support.checkClone&&e>1&&typeof b5==="string"&&bR.test(b5)){return this.each(function(){bG(this).domManip(b4,b8,b7)})}if(bG.isFunction(b5)){return this.each(function(ca){var b9=bG(this);b4[0]=b5.call(this,ca,b8?b9.html():aB);b9.domManip(b4,b8,b7)})}if(this[0]){b0=bG.buildFragment(b4,this,bZ);b3=b0.fragment;b2=b3.firstChild;if(b3.childNodes.length===1){b3=b2}if(b2){b8=b8&&bG.nodeName(b2,"tr");for(b6=b0.cacheable||e-1;b1<e;b1++){b7.call(b8&&bG.nodeName(this[b1],"table")?x(this[b1],"tbody"):this[b1],b1===b6?b3:bG.clone(b3,true,true))}}b3=b2=null;if(bZ.length){bG.each(bZ,function(b9,ca){if(ca.src){if(bG.ajax){bG.ajax({url:ca.src,type:"GET",dataType:"script",async:false,global:false,"throws":true})}else{bG.error("no ajax")}}else{bG.globalEval((ca.text||ca.textContent||ca.innerHTML||"").replace(aH,""))}if(ca.parentNode){ca.parentNode.removeChild(ca)}})}}return this}});function x(bZ,e){return bZ.getElementsByTagName(e)[0]||bZ.appendChild(bZ.ownerDocument.createElement(e))}function ao(b5,bZ){if(bZ.nodeType!==1||!bG.hasData(b5)){return}var b2,b1,e,b4=bG._data(b5),b3=bG._data(bZ,b4),b0=b4.events;if(b0){delete b3.handle;b3.events={};for(b2 in b0){for(b1=0,e=b0[b2].length;b1<e;b1++){bG.event.add(bZ,b2,b0[b2][b1])}}}if(b3.data){b3.data=bG.extend({},b3.data)}}function F(bZ,e){var b0;if(e.nodeType!==1){return}if(e.clearAttributes){e.clearAttributes()}if(e.mergeAttributes){e.mergeAttributes(bZ)}b0=e.nodeName.toLowerCase();if(b0==="object"){if(e.parentNode){e.outerHTML=bZ.outerHTML}if(bG.support.html5Clone&&(bZ.innerHTML&&!bG.trim(e.innerHTML))){e.innerHTML=bZ.innerHTML}}else{if(b0==="input"&&aE.test(bZ.type)){e.defaultChecked=e.checked=bZ.checked;if(e.value!==bZ.value){e.value=bZ.value}}else{if(b0==="option"){e.selected=bZ.defaultSelected}else{if(b0==="input"||b0==="textarea"){e.defaultValue=bZ.defaultValue}else{if(b0==="script"&&e.text!==bZ.text){e.text=bZ.text}}}}}e.removeAttribute(bG.expando)}bG.buildFragment=function(b1,b2,bZ){var b0,e,b3,b4=b1[0];b2=b2||o;b2=!b2.nodeType&&b2[0]||b2;b2=b2.ownerDocument||b2;if(b1.length===1&&typeof b4==="string"&&b4.length<512&&b2===o&&b4.charAt(0)==="<"&&!ap.test(b4)&&(bG.support.checkClone||!bR.test(b4))&&(bG.support.html5Clone||!K.test(b4))){e=true;b0=bG.fragments[b4];b3=b0!==aB}if(!b0){b0=b2.createDocumentFragment();bG.clean(b1,b2,b0,bZ);if(e){bG.fragments[b4]=b3&&b0}}return{fragment:b0,cacheable:e}};bG.fragments={};bG.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,bZ){bG.fn[e]=function(b0){var b2,b4=0,b3=[],b6=bG(b0),b1=b6.length,b5=this.length===1&&this[0].parentNode;if((b5==null||b5&&b5.nodeType===11&&b5.childNodes.length===1)&&b1===1){b6[bZ](this[0]);return this}else{for(;b4<b1;b4++){b2=(b4>0?this.clone(true):this).get();bG(b6[b4])[bZ](b2);b3=b3.concat(b2)}return this.pushStack(b3,e,b6.selector)}}});function m(e){if(typeof e.getElementsByTagName!=="undefined"){return e.getElementsByTagName("*")}else{if(typeof e.querySelectorAll!=="undefined"){return e.querySelectorAll("*")}else{return[]}}}function bS(e){if(aE.test(e.type)){e.defaultChecked=e.checked}}bG.extend({clone:function(b2,b4,b0){var e,bZ,b1,b3;if(bG.support.html5Clone||bG.isXMLDoc(b2)||!K.test("<"+b2.nodeName+">")){b3=b2.cloneNode(true)}else{l.innerHTML=b2.outerHTML;l.removeChild(b3=l.firstChild)}if((!bG.support.noCloneEvent||!bG.support.noCloneChecked)&&(b2.nodeType===1||b2.nodeType===11)&&!bG.isXMLDoc(b2)){F(b2,b3);e=m(b2);bZ=m(b3);for(b1=0;e[b1];++b1){if(bZ[b1]){F(e[b1],bZ[b1])}}}if(b4){ao(b2,b3);if(b0){e=m(b2);bZ=m(b3);for(b1=0;e[b1];++b1){ao(e[b1],bZ[b1])}}}e=bZ=null;return b3},clean:function(cb,b0,e,b1){var b8,b7,ca,cf,b4,ce,b5,b2,bZ,b9,cd,b6,b3=b0===o&&aQ,cc=[];if(!b0||typeof b0.createDocumentFragment==="undefined"){b0=o}for(b8=0;(ca=cb[b8])!=null;b8++){if(typeof ca==="number"){ca+=""}if(!ca){continue}if(typeof ca==="string"){if(!J.test(ca)){ca=b0.createTextNode(ca)}else{b3=b3||A(b0);b5=b0.createElement("div");b3.appendChild(b5);ca=ca.replace(ay,"<$1></$2>");cf=(p.exec(ca)||["",""])[1].toLowerCase();b4=T[cf]||T._default;ce=b4[0];b5.innerHTML=b4[1]+ca+b4[2];while(ce--){b5=b5.lastChild}if(!bG.support.tbody){b2=bT.test(ca);bZ=cf==="table"&&!b2?b5.firstChild&&b5.firstChild.childNodes:b4[1]==="<table>"&&!b2?b5.childNodes:[];for(b7=bZ.length-1;b7>=0;--b7){if(bG.nodeName(bZ[b7],"tbody")&&!bZ[b7].childNodes.length){bZ[b7].parentNode.removeChild(bZ[b7])}}}if(!bG.support.leadingWhitespace&&bY.test(ca)){b5.insertBefore(b0.createTextNode(bY.exec(ca)[0]),b5.firstChild)}ca=b5.childNodes;b5.parentNode.removeChild(b5)}}if(ca.nodeType){cc.push(ca)}else{bG.merge(cc,ca)}}if(b5){ca=b5=b3=null}if(!bG.support.appendChecked){for(b8=0;(ca=cc[b8])!=null;b8++){if(bG.nodeName(ca,"input")){bS(ca)}else{if(typeof ca.getElementsByTagName!=="undefined"){bG.grep(ca.getElementsByTagName("input"),bS)}}}}if(e){cd=function(cg){if(!cg.type||bw.test(cg.type)){return b1?b1.push(cg.parentNode?cg.parentNode.removeChild(cg):cg):e.appendChild(cg)}};for(b8=0;(ca=cc[b8])!=null;b8++){if(!(bG.nodeName(ca,"script")&&cd(ca))){e.appendChild(ca);if(typeof ca.getElementsByTagName!=="undefined"){b6=bG.grep(bG.merge([],ca.getElementsByTagName("script")),cd);cc.splice.apply(cc,[b8+1,0].concat(b6));b8+=b6.length}}}}return cc},cleanData:function(bZ,b7){var b2,b0,b1,b6,b3=0,b8=bG.expando,e=bG.cache,b4=bG.support.deleteExpando,b5=bG.event.special;for(;(b1=bZ[b3])!=null;b3++){if(b7||bG.acceptData(b1)){b0=b1[b8];b2=b0&&e[b0];if(b2){if(b2.events){for(b6 in b2.events){if(b5[b6]){bG.event.remove(b1,b6)}else{bG.removeEvent(b1,b6,b2.handle)}}}if(e[b0]){delete e[b0];if(b4){delete b1[b8]}else{if(b1.removeAttribute){b1.removeAttribute(b8)}else{b1[b8]=null}}bG.deletedIds.push(b0)}}}}}});(function(){var e,bZ;bG.uaMatch=function(b1){b1=b1.toLowerCase();var b0=/(chrome)[ \/]([\w.]+)/.exec(b1)||/(webkit)[ \/]([\w.]+)/.exec(b1)||/(opera)(?:.*version|)[ \/]([\w.]+)/.exec(b1)||/(msie) ([\w.]+)/.exec(b1)||b1.indexOf("compatible")<0&&/(mozilla)(?:.*? rv:([\w.]+)|)/.exec(b1)||[];return{browser:b0[1]||"",version:b0[2]||"0"}};e=bG.uaMatch(d.userAgent);bZ={};if(e.browser){bZ[e.browser]=true;bZ.version=e.version}if(bZ.chrome){bZ.webkit=true}else{if(bZ.webkit){bZ.safari=true}}bG.browser=bZ;bG.sub=function(){function b0(b3,b4){return new b0.fn.init(b3,b4)}bG.extend(true,b0,this);b0.superclass=this;b0.fn=b0.prototype=this();b0.fn.constructor=b0;b0.sub=this.sub;b0.fn.init=function b2(b3,b4){if(b4&&b4 instanceof bG&&!(b4 instanceof b0)){b4=b0(b4)}return bG.fn.init.call(this,b3,b4,b1)};b0.fn.init.prototype=b0.fn;var b1=b0(o);return b0}})();var E,az,aW,be=/alpha\([^)]*\)/i,aS=/opacity=([^)]*)/,bk=/^(top|right|bottom|left)$/,G=/^(none|table(?!-c[ea]).+)/,aZ=/^margin/,a8=new RegExp("^("+bx+")(.*)$","i"),W=new RegExp("^("+bx+")(?!px)[a-z%]+$","i"),S=new RegExp("^([-+])=("+bx+")","i"),bh={BODY:"block"},a9={position:"absolute",visibility:"hidden",display:"block"},bA={letterSpacing:0,fontWeight:400},bQ=["Top","Right","Bottom","Left"],ar=["Webkit","O","Moz","ms"],aJ=bG.fn.toggle;function b(b1,bZ){if(bZ in b1){return bZ}var b2=bZ.charAt(0).toUpperCase()+bZ.slice(1),e=bZ,b0=ar.length;while(b0--){bZ=ar[b0]+b2;if(bZ in b1){return bZ}}return e}function Q(bZ,e){bZ=e||bZ;return bG.css(bZ,"display")==="none"||!bG.contains(bZ.ownerDocument,bZ)}function s(b3,e){var b2,b4,bZ=[],b0=0,b1=b3.length;for(;b0<b1;b0++){b2=b3[b0];if(!b2.style){continue}bZ[b0]=bG._data(b2,"olddisplay");if(e){if(!bZ[b0]&&b2.style.display==="none"){b2.style.display=""}if(b2.style.display===""&&Q(b2)){bZ[b0]=bG._data(b2,"olddisplay",bC(b2.nodeName))}}else{b4=E(b2,"display");if(!bZ[b0]&&b4!=="none"){bG._data(b2,"olddisplay",b4)}}}for(b0=0;b0<b1;b0++){b2=b3[b0];if(!b2.style){continue}if(!e||b2.style.display==="none"||b2.style.display===""){b2.style.display=e?bZ[b0]||"":"none"}}return b3}bG.fn.extend({css:function(e,bZ){return bG.access(this,function(b1,b0,b2){return b2!==aB?bG.style(b1,b0,b2):bG.css(b1,b0)},e,bZ,arguments.length>1)},show:function(){return s(this,true)},hide:function(){return s(this)},toggle:function(b0,bZ){var e=typeof b0==="boolean";if(bG.isFunction(b0)&&bG.isFunction(bZ)){return aJ.apply(this,arguments)}return this.each(function(){if(e?b0:Q(this)){bG(this).show()}else{bG(this).hide()}})}});bG.extend({cssHooks:{opacity:{get:function(b0,bZ){if(bZ){var e=E(b0,"opacity");return e===""?"1":e}}}},cssNumber:{fillOpacity:true,fontWeight:true,lineHeight:true,opacity:true,orphans:true,widows:true,zIndex:true,zoom:true},cssProps:{"float":bG.support.cssFloat?"cssFloat":"styleFloat"},style:function(b1,b0,b7,b2){if(!b1||b1.nodeType===3||b1.nodeType===8||!b1.style){return}var b5,b6,b8,b3=bG.camelCase(b0),bZ=b1.style;b0=bG.cssProps[b3]||(bG.cssProps[b3]=b(bZ,b3));b8=bG.cssHooks[b0]||bG.cssHooks[b3];if(b7!==aB){b6=typeof b7;if(b6==="string"&&(b5=S.exec(b7))){b7=(b5[1]+1)*b5[2]+parseFloat(bG.css(b1,b0));b6="number"}if(b7==null||b6==="number"&&isNaN(b7)){return}if(b6==="number"&&!bG.cssNumber[b3]){b7+="px"}if(!b8||!("set" in b8)||(b7=b8.set(b1,b7,b2))!==aB){try{bZ[b0]=b7}catch(b4){}}}else{if(b8&&"get" in b8&&(b5=b8.get(b1,false,b2))!==aB){return b5}return bZ[b0]}},css:function(b4,b2,b3,bZ){var b5,b1,e,b0=bG.camelCase(b2);b2=bG.cssProps[b0]||(bG.cssProps[b0]=b(b4.style,b0));e=bG.cssHooks[b2]||bG.cssHooks[b0];if(e&&"get" in e){b5=e.get(b4,true,bZ)}if(b5===aB){b5=E(b4,b2)}if(b5==="normal"&&b2 in bA){b5=bA[b2]}if(b3||bZ!==aB){b1=parseFloat(b5);return b3||bG.isNumeric(b1)?b1||0:b5}return b5},swap:function(b2,b1,b3){var b0,bZ,e={};for(bZ in b1){e[bZ]=b2.style[bZ];b2.style[bZ]=b1[bZ]}b0=b3.call(b2);for(bZ in b1){b2.style[bZ]=e[bZ]}return b0}});if(a2.getComputedStyle){E=function(b5,bZ){var e,b2,b1,b4,b3=a2.getComputedStyle(b5,null),b0=b5.style;if(b3){e=b3.getPropertyValue(bZ)||b3[bZ];if(e===""&&!bG.contains(b5.ownerDocument,b5)){e=bG.style(b5,bZ)}if(W.test(e)&&aZ.test(bZ)){b2=b0.width;b1=b0.minWidth;b4=b0.maxWidth;b0.minWidth=b0.maxWidth=b0.width=e;e=b3.width;b0.width=b2;b0.minWidth=b1;b0.maxWidth=b4}}return e}}else{if(o.documentElement.currentStyle){E=function(b2,b0){var b3,e,bZ=b2.currentStyle&&b2.currentStyle[b0],b1=b2.style;if(bZ==null&&b1&&b1[b0]){bZ=b1[b0]}if(W.test(bZ)&&!bk.test(b0)){b3=b1.left;e=b2.runtimeStyle&&b2.runtimeStyle.left;if(e){b2.runtimeStyle.left=b2.currentStyle.left}b1.left=b0==="fontSize"?"1em":bZ;bZ=b1.pixelLeft+"px";b1.left=b3;if(e){b2.runtimeStyle.left=e}}return bZ===""?"auto":bZ}}}function aG(e,b0,b1){var bZ=a8.exec(b0);return bZ?Math.max(0,bZ[1]-(b1||0))+(bZ[2]||"px"):b0}function at(b1,bZ,e,b3){var b0=e===(b3?"border":"content")?4:bZ==="width"?1:0,b2=0;for(;b0<4;b0+=2){if(e==="margin"){b2+=bG.css(b1,e+bQ[b0],true)}if(b3){if(e==="content"){b2-=parseFloat(E(b1,"padding"+bQ[b0]))||0}if(e!=="margin"){b2-=parseFloat(E(b1,"border"+bQ[b0]+"Width"))||0}}else{b2+=parseFloat(E(b1,"padding"+bQ[b0]))||0;if(e!=="padding"){b2+=parseFloat(E(b1,"border"+bQ[b0]+"Width"))||0}}}return b2}function u(b1,bZ,e){var b2=bZ==="width"?b1.offsetWidth:b1.offsetHeight,b0=true,b3=bG.support.boxSizing&&bG.css(b1,"boxSizing")==="border-box";if(b2<=0||b2==null){b2=E(b1,bZ);if(b2<0||b2==null){b2=b1.style[bZ]}if(W.test(b2)){return b2}b0=b3&&(bG.support.boxSizingReliable||b2===b1.style[bZ]);b2=parseFloat(b2)||0}return(b2+at(b1,bZ,e||(b3?"border":"content"),b0))+"px"}function bC(b0){if(bh[b0]){return bh[b0]}var e=bG("<"+b0+">").appendTo(o.body),bZ=e.css("display");e.remove();if(bZ==="none"||bZ===""){az=o.body.appendChild(az||bG.extend(o.createElement("iframe"),{frameBorder:0,width:0,height:0}));if(!aW||!az.createElement){aW=(az.contentWindow||az.contentDocument).document;aW.write("<!doctype html><html><body>");aW.close()}e=aW.body.appendChild(aW.createElement(b0));bZ=E(e,"display");o.body.removeChild(az)}bh[b0]=bZ;return bZ}bG.each(["height","width"],function(bZ,e){bG.cssHooks[e]={get:function(b2,b1,b0){if(b1){if(b2.offsetWidth===0&&G.test(E(b2,"display"))){return bG.swap(b2,a9,function(){return u(b2,e,b0)})}else{return u(b2,e,b0)}}},set:function(b1,b2,b0){return aG(b1,b2,b0?at(b1,e,b0,bG.support.boxSizing&&bG.css(b1,"boxSizing")==="border-box"):0)}}});if(!bG.support.opacity){bG.cssHooks.opacity={get:function(bZ,e){return aS.test((e&&bZ.currentStyle?bZ.currentStyle.filter:bZ.style.filter)||"")?(0.01*parseFloat(RegExp.$1))+"":e?"1":""},set:function(b2,b3){var b1=b2.style,bZ=b2.currentStyle,e=bG.isNumeric(b3)?"alpha(opacity="+b3*100+")":"",b0=bZ&&bZ.filter||b1.filter||"";b1.zoom=1;if(b3>=1&&bG.trim(b0.replace(be,""))===""&&b1.removeAttribute){b1.removeAttribute("filter");if(bZ&&!bZ.filter){return}}b1.filter=be.test(b0)?b0.replace(be,e):b0+" "+e}}}bG(function(){if(!bG.support.reliableMarginRight){bG.cssHooks.marginRight={get:function(bZ,e){return bG.swap(bZ,{display:"inline-block"},function(){if(e){return E(bZ,"marginRight")}})}}}if(!bG.support.pixelPosition&&bG.fn.position){bG.each(["top","left"],function(e,bZ){bG.cssHooks[bZ]={get:function(b2,b1){if(b1){var b0=E(b2,bZ);return W.test(b0)?bG(b2).position()[bZ]+"px":b0}}}})}});if(bG.expr&&bG.expr.filters){bG.expr.filters.hidden=function(e){return(e.offsetWidth===0&&e.offsetHeight===0)||(!bG.support.reliableHiddenOffsets&&((e.style&&e.style.display)||E(e,"display"))==="none")};bG.expr.filters.visible=function(e){return !bG.expr.filters.hidden(e)}}bG.each({margin:"",padding:"",border:"Width"},function(e,bZ){bG.cssHooks[e+bZ]={expand:function(b2){var b1,b3=typeof b2==="string"?b2.split(" "):[b2],b0={};for(b1=0;b1<4;b1++){b0[e+bQ[b1]+bZ]=b3[b1]||b3[b1-2]||b3[0]}return b0}};if(!aZ.test(e)){bG.cssHooks[e+bZ].set=aG}});var bs=/%20/g,aP=/\[\]$/,U=/\r?\n/g,bz=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,aD=/^(?:select|textarea)/i;bG.fn.extend({serialize:function(){return bG.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?bG.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||aD.test(this.nodeName)||bz.test(this.type))}).map(function(e,bZ){var b0=bG(this).val();return b0==null?null:bG.isArray(b0)?bG.map(b0,function(b2,b1){return{name:bZ.name,value:b2.replace(U,"\r\n")}}):{name:bZ.name,value:b0.replace(U,"\r\n")}}).get()}});bG.param=function(e,b0){var b1,bZ=[],b2=function(b3,b4){b4=bG.isFunction(b4)?b4():(b4==null?"":b4);bZ[bZ.length]=encodeURIComponent(b3)+"="+encodeURIComponent(b4)};if(b0===aB){b0=bG.ajaxSettings&&bG.ajaxSettings.traditional}if(bG.isArray(e)||(e.jquery&&!bG.isPlainObject(e))){bG.each(e,function(){b2(this.name,this.value)})}else{for(b1 in e){k(b1,e[b1],b0,b2)}}return bZ.join("&").replace(bs,"+")};function k(b0,b2,bZ,b1){var e;if(bG.isArray(b2)){bG.each(b2,function(b4,b3){if(bZ||aP.test(b0)){b1(b0,b3)}else{k(b0+"["+(typeof b3==="object"?b4:"")+"]",b3,bZ,b1)}})}else{if(!bZ&&bG.type(b2)==="object"){for(e in b2){k(b0+"["+e+"]",b2[e],bZ,b1)}}else{b1(b0,b2)}}}var bX,Y,an=/#.*$/,ad=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,B=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,r=/^(?:GET|HEAD)$/,aC=/^\/\//,bN=/\?/,g=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,P=/([?&])_=[^&]*/,aT=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,bW=bG.fn.load,v={},a6={},aX=["*/"]+["*"];try{Y=aI.href}catch(bd){Y=o.createElement("a");Y.href="";Y=Y.href}bX=aT.exec(Y.toLowerCase())||[];function bI(e){return function(b2,b4){if(typeof b2!=="string"){b4=b2;b2="*"}var bZ,b5,b6,b1=b2.toLowerCase().split(aV),b0=0,b3=b1.length;if(bG.isFunction(b4)){for(;b0<b3;b0++){bZ=b1[b0];b6=/^\+/.test(bZ);if(b6){bZ=bZ.substr(1)||"*"}b5=e[bZ]=e[bZ]||[];b5[b6?"unshift":"push"](b4)}}}}function q(bZ,b8,b3,b6,b5,b1){b5=b5||b8.dataTypes[0];b1=b1||{};b1[b5]=true;var b7,b4=bZ[b5],b0=0,e=b4?b4.length:0,b2=(bZ===v);for(;b0<e&&(b2||!b7);b0++){b7=b4[b0](b8,b3,b6);if(typeof b7==="string"){if(!b2||b1[b7]){b7=aB}else{b8.dataTypes.unshift(b7);b7=q(bZ,b8,b3,b6,b7,b1)}}}if((b2||!b7)&&!b1["*"]){b7=q(bZ,b8,b3,b6,"*",b1)}return b7}function t(b0,b1){var bZ,e,b2=bG.ajaxSettings.flatOptions||{};for(bZ in b1){if(b1[bZ]!==aB){(b2[bZ]?b0:(e||(e={})))[bZ]=b1[bZ]}}if(e){bG.extend(true,b0,e)}}bG.fn.load=function(b1,b4,b5){if(typeof b1!=="string"&&bW){return bW.apply(this,arguments)}if(!this.length){return this}var e,b2,b0,bZ=this,b3=b1.indexOf(" ");if(b3>=0){e=b1.slice(b3,b1.length);b1=b1.slice(0,b3)}if(bG.isFunction(b4)){b5=b4;b4=aB}else{if(b4&&typeof b4==="object"){b2="POST"}}bG.ajax({url:b1,type:b2,dataType:"html",data:b4,complete:function(b7,b6){if(b5){bZ.each(b5,b0||[b7.responseText,b6,b7])}}}).done(function(b6){b0=arguments;bZ.html(e?bG("<div>").append(b6.replace(g,"")).find(e):b6)});return this};bG.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(e,bZ){bG.fn[bZ]=function(b0){return this.on(bZ,b0)}});bG.each(["get","post"],function(e,bZ){bG[bZ]=function(b0,b2,b3,b1){if(bG.isFunction(b2)){b1=b1||b3;b3=b2;b2=aB}return bG.ajax({type:bZ,url:b0,data:b2,success:b3,dataType:b1})}});bG.extend({getScript:function(e,bZ){return bG.get(e,aB,bZ,"script")},getJSON:function(e,bZ,b0){return bG.get(e,bZ,b0,"json")},ajaxSetup:function(bZ,e){if(e){t(bZ,bG.ajaxSettings)}else{e=bZ;bZ=bG.ajaxSettings}t(bZ,e);return bZ},ajaxSettings:{url:Y,isLocal:B.test(bX[1]),global:true,type:"GET",contentType:"application/x-www-form-urlencoded; charset=UTF-8",processData:true,async:true,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":aX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a2.String,"text html":true,"text json":bG.parseJSON,"text xml":bG.parseXML},flatOptions:{context:true,url:true}},ajaxPrefilter:bI(v),ajaxTransport:bI(a6),ajax:function(b4,b1){if(typeof b4==="object"){b1=b4;b4=aB}b1=b1||{};var b7,cl,b2,cg,b9,cd,b0,cf,b8=bG.ajaxSetup({},b1),cn=b8.context||b8,cb=cn!==b8&&(cn.nodeType||cn instanceof bG)?bG(cn):bG.event,cm=bG.Deferred(),ci=bG.Callbacks("once memory"),b5=b8.statusCode||{},cc={},cj={},b3=0,b6="canceled",ce={readyState:0,setRequestHeader:function(co,cp){if(!b3){var e=co.toLowerCase();co=cj[e]=cj[e]||co;cc[co]=cp}return this},getAllResponseHeaders:function(){return b3===2?cl:null},getResponseHeader:function(co){var e;if(b3===2){if(!b2){b2={};while((e=ad.exec(cl))){b2[e[1].toLowerCase()]=e[2]}}e=b2[co.toLowerCase()]}return e===aB?null:e},overrideMimeType:function(e){if(!b3){b8.mimeType=e}return this},abort:function(e){e=e||b6;if(cg){cg.abort(e)}ca(0,e);return this}};function ca(cs,co,ct,cq){var e,cw,cu,cr,cv,cp=co;if(b3===2){return}b3=2;if(b9){clearTimeout(b9)}cg=aB;cl=cq||"";ce.readyState=cs>0?4:0;if(ct){cr=h(b8,ce,ct)}if(cs>=200&&cs<300||cs===304){if(b8.ifModified){cv=ce.getResponseHeader("Last-Modified");if(cv){bG.lastModified[b7]=cv}cv=ce.getResponseHeader("Etag");if(cv){bG.etag[b7]=cv}}if(cs===304){cp="notmodified";e=true}else{e=ae(b8,cr);cp=e.state;cw=e.data;cu=e.error;e=!cu}}else{cu=cp;if(!cp||cs){cp="error";if(cs<0){cs=0}}}ce.status=cs;ce.statusText=(co||cp)+"";if(e){cm.resolveWith(cn,[cw,cp,ce])}else{cm.rejectWith(cn,[ce,cp,cu])}ce.statusCode(b5);b5=aB;if(b0){cb.trigger("ajax"+(e?"Success":"Error"),[ce,b8,e?cw:cu])}ci.fireWith(cn,[ce,cp]);if(b0){cb.trigger("ajaxComplete",[ce,b8]);if(!(--bG.active)){bG.event.trigger("ajaxStop")}}}cm.promise(ce);ce.success=ce.done;ce.error=ce.fail;ce.complete=ci.add;ce.statusCode=function(co){if(co){var e;if(b3<2){for(e in co){b5[e]=[b5[e],co[e]]}}else{e=co[ce.status];ce.always(e)}}return this};b8.url=((b4||b8.url)+"").replace(an,"").replace(aC,bX[1]+"//");b8.dataTypes=bG.trim(b8.dataType||"*").toLowerCase().split(aV);if(b8.crossDomain==null){cd=aT.exec(b8.url.toLowerCase());b8.crossDomain=!!(cd&&(cd[1]!==bX[1]||cd[2]!==bX[2]||(cd[3]||(cd[1]==="http:"?80:443))!=(bX[3]||(bX[1]==="http:"?80:443))))}if(b8.data&&b8.processData&&typeof b8.data!=="string"){b8.data=bG.param(b8.data,b8.traditional)}q(v,b8,b1,ce);if(b3===2){return ce}b0=b8.global;b8.type=b8.type.toUpperCase();b8.hasContent=!r.test(b8.type);if(b0&&bG.active++===0){bG.event.trigger("ajaxStart")}if(!b8.hasContent){if(b8.data){b8.url+=(bN.test(b8.url)?"&":"?")+b8.data;delete b8.data}b7=b8.url;if(b8.cache===false){var bZ=bG.now(),ck=b8.url.replace(P,"$1_="+bZ);b8.url=ck+((ck===b8.url)?(bN.test(b8.url)?"&":"?")+"_="+bZ:"")}}if(b8.data&&b8.hasContent&&b8.contentType!==false||b1.contentType){ce.setRequestHeader("Content-Type",b8.contentType)}if(b8.ifModified){b7=b7||b8.url;if(bG.lastModified[b7]){ce.setRequestHeader("If-Modified-Since",bG.lastModified[b7])}if(bG.etag[b7]){ce.setRequestHeader("If-None-Match",bG.etag[b7])}}ce.setRequestHeader("Accept",b8.dataTypes[0]&&b8.accepts[b8.dataTypes[0]]?b8.accepts[b8.dataTypes[0]]+(b8.dataTypes[0]!=="*"?", "+aX+"; q=0.01":""):b8.accepts["*"]);for(cf in b8.headers){ce.setRequestHeader(cf,b8.headers[cf])}if(b8.beforeSend&&(b8.beforeSend.call(cn,ce,b8)===false||b3===2)){return ce.abort()}b6="abort";for(cf in {success:1,error:1,complete:1}){ce[cf](b8[cf])}cg=q(a6,b8,b1,ce);if(!cg){ca(-1,"No Transport")}else{ce.readyState=1;if(b0){cb.trigger("ajaxSend",[ce,b8])}if(b8.async&&b8.timeout>0){b9=setTimeout(function(){ce.abort("timeout")},b8.timeout)}try{b3=1;cg.send(cc,ca)}catch(ch){if(b3<2){ca(-1,ch)}else{throw ch}}}return ce},active:0,lastModified:{},etag:{}});function h(b7,b6,b3){var b2,b4,b1,e,bZ=b7.contents,b5=b7.dataTypes,b0=b7.responseFields;for(b4 in b0){if(b4 in b3){b6[b0[b4]]=b3[b4]}}while(b5[0]==="*"){b5.shift();if(b2===aB){b2=b7.mimeType||b6.getResponseHeader("content-type")}}if(b2){for(b4 in bZ){if(bZ[b4]&&bZ[b4].test(b2)){b5.unshift(b4);break}}}if(b5[0] in b3){b1=b5[0]}else{for(b4 in b3){if(!b5[0]||b7.converters[b4+" "+b5[0]]){b1=b4;break}if(!e){e=b4}}b1=b1||e}if(b1){if(b1!==b5[0]){b5.unshift(b1)}return b3[b1]}}function ae(b9,b1){var b7,bZ,b5,b3,b6=b9.dataTypes.slice(),b0=b6[0],b8={},b2=0;if(b9.dataFilter){b1=b9.dataFilter(b1,b9.dataType)}if(b6[1]){for(b7 in b9.converters){b8[b7.toLowerCase()]=b9.converters[b7]}}for(;(b5=b6[++b2]);){if(b5!=="*"){if(b0!=="*"&&b0!==b5){b7=b8[b0+" "+b5]||b8["* "+b5];if(!b7){for(bZ in b8){b3=bZ.split(" ");if(b3[1]===b5){b7=b8[b0+" "+b3[0]]||b8["* "+b3[0]];if(b7){if(b7===true){b7=b8[bZ]}else{if(b8[bZ]!==true){b5=b3[0];b6.splice(b2--,0,b5)}}break}}}}if(b7!==true){if(b7&&b9["throws"]){b1=b7(b1)}else{try{b1=b7(b1)}catch(b4){return{state:"parsererror",error:b7?b4:"No conversion from "+b0+" to "+b5}}}}}b0=b5}}return{state:"success",data:b1}}var bp=[],aw=/\?/,a5=/(=)\?(?=&|$)|\?\?/,bl=bG.now();bG.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=bp.pop()||(bG.expando+"_"+(bl++));this[e]=true;return e}});bG.ajaxPrefilter("json jsonp",function(b8,b3,b7){var b6,e,b5,b1=b8.data,bZ=b8.url,b0=b8.jsonp!==false,b4=b0&&a5.test(bZ),b2=b0&&!b4&&typeof b1==="string"&&!(b8.contentType||"").indexOf("application/x-www-form-urlencoded")&&a5.test(b1);if(b8.dataTypes[0]==="jsonp"||b4||b2){b6=b8.jsonpCallback=bG.isFunction(b8.jsonpCallback)?b8.jsonpCallback():b8.jsonpCallback;e=a2[b6];if(b4){b8.url=bZ.replace(a5,"$1"+b6)}else{if(b2){b8.data=b1.replace(a5,"$1"+b6)}else{if(b0){b8.url+=(aw.test(bZ)?"&":"?")+b8.jsonp+"="+b6}}}b8.converters["script json"]=function(){if(!b5){bG.error(b6+" was not called")}return b5[0]};b8.dataTypes[0]="json";a2[b6]=function(){b5=arguments};b7.always(function(){a2[b6]=e;if(b8[b6]){b8.jsonpCallback=b3.jsonpCallback;bp.push(b6)}if(b5&&bG.isFunction(e)){e(b5[0])}b5=e=aB});return"script"}});bG.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(e){bG.globalEval(e);return e}}});bG.ajaxPrefilter("script",function(e){if(e.cache===aB){e.cache=false}if(e.crossDomain){e.type="GET";e.global=false}});bG.ajaxTransport("script",function(b0){if(b0.crossDomain){var e,bZ=o.head||o.getElementsByTagName("head")[0]||o.documentElement;return{send:function(b1,b2){e=o.createElement("script");e.async="async";if(b0.scriptCharset){e.charset=b0.scriptCharset}e.src=b0.url;e.onload=e.onreadystatechange=function(b4,b3){if(b3||!e.readyState||/loaded|complete/.test(e.readyState)){e.onload=e.onreadystatechange=null;if(bZ&&e.parentNode){bZ.removeChild(e)}e=aB;if(!b3){b2(200,"success")}}};bZ.insertBefore(e,bZ.firstChild)},abort:function(){if(e){e.onload(0,1)}}}}});var ah,aN=a2.ActiveXObject?function(){for(var e in ah){ah[e](0,1)}}:false,au=0;function bB(){try{return new a2.XMLHttpRequest()}catch(bZ){}}function bb(){try{return new a2.ActiveXObject("Microsoft.XMLHTTP")}catch(bZ){}}bG.ajaxSettings.xhr=a2.ActiveXObject?function(){return !this.isLocal&&bB()||bb()}:bB;(function(e){bG.extend(bG.support,{ajax:!!e,cors:!!e&&("withCredentials" in e)})})(bG.ajaxSettings.xhr());if(bG.support.ajax){bG.ajaxTransport(function(e){if(!e.crossDomain||bG.support.cors){var bZ;return{send:function(b5,b0){var b3,b2,b4=e.xhr();if(e.username){b4.open(e.type,e.url,e.async,e.username,e.password)}else{b4.open(e.type,e.url,e.async)}if(e.xhrFields){for(b2 in e.xhrFields){b4[b2]=e.xhrFields[b2]}}if(e.mimeType&&b4.overrideMimeType){b4.overrideMimeType(e.mimeType)}if(!e.crossDomain&&!b5["X-Requested-With"]){b5["X-Requested-With"]="XMLHttpRequest"}try{for(b2 in b5){b4.setRequestHeader(b2,b5[b2])}}catch(b1){}b4.send((e.hasContent&&e.data)||null);bZ=function(ce,b8){var b9,b7,b6,cc,cb;try{if(bZ&&(b8||b4.readyState===4)){bZ=aB;if(b3){b4.onreadystatechange=bG.noop;if(aN){delete ah[b3]}}if(b8){if(b4.readyState!==4){b4.abort()}}else{b9=b4.status;b6=b4.getAllResponseHeaders();cc={};cb=b4.responseXML;if(cb&&cb.documentElement){cc.xml=cb}try{cc.text=b4.responseText}catch(cd){}try{b7=b4.statusText}catch(cd){b7=""}if(!b9&&e.isLocal&&!e.crossDomain){b9=cc.text?200:404}else{if(b9===1223){b9=204}}}}}catch(ca){if(!b8){b0(-1,ca)}}if(cc){b0(b9,b7,cc,b6)}};if(!e.async){bZ()}else{if(b4.readyState===4){setTimeout(bZ,0)}else{b3=++au;if(aN){if(!ah){ah={};bG(a2).unload(aN)}ah[b3]=bZ}b4.onreadystatechange=bZ}}},abort:function(){if(bZ){bZ(0,1)}}}}})}var L,ab,bO=/^(?:toggle|show|hide)$/,bH=new RegExp("^(?:([-+])=|)("+bx+")([a-z%]*)$","i"),bM=/queueHooks$/,ax=[i],a1={"*":[function(e,b5){var b1,b6,b7=this.createTween(e,b5),b2=bH.exec(b5),b3=b7.cur(),bZ=+b3||0,b0=1,b4=20;if(b2){b1=+b2[2];b6=b2[3]||(bG.cssNumber[e]?"":"px");if(b6!=="px"&&bZ){bZ=bG.css(b7.elem,e,true)||b1||1;do{b0=b0||".5";bZ=bZ/b0;bG.style(b7.elem,e,bZ+b6)}while(b0!==(b0=b7.cur()/b3)&&b0!==1&&--b4)}b7.unit=b6;b7.start=bZ;b7.end=b2[1]?bZ+(b2[1]+1)*b1:b1}return b7}]};function bj(){setTimeout(function(){L=aB},0);return(L=bG.now())}function bc(bZ,e){bG.each(e,function(b4,b2){var b3=(a1[b4]||[]).concat(a1["*"]),b0=0,b1=b3.length;for(;b0<b1;b0++){if(b3[b0].call(bZ,b4,b2)){return}}})}function f(b0,b4,b7){var b8,b3=0,e=0,bZ=ax.length,b6=bG.Deferred().always(function(){delete b2.elem}),b2=function(){var ce=L||bj(),cb=Math.max(0,b1.startTime+b1.duration-ce),b9=cb/b1.duration||0,cd=1-b9,ca=0,cc=b1.tweens.length;for(;ca<cc;ca++){b1.tweens[ca].run(cd)}b6.notifyWith(b0,[b1,cd,cb]);if(cd<1&&cc){return cb}else{b6.resolveWith(b0,[b1]);return false}},b1=b6.promise({elem:b0,props:bG.extend({},b4),opts:bG.extend(true,{specialEasing:{}},b7),originalProperties:b4,originalOptions:b7,startTime:L||bj(),duration:b7.duration,tweens:[],createTween:function(cc,b9,cb){var ca=bG.Tween(b0,b1.opts,cc,b9,b1.opts.specialEasing[cc]||b1.opts.easing);b1.tweens.push(ca);return ca},stop:function(ca){var b9=0,cb=ca?b1.tweens.length:0;for(;b9<cb;b9++){b1.tweens[b9].run(1)}if(ca){b6.resolveWith(b0,[b1,ca])}else{b6.rejectWith(b0,[b1,ca])}return this}}),b5=b1.props;ak(b5,b1.opts.specialEasing);for(;b3<bZ;b3++){b8=ax[b3].call(b1,b0,b5,b1.opts);if(b8){return b8}}bc(b1,b5);if(bG.isFunction(b1.opts.start)){b1.opts.start.call(b0,b1)}bG.fx.timer(bG.extend(b2,{anim:b1,queue:b1.opts.queue,elem:b0}));return b1.progress(b1.opts.progress).done(b1.opts.done,b1.opts.complete).fail(b1.opts.fail).always(b1.opts.always)}function ak(b1,b3){var b0,bZ,b4,b2,e;for(b0 in b1){bZ=bG.camelCase(b0);b4=b3[bZ];b2=b1[b0];if(bG.isArray(b2)){b4=b2[1];b2=b1[b0]=b2[0]}if(b0!==bZ){b1[bZ]=b2;delete b1[b0]}e=bG.cssHooks[bZ];if(e&&"expand" in e){b2=e.expand(b2);delete b1[bZ];for(b0 in b2){if(!(b0 in b1)){b1[b0]=b2[b0];b3[b0]=b4}}}else{b3[bZ]=b4}}}bG.Animation=bG.extend(f,{tweener:function(bZ,b2){if(bG.isFunction(bZ)){b2=bZ;bZ=["*"]}else{bZ=bZ.split(" ")}var b1,e=0,b0=bZ.length;for(;e<b0;e++){b1=bZ[e];a1[b1]=a1[b1]||[];a1[b1].unshift(b2)}},prefilter:function(bZ,e){if(e){ax.unshift(bZ)}else{ax.push(bZ)}}});function i(b2,b8,e){var b7,b0,ca,b1,ce,b4,cd,cc,cb,b3=this,bZ=b2.style,b9={},b6=[],b5=b2.nodeType&&Q(b2);if(!e.queue){cc=bG._queueHooks(b2,"fx");if(cc.unqueued==null){cc.unqueued=0;cb=cc.empty.fire;cc.empty.fire=function(){if(!cc.unqueued){cb()}}}cc.unqueued++;b3.always(function(){b3.always(function(){cc.unqueued--;if(!bG.queue(b2,"fx").length){cc.empty.fire()}})})}if(b2.nodeType===1&&("height" in b8||"width" in b8)){e.overflow=[bZ.overflow,bZ.overflowX,bZ.overflowY];if(bG.css(b2,"display")==="inline"&&bG.css(b2,"float")==="none"){if(!bG.support.inlineBlockNeedsLayout||bC(b2.nodeName)==="inline"){bZ.display="inline-block"}else{bZ.zoom=1}}}if(e.overflow){bZ.overflow="hidden";if(!bG.support.shrinkWrapBlocks){b3.done(function(){bZ.overflow=e.overflow[0];bZ.overflowX=e.overflow[1];bZ.overflowY=e.overflow[2]})}}for(b7 in b8){ca=b8[b7];if(bO.exec(ca)){delete b8[b7];b4=b4||ca==="toggle";if(ca===(b5?"hide":"show")){continue}b6.push(b7)}}b1=b6.length;if(b1){ce=bG._data(b2,"fxshow")||bG._data(b2,"fxshow",{});if("hidden" in ce){b5=ce.hidden}if(b4){ce.hidden=!b5}if(b5){bG(b2).show()}else{b3.done(function(){bG(b2).hide()})}b3.done(function(){var cf;bG.removeData(b2,"fxshow",true);for(cf in b9){bG.style(b2,cf,b9[cf])}});for(b7=0;b7<b1;b7++){b0=b6[b7];cd=b3.createTween(b0,b5?ce[b0]:0);b9[b0]=ce[b0]||bG.style(b2,b0);if(!(b0 in ce)){ce[b0]=cd.start;if(b5){cd.end=cd.start;cd.start=b0==="width"||b0==="height"?1:0}}}}}function H(b0,bZ,b2,e,b1){return new H.prototype.init(b0,bZ,b2,e,b1)}bG.Tween=H;H.prototype={constructor:H,init:function(b1,bZ,b3,e,b2,b0){this.elem=b1;this.prop=b3;this.easing=b2||"swing";this.options=bZ;this.start=this.now=this.cur();this.end=e;this.unit=b0||(bG.cssNumber[b3]?"":"px")},cur:function(){var e=H.propHooks[this.prop];return e&&e.get?e.get(this):H.propHooks._default.get(this)},run:function(b0){var bZ,e=H.propHooks[this.prop];if(this.options.duration){this.pos=bZ=bG.easing[this.easing](b0,this.options.duration*b0,0,1,this.options.duration)}else{this.pos=bZ=b0}this.now=(this.end-this.start)*bZ+this.start;if(this.options.step){this.options.step.call(this.elem,this.now,this)}if(e&&e.set){e.set(this)}else{H.propHooks._default.set(this)}return this}};H.prototype.init.prototype=H.prototype;H.propHooks={_default:{get:function(bZ){var e;if(bZ.elem[bZ.prop]!=null&&(!bZ.elem.style||bZ.elem.style[bZ.prop]==null)){return bZ.elem[bZ.prop]}e=bG.css(bZ.elem,bZ.prop,false,"");return !e||e==="auto"?0:e},set:function(e){if(bG.fx.step[e.prop]){bG.fx.step[e.prop](e)}else{if(e.elem.style&&(e.elem.style[bG.cssProps[e.prop]]!=null||bG.cssHooks[e.prop])){bG.style(e.elem,e.prop,e.now+e.unit)}else{e.elem[e.prop]=e.now}}}}};H.propHooks.scrollTop=H.propHooks.scrollLeft={set:function(e){if(e.elem.nodeType&&e.elem.parentNode){e.elem[e.prop]=e.now}}};bG.each(["toggle","show","hide"],function(bZ,e){var b0=bG.fn[e];bG.fn[e]=function(b1,b3,b2){return b1==null||typeof b1==="boolean"||(!bZ&&bG.isFunction(b1)&&bG.isFunction(b3))?b0.apply(this,arguments):this.animate(bF(e,true),b1,b3,b2)}});bG.fn.extend({fadeTo:function(e,b1,b0,bZ){return this.filter(Q).css("opacity",0).show().end().animate({opacity:b1},e,b0,bZ)},animate:function(b4,b1,b3,b2){var b0=bG.isEmptyObject(b4),e=bG.speed(b1,b3,b2),bZ=function(){var b5=f(this,bG.extend({},b4),e);if(b0){b5.stop(true)}};return b0||e.queue===false?this.each(bZ):this.queue(e.queue,bZ)},stop:function(b0,bZ,e){var b1=function(b2){var b3=b2.stop;delete b2.stop;b3(e)};if(typeof b0!=="string"){e=bZ;bZ=b0;b0=aB}if(bZ&&b0!==false){this.queue(b0||"fx",[])}return this.each(function(){var b5=true,b2=b0!=null&&b0+"queueHooks",b4=bG.timers,b3=bG._data(this);if(b2){if(b3[b2]&&b3[b2].stop){b1(b3[b2])}}else{for(b2 in b3){if(b3[b2]&&b3[b2].stop&&bM.test(b2)){b1(b3[b2])}}}for(b2=b4.length;b2--;){if(b4[b2].elem===this&&(b0==null||b4[b2].queue===b0)){b4[b2].anim.stop(e);b5=false;b4.splice(b2,1)}}if(b5||!e){bG.dequeue(this,b0)}})}});function bF(b0,b2){var b1,e={height:b0},bZ=0;b2=b2?1:0;for(;bZ<4;bZ+=2-b2){b1=bQ[bZ];e["margin"+b1]=e["padding"+b1]=b0}if(b2){e.opacity=e.width=b0}return e}bG.each({slideDown:bF("show"),slideUp:bF("hide"),slideToggle:bF("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,bZ){bG.fn[e]=function(b0,b2,b1){return this.animate(bZ,b0,b2,b1)}});bG.speed=function(b0,b1,bZ){var e=b0&&typeof b0==="object"?bG.extend({},b0):{complete:bZ||!bZ&&b1||bG.isFunction(b0)&&b0,duration:b0,easing:bZ&&b1||b1&&!bG.isFunction(b1)&&b1};e.duration=bG.fx.off?0:typeof e.duration==="number"?e.duration:e.duration in bG.fx.speeds?bG.fx.speeds[e.duration]:bG.fx.speeds._default;if(e.queue==null||e.queue===true){e.queue="fx"}e.old=e.complete;e.complete=function(){if(bG.isFunction(e.old)){e.old.call(this)}if(e.queue){bG.dequeue(this,e.queue)}};return e};bG.easing={linear:function(e){return e},swing:function(e){return 0.5-Math.cos(e*Math.PI)/2}};bG.timers=[];bG.fx=H.prototype.init;bG.fx.tick=function(){var b0,bZ=bG.timers,e=0;L=bG.now();for(;e<bZ.length;e++){b0=bZ[e];if(!b0()&&bZ[e]===b0){bZ.splice(e--,1)}}if(!bZ.length){bG.fx.stop()}L=aB};bG.fx.timer=function(e){if(e()&&bG.timers.push(e)&&!ab){ab=setInterval(bG.fx.tick,bG.fx.interval)}};bG.fx.interval=13;bG.fx.stop=function(){clearInterval(ab);ab=null};bG.fx.speeds={slow:600,fast:200,_default:400};bG.fx.step={};if(bG.expr&&bG.expr.filters){bG.expr.filters.animated=function(e){return bG.grep(bG.timers,function(bZ){return e===bZ.elem}).length}}var bm=/^(?:body|html)$/i;bG.fn.offset=function(b8){if(arguments.length){return b8===aB?this:this.each(function(b9){bG.offset.setOffset(this,b8,b9)})}var bZ,b4,b5,b2,b6,e,b1,b3={top:0,left:0},b0=this[0],b7=b0&&b0.ownerDocument;if(!b7){return}if((b4=b7.body)===b0){return bG.offset.bodyOffset(b0)}bZ=b7.documentElement;if(!bG.contains(bZ,b0)){return b3}if(typeof b0.getBoundingClientRect!=="undefined"){b3=b0.getBoundingClientRect()}b5=bn(b7);b2=bZ.clientTop||b4.clientTop||0;b6=bZ.clientLeft||b4.clientLeft||0;e=b5.pageYOffset||bZ.scrollTop;b1=b5.pageXOffset||bZ.scrollLeft;return{top:b3.top+e-b2,left:b3.left+b1-b6}};bG.offset={bodyOffset:function(e){var b0=e.offsetTop,bZ=e.offsetLeft;if(bG.support.doesNotIncludeMarginInBodyOffset){b0+=parseFloat(bG.css(e,"marginTop"))||0;bZ+=parseFloat(bG.css(e,"marginLeft"))||0}return{top:b0,left:bZ}},setOffset:function(b1,ca,b4){var b5=bG.css(b1,"position");if(b5==="static"){b1.style.position="relative"}var b3=bG(b1),bZ=b3.offset(),e=bG.css(b1,"top"),b8=bG.css(b1,"left"),b9=(b5==="absolute"||b5==="fixed")&&bG.inArray("auto",[e,b8])>-1,b7={},b6={},b0,b2;if(b9){b6=b3.position();b0=b6.top;b2=b6.left}else{b0=parseFloat(e)||0;b2=parseFloat(b8)||0}if(bG.isFunction(ca)){ca=ca.call(b1,b4,bZ)}if(ca.top!=null){b7.top=(ca.top-bZ.top)+b0}if(ca.left!=null){b7.left=(ca.left-bZ.left)+b2}if("using" in ca){ca.using.call(b1,b7)}else{b3.css(b7)}}};bG.fn.extend({position:function(){if(!this[0]){return}var b0=this[0],bZ=this.offsetParent(),b1=this.offset(),e=bm.test(bZ[0].nodeName)?{top:0,left:0}:bZ.offset();b1.top-=parseFloat(bG.css(b0,"marginTop"))||0;b1.left-=parseFloat(bG.css(b0,"marginLeft"))||0;e.top+=parseFloat(bG.css(bZ[0],"borderTopWidth"))||0;e.left+=parseFloat(bG.css(bZ[0],"borderLeftWidth"))||0;return{top:b1.top-e.top,left:b1.left-e.left}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.body;while(e&&(!bm.test(e.nodeName)&&bG.css(e,"position")==="static")){e=e.offsetParent}return e||o.body})}});bG.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(b0,bZ){var e=/Y/.test(bZ);bG.fn[b0]=function(b1){return bG.access(this,function(b2,b5,b4){var b3=bn(b2);if(b4===aB){return b3?(bZ in b3)?b3[bZ]:b3.document.documentElement[b5]:b2[b5]}if(b3){b3.scrollTo(!e?b4:bG(b3).scrollLeft(),e?b4:bG(b3).scrollTop())}else{b2[b5]=b4}},b0,b1,arguments.length,null)}});function bn(e){return bG.isWindow(e)?e:e.nodeType===9?e.defaultView||e.parentWindow:false}bG.each({Height:"height",Width:"width"},function(e,bZ){bG.each({padding:"inner"+e,content:bZ,"":"outer"+e},function(b0,b1){bG.fn[b1]=function(b5,b4){var b3=arguments.length&&(b0||typeof b5!=="boolean"),b2=b0||(b5===true||b4===true?"margin":"border");return bG.access(this,function(b7,b6,b8){var b9;if(bG.isWindow(b7)){return b7.document.documentElement["client"+e]}if(b7.nodeType===9){b9=b7.documentElement;return Math.max(b7.body["scroll"+e],b9["scroll"+e],b7.body["offset"+e],b9["offset"+e],b9["client"+e])}return b8===aB?bG.css(b7,b6,b8,b2):bG.style(b7,b6,b8,b2)},bZ,b3?b5:aB,b3,null)}})});a2.jQuery=a2.$=bG;if(typeof define==="function"&&define.amd&&define.amd.jQuery){define("jquery",[],function(){return bG})}})(window); /* THIS FILE HAS BEEN MODIFIED BY ATLASSIAN. See https://ecosystem.atlassian.net/browse/AUI-1535 for details. Modified lines are marked below, search "ATLASSIAN" */ (function(i){var e="0.3.4",j="hasOwnProperty",b=/[\.\/]/,a="*",g=function(){},f=function(m,l){return m-l},d,h,k={n:{}},c=function(m,C){var v=k,s=h,w=Array.prototype.slice.call(arguments,2),y=c.listeners(m),x=0,u=false,p,o=[],t={},q=[],n=d,A=[];d=m;h=0;for(var r=0,B=y.length;r<B;r++){if("zIndex" in y[r]){o.push(y[r].zIndex);if(y[r].zIndex<0){t[y[r].zIndex]=y[r]}}}o.sort(f);while(o[x]<0){p=t[o[x++]];q.push(p.apply(C,w));if(h){h=s;return q}}for(r=0;r<B;r++){p=y[r];if("zIndex" in p){if(p.zIndex==o[x]){q.push(p.apply(C,w));if(h){break}do{x++;p=t[o[x]];p&&q.push(p.apply(C,w));if(h){break}}while(p)}else{t[p.zIndex]=p}}else{q.push(p.apply(C,w));if(h){break}}}h=s;d=n;return q.length?q:null};c.listeners=function(l){var t=l.split(b),r=k,x,s,m,p,w,o,q,u,v=[r],n=[];for(p=0,w=t.length;p<w;p++){u=[];for(o=0,q=v.length;o<q;o++){r=v[o].n;s=[r[t[p]],r[a]];m=2;while(m--){x=s[m];if(x){u.push(x);n=n.concat(x.f||[])}}}v=u}return n};c.on=function(l,o){var q=l.split(b),p=k;for(var m=0,n=q.length;m<n;m++){p=p.n;!p[q[m]]&&(p[q[m]]={n:{}});p=p[q[m]]}p.f=p.f||[];for(m=0,n=p.f.length;m<n;m++){if(p.f[m]==o){return g}}p.f.push(o);return function(r){if(+r==+r){o.zIndex=+r}}};c.stop=function(){h=1};c.nt=function(l){if(l){return new RegExp("(?:\\.|\\/|^)"+l+"(?:\\.|\\/|$)").test(d)}return d};c.off=c.unbind=function(m,r){var t=m.split(b),s,v,n,p,w,o,q,u=[k];for(p=0,w=t.length;p<w;p++){for(o=0;o<u.length;o+=n.length-2){n=[o,1];s=u[o].n;if(t[p]!=a){if(s[t[p]]){n.push(s[t[p]])}}else{for(v in s){if(s[j](v)){n.push(s[v])}}}u.splice.apply(u,n)}}for(p=0,w=u.length;p<w;p++){s=u[p];while(s.n){if(r){if(s.f){for(o=0,q=s.f.length;o<q;o++){if(s.f[o]==r){s.f.splice(o,1);break}}!s.f.length&&delete s.f}for(v in s.n){if(s.n[j](v)&&s.n[v].f){var l=s.n[v].f;for(o=0,q=l.length;o<q;o++){if(l[o]==r){l.splice(o,1);break}}!l.length&&delete s.n[v].f}}}else{delete s.f;for(v in s.n){if(s.n[j](v)&&s.n[v].f){delete s.n[v].f}}}s=s.n}}};c.once=function(l,m){var n=function(){var o=m.apply(this,arguments);c.unbind(l,n);return o};return c.on(l,n)};c.version=e;c.toString=function(){return"You are running Eve "+e};(typeof module!="undefined"&&module.exports)?(module.exports=c):(typeof define!="undefined"?(define("eve",[],function(){return c})):(i.eve=c))})(this);(function(){function aR(g){if(aR.is(g,"function")){return ao?g():eve.on("raphael.DOMload",g)}else{if(aR.is(g,bd)){return aR._engine.create[bG](aR,g.splice(0,3+aR.is(g[0],aL))).add(g)}else{var b=Array.prototype.slice.call(arguments,0);if(aR.is(b[b.length-1],"function")){var d=b.pop();return ao?d.call(aR._engine.create[bG](aR,b)):eve.on("raphael.DOMload",function(){d.call(aR._engine.create[bG](aR,b))})}else{return aR._engine.create[bG](aR,arguments)}}}}aR.version="2.1.0";aR.eve=eve;var ao,a=/[, ]+/,bw={circle:1,rect:1,path:1,ellipse:1,text:1,image:1},br=/\{(\d+)\}/g,bJ="prototype",ak="hasOwnProperty",aA={doc:document,win:window},s={was:Object.prototype[ak].call(aA.win,"Raphael"),is:aA.win.Raphael},bF=function(){this.ca=this.customAttributes={}},a4,bo="appendChild",bG="apply",bE="concat",Z="createTouch" in aA.doc,aX="",aQ=" ",bH=String,F="split",Q="click dblclick mousedown mousemove mouseout mouseover mouseup touchstart touchmove touchend touchcancel"[F](aQ),bx={mousedown:"touchstart",mousemove:"touchmove",mouseup:"touchend"},bK=bH.prototype.toLowerCase,au=Math,m=au.max,bm=au.min,aw=au.abs,bp=au.pow,aV=au.PI,aL="number",aj="string",bd="array",a5="toString",a9="fill",a1=Object.prototype.toString,bz={},j="push",f=aR._ISURL=/^url\(['"]?([^\)]+?)['"]?\)$/i,A=/^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i,av={"NaN":1,"Infinity":1,"-Infinity":1},c=/^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/,ah=au.round,z="setAttribute",an=parseFloat,U=parseInt,bt=bH.prototype.toUpperCase,r=aR._availableAttrs={"arrow-end":"none","arrow-start":"none",blur:0,"clip-rect":"0 0 1e9 1e9",cursor:"default",cx:0,cy:0,fill:"#fff","fill-opacity":1,font:'10px "Arial"',"font-family":'"Arial"',"font-size":"10","font-style":"normal","font-weight":400,gradient:0,height:0,href:"http://raphaeljs.com/","letter-spacing":0,opacity:1,path:"M0,0",r:0,rx:0,ry:0,src:"",stroke:"#000","stroke-dasharray":"","stroke-linecap":"butt","stroke-linejoin":"butt","stroke-miterlimit":0,"stroke-opacity":1,"stroke-width":1,target:"_blank","text-anchor":"middle",title:"Raphael",transform:"",width:0,x:0,y:0},ar=aR._availableAnimAttrs={blur:aL,"clip-rect":"csv",cx:aL,cy:aL,fill:"colour","fill-opacity":aL,"font-size":aL,height:aL,opacity:aL,path:"path",r:aL,rx:aL,ry:aL,stroke:"colour","stroke-opacity":aL,"stroke-width":aL,transform:"transform",width:aL,x:aL,y:aL},ac=/[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]/g,bi=/[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/,n={hs:1,rg:1},bg=/,?([achlmqrstvxz]),?/gi,a0=/([achlmrqstvz])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig,ai=/([rstm])[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029,]*((-?\d*\.?\d*(?:e[\-+]?\d+)?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*)+)/ig,aP=/(-?\d*\.?\d*(?:e[\-+]?\d+)?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,?[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*/ig,aW=aR._radial_gradient=/^r(?:\(([^,]+?)[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*,[\x09\x0a\x0b\x0c\x0d\x20\xa0\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000\u2028\u2029]*([^\)]+?)\))?/,aU={},bq=function(g,d){return g.key-d.key},u=function(g,d){return an(g)-an(d)},I=function(){},bB=function(b){return b},az=aR._rectPath=function(b,E,d,g,i){if(i){return[["M",b+i,E],["l",d-i*2,0],["a",i,i,0,0,1,i,i],["l",0,g-i*2],["a",i,i,0,0,1,-i,i],["l",i*2-d,0],["a",i,i,0,0,1,-i,-i],["l",0,i*2-g],["a",i,i,0,0,1,i,-i],["z"]]}return[["M",b,E],["l",d,0],["l",0,g],["l",-d,0],["z"]]},K=function(b,i,g,d){if(d==null){d=g}return[["M",b,i],["m",0,-d],["a",g,d,0,1,1,0,2*d],["a",g,d,0,1,1,0,-2*d],["z"]]},N=aR._getPath={path:function(b){return b.attr("path")},circle:function(d){var b=d.attrs;return K(b.cx,b.cy,b.r)},ellipse:function(d){var b=d.attrs;return K(b.cx,b.cy,b.rx,b.ry)},rect:function(d){var b=d.attrs;return az(b.x,b.y,b.width,b.height,b.r)},image:function(d){var b=d.attrs;return az(b.x,b.y,b.width,b.height)},text:function(b){var d=b._getBBox();return az(d.x,d.y,d.width,d.height)}},L=aR.mapPath=function(bN,S){if(!S){return bN}var bL,R,g,b,bM,E,d;bN=W(bN);for(g=0,bM=bN.length;g<bM;g++){d=bN[g];for(b=1,E=d.length;b<E;b+=2){bL=S.x(d[b],d[b+1]);R=S.y(d[b],d[b+1]);d[b]=bL;d[b+1]=R}}return bN};aR._g=aA;aR.type=(aA.win.SVGAngle||aA.doc.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure","1.1")?"SVG":"VML");if(aR.type=="VML"){var aE=aA.doc.createElement("div"),aH;aE.innerHTML='<v:shape adj="1"/>';aH=aE.firstChild;aH.style.behavior="url(#default#VML)";if(!(aH&&typeof aH.adj=="object")){return(aR.type=aX)}aE=null}aR.svg=!(aR.vml=aR.type=="VML");aR._Paper=bF;aR.fn=a4=bF.prototype=aR.prototype;aR._id=0;aR._oid=0;aR.is=function(d,b){b=bK.call(b);if(b=="finite"){return !av[ak](+d)}if(b=="array"){return d instanceof Array}return(b=="null"&&d===null)||(b==typeof d&&d!==null)||(b=="object"&&d===Object(d))||(b=="array"&&Array.isArray&&Array.isArray(d))||a1.call(d).slice(8,-1).toLowerCase()==b};function X(g){if(Object(g)!==g){return g}var d=new g.constructor;for(var b in g){if(g[ak](b)){d[b]=X(g[b])}}return d}aR.angle=function(E,S,g,R,d,i){if(d==null){var b=E-g,bL=S-R;if(!b&&!bL){return 0}return(180+au.atan2(-bL,-b)*180/aV+360)%360}else{return aR.angle(E,S,d,i)-aR.angle(g,R,d,i)}};aR.rad=function(b){return b%360*aV/180};aR.deg=function(b){return b*180/aV%360};aR.snapTo=function(d,E,b){b=aR.is(b,"finite")?b:10;if(aR.is(d,bd)){var g=d.length;while(g--){if(aw(d[g]-E)<=b){return d[g]}}}else{d=+d;var R=E%d;if(R<b){return E-R}if(R>d-b){return E-R+d}}return E};var h=aR.createUUID=(function(b,d){return function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(b,d).toUpperCase()}})(/[xy]/g,function(g){var d=au.random()*16|0,b=g=="x"?d:(d&3|8);return b.toString(16)});aR.setWindow=function(b){eve("raphael.setWindow",aR,aA.win,b);aA.win=b;aA.doc=aA.win.document;if(aR._engine.initWin){aR._engine.initWin(aA.win)}};var bf=function(g){if(aR.vml){var b=/^\s+|\s+$/g;var R;try{var S=new ActiveXObject("htmlfile");S.write("<body>");S.close();R=S.body}catch(bL){R=createPopup().document.body}var d=R.createTextRange();bf=aG(function(i){try{R.style.color=bH(i).replace(b,aX);var bM=d.queryCommandValue("ForeColor");bM=((bM&255)<<16)|(bM&65280)|((bM&16711680)>>>16);return"#"+("000000"+bM.toString(16)).slice(-6)}catch(bN){return"none"}})}else{var E=aA.doc.createElement("i");E.title="Rapha\xebl Colour Picker";E.style.display="none";aA.doc.body.appendChild(E);bf=aG(function(i){E.style.color=i;return aA.doc.defaultView.getComputedStyle(E,aX).getPropertyValue("color")})}return bf(g)},aI=function(){return"hsb("+[this.h,this.s,this.b]+")"},M=function(){return"hsl("+[this.h,this.s,this.l]+")"},x=function(){return this.hex},aY=function(R,E,d){if(E==null&&aR.is(R,"object")&&"r" in R&&"g" in R&&"b" in R){d=R.b;E=R.g;R=R.r}if(E==null&&aR.is(R,aj)){var i=aR.getRGB(R);R=i.r;E=i.g;d=i.b}if(R>1||E>1||d>1){R/=255;E/=255;d/=255}return[R,E,d]},a2=function(R,E,d,S){R*=255;E*=255;d*=255;var i={r:R,g:E,b:d,hex:aR.rgb(R,E,d),toString:x};aR.is(S,"finite")&&(i.opacity=S);return i};aR.color=function(b){var d;if(aR.is(b,"object")&&"h" in b&&"s" in b&&"b" in b){d=aR.hsb2rgb(b);b.r=d.r;b.g=d.g;b.b=d.b;b.hex=d.hex}else{if(aR.is(b,"object")&&"h" in b&&"s" in b&&"l" in b){d=aR.hsl2rgb(b);b.r=d.r;b.g=d.g;b.b=d.b;b.hex=d.hex}else{if(aR.is(b,"string")){b=aR.getRGB(b)}if(aR.is(b,"object")&&"r" in b&&"g" in b&&"b" in b){d=aR.rgb2hsl(b);b.h=d.h;b.s=d.s;b.l=d.l;d=aR.rgb2hsb(b);b.v=d.b}else{b={hex:"none"};b.r=b.g=b.b=b.h=b.s=b.v=b.l=-1}}}b.toString=x;return b};aR.hsb2rgb=function(S,bN,bL,i){if(this.is(S,"object")&&"h" in S&&"s" in S&&"b" in S){bL=S.b;bN=S.s;S=S.h;i=S.o}S*=360;var E,bM,d,g,b;S=(S%360)/60;b=bL*bN;g=b*(1-aw(S%2-1));E=bM=d=bL-b;S=~~S;E+=[b,g,0,0,g,b][S];bM+=[g,b,b,g,0,0][S];d+=[0,0,g,b,b,g][S];return a2(E,bM,d,i)};aR.hsl2rgb=function(bL,bN,E,i){if(this.is(bL,"object")&&"h" in bL&&"s" in bL&&"l" in bL){E=bL.l;bN=bL.s;bL=bL.h}if(bL>1||bN>1||E>1){bL/=360;bN/=100;E/=100}bL*=360;var S,bM,d,g,b;bL=(bL%360)/60;b=2*bN*(E<0.5?E:1-E);g=b*(1-aw(bL%2-1));S=bM=d=E-b/2;bL=~~bL;S+=[b,g,0,0,g,b][bL];bM+=[g,b,b,g,0,0][bL];d+=[0,0,g,b,b,g][bL];return a2(S,bM,d,i)};aR.rgb2hsb=function(bM,bL,d){d=aY(bM,bL,d);bM=d[0];bL=d[1];d=d[2];var R,E,i,bN;i=m(bM,bL,d);bN=i-bm(bM,bL,d);R=(bN==0?null:i==bM?(bL-d)/bN:i==bL?(d-bM)/bN+2:(bM-bL)/bN+4);R=((R+360)%6)*60/360;E=bN==0?0:bN/i;return{h:R,s:E,b:i,toString:aI}};aR.rgb2hsl=function(d,bL,bO){bO=aY(d,bL,bO);d=bO[0];bL=bO[1];bO=bO[2];var bP,R,bN,bM,E,i;bM=m(d,bL,bO);E=bm(d,bL,bO);i=bM-E;bP=(i==0?null:bM==d?(bL-bO)/i:bM==bL?(bO-d)/i+2:(d-bL)/i+4);bP=((bP+360)%6)*60/360;bN=(bM+E)/2;R=(i==0?0:bN<0.5?i/(2*bN):i/(2-2*bN));return{h:bP,s:R,l:bN,toString:M}};aR._path2string=function(){return this.join(",").replace(bg,"$1")};function bk(E,g){for(var b=0,d=E.length;b<d;b++){if(E[b]===g){return E.push(E.splice(b,1)[0])}}}function aG(i,d,b){function g(){var E=Array.prototype.slice.call(arguments,0),S=E.join("\u2400"),R=g.cache=g.cache||{},bL=g.count=g.count||[];if(R[ak](S)){bk(bL,S);return b?b(R[S]):R[S]}bL.length>=1000&&delete R[bL.shift()];bL.push(S);R[S]=i[bG](d,E);return b?b(R[S]):R[S]}return g}var bv=aR._preload=function(g,d){var b=aA.doc.createElement("img");b.style.cssText="position:absolute;left:-9999em;top:-9999em";b.onload=function(){d.call(this);this.onload=null;aA.doc.body.removeChild(this)};b.onerror=function(){aA.doc.body.removeChild(this)};aA.doc.body.appendChild(b);b.src=g};function aq(){return this.hex}aR.getRGB=aG(function(b){if(!b||!!((b=bH(b)).indexOf("-")+1)){return{r:-1,g:-1,b:-1,hex:"none",error:1,toString:aq}}if(b=="none"){return{r:-1,g:-1,b:-1,hex:"none",toString:aq}}!(n[ak](b.toLowerCase().substring(0,2))||b.charAt()=="#")&&(b=bf(b));var E,d,g,S,i,bM,bL,R=b.match(A);if(R){if(R[2]){S=U(R[2].substring(5),16);g=U(R[2].substring(3,5),16);d=U(R[2].substring(1,3),16)}if(R[3]){S=U((bM=R[3].charAt(3))+bM,16);g=U((bM=R[3].charAt(2))+bM,16);d=U((bM=R[3].charAt(1))+bM,16)}if(R[4]){bL=R[4][F](bi);d=an(bL[0]);bL[0].slice(-1)=="%"&&(d*=2.55);g=an(bL[1]);bL[1].slice(-1)=="%"&&(g*=2.55);S=an(bL[2]);bL[2].slice(-1)=="%"&&(S*=2.55);R[1].toLowerCase().slice(0,4)=="rgba"&&(i=an(bL[3]));bL[3]&&bL[3].slice(-1)=="%"&&(i/=100)}if(R[5]){bL=R[5][F](bi);d=an(bL[0]);bL[0].slice(-1)=="%"&&(d*=2.55);g=an(bL[1]);bL[1].slice(-1)=="%"&&(g*=2.55);S=an(bL[2]);bL[2].slice(-1)=="%"&&(S*=2.55);(bL[0].slice(-3)=="deg"||bL[0].slice(-1)=="\xb0")&&(d/=360);R[1].toLowerCase().slice(0,4)=="hsba"&&(i=an(bL[3]));bL[3]&&bL[3].slice(-1)=="%"&&(i/=100);return aR.hsb2rgb(d,g,S,i)}if(R[6]){bL=R[6][F](bi);d=an(bL[0]);bL[0].slice(-1)=="%"&&(d*=2.55);g=an(bL[1]);bL[1].slice(-1)=="%"&&(g*=2.55);S=an(bL[2]);bL[2].slice(-1)=="%"&&(S*=2.55);(bL[0].slice(-3)=="deg"||bL[0].slice(-1)=="\xb0")&&(d/=360);R[1].toLowerCase().slice(0,4)=="hsla"&&(i=an(bL[3]));bL[3]&&bL[3].slice(-1)=="%"&&(i/=100);return aR.hsl2rgb(d,g,S,i)}R={r:d,g:g,b:S,toString:aq};R.hex="#"+(16777216|S|(g<<8)|(d<<16)).toString(16).slice(1);aR.is(i,"finite")&&(R.opacity=i);return R}return{r:-1,g:-1,b:-1,hex:"none",error:1,toString:aq}},aR);aR.hsb=aG(function(i,g,d){return aR.hsb2rgb(i,g,d).hex});aR.hsl=aG(function(g,d,b){return aR.hsl2rgb(g,d,b).hex});aR.rgb=aG(function(E,i,d){return"#"+(16777216|d|(i<<8)|(E<<16)).toString(16).slice(1)});aR.getColor=function(d){var g=this.getColor.start=this.getColor.start||{h:0,s:1,b:d||0.75},b=this.hsb2rgb(g.h,g.s,g.b);g.h+=0.075;if(g.h>1){g.h=0;g.s-=0.2;g.s<=0&&(this.getColor.start={h:0,s:1,b:g.b})}return b.hex};aR.getColor.reset=function(){delete this.start};function bb(E,bL){var S=[];for(var g=0,b=E.length;b-2*!bL>g;g+=2){var R=[{x:+E[g-2],y:+E[g-1]},{x:+E[g],y:+E[g+1]},{x:+E[g+2],y:+E[g+3]},{x:+E[g+4],y:+E[g+5]}];if(bL){if(!g){R[0]={x:+E[b-2],y:+E[b-1]}}else{if(b-4==g){R[3]={x:+E[0],y:+E[1]}}else{if(b-2==g){R[2]={x:+E[0],y:+E[1]};R[3]={x:+E[2],y:+E[3]}}}}}else{if(b-4==g){R[3]=R[2]}else{if(!g){R[0]={x:+E[g],y:+E[g+1]}}}}S.push(["C",(-R[0].x+6*R[1].x+R[2].x)/6,(-R[0].y+6*R[1].y+R[2].y)/6,(R[1].x+6*R[2].x-R[3].x)/6,(R[1].y+6*R[2].y-R[3].y)/6,R[2].x,R[2].y])}return S}aR.parsePathString=function(b){if(!b){return null}var g=Y(b);if(g.arr){return aZ(g.arr)}var i={a:7,c:6,h:1,l:2,m:2,r:4,q:4,s:4,t:2,v:1,z:0},d=[];if(aR.is(b,bd)&&aR.is(b[0],bd)){d=aZ(b)}if(!d.length){bH(b).replace(a0,function(R,E,bM){var bL=[],S=E.toLowerCase();bM.replace(aP,function(bO,bN){bN&&bL.push(+bN)});if(S=="m"&&bL.length>2){d.push([E][bE](bL.splice(0,2)));S="l";E=E=="m"?"l":"L"}if(S=="r"){d.push([E][bE](bL))}else{while(bL.length>=i[S]){d.push([E][bE](bL.splice(0,i[S])));if(!i[S]){break}}}})}d.toString=aR._path2string;g.arr=aZ(d);return d};aR.parseTransformString=aG(function(d){if(!d){return null}var g={r:3,s:4,t:2,m:6},b=[];if(aR.is(d,bd)&&aR.is(d[0],bd)){b=aZ(d)}if(!b.length){bH(d).replace(ai,function(E,i,bL){var S=[],R=bK.call(i);bL.replace(aP,function(bN,bM){bM&&S.push(+bM)});b.push([i][bE](S))})}b.toString=aR._path2string;return b});var Y=function(d){var b=Y.ps=Y.ps||{};if(b[d]){b[d].sleep=100}else{b[d]={sleep:100}}setTimeout(function(){for(var g in b){if(b[ak](g)&&g!=d){b[g].sleep--;!b[g].sleep&&delete b[g]}}});return b[d]};aR.findDotsAtSegment=function(d,b,b2,b0,S,E,bN,bL,bV){var bS=1-bV,bX=bp(bS,3),bY=bp(bS,2),bP=bV*bV,bM=bP*bV,bR=bX*d+bY*3*bV*b2+bS*3*bV*bV*S+bM*bN,bO=bX*b+bY*3*bV*b0+bS*3*bV*bV*E+bM*bL,bW=d+2*bV*(b2-d)+bP*(S-2*b2+d),bU=b+2*bV*(b0-b)+bP*(E-2*b0+b),b1=b2+2*bV*(S-b2)+bP*(bN-2*S+b2),bZ=b0+2*bV*(E-b0)+bP*(bL-2*E+b0),bT=bS*d+bV*b2,bQ=bS*b+bV*b0,i=bS*S+bV*bN,g=bS*E+bV*bL,R=(90-au.atan2(bW-b1,bU-bZ)*180/aV);(bW>b1||bU<bZ)&&(R+=180);return{x:bR,y:bO,m:{x:bW,y:bU},n:{x:b1,y:bZ},start:{x:bT,y:bQ},end:{x:i,y:g},alpha:R}};aR.bezierBBox=function(d,b,i,g,bM,S,R,E){if(!aR.is(d,"array")){d=[d,b,i,g,bM,S,R,E]}var bL=ba.apply(null,d);return{x:bL.min.x,y:bL.min.y,x2:bL.max.x,y2:bL.max.y,width:bL.max.x-bL.min.x,height:bL.max.y-bL.min.y}};aR.isPointInsideBBox=function(d,b,g){return b>=d.x&&b<=d.x2&&g>=d.y&&g<=d.y2};aR.isBBoxIntersect=function(g,d){var b=aR.isPointInsideBBox;return b(d,g.x,g.y)||b(d,g.x2,g.y)||b(d,g.x,g.y2)||b(d,g.x2,g.y2)||b(g,d.x,d.y)||b(g,d.x2,d.y)||b(g,d.x,d.y2)||b(g,d.x2,d.y2)||(g.x<d.x2&&g.x>d.x||d.x<g.x2&&d.x>g.x)&&(g.y<d.y2&&g.y>d.y||d.y<g.y2&&d.y>g.y)};function bj(b,S,R,E,i){var g=-3*S+9*R-9*E+3*i,d=b*g+6*S-12*R+6*E;return b*d-3*S+3*R}function q(bW,R,bV,g,bU,d,bR,b,bO){if(bO==null){bO=1}bO=bO>1?1:bO<0?0:bO;var bP=bO/2,bQ=12,bL=[-0.1252,0.1252,-0.3678,0.3678,-0.5873,0.5873,-0.7699,0.7699,-0.9041,0.9041,-0.9816,0.9816],bT=[0.2491,0.2491,0.2335,0.2335,0.2032,0.2032,0.1601,0.1601,0.1069,0.1069,0.0472,0.0472],E=0;for(var bS=0;bS<bQ;bS++){var bM=bP*bL[bS]+bP,bN=bj(bM,bW,bV,bU,bR),bX=bj(bM,R,g,d,b),S=bN*bN+bX*bX;E+=bT[bS]*au.sqrt(S)}return bP*E}function C(g,bP,d,bO,b,bM,bR,bL,bN){if(bN<0||q(g,bP,d,bO,b,bM,bR,bL)<bN){return}var bQ=1,i=bQ/2,R=bQ-i,E,S=0.01;E=q(g,bP,d,bO,b,bM,bR,bL,R);while(aw(E-bN)>S){i/=2;R+=(E<bN?1:-1)*i;E=q(g,bP,d,bO,b,bM,bR,bL,R)}return R}function O(i,bQ,g,bO,b,bN,bS,bM){if(m(i,g)<bm(b,bS)||bm(i,g)>m(b,bS)||m(bQ,bO)<bm(bN,bM)||bm(bQ,bO)>m(bN,bM)){return}var bL=(i*bO-bQ*g)*(b-bS)-(i-g)*(b*bM-bN*bS),S=(i*bO-bQ*g)*(bN-bM)-(bQ-bO)*(b*bM-bN*bS),E=(i-g)*(bN-bM)-(bQ-bO)*(b-bS);if(!E){return}var bR=bL/E,bP=S/E,R=+bR.toFixed(2),d=+bP.toFixed(2);if(R<+bm(i,g).toFixed(2)||R>+m(i,g).toFixed(2)||R<+bm(b,bS).toFixed(2)||R>+m(b,bS).toFixed(2)||d<+bm(bQ,bO).toFixed(2)||d>+m(bQ,bO).toFixed(2)||d<+bm(bN,bM).toFixed(2)||d>+m(bN,bM).toFixed(2)){return}return{x:bR,y:bP}}function ay(d,b){return af(d,b)}function t(d,b){return af(d,b,1)}function af(b2,b1,b0){var E=aR.bezierBBox(b2),d=aR.bezierBBox(b1);if(!aR.isBBoxIntersect(E,d)){return b0?0:[]}var bV=q.apply(0,b2),bU=q.apply(0,b1),bM=~~(bV/5),bL=~~(bU/5),bS=[],bR=[],g={},b3=b0?0:[];for(var bX=0;bX<bM+1;bX++){var bT=aR.findDotsAtSegment.apply(aR,b2.concat(bX/bM));bS.push({x:bT.x,y:bT.y,t:bX/bM})}for(bX=0;bX<bL+1;bX++){bT=aR.findDotsAtSegment.apply(aR,b1.concat(bX/bL));bR.push({x:bT.x,y:bT.y,t:bX/bL})}for(bX=0;bX<bM;bX++){for(var bW=0;bW<bL;bW++){var bZ=bS[bX],b=bS[bX+1],bY=bR[bW],S=bR[bW+1],bQ=aw(b.x-bZ.x)<0.001?"y":"x",bP=aw(S.x-bY.x)<0.001?"y":"x",R=O(bZ.x,bZ.y,b.x,b.y,bY.x,bY.y,S.x,S.y);if(R){if(g[R.x.toFixed(4)]==R.y.toFixed(4)){continue}g[R.x.toFixed(4)]=R.y.toFixed(4);var bO=bZ.t+aw((R[bQ]-bZ[bQ])/(b[bQ]-bZ[bQ]))*(b.t-bZ.t),bN=bY.t+aw((R[bP]-bY[bP])/(S[bP]-bY[bP]))*(S.t-bY.t);if(bO>=0&&bO<=1&&bN>=0&&bN<=1){if(b0){b3++}else{b3.push({x:R.x,y:R.y,t1:bO,t2:bN})}}}}}return b3}aR.pathIntersection=function(d,b){return D(d,b)};aR.pathIntersectionNumber=function(d,b){return D(d,b,1)};function D(g,b,bW){g=aR._path2curve(g);b=aR._path2curve(b);var bU,S,bT,E,bR,bL,d,bO,b0,bZ,b1=bW?0:[];for(var bS=0,bM=g.length;bS<bM;bS++){var bY=g[bS];if(bY[0]=="M"){bU=bR=bY[1];S=bL=bY[2]}else{if(bY[0]=="C"){b0=[bU,S].concat(bY.slice(1));bU=b0[6];S=b0[7]}else{b0=[bU,S,bU,S,bR,bL,bR,bL];bU=bR;S=bL}for(var bQ=0,bV=b.length;bQ<bV;bQ++){var bX=b[bQ];if(bX[0]=="M"){bT=d=bX[1];E=bO=bX[2]}else{if(bX[0]=="C"){bZ=[bT,E].concat(bX.slice(1));bT=bZ[6];E=bZ[7]}else{bZ=[bT,E,bT,E,d,bO,d,bO];bT=d;E=bO}var bN=af(b0,bZ,bW);if(bW){b1+=bN}else{for(var bP=0,R=bN.length;bP<R;bP++){bN[bP].segment1=bS;bN[bP].segment2=bQ;bN[bP].bez1=b0;bN[bP].bez2=bZ}b1=b1.concat(bN)}}}}}return b1}aR.isPointInsidePath=function(d,b,i){var g=aR.pathBBox(d);return aR.isPointInsideBBox(g,b,i)&&D(d,[["M",b,i],["H",g.x2+10]],1)%2==1};aR._removedFactory=function(b){return function(){eve("raphael.log",null,"Rapha\xebl: you are calling to method \u201c"+b+"\u201d of removed object",b)}};var am=aR.pathBBox=function(bT){var bN=Y(bT);if(bN.bbox){return bN.bbox}if(!bT){return{x:0,y:0,width:0,height:0,x2:0,y2:0}}bT=W(bT);var bQ=0,bP=0,R=[],d=[],g;for(var bL=0,bS=bT.length;bL<bS;bL++){g=bT[bL];if(g[0]=="M"){bQ=g[1];bP=g[2];R.push(bQ);d.push(bP)}else{var bM=ba(bQ,bP,g[1],g[2],g[3],g[4],g[5],g[6]);R=R[bE](bM.min.x,bM.max.x);d=d[bE](bM.min.y,bM.max.y);bQ=g[5];bP=g[6]}}var b=bm[bG](0,R),bR=bm[bG](0,d),S=m[bG](0,R),E=m[bG](0,d),bO={x:b,y:bR,x2:S,y2:E,width:S-b,height:E-bR};bN.bbox=X(bO);return bO},aZ=function(d){var b=X(d);b.toString=aR._path2string;return b},aC=aR._pathToRelative=function(E){var bM=Y(E);if(bM.rel){return aZ(bM.rel)}if(!aR.is(E,bd)||!aR.is(E&&E[0],bd)){E=aR.parsePathString(E)}var bP=[],bR=0,bQ=0,bU=0,bT=0,g=0;if(E[0][0]=="M"){bR=E[0][1];bQ=E[0][2];bU=bR;bT=bQ;g++;bP.push(["M",bR,bQ])}for(var bL=g,bV=E.length;bL<bV;bL++){var b=bP[bL]=[],bS=E[bL];if(bS[0]!=bK.call(bS[0])){b[0]=bK.call(bS[0]);switch(b[0]){case"a":b[1]=bS[1];b[2]=bS[2];b[3]=bS[3];b[4]=bS[4];b[5]=bS[5];b[6]=+(bS[6]-bR).toFixed(3);b[7]=+(bS[7]-bQ).toFixed(3);break;case"v":b[1]=+(bS[1]-bQ).toFixed(3);break;case"m":bU=bS[1];bT=bS[2];default:for(var S=1,bN=bS.length;S<bN;S++){b[S]=+(bS[S]-((S%2)?bR:bQ)).toFixed(3)}}}else{b=bP[bL]=[];if(bS[0]=="m"){bU=bS[1]+bR;bT=bS[2]+bQ}for(var R=0,d=bS.length;R<d;R++){bP[bL][R]=bS[R]}}var bO=bP[bL].length;switch(bP[bL][0]){case"z":bR=bU;bQ=bT;break;case"h":bR+=+bP[bL][bO-1];break;case"v":bQ+=+bP[bL][bO-1];break;default:bR+=+bP[bL][bO-2];bQ+=+bP[bL][bO-1]}}bP.toString=aR._path2string;bM.rel=aZ(bP);return bP},w=aR._pathToAbsolute=function(bQ){var g=Y(bQ);if(g.abs){return aZ(g.abs)}if(!aR.is(bQ,bd)||!aR.is(bQ&&bQ[0],bd)){bQ=aR.parsePathString(bQ)}if(!bQ||!bQ.length){return[["M",0,0]]}var bW=[],bL=0,S=0,bO=0,bN=0,E=0;if(bQ[0][0]=="M"){bL=+bQ[0][1];S=+bQ[0][2];bO=bL;bN=S;E++;bW[0]=["M",bL,S]}var bV=bQ.length==3&&bQ[0][0]=="M"&&bQ[1][0].toUpperCase()=="R"&&bQ[2][0].toUpperCase()=="Z";for(var bP,b,bT=E,bM=bQ.length;bT<bM;bT++){bW.push(bP=[]);b=bQ[bT];if(b[0]!=bt.call(b[0])){bP[0]=bt.call(b[0]);switch(bP[0]){case"A":bP[1]=b[1];bP[2]=b[2];bP[3]=b[3];bP[4]=b[4];bP[5]=b[5];bP[6]=+(b[6]+bL);bP[7]=+(b[7]+S);break;case"V":bP[1]=+b[1]+S;break;case"H":bP[1]=+b[1]+bL;break;case"R":var R=[bL,S][bE](b.slice(1));for(var bS=2,bU=R.length;bS<bU;bS++){R[bS]=+R[bS]+bL;R[++bS]=+R[bS]+S}bW.pop();bW=bW[bE](bb(R,bV));break;case"M":bO=+b[1]+bL;bN=+b[2]+S;default:for(bS=1,bU=b.length;bS<bU;bS++){bP[bS]=+b[bS]+((bS%2)?bL:S)}}}else{if(b[0]=="R"){R=[bL,S][bE](b.slice(1));bW.pop();bW=bW[bE](bb(R,bV));bP=["R"][bE](b.slice(-2))}else{for(var bR=0,d=b.length;bR<d;bR++){bP[bR]=b[bR]}}}switch(bP[0]){case"Z":bL=bO;S=bN;break;case"H":bL=bP[1];break;case"V":S=bP[1];break;case"M":bO=bP[bP.length-2];bN=bP[bP.length-1];default:bL=bP[bP.length-2];S=bP[bP.length-1]}}bW.toString=aR._path2string;g.abs=aZ(bW);return bW},bI=function(d,i,b,g){return[d,i,b,g,b,g]},bn=function(d,i,S,E,b,g){var R=1/3,bL=2/3;return[R*d+bL*S,R*i+bL*E,R*b+bL*S,R*g+bL*E,b,g]},ae=function(bS,cn,b1,bZ,bT,bN,E,bR,cm,bU){var bY=aV*120/180,b=aV/180*(+bT||0),b5=[],b2,cj=aG(function(co,cr,i){var cq=co*au.cos(i)-cr*au.sin(i),cp=co*au.sin(i)+cr*au.cos(i);return{x:cq,y:cp}});if(!bU){b2=cj(bS,cn,-b);bS=b2.x;cn=b2.y;b2=cj(bR,cm,-b);bR=b2.x;cm=b2.y;var d=au.cos(aV/180*bT),bP=au.sin(aV/180*bT),b7=(bS-bR)/2,b6=(cn-cm)/2;var ch=(b7*b7)/(b1*b1)+(b6*b6)/(bZ*bZ);if(ch>1){ch=au.sqrt(ch);b1=ch*b1;bZ=ch*bZ}var g=b1*b1,ca=bZ*bZ,cc=(bN==E?-1:1)*au.sqrt(aw((g*ca-g*b6*b6-ca*b7*b7)/(g*b6*b6+ca*b7*b7))),bW=cc*b1*b6/bZ+(bS+bR)/2,bV=cc*-bZ*b7/b1+(cn+cm)/2,bM=au.asin(((cn-bV)/bZ).toFixed(9)),bL=au.asin(((cm-bV)/bZ).toFixed(9));bM=bS<bW?aV-bM:bM;bL=bR<bW?aV-bL:bL;bM<0&&(bM=aV*2+bM);bL<0&&(bL=aV*2+bL);if(E&&bM>bL){bM=bM-aV*2}if(!E&&bL>bM){bL=bL-aV*2}}else{bM=bU[0];bL=bU[1];bW=bU[2];bV=bU[3]}var bQ=bL-bM;if(aw(bQ)>bY){var bX=bL,b0=bR,bO=cm;bL=bM+bY*(E&&bL>bM?1:-1);bR=bW+b1*au.cos(bL);cm=bV+bZ*au.sin(bL);b5=ae(bR,cm,b1,bZ,bT,0,E,b0,bO,[bL,bX,bW,bV])}bQ=bL-bM;var S=au.cos(bM),cl=au.sin(bM),R=au.cos(bL),ck=au.sin(bL),b8=au.tan(bQ/4),cb=4/3*b1*b8,b9=4/3*bZ*b8,ci=[bS,cn],cg=[bS+cb*cl,cn-b9*S],cf=[bR+cb*ck,cm-b9*R],cd=[bR,cm];cg[0]=2*ci[0]-cg[0];cg[1]=2*ci[1]-cg[1];if(bU){return[cg,cf,cd][bE](b5)}else{b5=[cg,cf,cd][bE](b5).join()[F](",");var b3=[];for(var ce=0,b4=b5.length;ce<b4;ce++){b3[ce]=ce%2?cj(b5[ce-1],b5[ce],b).y:cj(b5[ce],b5[ce+1],b).x}return b3}},ag=function(d,b,i,g,bM,bL,S,R,bN){var E=1-bN;return{x:bp(E,3)*d+bp(E,2)*3*bN*i+E*3*bN*bN*bM+bp(bN,3)*S,y:bp(E,3)*b+bp(E,2)*3*bN*g+E*3*bN*bN*bL+bp(bN,3)*R}},ba=aG(function(i,d,R,E,bU,bT,bQ,bN){var bS=(bU-2*R+i)-(bQ-2*bU+R),bP=2*(R-i)-2*(bU-R),bM=i-R,bL=(-bP+au.sqrt(bP*bP-4*bS*bM))/2/bS,S=(-bP-au.sqrt(bP*bP-4*bS*bM))/2/bS,bO=[d,bN],bR=[i,bQ],g;aw(bL)>"1e12"&&(bL=0.5);aw(S)>"1e12"&&(S=0.5);if(bL>0&&bL<1){g=ag(i,d,R,E,bU,bT,bQ,bN,bL);bR.push(g.x);bO.push(g.y)}if(S>0&&S<1){g=ag(i,d,R,E,bU,bT,bQ,bN,S);bR.push(g.x);bO.push(g.y)}bS=(bT-2*E+d)-(bN-2*bT+E);bP=2*(E-d)-2*(bT-E);bM=d-E;bL=(-bP+au.sqrt(bP*bP-4*bS*bM))/2/bS;S=(-bP-au.sqrt(bP*bP-4*bS*bM))/2/bS;aw(bL)>"1e12"&&(bL=0.5);aw(S)>"1e12"&&(S=0.5);if(bL>0&&bL<1){g=ag(i,d,R,E,bU,bT,bQ,bN,bL);bR.push(g.x);bO.push(g.y)}if(S>0&&S<1){g=ag(i,d,R,E,bU,bT,bQ,bN,S);bR.push(g.x);bO.push(g.y)}return{min:{x:bm[bG](0,bR),y:bm[bG](0,bO)},max:{x:m[bG](0,bR),y:m[bG](0,bO)}}}),W=aR._path2curve=aG(function(bU,bP){var bN=!bP&&Y(bU);if(!bP&&bN.curve){return aZ(bN.curve)}var E=w(bU),bQ=bP&&w(bP),bR={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},d={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},S=function(bV,bW){var i,bX;if(!bV){return["C",bW.x,bW.y,bW.x,bW.y,bW.x,bW.y]}!(bV[0] in {T:1,Q:1})&&(bW.qx=bW.qy=null);switch(bV[0]){case"M":bW.X=bV[1];bW.Y=bV[2];break;case"A":bV=["C"][bE](ae[bG](0,[bW.x,bW.y][bE](bV.slice(1))));break;case"S":i=bW.x+(bW.x-(bW.bx||bW.x));bX=bW.y+(bW.y-(bW.by||bW.y));bV=["C",i,bX][bE](bV.slice(1));break;case"T":bW.qx=bW.x+(bW.x-(bW.qx||bW.x));bW.qy=bW.y+(bW.y-(bW.qy||bW.y));bV=["C"][bE](bn(bW.x,bW.y,bW.qx,bW.qy,bV[1],bV[2]));break;case"Q":bW.qx=bV[1];bW.qy=bV[2];bV=["C"][bE](bn(bW.x,bW.y,bV[1],bV[2],bV[3],bV[4]));break;case"L":bV=["C"][bE](bI(bW.x,bW.y,bV[1],bV[2]));break;case"H":bV=["C"][bE](bI(bW.x,bW.y,bV[1],bW.y));break;case"V":bV=["C"][bE](bI(bW.x,bW.y,bW.x,bV[1]));break;case"Z":bV=["C"][bE](bI(bW.x,bW.y,bW.X,bW.Y));break}return bV},b=function(bV,bW){if(bV[bW].length>7){bV[bW].shift();var bX=bV[bW];while(bX.length){bV.splice(bW++,0,["C"][bE](bX.splice(0,6)))}bV.splice(bW,1);bS=m(E.length,bQ&&bQ.length||0)}},g=function(bZ,bY,bW,bV,bX){if(bZ&&bY&&bZ[bX][0]=="M"&&bY[bX][0]!="M"){bY.splice(bX,0,["M",bV.x,bV.y]);bW.bx=0;bW.by=0;bW.x=bZ[bX][1];bW.y=bZ[bX][2];bS=m(E.length,bQ&&bQ.length||0)}};for(var bM=0,bS=m(E.length,bQ&&bQ.length||0);bM<bS;bM++){E[bM]=S(E[bM],bR);b(E,bM);bQ&&(bQ[bM]=S(bQ[bM],d));bQ&&b(bQ,bM);g(E,bQ,bR,d,bM);g(bQ,E,d,bR,bM);var bL=E[bM],bT=bQ&&bQ[bM],R=bL.length,bO=bQ&&bT.length;bR.x=bL[R-2];bR.y=bL[R-1];bR.bx=an(bL[R-4])||bR.x;bR.by=an(bL[R-3])||bR.y;d.bx=bQ&&(an(bT[bO-4])||d.x);d.by=bQ&&(an(bT[bO-3])||d.y);d.x=bQ&&bT[bO-2];d.y=bQ&&bT[bO-1]}if(!bQ){bN.curve=aZ(E)}return bQ?[E,bQ]:E},null,aZ),v=aR._parseDots=aG(function(bO){var bN=[];for(var S=0,bP=bO.length;S<bP;S++){var b={},bM=bO[S].match(/^([^:]*):?([\d\.]*)/);b.color=aR.getRGB(bM[1]);if(b.color.error){return null}b.color=b.color.hex;bM[2]&&(b.offset=bM[2]+"%");bN.push(b)}for(S=1,bP=bN.length-1;S<bP;S++){if(!bN[S].offset){var g=an(bN[S-1].offset||0),E=0;for(var R=S+1;R<bP;R++){if(bN[R].offset){E=bN[R].offset;break}}if(!E){E=100;R=bP}E=an(E);var bL=(E-g)/(R-S+1);for(;S<R;S++){g+=bL;bN[S].offset=g+"%"}}}return bN}),aK=aR._tear=function(b,d){b==d.top&&(d.top=b.prev);b==d.bottom&&(d.bottom=b.next);b.next&&(b.next.prev=b.prev);b.prev&&(b.prev.next=b.next)},ap=aR._tofront=function(b,d){if(d.top===b){return}aK(b,d);b.next=null;b.prev=d.top;d.top.next=b;d.top=b},p=aR._toback=function(b,d){if(d.bottom===b){return}aK(b,d);b.next=d.bottom;b.prev=null;d.bottom.prev=b;d.bottom=b},G=aR._insertafter=function(d,b,g){aK(d,g);b==g.top&&(g.top=d);b.next&&(b.next.prev=d);d.next=b.next;d.prev=b;b.next=d},aT=aR._insertbefore=function(d,b,g){aK(d,g);b==g.bottom&&(g.bottom=d);b.prev&&(b.prev.next=d);d.prev=b.prev;b.prev=d;d.next=b},bl=aR.toMatrix=function(g,b){var i=am(g),d={_:{transform:aX},getBBox:function(){return i}};aO(d,b);return d.matrix},T=aR.transformPath=function(d,b){return L(d,bl(d,b))},aO=aR._extractTransform=function(d,bZ){if(bZ==null){return d._.transform}bZ=bH(bZ).replace(/\.{3}|\u2026/g,d._.transform||aX);var bR=aR.parseTransformString(bZ),bP=0,bN=0,bM=0,bT=1,bS=1,b0=d._,bU=new aF;b0.transform=bR||[];if(bR){for(var bV=0,bO=bR.length;bV<bO;bV++){var bQ=bR[bV],b=bQ.length,R=bH(bQ[0]).toLowerCase(),bY=bQ[0]!=R,bL=bY?bU.invert():0,bX,E,bW,g,S;if(R=="t"&&b==3){if(bY){bX=bL.x(0,0);E=bL.y(0,0);bW=bL.x(bQ[1],bQ[2]);g=bL.y(bQ[1],bQ[2]);bU.translate(bW-bX,g-E)}else{bU.translate(bQ[1],bQ[2])}}else{if(R=="r"){if(b==2){S=S||d.getBBox(1);bU.rotate(bQ[1],S.x+S.width/2,S.y+S.height/2);bP+=bQ[1]}else{if(b==4){if(bY){bW=bL.x(bQ[2],bQ[3]);g=bL.y(bQ[2],bQ[3]);bU.rotate(bQ[1],bW,g)}else{bU.rotate(bQ[1],bQ[2],bQ[3])}bP+=bQ[1]}}}else{if(R=="s"){if(b==2||b==3){S=S||d.getBBox(1);bU.scale(bQ[1],bQ[b-1],S.x+S.width/2,S.y+S.height/2);bT*=bQ[1];bS*=bQ[b-1]}else{if(b==5){if(bY){bW=bL.x(bQ[3],bQ[4]);g=bL.y(bQ[3],bQ[4]);bU.scale(bQ[1],bQ[2],bW,g)}else{bU.scale(bQ[1],bQ[2],bQ[3],bQ[4])}bT*=bQ[1];bS*=bQ[2]}}}else{if(R=="m"&&b==7){bU.add(bQ[1],bQ[2],bQ[3],bQ[4],bQ[5],bQ[6])}}}}b0.dirtyT=1;d.matrix=bU}}d.matrix=bU;b0.sx=bT;b0.sy=bS;b0.deg=bP;b0.dx=bN=bU.e;b0.dy=bM=bU.f;if(bT==1&&bS==1&&!bP&&b0.bbox){b0.bbox.x+=+bN;b0.bbox.y+=+bM}else{b0.dirtyT=1}},l=function(d){var b=d[0];switch(b.toLowerCase()){case"t":return[b,0,0];case"m":return[b,1,0,0,1,0,0];case"r":if(d.length==4){return[b,0,d[2],d[3]]}else{return[b,0]}case"s":if(d.length==5){return[b,1,1,d[3],d[4]]}else{if(d.length==3){return[b,1,1]}else{return[b,1]}}}},aB=aR._equaliseTransform=function(R,E){E=bH(E).replace(/\.{3}|\u2026/g,R);R=aR.parseTransformString(R)||[];E=aR.parseTransformString(E)||[];var b=m(R.length,E.length),bN=[],bO=[],g=0,d,S,bM,bL;for(;g<b;g++){bM=R[g]||l(E[g]);bL=E[g]||l(bM);if((bM[0]!=bL[0])||(bM[0].toLowerCase()=="r"&&(bM[2]!=bL[2]||bM[3]!=bL[3]))||(bM[0].toLowerCase()=="s"&&(bM[3]!=bL[3]||bM[4]!=bL[4]))){return}bN[g]=[];bO[g]=[];for(d=0,S=m(bM.length,bL.length);d<S;d++){d in bM&&(bN[g][d]=bM[d]);d in bL&&(bO[g][d]=bL[d])}}return{from:bN,to:bO}};aR._getContainer=function(b,E,g,i){var d;d=i==null&&!aR.is(b,"object")?aA.doc.getElementById(b):b;if(d==null){return}if(d.tagName){if(E==null){return{container:d,width:d.style.pixelWidth||d.offsetWidth,height:d.style.pixelHeight||d.offsetHeight}}else{return{container:d,width:E,height:g}}}return{container:1,x:b,y:E,width:g,height:i}};aR.pathToRelative=aC;aR._engine={};aR.path2curve=W;aR.matrix=function(i,g,bL,S,R,E){return new aF(i,g,bL,S,R,E)};function aF(i,g,bL,S,R,E){if(i!=null){this.a=+i;this.b=+g;this.c=+bL;this.d=+S;this.e=+R;this.f=+E}else{this.a=1;this.b=0;this.c=0;this.d=1;this.e=0;this.f=0}}(function(g){g.add=function(bT,bQ,bO,bM,S,R){var E=[[],[],[]],i=[[this.a,this.c,this.e],[this.b,this.d,this.f],[0,0,1]],bS=[[bT,bO,S],[bQ,bM,R],[0,0,1]],bR,bP,bN,bL;if(bT&&bT instanceof aF){bS=[[bT.a,bT.c,bT.e],[bT.b,bT.d,bT.f],[0,0,1]]}for(bR=0;bR<3;bR++){for(bP=0;bP<3;bP++){bL=0;for(bN=0;bN<3;bN++){bL+=i[bR][bN]*bS[bN][bP]}E[bR][bP]=bL}}this.a=E[0][0];this.b=E[1][0];this.c=E[0][1];this.d=E[1][1];this.e=E[0][2];this.f=E[1][2]};g.invert=function(){var E=this,i=E.a*E.d-E.b*E.c;return new aF(E.d/i,-E.b/i,-E.c/i,E.a/i,(E.c*E.f-E.d*E.e)/i,(E.b*E.e-E.a*E.f)/i)};g.clone=function(){return new aF(this.a,this.b,this.c,this.d,this.e,this.f)};g.translate=function(i,E){this.add(1,0,0,1,i,E)};g.scale=function(E,S,i,R){S==null&&(S=E);(i||R)&&this.add(1,0,0,1,i,R);this.add(E,0,0,S,0,0);(i||R)&&this.add(1,0,0,1,-i,-R)};g.rotate=function(E,i,bL){E=aR.rad(E);i=i||0;bL=bL||0;var S=+au.cos(E).toFixed(9),R=+au.sin(E).toFixed(9);this.add(S,R,-R,S,i,bL);this.add(1,0,0,1,-i,-bL)};g.x=function(i,E){return i*this.a+E*this.c+this.e};g.y=function(i,E){return i*this.b+E*this.d+this.f};g.get=function(E){return +this[bH.fromCharCode(97+E)].toFixed(4)};g.toString=function(){return aR.svg?"matrix("+[this.get(0),this.get(1),this.get(2),this.get(3),this.get(4),this.get(5)].join()+")":[this.get(0),this.get(2),this.get(1),this.get(3),0,0].join()};g.toFilter=function(){return"progid:DXImageTransform.Microsoft.Matrix(M11="+this.get(0)+", M12="+this.get(2)+", M21="+this.get(1)+", M22="+this.get(3)+", Dx="+this.get(4)+", Dy="+this.get(5)+", sizingmethod='auto expand')"};g.offset=function(){return[this.e.toFixed(4),this.f.toFixed(4)]};function d(i){return i[0]*i[0]+i[1]*i[1]}function b(i){var E=au.sqrt(d(i));i[0]&&(i[0]/=E);i[1]&&(i[1]/=E)}g.split=function(){var E={};E.dx=this.e;E.dy=this.f;var S=[[this.a,this.c],[this.b,this.d]];E.scalex=au.sqrt(d(S[0]));b(S[0]);E.shear=S[0][0]*S[1][0]+S[0][1]*S[1][1];S[1]=[S[1][0]-S[0][0]*E.shear,S[1][1]-S[0][1]*E.shear];E.scaley=au.sqrt(d(S[1]));b(S[1]);E.shear/=E.scaley;var i=-S[0][1],R=S[1][1];if(R<0){E.rotate=aR.deg(au.acos(R));if(i<0){E.rotate=360-E.rotate}}else{E.rotate=aR.deg(au.asin(i))}E.isSimple=!+E.shear.toFixed(9)&&(E.scalex.toFixed(9)==E.scaley.toFixed(9)||!E.rotate);E.isSuperSimple=!+E.shear.toFixed(9)&&E.scalex.toFixed(9)==E.scaley.toFixed(9)&&!E.rotate;E.noRotation=!+E.shear.toFixed(9)&&!E.rotate;return E};g.toTransformString=function(i){var E=i||this[F]();if(E.isSimple){E.scalex=+E.scalex.toFixed(4);E.scaley=+E.scaley.toFixed(4);E.rotate=+E.rotate.toFixed(4);return(E.dx||E.dy?"t"+[E.dx,E.dy]:aX)+(E.scalex!=1||E.scaley!=1?"s"+[E.scalex,E.scaley,0,0]:aX)+(E.rotate?"r"+[E.rotate,0,0]:aX)}else{return"m"+[this.get(0),this.get(1),this.get(2),this.get(3),this.get(4),this.get(5)]}}})(aF.prototype);var V=navigator.userAgent.match(/Version\/(.*?)\s/)||navigator.userAgent.match(/Chrome\/(\d+)/);if((navigator.vendor=="Apple Computer, Inc.")&&(V&&V[1]<4||navigator.platform.slice(0,2)=="iP")||(navigator.vendor=="Google Inc."&&V&&V[1]<8)){a4.safari=function(){var b=this.rect(-99,-99,this.width+99,this.height+99).attr({stroke:"none"});setTimeout(function(){b.remove()})}}else{a4.safari=I}var P=function(){this.returnValue=false},bD=function(){return this.originalEvent.preventDefault()},a8=function(){this.cancelBubble=true},aJ=function(){return this.originalEvent.stopPropagation()},aD=(function(){if(aA.doc.addEventListener){return function(R,i,g,d){var b=Z&&bx[i]?bx[i]:i,E=function(bP){var bO=aA.doc.documentElement.scrollTop||aA.doc.body.scrollTop,bQ=aA.doc.documentElement.scrollLeft||aA.doc.body.scrollLeft,S=bP.clientX+bQ,bR=bP.clientY+bO;if(Z&&bx[ak](i)){for(var bM=0,bN=bP.targetTouches&&bP.targetTouches.length;bM<bN;bM++){if(bP.targetTouches[bM].target==R){var bL=bP;bP=bP.targetTouches[bM];bP.originalEvent=bL;bP.preventDefault=bD;bP.stopPropagation=aJ;break}}}return g.call(d,bP,S,bR)};R.addEventListener(b,E,false);return function(){R.removeEventListener(b,E,false);return true}}}else{if(aA.doc.attachEvent){return function(R,i,g,d){var E=function(bM){bM=bM||aA.win.event;var bL=aA.doc.documentElement.scrollTop||aA.doc.body.scrollTop,bN=aA.doc.documentElement.scrollLeft||aA.doc.body.scrollLeft,S=bM.clientX+bN,bO=bM.clientY+bL;bM.preventDefault=bM.preventDefault||P;bM.stopPropagation=bM.stopPropagation||a8;return g.call(d,bM,S,bO)};R.attachEvent("on"+i,E);var b=function(){R.detachEvent("on"+i,E);return true};return b}}}})(),be=[],by=function(bM){var bP=bM.clientX,bO=bM.clientY,bR=aA.doc.documentElement.scrollTop||aA.doc.body.scrollTop,bS=aA.doc.documentElement.scrollLeft||aA.doc.body.scrollLeft,g,E=be.length;while(E--){g=be[E];if(Z){var S=bM.touches.length,R;while(S--){R=bM.touches[S];if(R.identifier==g.el._drag.id){bP=R.clientX;bO=R.clientY;(bM.originalEvent?bM.originalEvent:bM).preventDefault();break}}}else{bM.preventDefault()}var d=g.el.node,b,bL=d.nextSibling,bQ=d.parentNode,bN=d.style.display;aA.win.opera&&bQ.removeChild(d);d.style.display="none";b=g.el.paper.getElementByPoint(bP,bO);d.style.display=bN;aA.win.opera&&(bL?bQ.insertBefore(d,bL):bQ.appendChild(d));b&&eve("raphael.drag.over."+g.el.id,g.el,b);bP+=bS;bO+=bR;eve("raphael.drag.move."+g.el.id,g.move_scope||g.el,bP-g.el._drag.x,bO-g.el._drag.y,bP,bO,bM)}},e=function(g){aR.unmousemove(by).unmouseup(e);var d=be.length,b;while(d--){b=be[d];b.el._drag={};eve("raphael.drag.end."+b.el.id,b.end_scope||b.start_scope||b.move_scope||b.el,g)}be=[]},bh=aR.el={};for(var ax=Q.length;ax--;){(function(b){aR[b]=bh[b]=function(g,d){if(aR.is(g,"function")){this.events=this.events||[];this.events.push({name:b,f:g,unbind:aD(this.shape||this.node||aA.doc,b,g,d||this)})}return this};aR["un"+b]=bh["un"+b]=function(i){var g=this.events||[],d=g.length;while(d--){if(g[d].name==b&&g[d].f==i){g[d].unbind();g.splice(d,1);!g.length&&delete this.events;return this}}return this}})(Q[ax])}bh.data=function(d,E){var g=aU[this.id]=aU[this.id]||{};if(arguments.length==1){if(aR.is(d,"object")){for(var b in d){if(d[ak](b)){this.data(b,d[b])}}return this}eve("raphael.data.get."+this.id,this,g[d],d);return g[d]}g[d]=E;eve("raphael.data.set."+this.id,this,E,d);return this};bh.removeData=function(b){if(b==null){aU[this.id]={}}else{aU[this.id]&&delete aU[this.id][b]}return this};bh.hover=function(i,b,g,d){return this.mouseover(i,g).mouseout(b,d||g)};bh.unhover=function(d,b){return this.unmouseover(d).unmouseout(b)};var bu=[];bh.drag=function(d,R,E,b,g,i){function S(bM){(bM.originalEvent||bM).preventDefault();var bL=aA.doc.documentElement.scrollTop||aA.doc.body.scrollTop,bN=aA.doc.documentElement.scrollLeft||aA.doc.body.scrollLeft;this._drag.x=bM.clientX+bN;this._drag.y=bM.clientY+bL;this._drag.id=bM.identifier;!be.length&&aR.mousemove(by).mouseup(e);be.push({el:this,move_scope:b,start_scope:g,end_scope:i});R&&eve.on("raphael.drag.start."+this.id,R);d&&eve.on("raphael.drag.move."+this.id,d);E&&eve.on("raphael.drag.end."+this.id,E);eve("raphael.drag.start."+this.id,g||b||this,bM.clientX+bN,bM.clientY+bL,bM)}this._drag={};bu.push({el:this,start:S});this.mousedown(S);return this};bh.onDragOver=function(b){b?eve.on("raphael.drag.over."+this.id,b):eve.unbind("raphael.drag.over."+this.id)};bh.undrag=function(){var b=bu.length;while(b--){if(bu[b].el==this){this.unmousedown(bu[b].start);bu.splice(b,1);eve.unbind("raphael.drag.*."+this.id)}}!bu.length&&aR.unmousemove(by).unmouseup(e)};a4.circle=function(b,i,g){var d=aR._engine.circle(this,b||0,i||0,g||0);this.__set__&&this.__set__.push(d);return d};a4.rect=function(b,R,d,i,E){var g=aR._engine.rect(this,b||0,R||0,d||0,i||0,E||0);this.__set__&&this.__set__.push(g);return g};a4.ellipse=function(b,E,i,g){var d=aR._engine.ellipse(this,b||0,E||0,i||0,g||0);this.__set__&&this.__set__.push(d);return d};a4.path=function(b){b&&!aR.is(b,aj)&&!aR.is(b[0],bd)&&(b+=aX);var d=aR._engine.path(aR.format[bG](aR,arguments),this);this.__set__&&this.__set__.push(d);return d};a4.image=function(E,b,R,d,i){var g=aR._engine.image(this,E||"about:blank",b||0,R||0,d||0,i||0);this.__set__&&this.__set__.push(g);return g};a4.text=function(b,i,g){var d=aR._engine.text(this,b||0,i||0,bH(g));this.__set__&&this.__set__.push(d);return d};a4.set=function(d){!aR.is(d,"array")&&(d=Array.prototype.splice.call(arguments,0,arguments.length));var b=new al(d);this.__set__&&this.__set__.push(b);return b};a4.setStart=function(b){this.__set__=b||this.set()};a4.setFinish=function(d){var b=this.__set__;delete this.__set__;return b};a4.setSize=function(d,b){return aR._engine.setSize.call(this,d,b)};a4.setViewBox=function(b,E,d,i,g){return aR._engine.setViewBox.call(this,b,E,d,i,g)};a4.top=a4.bottom=null;a4.raphael=aR;var bs=function(g){var E=g.getBoundingClientRect(),bM=g.ownerDocument,R=bM.body,b=bM.documentElement,i=b.clientTop||R.clientTop||0,S=b.clientLeft||R.clientLeft||0,bL=E.top+(aA.win.pageYOffset||b.scrollTop||R.scrollTop)-i,d=E.left+(aA.win.pageXOffset||b.scrollLeft||R.scrollLeft)-S;return{y:bL,x:d}};a4.getElementByPoint=function(d,bL){var S=this,g=S.canvas,R=aA.doc.elementFromPoint(d,bL);if(aA.win.opera&&R.tagName=="svg"){var E=bs(g),i=g.createSVGRect();i.x=d-E.x;i.y=bL-E.y;i.width=i.height=1;var b=g.getIntersectionList(i,null);if(b.length){R=b[b.length-1]}}if(!R){return null}while(R.parentNode&&R!=g.parentNode&&!R.raphael){R=R.parentNode}R==S.canvas.parentNode&&(R=g);R=R&&R.raphael?S.getById(R.raphaelid):null;return R};a4.getById=function(d){var b=this.bottom;while(b){if(b.id==d){return b}b=b.next}return null};a4.forEach=function(g,b){var d=this.bottom;while(d){if(g.call(b,d)===false){return this}d=d.next}return this};a4.getElementsByPoint=function(b,g){var d=this.set();this.forEach(function(i){if(i.isPointInside(b,g)){d.push(i)}});return d};function y(){return this.x+aQ+this.y}function at(){return this.x+aQ+this.y+aQ+this.width+" \xd7 "+this.height}bh.isPointInside=function(b,g){var d=this.realPath=this.realPath||N[this.type](this);return aR.isPointInsidePath(d,b,g)};bh.getBBox=function(d){if(this.removed){return{}}var b=this._;if(d){if(b.dirty||!b.bboxwt){this.realPath=N[this.type](this);b.bboxwt=am(this.realPath);b.bboxwt.toString=at;b.dirty=0}return b.bboxwt}if(b.dirty||b.dirtyT||!b.bbox){if(b.dirty||!this.realPath){b.bboxwt=0;this.realPath=N[this.type](this)}b.bbox=am(L(this.realPath,this.matrix));b.bbox.toString=at;b.dirty=b.dirtyT=0}return b.bbox};bh.clone=function(){if(this.removed){return null}var b=this.paper[this.type]().attr(this.attr());this.__set__&&this.__set__.push(b);return b};bh.glow=function(bL){if(this.type=="text"){return null}bL=bL||{};var g={width:(bL.width||10)+(+this.attr("stroke-width")||1),fill:bL.fill||false,opacity:bL.opacity||0.5,offsetx:bL.offsetx||0,offsety:bL.offsety||0,color:bL.color||"#000"},S=g.width/2,E=this.paper,b=E.set(),R=this.realPath||N[this.type](this);R=this.matrix?L(R,this.matrix):R;for(var d=1;d<S+1;d++){b.push(E.path(R).attr({stroke:g.color,fill:g.fill?g.color:"none","stroke-linejoin":"round","stroke-linecap":"round","stroke-width":+(g.width/S*d).toFixed(3),opacity:+(g.opacity/S).toFixed(3)}))}return b.insertBefore(this).translate(g.offsetx,g.offsety)};var a7={},k=function(d,b,E,i,bM,bL,S,R,g){if(g==null){return q(d,b,E,i,bM,bL,S,R)}else{return aR.findDotsAtSegment(d,b,E,i,bM,bL,S,R,C(d,b,E,i,bM,bL,S,R,g))}},a6=function(b,d){return function(bT,R,S){bT=W(bT);var bP,bO,g,bL,E="",bS={},bQ,bN=0;for(var bM=0,bR=bT.length;bM<bR;bM++){g=bT[bM];if(g[0]=="M"){bP=+g[1];bO=+g[2]}else{bL=k(bP,bO,g[1],g[2],g[3],g[4],g[5],g[6]);if(bN+bL>R){if(d&&!bS.start){bQ=k(bP,bO,g[1],g[2],g[3],g[4],g[5],g[6],R-bN);E+=["C"+bQ.start.x,bQ.start.y,bQ.m.x,bQ.m.y,bQ.x,bQ.y];if(S){return E}bS.start=E;E=["M"+bQ.x,bQ.y+"C"+bQ.n.x,bQ.n.y,bQ.end.x,bQ.end.y,g[5],g[6]].join();bN+=bL;bP=+g[5];bO=+g[6];continue}if(!b&&!d){bQ=k(bP,bO,g[1],g[2],g[3],g[4],g[5],g[6],R-bN);return{x:bQ.x,y:bQ.y,alpha:bQ.alpha}}}bN+=bL;bP=+g[5];bO=+g[6]}E+=g.shift()+g}bS.end=E;bQ=b?bN:d?bS:aR.findDotsAtSegment(bP,bO,g[0],g[1],g[2],g[3],g[4],g[5],1);bQ.alpha&&(bQ={x:bQ.x,y:bQ.y,alpha:bQ.alpha});return bQ}};var aS=a6(1),J=a6(),ad=a6(0,1);aR.getTotalLength=aS;aR.getPointAtLength=J;aR.getSubpath=function(d,i,g){if(this.getTotalLength(d)-g<0.000001){return ad(d,i).end}var b=ad(d,g,1);return i?ad(b,i).end:b};bh.getTotalLength=function(){if(this.type!="path"){return}if(this.node.getTotalLength){return this.node.getTotalLength()}return aS(this.attrs.path)};bh.getPointAtLength=function(b){if(this.type!="path"){return}return J(this.attrs.path,b)};bh.getSubpath=function(d,b){if(this.type!="path"){return}return aR.getSubpath(this.attrs.path,d,b)};var o=aR.easing_formulas={linear:function(b){return b},"<":function(b){return bp(b,1.7)},">":function(b){return bp(b,0.48)},"<>":function(bL){var i=0.48-bL/1.04,g=au.sqrt(0.1734+i*i),b=g-i,S=bp(aw(b),1/3)*(b<0?-1:1),R=-g-i,E=bp(aw(R),1/3)*(R<0?-1:1),d=S+E+0.5;return(1-d)*3*d*d+d*d*d},backIn:function(d){var b=1.70158;return d*d*((b+1)*d-b)},backOut:function(d){d=d-1;var b=1.70158;return d*d*((b+1)*d+b)+1},elastic:function(b){if(b==!!b){return b}return bp(2,-10*b)*au.sin((b-0.075)*(2*aV)/0.3)+1},bounce:function(i){var d=7.5625,g=2.75,b;if(i<(1/g)){b=d*i*i}else{if(i<(2/g)){i-=(1.5/g);b=d*i*i+0.75}else{if(i<(2.5/g)){i-=(2.25/g);b=d*i*i+0.9375}else{i-=(2.625/g);b=d*i*i+0.984375}}}return b}};o.easeIn=o["ease-in"]=o["<"];o.easeOut=o["ease-out"]=o[">"];o.easeInOut=o["ease-in-out"]=o["<>"];o["back-in"]=o.backIn;o["back-out"]=o.backOut;var ab=[],aN=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(b){setTimeout(b,16)},bC=function(){var bL=+new Date,bT=0;for(;bT<ab.length;bT++){var bZ=ab[bT];if(bZ.el.removed||bZ.paused){continue}var E=bL-bZ.start,bR=bZ.ms,bQ=bZ.easing,bU=bZ.from,bO=bZ.diff,d=bZ.to,bN=bZ.t,S=bZ.el,bP={},b,bX={},b1;if(bZ.initstatus){E=(bZ.initstatus*bZ.anim.top-bZ.prev)/(bZ.percent-bZ.prev)*bR;bZ.status=bZ.initstatus;delete bZ.initstatus;bZ.stop&&ab.splice(bT--,1)}else{bZ.status=(bZ.prev+(bZ.percent-bZ.prev)*(E/bR))/bZ.anim.top}if(E<0){continue}if(E<bR){var g=bQ(E/bR);for(var bS in bU){if(bU[ak](bS)){switch(ar[bS]){case aL:b=+bU[bS]+g*bR*bO[bS];break;case"colour":b="rgb("+[H(ah(bU[bS].r+g*bR*bO[bS].r)),H(ah(bU[bS].g+g*bR*bO[bS].g)),H(ah(bU[bS].b+g*bR*bO[bS].b))].join(",")+")";break;case"path":b=[];for(var bW=0,bM=bU[bS].length;bW<bM;bW++){b[bW]=[bU[bS][bW][0]];for(var bV=1,bY=bU[bS][bW].length;bV<bY;bV++){b[bW][bV]=+bU[bS][bW][bV]+g*bR*bO[bS][bW][bV]}b[bW]=b[bW].join(aQ)}b=b.join(aQ);break;case"transform":if(bO[bS].real){b=[];for(bW=0,bM=bU[bS].length;bW<bM;bW++){b[bW]=[bU[bS][bW][0]];for(bV=1,bY=bU[bS][bW].length;bV<bY;bV++){b[bW][bV]=bU[bS][bW][bV]+g*bR*bO[bS][bW][bV]}}}else{var b0=function(b2){return +bU[bS][b2]+g*bR*bO[bS][b2]};b=[["m",b0(0),b0(1),b0(2),b0(3),b0(4),b0(5)]]}break;case"csv":if(bS=="clip-rect"){b=[];bW=4;while(bW--){b[bW]=+bU[bS][bW]+g*bR*bO[bS][bW]}}break;default:var R=[][bE](bU[bS]);b=[];bW=S.paper.customAttributes[bS].length;while(bW--){b[bW]=+R[bW]+g*bR*bO[bS][bW]}break}bP[bS]=b}}S.attr(bP);(function(b3,i,b2){setTimeout(function(){eve("raphael.anim.frame."+b3,i,b2)})})(S.id,S,bZ.anim)}else{(function(b3,b2,i){setTimeout(function(){eve("raphael.anim.frame."+b2.id,b2,i);eve("raphael.anim.finish."+b2.id,b2,i);aR.is(b3,"function")&&b3.call(b2)})})(bZ.callback,S,bZ.anim);S.attr(d);ab.splice(bT--,1);if(bZ.repeat>1&&!bZ.next){for(b1 in d){if(d[ak](b1)){bX[b1]=bZ.totalOrigin[b1]}}bZ.el.attr(bX);aM(bZ.anim,bZ.el,bZ.anim.percents[0],null,bZ.totalOrigin,bZ.repeat-1)}if(bZ.next&&!bZ.stop){aM(bZ.anim,bZ.el,bZ.next,null,bZ.totalOrigin,bZ.repeat)}}}aR.svg&&S&&S.paper&&S.paper.safari();ab.length&&aN(bC)},H=function(b){return b>255?255:b<0?0:b};bh.animateWith=function(d,E,g,b,bL,bQ){var S=this;if(S.removed){bQ&&bQ.call(S);return S}var bO=g instanceof bA?g:aR.animation(g,b,bL,bQ),bN,bM;aM(bO,S,bO.percents[0],null,S.attr());for(var R=0,bP=ab.length;R<bP;R++){if(ab[R].anim==E&&ab[R].el==d){ab[bP-1].start=ab[R].start;break}}return S};function a3(bR,i,d,bQ,bP,bL){var bM=3*i,bO=3*(bQ-i)-bM,b=1-bM-bO,S=3*d,bN=3*(bP-d)-S,bS=1-S-bN;function R(bT){return((b*bT+bO)*bT+bM)*bT}function g(bT,bV){var bU=E(bT,bV);return((bS*bU+bN)*bU+S)*bU}function E(bT,b0){var bZ,bY,bW,bU,bX,bV;for(bW=bT,bV=0;bV<8;bV++){bU=R(bW)-bT;if(aw(bU)<b0){return bW}bX=(3*b*bW+2*bO)*bW+bM;if(aw(bX)<0.000001){break}bW=bW-bU/bX}bZ=0;bY=1;bW=bT;if(bW<bZ){return bZ}if(bW>bY){return bY}while(bZ<bY){bU=R(bW);if(aw(bU-bT)<b0){return bW}if(bT>bU){bZ=bW}else{bY=bW}bW=(bY-bZ)/2+bZ}return bW}return g(bR,1/(200*bL))}bh.onAnimation=function(b){b?eve.on("raphael.anim.frame."+this.id,b):eve.unbind("raphael.anim.frame."+this.id);return this};function bA(E,g){var d=[],i={};this.ms=g;this.times=1;if(E){for(var b in E){if(E[ak](b)){i[an(b)]=E[b];d.push(an(b))}}d.sort(u)}this.anim=i;this.top=d[d.length-1];this.percents=d}bA.prototype.delay=function(d){var b=new bA(this.anim,this.ms);b.times=this.times;b.del=+d||0;return b};bA.prototype.repeat=function(d){var b=new bA(this.anim,this.ms);b.del=this.del;b.times=au.floor(m(d,0))||1;return b};function aM(b3,g,b,b1,bL,bP){b=an(b);var ca,S,bO,cb=[],bV,bU,R,bX=b3.ms,b2={},E={},bR={};if(b1){for(b6=0,bQ=ab.length;b6<bQ;b6++){var b8=ab[b6];if(b8.el.id==g.id&&b8.anim==b3){if(b8.percent!=b){ab.splice(b6,1);bO=1}else{S=b8}g.attr(b8.totalOrigin);break}}}else{b1=+E}for(var b6=0,bQ=b3.percents.length;b6<bQ;b6++){if(b3.percents[b6]==b||b3.percents[b6]>b1*b3.top){b=b3.percents[b6];bU=b3.percents[b6-1]||0;bX=bX/b3.top*(b-bU);bV=b3.percents[b6+1];ca=b3.anim[b];break}else{if(b1){g.attr(b3.anim[b3.percents[b6]])}}}if(!ca){return}if(!S){for(var bZ in ca){if(ca[ak](bZ)){if(ar[ak](bZ)||g.paper.customAttributes[ak](bZ)){b2[bZ]=g.attr(bZ);(b2[bZ]==null)&&(b2[bZ]=r[bZ]);E[bZ]=ca[bZ];switch(ar[bZ]){case aL:bR[bZ]=(E[bZ]-b2[bZ])/bX;break;case"colour":b2[bZ]=aR.getRGB(b2[bZ]);var b0=aR.getRGB(E[bZ]);bR[bZ]={r:(b0.r-b2[bZ].r)/bX,g:(b0.g-b2[bZ].g)/bX,b:(b0.b-b2[bZ].b)/bX};break;case"path":var bM=W(b2[bZ],E[bZ]),bT=bM[1];b2[bZ]=bM[0];bR[bZ]=[];for(b6=0,bQ=b2[bZ].length;b6<bQ;b6++){bR[bZ][b6]=[0];for(var b5=1,b7=b2[bZ][b6].length;b5<b7;b5++){bR[bZ][b6][b5]=(bT[b6][b5]-b2[bZ][b6][b5])/bX}}break;case"transform":var cd=g._,cc=aB(cd[bZ],E[bZ]);if(cc){b2[bZ]=cc.from;E[bZ]=cc.to;bR[bZ]=[];bR[bZ].real=true;for(b6=0,bQ=b2[bZ].length;b6<bQ;b6++){bR[bZ][b6]=[b2[bZ][b6][0]];for(b5=1,b7=b2[bZ][b6].length;b5<b7;b5++){bR[bZ][b6][b5]=(E[bZ][b6][b5]-b2[bZ][b6][b5])/bX}}}else{var bY=(g.matrix||new aF),b9={_:{transform:cd.transform},getBBox:function(){return g.getBBox(1)}};b2[bZ]=[bY.a,bY.b,bY.c,bY.d,bY.e,bY.f];aO(b9,E[bZ]);E[bZ]=b9._.transform;bR[bZ]=[(b9.matrix.a-bY.a)/bX,(b9.matrix.b-bY.b)/bX,(b9.matrix.c-bY.c)/bX,(b9.matrix.d-bY.d)/bX,(b9.matrix.e-bY.e)/bX,(b9.matrix.f-bY.f)/bX]}break;case"csv":var d=bH(ca[bZ])[F](a),bN=bH(b2[bZ])[F](a);if(bZ=="clip-rect"){b2[bZ]=bN;bR[bZ]=[];b6=bN.length;while(b6--){bR[bZ][b6]=(d[b6]-b2[bZ][b6])/bX}}E[bZ]=d;break;default:d=[][bE](ca[bZ]);bN=[][bE](b2[bZ]);bR[bZ]=[];b6=g.paper.customAttributes[bZ].length;while(b6--){bR[bZ][b6]=((d[b6]||0)-(bN[b6]||0))/bX}break}}}}var bW=ca.easing,b4=aR.easing_formulas[bW];if(!b4){b4=bH(bW).match(c);if(b4&&b4.length==5){var bS=b4;b4=function(i){return a3(i,+bS[1],+bS[2],+bS[3],+bS[4],bX)}}else{b4=bB}}R=ca.start||b3.start||+new Date;b8={anim:b3,percent:b,timestamp:R,start:R+(b3.del||0),status:0,initstatus:b1||0,stop:false,ms:bX,easing:b4,from:b2,diff:bR,to:E,el:g,callback:ca.callback,prev:bU,next:bV,repeat:bP||b3.times,origin:g.attr(),totalOrigin:bL};ab.push(b8);if(b1&&!S&&!bO){b8.stop=true;b8.start=new Date-bX*b1;if(ab.length==1){return bC()}}if(bO){b8.start=new Date-b8.ms*b1}ab.length==1&&aN(bC)}else{S.initstatus=b1;S.start=new Date-S.ms*b1}eve("raphael.anim.start."+g.id,g,b3)}aR.animation=function(E,d,S,R){if(E instanceof bA){return E}if(aR.is(S,"function")||!S){R=R||S||null;S=null}E=Object(E);d=+d||0;var i={},g,b;for(b in E){if(E[ak](b)&&an(b)!=b&&an(b)+"%"!=b){g=true;i[b]=E[b]}}if(!g){return new bA(E,d)}else{S&&(i.easing=S);R&&(i.callback=R);return new bA({100:i},d)}};bh.animate=function(i,b,R,E){var d=this;if(d.removed){E&&E.call(d);return d}var g=i instanceof bA?i:aR.animation(i,b,R,E);aM(g,d,g.percents[0],null,d.attr());return d};bh.setTime=function(d,b){if(d&&b!=null){this.status(d,bm(b,d.ms)/d.ms)}return this};bh.status=function(R,E){var d=[],g=0,b,S;if(E!=null){aM(R,this,-1,bm(E,1));return this}else{b=ab.length;for(;g<b;g++){S=ab[g];if(S.el.id==this.id&&(!R||S.anim==R)){if(R){return S.status}d.push({anim:S.anim,status:S.status})}}if(R){return 0}return d}};bh.pause=function(d){for(var b=0;b<ab.length;b++){if(ab[b].el.id==this.id&&(!d||ab[b].anim==d)){if(eve("raphael.anim.pause."+this.id,this,ab[b].anim)!==false){ab[b].paused=true}}}return this};bh.resume=function(d){for(var b=0;b<ab.length;b++){if(ab[b].el.id==this.id&&(!d||ab[b].anim==d)){var g=ab[b];if(eve("raphael.anim.resume."+this.id,this,g.anim)!==false){delete g.paused;this.status(g.anim,g.status)}}}return this};bh.stop=function(d){for(var b=0;b<ab.length;b++){if(ab[b].el.id==this.id&&(!d||ab[b].anim==d)){if(eve("raphael.anim.stop."+this.id,this,ab[b].anim)!==false){ab.splice(b--,1)}}}return this};function aa(d){for(var b=0;b<ab.length;b++){if(ab[b].el.paper==d){ab.splice(b--,1)}}}eve.on("raphael.remove",aa);eve.on("raphael.clear",aa);bh.toString=function(){return"Rapha\xebl\u2019s object"};var al=function(b){this.items=[];this.length=0;this.type="set";if(b){for(var d=0,g=b.length;d<g;d++){if(b[d]&&(b[d].constructor==bh.constructor||b[d].constructor==al)){this[this.items.length]=this.items[this.items.length]=b[d];this.length++}}}},bc=al.prototype;bc.push=function(){var E,b;for(var d=0,g=arguments.length;d<g;d++){E=arguments[d];if(E&&(E.constructor==bh.constructor||E.constructor==al)){b=this.items.length;this[b]=this.items[b]=E;this.length++}}return this};bc.pop=function(){this.length&&delete this[this.length--];return this.items.pop()};bc.forEach=function(E,b){for(var d=0,g=this.items.length;d<g;d++){if(E.call(b,this.items[d],d)===false){return this}}return this};for(var B in bh){if(bh[ak](B)){bc[B]=(function(b){return function(){var d=arguments;return this.forEach(function(g){g[b][bG](g,d)})}})(B)}}bc.attr=function(d,S){if(d&&aR.is(d,bd)&&aR.is(d[0],"object")){for(var b=0,R=d.length;b<R;b++){this.items[b].attr(d[b])}}else{for(var g=0,E=this.items.length;g<E;g++){this.items[g].attr(d,S)}}return this};bc.clear=function(){while(this.length){this.pop()}};bc.splice=function(E,bL,bM){E=E<0?m(this.length+E,0):E;bL=m(0,bm(this.length-E,bL));var g=[],b=[],d=[],R;for(R=2;R<arguments.length;R++){d.push(arguments[R])}for(R=0;R<bL;R++){b.push(this[E+R])}for(;R<this.length-E;R++){g.push(this[E+R])}var S=d.length;for(R=0;R<S+g.length;R++){this.items[E+R]=this[E+R]=R<S?d[R]:g[R-S]}R=this.items.length=this.length-=bL-S;while(this[R]){delete this[R++]}return new al(b)};bc.exclude=function(g){for(var b=0,d=this.length;b<d;b++){if(this[b]==g){this.splice(b,1);return true}}};bc.animate=function(g,b,bL,bN){(aR.is(bL,"function")||!bL)&&(bN=bL||null);var S=this.items.length,E=S,bO,bM=this,R;if(!S){return this}bN&&(R=function(){!--S&&bN.call(bM)});bL=aR.is(bL,aj)?bL:R;var d=aR.animation(g,b,bL,R);bO=this.items[--E].animate(d);while(E--){this.items[E]&&!this.items[E].removed&&this.items[E].animateWith(bO,d,d)}return this};bc.insertAfter=function(d){var b=this.items.length;while(b--){this.items[b].insertAfter(d)}return this};bc.getBBox=function(){var b=[],S=[],d=[],E=[];for(var g=this.items.length;g--;){if(!this.items[g].removed){var R=this.items[g].getBBox();b.push(R.x);S.push(R.y);d.push(R.x+R.width);E.push(R.y+R.height)}}b=bm[bG](0,b);S=bm[bG](0,S);d=m[bG](0,d);E=m[bG](0,E);return{x:b,y:S,x2:d,y2:E,width:d-b,height:E-S}};bc.clone=function(g){g=new al;for(var b=0,d=this.items.length;b<d;b++){g.push(this.items[b].clone())}return g};bc.toString=function(){return"Rapha\xebl\u2018s set"};aR.registerFont=function(d){if(!d.face){return d}this.fonts=this.fonts||{};var i={w:d.w,face:{},glyphs:{}},g=d.face["font-family"];for(var S in d.face){if(d.face[ak](S)){i.face[S]=d.face[S]}}if(this.fonts[g]){this.fonts[g].push(i)}else{this.fonts[g]=[i]}if(!d.svg){i.face["units-per-em"]=U(d.face["units-per-em"],10);for(var E in d.glyphs){if(d.glyphs[ak](E)){var R=d.glyphs[E];i.glyphs[E]={w:R.w,k:{},d:R.d&&"M"+R.d.replace(/[mlcxtrv]/g,function(bL){return{l:"L",c:"C",x:"z",t:"m",r:"l",v:"c"}[bL]||"M"})+"z"};if(R.k){for(var b in R.k){if(R[ak](b)){i.glyphs[E].k[b]=R.k[b]}}}}}}return d};a4.getFont=function(bM,bN,d,E){E=E||"normal";d=d||"normal";bN=+bN||{normal:400,bold:700,lighter:300,bolder:800}[bN]||400;if(!aR.fonts){return}var R=aR.fonts[bM];if(!R){var g=new RegExp("(^|\\s)"+bM.replace(/[^\w\d\s+!~.:_-]/g,aX)+"(\\s|$)","i");for(var b in aR.fonts){if(aR.fonts[ak](b)){if(g.test(b)){R=aR.fonts[b];break}}}}var S;if(R){for(var bL=0,bO=R.length;bL<bO;bL++){S=R[bL];if(S.face["font-weight"]==bN&&(S.face["font-style"]==d||!S.face["font-style"])&&S.face["font-stretch"]==E){break}}}return S};a4.print=function(bL,S,b,bO,bP,bY,d){bY=bY||"middle";d=m(bm(d||0,1),-1);var bX=bH(b)[F](aX),bU=0,bW=0,bS=aX,bZ;aR.is(bO,b)&&(bO=this.getFont(bO));if(bO){bZ=(bP||16)/bO.face["units-per-em"];var E=bO.face.bbox[F](a),bN=+E[0],g=E[3]-E[1],R=0,bQ=+E[1]+(bY=="baseline"?g+(+bO.face.descent):g/2);for(var bT=0,bM=bX.length;bT<bM;bT++){if(bX[bT]=="\n"){bU=0;bV=0;bW=0;R+=g}else{var bR=bW&&bO.glyphs[bX[bT-1]]||{},bV=bO.glyphs[bX[bT]];bU+=bW?(bR.w||bO.w)+(bR.k&&bR.k[bX[bT]]||0)+(bO.w*d):0;bW=1}if(bV&&bV.d){bS+=aR.transformPath(bV.d,["t",bU*bZ,R*bZ,"s",bZ,bZ,bN,bQ,"t",(bL-bN)/bZ,(S-bQ)/bZ])}}}return this.path(bS).attr({fill:"#000",stroke:"none"})};a4.add=function(E){if(aR.is(E,"array")){var g=this.set(),d=0,R=E.length,b;for(;d<R;d++){b=E[d]||{};bw[ak](b.type)&&g.push(this[b.type]().attr(b))}}return g};aR.format=function(d,g){var b=aR.is(g,bd)?[0][bE](g):arguments;d&&aR.is(d,aj)&&b.length-1&&(d=d.replace(br,function(R,E){return b[++E]==null?aX:b[E]}));return d||aX};aR.fullfill=(function(){var g=/\{([^\}]+)\}/g,b=/(?:(?:^|\.)(.+?)(?=\[|\.|$|\()|\[('|")(.+?)\2\])(\(\))?/g,d=function(R,E,S){var i=S;E.replace(b,function(bN,bM,bL,bP,bO){bM=bM||bP;if(i){if(bM in i){i=i[bM]}typeof i=="function"&&bO&&(i=i())}});i=(i==null||i==S?R:i)+"";return i};return function(E,i){return String(E).replace(g,function(S,R){return d(S,R,i)})}})();aR.ninja=function(){s.was?(aA.win.Raphael=s.is):delete Raphael;return aR};aR.st=bc;(function(i,d,g){if(i.readyState==null&&i.addEventListener){i.addEventListener(d,g=function(){i.removeEventListener(d,g,false);i.readyState="complete"},false);i.readyState="loading"}function b(){(/in/).test(i.readyState)?setTimeout(b,9):aR.eve("raphael.DOMload")}b()})(document,"DOMContentLoaded");s.was?(aA.win.Raphael=aR):(Raphael=aR);eve.on("raphael.DOMload",function(){ao=true})})();window.Raphael&&window.Raphael.svg&&function(l){var d="hasOwnProperty",B=String,n=parseFloat,q=parseInt,f=Math,C=f.max,s=f.abs,h=f.pow,g=/[, ]+/,z=l.eve,r="",j=" ";var o="http://www.w3.org/1999/xlink",y={block:"M5,0 0,2.5 5,5z",classic:"M5,0 0,2.5 5,5 3.5,3 3.5,2z",diamond:"M2.5,0 5,2.5 2.5,5 0,2.5z",open:"M6,1 1,3.5 6,6",oval:"M2.5,0A2.5,2.5,0,0,1,2.5,5 2.5,2.5,0,0,1,2.5,0z"},u={};l.toString=function(){return"Your browser supports SVG.\nYou are running Rapha\xebl "+this.version};var i=function(F,D){if(D){if(typeof F=="string"){F=i(F)}for(var E in D){if(D[d](E)){if(E.substring(0,6)=="xlink:"){F.setAttributeNS(o,E.substring(6),B(D[E]))}else{F.setAttribute(E,B(D[E]))}}}}else{F=l._g.doc.createElementNS("http://www.w3.org/2000/svg",F);F.style&&(F.style.webkitTapHighlightColor="rgba(0,0,0,0)")}return F},a=function(M,Q){var O="linear",E=M.id+Q,K=0.5,I=0.5,G=M.node,D=M.paper,S=G.style,F=l._g.doc.getElementById(E);if(!F){Q=B(Q).replace(l._radial_gradient,function(V,T,W){O="radial";if(T&&W){K=n(T);I=n(W);var U=((I>0.5)*2-1);h(K-0.5,2)+h(I-0.5,2)>0.25&&(I=f.sqrt(0.25-h(K-0.5,2))*U+0.5)&&I!=0.5&&(I=I.toFixed(5)-0.00001*U)}return r});Q=Q.split(/\s*\-\s*/);if(O=="linear"){var J=Q.shift();J=-n(J);if(isNaN(J)){return null}var H=[0,0,f.cos(l.rad(J)),f.sin(l.rad(J))],P=1/(C(s(H[2]),s(H[3]))||1);H[2]*=P;H[3]*=P;if(H[2]<0){H[0]=-H[2];H[2]=0}if(H[3]<0){H[1]=-H[3];H[3]=0}}var N=l._parseDots(Q);if(!N){return null}E=E.replace(/[\(\)\s,\xb0#]/g,"_");if(M.gradient&&E!=M.gradient.id){D.defs.removeChild(M.gradient);delete M.gradient}if(!M.gradient){F=i(O+"Gradient",{id:E});M.gradient=F;i(F,O=="radial"?{fx:K,fy:I}:{x1:H[0],y1:H[1],x2:H[2],y2:H[3],gradientTransform:M.matrix.invert()});D.defs.appendChild(F);for(var L=0,R=N.length;L<R;L++){F.appendChild(i("stop",{offset:N[L].offset?N[L].offset:L?"100%":"0%","stop-color":N[L].color||"#fff"}))}}}i(G,{fill:"url(#"+E+")",opacity:1,"fill-opacity":1});S.fill=r;S.opacity=1;S.fillOpacity=1;return 1},b=function(E){var D=E.getBBox(1);i(E.pattern,{patternTransform:E.matrix.invert()+" translate("+D.x+","+D.y+")"})},c=function(O,Q,J){if(O.type=="path"){var D=B(Q).toLowerCase().split("-"),N=O.paper,ab=J?"end":"start",S=O.node,P=O.attrs,I=P["stroke-width"],W=D.length,G="classic",V,F,L,T,R,K=3,X=3,M=5;while(W--){switch(D[W]){case"block":case"classic":case"oval":case"diamond":case"open":case"none":G=D[W];break;case"wide":X=5;break;case"narrow":X=2;break;case"long":K=5;break;case"short":K=2;break}}if(G=="open"){K+=2;X+=2;M+=2;L=1;T=J?4:1;R={fill:"none",stroke:P.stroke}}else{T=L=K/2;R={fill:P.stroke,stroke:"none"}}if(O._.arrows){if(J){O._.arrows.endPath&&u[O._.arrows.endPath]--;O._.arrows.endMarker&&u[O._.arrows.endMarker]--}else{O._.arrows.startPath&&u[O._.arrows.startPath]--;O._.arrows.startMarker&&u[O._.arrows.startMarker]--}}else{O._.arrows={}}if(G!="none"){var E="raphael-marker-"+G,aa="raphael-marker-"+ab+G+K+X;if(!l._g.doc.getElementById(E)){N.defs.appendChild(i(i("path"),{"stroke-linecap":"round",d:y[G],id:E}));u[E]=1}else{u[E]++}var H=l._g.doc.getElementById(aa),U;if(!H){H=i(i("marker"),{id:aa,markerHeight:X,markerWidth:K,orient:"auto",refX:T,refY:X/2});U=i(i("use"),{"xlink:href":"#"+E,transform:(J?"rotate(180 "+K/2+" "+X/2+") ":r)+"scale("+K/M+","+X/M+")","stroke-width":(1/((K/M+X/M)/2)).toFixed(4)});H.appendChild(U);N.defs.appendChild(H);u[aa]=1}else{u[aa]++;U=H.getElementsByTagName("use")[0]}i(U,R);var Z=L*(G!="diamond"&&G!="oval");if(J){V=O._.arrows.startdx*I||0;F=l.getTotalLength(P.path)-Z*I}else{V=Z*I;F=l.getTotalLength(P.path)-(O._.arrows.enddx*I||0)}R={};R["marker-"+ab]="url(#"+aa+")";if(F||V){R.d=Raphael.getSubpath(P.path,V,F)}i(S,R);O._.arrows[ab+"Path"]=E;O._.arrows[ab+"Marker"]=aa;O._.arrows[ab+"dx"]=Z;O._.arrows[ab+"Type"]=G;O._.arrows[ab+"String"]=Q}else{if(J){V=O._.arrows.startdx*I||0;F=l.getTotalLength(P.path)-V}else{V=0;F=l.getTotalLength(P.path)-(O._.arrows.enddx*I||0)}O._.arrows[ab+"Path"]&&i(S,{d:Raphael.getSubpath(P.path,V,F)});delete O._.arrows[ab+"Path"];delete O._.arrows[ab+"Marker"];delete O._.arrows[ab+"dx"];delete O._.arrows[ab+"Type"];delete O._.arrows[ab+"String"]}for(R in u){if(u[d](R)&&!u[R]){var Y=l._g.doc.getElementById(R);Y&&Y.parentNode.removeChild(Y)}}}},v={"":[0],none:[0],"-":[3,1],".":[1,1],"-.":[3,1,1,1],"-..":[3,1,1,1,1,1],". ":[1,3],"- ":[4,3],"--":[8,3],"- .":[4,3,1,3],"--.":[8,3,1,3],"--..":[8,3,1,3,1,3]},k=function(J,H,I){H=v[B(H).toLowerCase()];if(H){var F=J.attrs["stroke-width"]||"1",D={round:F,square:F,butt:0}[J.attrs["stroke-linecap"]||I["stroke-linecap"]]||0,G=[],E=H.length;while(E--){G[E]=H[E]*F+((E%2)?1:-1)*D}i(J.node,{"stroke-dasharray":G.join(",")})}},w=function(O,W){var S=O.node,P=O.attrs,M=S.style.visibility;S.style.visibility="hidden";for(var R in W){if(W[d](R)){if(!l._availableAttrs[d](R)){continue}var Q=W[R];P[R]=Q;switch(R){case"blur":O.blur(Q);break;case"href":case"title":case"target":var U=S.parentNode;if(U.tagName.toLowerCase()!="a"){var H=i("a");U.insertBefore(H,S);H.appendChild(S);U=H}if(R=="target"){U.setAttributeNS(o,"show",Q=="blank"?"new":Q)}else{U.setAttributeNS(o,R,Q)}break;case"cursor":S.style.cursor=Q;break;case"transform":O.transform(Q);break;case"arrow-start":c(O,Q);break;case"arrow-end":c(O,Q,1);break;case"clip-rect":var E=B(Q).split(g);if(E.length==4){O.clip&&O.clip.parentNode.parentNode.removeChild(O.clip.parentNode);var F=i("clipPath"),T=i("rect");F.id=l.createUUID();i(T,{x:E[0],y:E[1],width:E[2],height:E[3]});F.appendChild(T);O.paper.defs.appendChild(F);i(S,{"clip-path":"url(#"+F.id+")"});O.clip=T}if(!Q){var N=S.getAttribute("clip-path");if(N){var V=l._g.doc.getElementById(N.replace(/(^url\(#|\)$)/g,r));V&&V.parentNode.removeChild(V);i(S,{"clip-path":r});delete O.clip}}break;case"path":if(O.type=="path"){i(S,{d:Q?P.path=l._pathToAbsolute(Q):"M0,0"});O._.dirty=1;if(O._.arrows){"startString" in O._.arrows&&c(O,O._.arrows.startString);"endString" in O._.arrows&&c(O,O._.arrows.endString,1)}}break;case"width":S.setAttribute(R,Q);O._.dirty=1;if(P.fx){R="x";Q=P.x}else{break}case"x":if(P.fx){Q=-P.x-(P.width||0)}case"rx":if(R=="rx"&&O.type=="rect"){break}case"cx":S.setAttribute(R,Q);O.pattern&&b(O);O._.dirty=1;break;case"height":S.setAttribute(R,Q);O._.dirty=1;if(P.fy){R="y";Q=P.y}else{break}case"y":if(P.fy){Q=-P.y-(P.height||0)}case"ry":if(R=="ry"&&O.type=="rect"){break}case"cy":S.setAttribute(R,Q);O.pattern&&b(O);O._.dirty=1;break;case"r":if(O.type=="rect"){i(S,{rx:Q,ry:Q})}else{S.setAttribute(R,Q)}O._.dirty=1;break;case"src":if(O.type=="image"){S.setAttributeNS(o,"href",Q)}break;case"stroke-width":if(O._.sx!=1||O._.sy!=1){Q/=C(s(O._.sx),s(O._.sy))||1}if(O.paper._vbSize){Q*=O.paper._vbSize}S.setAttribute(R,Q);if(P["stroke-dasharray"]){k(O,P["stroke-dasharray"],W)}if(O._.arrows){"startString" in O._.arrows&&c(O,O._.arrows.startString);"endString" in O._.arrows&&c(O,O._.arrows.endString,1)}break;case"stroke-dasharray":k(O,Q,W);break;case"fill":var I=B(Q).match(l._ISURL);if(I){F=i("pattern");var L=i("image");F.id=l.createUUID();i(F,{x:0,y:0,patternUnits:"userSpaceOnUse",height:1,width:1});i(L,{x:0,y:0,"xlink:href":I[1]});F.appendChild(L);(function(X){l._preload(I[1],function(){var Y=this.offsetWidth,Z=this.offsetHeight;i(X,{width:Y,height:Z});i(L,{width:Y,height:Z});O.paper.safari()})})(F);O.paper.defs.appendChild(F);i(S,{fill:"url(#"+F.id+")"});O.pattern=F;O.pattern&&b(O);break}var G=l.getRGB(Q);if(!G.error){delete W.gradient;delete P.gradient;!l.is(P.opacity,"undefined")&&l.is(W.opacity,"undefined")&&i(S,{opacity:P.opacity});!l.is(P["fill-opacity"],"undefined")&&l.is(W["fill-opacity"],"undefined")&&i(S,{"fill-opacity":P["fill-opacity"]})}else{if((O.type=="circle"||O.type=="ellipse"||B(Q).charAt()!="r")&&a(O,Q)){if("opacity" in P||"fill-opacity" in P){var D=l._g.doc.getElementById(S.getAttribute("fill").replace(/^url\(#|\)$/g,r));if(D){var J=D.getElementsByTagName("stop");i(J[J.length-1],{"stop-opacity":("opacity" in P?P.opacity:1)*("fill-opacity" in P?P["fill-opacity"]:1)})}}P.gradient=Q;P.fill="none";break}}G[d]("opacity")&&i(S,{"fill-opacity":G.opacity>1?G.opacity/100:G.opacity});case"stroke":G=l.getRGB(Q);S.setAttribute(R,G.hex);R=="stroke"&&G[d]("opacity")&&i(S,{"stroke-opacity":G.opacity>1?G.opacity/100:G.opacity});if(R=="stroke"&&O._.arrows){"startString" in O._.arrows&&c(O,O._.arrows.startString);"endString" in O._.arrows&&c(O,O._.arrows.endString,1)}break;case"gradient":(O.type=="circle"||O.type=="ellipse"||B(Q).charAt()!="r")&&a(O,Q);break;case"opacity":if(P.gradient&&!P[d]("stroke-opacity")){i(S,{"stroke-opacity":Q>1?Q/100:Q})}case"fill-opacity":if(P.gradient){D=l._g.doc.getElementById(S.getAttribute("fill").replace(/^url\(#|\)$/g,r));if(D){J=D.getElementsByTagName("stop");i(J[J.length-1],{"stop-opacity":Q})}break}default:R=="font-size"&&(Q=q(Q,10)+"px");var K=R.replace(/(\-.)/g,function(X){return X.substring(1).toUpperCase()});S.style[K]=Q;O._.dirty=1;S.setAttribute(R,Q);break}}}p(O,W);S.style.visibility=M},A=1.2,p=function(D,H){if(D.type!="text"||!(H[d]("text")||H[d]("font")||H[d]("font-size")||H[d]("x")||H[d]("y"))){return}var M=D.attrs,F=D.node,O=F.firstChild?q(l._g.doc.defaultView.getComputedStyle(F.firstChild,r).getPropertyValue("font-size"),10):10;if(H[d]("text")){M.text=H.text;while(F.firstChild){F.removeChild(F.firstChild)}var G=B(H.text).split("\n"),E=[],K;for(var I=0,N=G.length;I<N;I++){K=i("tspan");I&&i(K,{dy:O*A,x:M.x});K.appendChild(l._g.doc.createTextNode(G[I]));F.appendChild(K);E[I]=K}}else{E=F.getElementsByTagName("tspan");for(I=0,N=E.length;I<N;I++){if(I){i(E[I],{dy:O*A,x:M.x})}else{i(E[0],{dy:0})}}}i(F,{x:M.x,y:M.y});D._.dirty=1;var J=D._getBBox(),L=M.y-(J.y+J.height/2);L&&l.is(L,"finite")&&i(E[0],{dy:L})},t=function(E,D){var G=0,F=0;this[0]=this.node=E;E.raphael=true;this.id=l._oid++;E.raphaelid=this.id;this.matrix=l.matrix();this.realPath=null;this.paper=D;this.attrs=this.attrs||{};this._={transform:[],sx:1,sy:1,deg:0,dx:0,dy:0,dirty:1};!D.bottom&&(D.bottom=this);this.prev=D.top;D.top&&(D.top.next=this);D.top=this;this.next=null},m=l.el;t.prototype=m;m.constructor=t;l._engine.path=function(D,G){var E=i("path");G.canvas&&G.canvas.appendChild(E);var F=new t(E,G);F.type="path";w(F,{fill:"none",stroke:"#000",path:D});return F};m.rotate=function(E,D,G){if(this.removed){return this}E=B(E).split(g);if(E.length-1){D=n(E[1]);G=n(E[2])}E=n(E[0]);(G==null)&&(D=G);if(D==null||G==null){var F=this.getBBox(1);D=F.x+F.width/2;G=F.y+F.height/2}this.transform(this._.transform.concat([["r",E,D,G]]));return this};m.scale=function(H,F,D,G){if(this.removed){return this}H=B(H).split(g);if(H.length-1){F=n(H[1]);D=n(H[2]);G=n(H[3])}H=n(H[0]);(F==null)&&(F=H);(G==null)&&(D=G);if(D==null||G==null){var E=this.getBBox(1)}D=D==null?E.x+E.width/2:D;G=G==null?E.y+E.height/2:G;this.transform(this._.transform.concat([["s",H,F,D,G]]));return this};m.translate=function(E,D){if(this.removed){return this}E=B(E).split(g);if(E.length-1){D=n(E[1])}E=n(E[0])||0;D=+D||0;this.transform(this._.transform.concat([["t",E,D]]));return this};m.transform=function(E){var F=this._;if(E==null){return F.transform}l._extractTransform(this,E);this.clip&&i(this.clip,{transform:this.matrix.invert()});this.pattern&&b(this);this.node&&i(this.node,{transform:this.matrix});if(F.sx!=1||F.sy!=1){var D=this.attrs[d]("stroke-width")?this.attrs["stroke-width"]:1;this.attr({"stroke-width":D})}return this};m.hide=function(){!this.removed&&this.paper.safari(this.node.style.display="none");return this};m.show=function(){!this.removed&&this.paper.safari(this.node.style.display="");return this};m.remove=function(){if(this.removed||!this.node.parentNode){return}var E=this.paper;E.__set__&&E.__set__.exclude(this);z.unbind("raphael.*.*."+this.id);if(this.gradient){E.defs.removeChild(this.gradient)}l._tear(this,E);if(this.node.parentNode.tagName.toLowerCase()=="a"){this.node.parentNode.parentNode.removeChild(this.node.parentNode)}else{this.node.parentNode.removeChild(this.node)}for(var D in this){this[D]=typeof this[D]=="function"?l._removedFactory(D):null}this.removed=true};m._getBBox=function(){if(this.node.style.display=="none"){this.show();var D=true}var F={};try{F=this.node.getBBox()}catch(E){}finally{F=F||{}}D&&this.hide();return F};m.attr=function(D,M){if(this.removed){return this}if(D==null){var J={};for(var L in this.attrs){if(this.attrs[d](L)){J[L]=this.attrs[L]}}J.gradient&&J.fill=="none"&&(J.fill=J.gradient)&&delete J.gradient;J.transform=this._.transform;return J}if(M==null&&l.is(D,"string")){if(D=="fill"&&this.attrs.fill=="none"&&this.attrs.gradient){return this.attrs.gradient}if(D=="transform"){return this._.transform}var K=D.split(g),G={};for(var H=0,O=K.length;H<O;H++){D=K[H];if(D in this.attrs){G[D]=this.attrs[D]}else{if(l.is(this.paper.customAttributes[D],"function")){G[D]=this.paper.customAttributes[D].def}else{G[D]=l._availableAttrs[D]}}}return O-1?G:G[K[0]]}if(M==null&&l.is(D,"array")){G={};for(H=0,O=D.length;H<O;H++){G[D[H]]=this.attr(D[H])}return G}if(M!=null){var E={};E[D]=M}else{if(D!=null&&l.is(D,"object")){E=D}}for(var N in E){z("raphael.attr."+N+"."+this.id,this,E[N])}for(N in this.paper.customAttributes){if(this.paper.customAttributes[d](N)&&E[d](N)&&l.is(this.paper.customAttributes[N],"function")){var I=this.paper.customAttributes[N].apply(this,[].concat(E[N]));this.attrs[N]=E[N];for(var F in I){if(I[d](F)){E[F]=I[F]}}}}w(this,E);return this};m.toFront=function(){if(this.removed){return this}if(this.node.parentNode.tagName.toLowerCase()=="a"){this.node.parentNode.parentNode.appendChild(this.node.parentNode)}else{this.node.parentNode.appendChild(this.node)}var D=this.paper;D.top!=this&&l._tofront(this,D);return this};m.toBack=function(){if(this.removed){return this}var E=this.node.parentNode;if(E.tagName.toLowerCase()=="a"){E.parentNode.insertBefore(this.node.parentNode,this.node.parentNode.parentNode.firstChild)}else{if(E.firstChild!=this.node){E.insertBefore(this.node,this.node.parentNode.firstChild)}}l._toback(this,this.paper);var D=this.paper;return this};m.insertAfter=function(D){if(this.removed){return this}var E=D.node||D[D.length-1].node;if(E.nextSibling){E.parentNode.insertBefore(this.node,E.nextSibling)}else{E.parentNode.appendChild(this.node)}l._insertafter(this,D,this.paper);return this};m.insertBefore=function(D){if(this.removed){return this}var E=D.node||D[0].node;E.parentNode.insertBefore(this.node,E);l._insertbefore(this,D,this.paper);return this};m.blur=function(E){var D=this;if(+E!==0){var F=i("filter"),G=i("feGaussianBlur");D.attrs.blur=E;F.id=l.createUUID();i(G,{stdDeviation:+E||1.5});F.appendChild(G);D.paper.defs.appendChild(F);D._blur=F;i(D.node,{filter:"url(#"+F.id+")"})}else{if(D._blur){D._blur.parentNode.removeChild(D._blur);delete D._blur;delete D.attrs.blur}D.node.removeAttribute("filter")}};l._engine.circle=function(E,D,I,H){var G=i("circle");E.canvas&&E.canvas.appendChild(G);var F=new t(G,E);F.attrs={cx:D,cy:I,r:H,fill:"none",stroke:"#000"};F.type="circle";i(G,F.attrs);return F};l._engine.rect=function(F,D,K,E,I,J){var H=i("rect");F.canvas&&F.canvas.appendChild(H);var G=new t(H,F);G.attrs={x:D,y:K,width:E,height:I,r:J||0,rx:J||0,ry:J||0,fill:"none",stroke:"#000"};G.type="rect";i(H,G.attrs);return G};l._engine.ellipse=function(E,D,J,I,H){var G=i("ellipse");E.canvas&&E.canvas.appendChild(G);var F=new t(G,E);F.attrs={cx:D,cy:J,rx:I,ry:H,fill:"none",stroke:"#000"};F.type="ellipse";i(G,F.attrs);return F};l._engine.image=function(F,J,D,K,E,I){var H=i("image");i(H,{x:D,y:K,width:E,height:I,preserveAspectRatio:"none"});H.setAttributeNS(o,"href",J);F.canvas&&F.canvas.appendChild(H);var G=new t(H,F);G.attrs={x:D,y:K,width:E,height:I,src:J};G.type="image";return G};l._engine.text=function(E,D,I,H){var G=i("text");E.canvas&&E.canvas.appendChild(G);var F=new t(G,E);F.attrs={x:D,y:I,"text-anchor":"middle",text:H,font:l._availableAttrs.font,stroke:"none",fill:"#000"};F.type="text";w(F,F.attrs);return F};l._engine.setSize=function(E,D){this.width=E||this.width;this.height=D||this.height;this.canvas.setAttribute("width",this.width);this.canvas.setAttribute("height",this.height);if(this._viewBox){this.setViewBox.apply(this,this._viewBox)}return this};l._engine.create=function(){var G=l._getContainer.apply(0,arguments),E=G&&G.container,K=G.x,J=G.y,F=G.width,L=G.height;if(!E){throw new Error("SVG container not found.")}var D=i("svg"),I="overflow:hidden;",H;K=K||0;J=J||0;F=F||512;L=L||342;i(D,{height:L,version:1.1,width:F,xmlns:"http://www.w3.org/2000/svg"});if(E==1){D.style.cssText=I+"position:absolute;left:"+K+"px;top:"+J+"px";l._g.doc.body.appendChild(D);H=1}else{D.style.cssText=I+"position:relative";if(E.firstChild){E.insertBefore(D,E.firstChild)}else{E.appendChild(D)}}E=new l._Paper;E.width=F;E.height=L;E.canvas=D;E.clear();E._left=E._top=0;H&&(E.renderfix=function(){});E.renderfix();return E};l._engine.setViewBox=function(I,G,K,D,E){z("raphael.setViewBox",this,this._viewBox,[I,G,K,D,E]);var M=C(K/this.width,D/this.height),H=this.top,L=E?"meet":"xMinYMin",F,J;if(I==null){if(this._vbSize){M=1}delete this._vbSize;F="0 0 "+this.width+j+this.height}else{this._vbSize=M;F=I+j+G+j+K+j+D}i(this.canvas,{viewBox:F,preserveAspectRatio:L});while(M&&H){J="stroke-width" in H.attrs?H.attrs["stroke-width"]:1;H.attr({"stroke-width":J});H._.dirty=1;H._.dirtyT=1;H=H.prev}this._viewBox=[I,G,K,D,!!E];return this};l.prototype.renderfix=function(){var I=this.canvas,D=I.style,H;try{H=I.getScreenCTM()||I.createSVGMatrix()}catch(G){H=I.createSVGMatrix()}var F=-H.e%1,E=-H.f%1;if(F||E){if(F){this._left=(this._left+F)%1;D.left=this._left+"px"}if(E){this._top=(this._top+E)%1;D.top=this._top+"px"}}};l.prototype.clear=function(){l.eve("raphael.clear",this);var D=this.canvas;while(D.firstChild){D.removeChild(D.firstChild)}this.bottom=this.top=null;(this.desc=i("desc")).appendChild(l._g.doc.createTextNode("Created with Rapha\xebl "+l.version));D.appendChild(this.desc);D.appendChild(this.defs=i("defs"))};l.prototype.remove=function(){z("raphael.remove",this);this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas);for(var D in this){this[D]=typeof this[D]=="function"?l._removedFactory(D):null}};var x=l.st;for(var e in m){if(m[d](e)&&!x[d](e)){x[e]=(function(D){return function(){var E=arguments;return this.forEach(function(F){F[D].apply(F,E)})}})(e)}}}(window.Raphael);window.Raphael&&window.Raphael.vml&&function(l){var e="hasOwnProperty",F=String,n=parseFloat,h=Math,B=h.round,I=h.max,C=h.min,s=h.abs,v="fill",i=/[, ]+/,A=l.eve,w=" progid:DXImageTransform.Microsoft",k=" ",q="",D={M:"m",L:"l",C:"c",Z:"x",m:"t",l:"r",c:"v",z:"x"},j=/([clmz]),?([^clmz]*)/gi,t=/ progid:\S+Blur\([^\)]+\)/g,H=/-?[^,\s-]+/g,d="position:absolute;left:0;top:0;width:1px;height:1px",b=21600,z={path:1,rect:1,image:1},r={circle:1,ellipse:1},f=function(S){var P=/[ahqstv]/ig,K=l._pathToAbsolute;F(S).match(P)&&(K=l._path2curve);P=/[clmz]/g;if(K==l._pathToAbsolute&&!F(S).match(P)){var O=F(S).replace(j,function(W,Y,U){var X=[],T=Y.toLowerCase()=="m",V=D[Y];U.replace(H,function(Z){if(T&&X.length==2){V+=X+D[Y=="m"?"l":"L"];X=[]}X.push(B(Z*b))});return V+X});return O}var Q=K(S),J,E;O=[];for(var M=0,R=Q.length;M<R;M++){J=Q[M];E=Q[M][0].toLowerCase();E=="z"&&(E="x");for(var L=1,N=J.length;L<N;L++){E+=B(J[L]*b)+(L!=N-1?",":q)}O.push(E)}return O.join(k)},o=function(L,K,J){var E=l.matrix();E.rotate(-L,0.5,0.5);return{dx:E.x(K,J),dy:E.y(K,J)}},p=function(R,Q,P,M,L,N){var Z=R._,T=R.matrix,E=Z.fillpos,S=R.node,O=S.style,K=1,J="",V,X=b/Q,W=b/P;O.visibility="hidden";if(!Q||!P){return}S.coordsize=s(X)+k+s(W);O.rotation=N*(Q*P<0?-1:1);if(N){var Y=o(N,M,L);M=Y.dx;L=Y.dy}Q<0&&(J+="x");P<0&&(J+=" y")&&(K=-1);O.flip=J;S.coordorigin=(M*-X)+k+(L*-W);if(E||Z.fillsize){var U=S.getElementsByTagName(v);U=U&&U[0];S.removeChild(U);if(E){Y=o(N,T.x(E[0],E[1]),T.y(E[0],E[1]));U.position=Y.dx*K+k+Y.dy*K}if(Z.fillsize){U.size=Z.fillsize[0]*s(Q)+k+Z.fillsize[1]*s(P)}S.appendChild(U)}O.visibility="visible"};l.toString=function(){return"Your browser doesn\u2019t support SVG. Falling down to VML.\nYou are running Rapha\xebl "+this.version};var c=function(E,O,J){var Q=F(O).toLowerCase().split("-"),M=J?"end":"start",K=Q.length,N="classic",P="medium",L="medium";while(K--){switch(Q[K]){case"block":case"classic":case"oval":case"diamond":case"open":case"none":N=Q[K];break;case"wide":case"narrow":L=Q[K];break;case"long":case"short":P=Q[K];break}}var R=E.node.getElementsByTagName("stroke")[0];R[M+"arrow"]=N;R[M+"arrowlength"]=P;R[M+"arrowwidth"]=L},x=function(Z,aj){Z.attrs=Z.attrs||{};var ae=Z.node,an=Z.attrs,V=ae.style,R,ah=z[Z.type]&&(aj.x!=an.x||aj.y!=an.y||aj.width!=an.width||aj.height!=an.height||aj.cx!=an.cx||aj.cy!=an.cy||aj.rx!=an.rx||aj.ry!=an.ry||aj.r!=an.r),Y=r[Z.type]&&(an.cx!=aj.cx||an.cy!=aj.cy||an.r!=aj.r||an.rx!=aj.rx||an.ry!=aj.ry),aq=Z;for(var W in aj){if(aj[e](W)){an[W]=aj[W]}}if(ah){an.path=l._getPath[Z.type](Z);Z._.dirty=1}aj.href&&(ae.href=aj.href);aj.title&&(ae.title=aj.title);aj.target&&(ae.target=aj.target);aj.cursor&&(V.cursor=aj.cursor);"blur" in aj&&Z.blur(aj.blur);if(aj.path&&Z.type=="path"||ah){ae.path=f(~F(an.path).toLowerCase().indexOf("r")?l._pathToAbsolute(an.path):an.path);if(Z.type=="image"){Z._.fillpos=[an.x,an.y];Z._.fillsize=[an.width,an.height];p(Z,1,1,0,0,0)}}"transform" in aj&&Z.transform(aj.transform);if(Y){var M=+an.cx,K=+an.cy,Q=+an.rx||+an.r||0,P=+an.ry||+an.r||0;ae.path=l.format("ar{0},{1},{2},{3},{4},{1},{4},{1}x",B((M-Q)*b),B((K-P)*b),B((M+Q)*b),B((K+P)*b),B(M*b))}if("clip-rect" in aj){var J=F(aj["clip-rect"]).split(i);if(J.length==4){J[2]=+J[2]+(+J[0]);J[3]=+J[3]+(+J[1]);var X=ae.clipRect||l._g.doc.createElement("div"),ap=X.style;ap.clip=l.format("rect({1}px {2}px {3}px {0}px)",J);if(!ae.clipRect){ap.position="absolute";ap.top=0;ap.left=0;ap.width=Z.paper.width+"px";ap.height=Z.paper.height+"px";ae.parentNode.insertBefore(X,ae);X.appendChild(ae);ae.clipRect=X}}if(!aj["clip-rect"]){ae.clipRect&&(ae.clipRect.style.clip="auto")}}if(Z.textpath){var al=Z.textpath.style;aj.font&&(al.font=aj.font);aj["font-family"]&&(al.fontFamily='"'+aj["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g,q)+'"');aj["font-size"]&&(al.fontSize=aj["font-size"]);aj["font-weight"]&&(al.fontWeight=aj["font-weight"]);aj["font-style"]&&(al.fontStyle=aj["font-style"])}if("arrow-start" in aj){c(aq,aj["arrow-start"])}if("arrow-end" in aj){c(aq,aj["arrow-end"],1)}if(aj.opacity!=null||aj["stroke-width"]!=null||aj.fill!=null||aj.src!=null||aj.stroke!=null||aj["stroke-width"]!=null||aj["stroke-opacity"]!=null||aj["fill-opacity"]!=null||aj["stroke-dasharray"]!=null||aj["stroke-miterlimit"]!=null||aj["stroke-linejoin"]!=null||aj["stroke-linecap"]!=null){var af=ae.getElementsByTagName(v),am=false;af=af&&af[0];!af&&(am=af=G(v));if(Z.type=="image"&&aj.src){af.src=aj.src}aj.fill&&(af.on=true);if(af.on==null||aj.fill=="none"||aj.fill===null){af.on=false}if(af.on&&aj.fill){var O=F(aj.fill).match(l._ISURL);if(O){af.parentNode==ae&&ae.removeChild(af);af.rotate=true;af.src=O[1];af.type="tile";var E=Z.getBBox(1);af.position=E.x+k+E.y;Z._.fillpos=[E.x,E.y];l._preload(O[1],function(){Z._.fillsize=[this.offsetWidth,this.offsetHeight]})}else{af.color=l.getRGB(aj.fill).hex;af.src=q;af.type="solid";if(l.getRGB(aj.fill).error&&(aq.type in {circle:1,ellipse:1}||F(aj.fill).charAt()!="r")&&a(aq,aj.fill,af)){an.fill="none";an.gradient=aj.fill;af.rotate=false}}}if("fill-opacity" in aj||"opacity" in aj){var N=((+an["fill-opacity"]+1||2)-1)*((+an.opacity+1||2)-1)*((+l.getRGB(aj.fill).o+1||2)-1);N=C(I(N,0),1);af.opacity=N;if(af.src){af.color="none"}}ae.appendChild(af);var S=(ae.getElementsByTagName("stroke")&&ae.getElementsByTagName("stroke")[0]),ao=false;!S&&(ao=S=G("stroke"));if((aj.stroke&&aj.stroke!="none")||aj["stroke-width"]||aj["stroke-opacity"]!=null||aj["stroke-dasharray"]||aj["stroke-miterlimit"]||aj["stroke-linejoin"]||aj["stroke-linecap"]){S.on=true}(aj.stroke=="none"||aj.stroke===null||S.on==null||aj.stroke==0||aj["stroke-width"]==0)&&(S.on=false);var ad=l.getRGB(aj.stroke);S.on&&aj.stroke&&(S.color=ad.hex);N=((+an["stroke-opacity"]+1||2)-1)*((+an.opacity+1||2)-1)*((+ad.o+1||2)-1);var aa=(n(aj["stroke-width"])||1)*0.75;N=C(I(N,0),1);aj["stroke-width"]==null&&(aa=an["stroke-width"]);aj["stroke-width"]&&(S.weight=aa);aa&&aa<1&&(N*=aa)&&(S.weight=1);S.opacity=N;aj["stroke-linejoin"]&&(S.joinstyle=aj["stroke-linejoin"]||"miter");S.miterlimit=aj["stroke-miterlimit"]||8;aj["stroke-linecap"]&&(S.endcap=aj["stroke-linecap"]=="butt"?"flat":aj["stroke-linecap"]=="square"?"square":"round");if(aj["stroke-dasharray"]){var ac={"-":"shortdash",".":"shortdot","-.":"shortdashdot","-..":"shortdashdotdot",". ":"dot","- ":"dash","--":"longdash","- .":"dashdot","--.":"longdashdot","--..":"longdashdotdot"};S.dashstyle=ac[e](aj["stroke-dasharray"])?ac[aj["stroke-dasharray"]]:q}ao&&ae.appendChild(S)}if(aq.type=="text"){aq.paper.canvas.style.display=q;var ag=aq.paper.span,ab=100,L=an.font&&an.font.match(/\d+(?:\.\d*)?(?=px)/);V=ag.style;an.font&&(V.font=an.font);an["font-family"]&&(V.fontFamily=an["font-family"]);an["font-weight"]&&(V.fontWeight=an["font-weight"]);an["font-style"]&&(V.fontStyle=an["font-style"]);L=n(an["font-size"]||L&&L[0])||10;V.fontSize=L*ab+"px";aq.textpath.string&&(ag.innerHTML=F(aq.textpath.string).replace(/</g,"&#60;").replace(/&/g,"&#38;").replace(/\n/g,"<br>"));var U=ag.getBoundingClientRect();aq.W=an.w=(U.right-U.left)/ab;aq.H=an.h=(U.bottom-U.top)/ab;aq.X=an.x;aq.Y=an.y+aq.H/2;("x" in aj||"y" in aj)&&(aq.path.v=l.format("m{0},{1}l{2},{1}",B(an.x*b),B(an.y*b),B(an.x*b)+1));var T=["x","y","text","font","font-family","font-weight","font-style","font-size"];for(var ai=0,ak=T.length;ai<ak;ai++){if(T[ai] in aj){aq._.dirty=1;break}}switch(an["text-anchor"]){case"start":aq.textpath.style["v-text-align"]="left";aq.bbx=aq.W/2;break;case"end":aq.textpath.style["v-text-align"]="right";aq.bbx=-aq.W/2;break;default:aq.textpath.style["v-text-align"]="center";aq.bbx=0;break}aq.textpath.style["v-text-kern"]=true}},a=function(E,R,U){E.attrs=E.attrs||{};var S=E.attrs,L=Math.pow,M,N,P="linear",Q=".5 .5";E.attrs.gradient=R;R=F(R).replace(l._radial_gradient,function(X,Y,W){P="radial";if(Y&&W){Y=n(Y);W=n(W);L(Y-0.5,2)+L(W-0.5,2)>0.25&&(W=h.sqrt(0.25-L(Y-0.5,2))*((W>0.5)*2-1)+0.5);Q=Y+k+W}return q});R=R.split(/\s*\-\s*/);if(P=="linear"){var J=R.shift();J=-n(J);if(isNaN(J)){return null}}var O=l._parseDots(R);if(!O){return null}E=E.shape||E.node;if(O.length){E.removeChild(U);U.on=true;U.method="none";U.color=O[0].color;U.color2=O[O.length-1].color;var V=[];for(var K=0,T=O.length;K<T;K++){O[K].offset&&V.push(O[K].offset+k+O[K].color)}U.colors=V.length?V.join():"0% "+U.color;if(P=="radial"){U.type="gradientTitle";U.focus="100%";U.focussize="0 0";U.focusposition=Q;U.angle=0}else{U.type="gradient";U.angle=(270-J)%360}E.appendChild(U)}return 1},u=function(J,E){this[0]=this.node=J;J.raphael=true;this.id=l._oid++;J.raphaelid=this.id;this.X=0;this.Y=0;this.attrs={};this.paper=E;this.matrix=l.matrix();this._={transform:[],sx:1,sy:1,dx:0,dy:0,deg:0,dirty:1,dirtyT:1};!E.bottom&&(E.bottom=this);this.prev=E.top;E.top&&(E.top.next=this);E.top=this;this.next=null};var m=l.el;u.prototype=m;m.constructor=u;m.transform=function(M){if(M==null){return this._.transform}var O=this.paper._viewBoxShift,N=O?"s"+[O.scale,O.scale]+"-1-1t"+[O.dx,O.dy]:q,R;if(O){R=M=F(M).replace(/\.{3}|\u2026/g,this._.transform||q)}l._extractTransform(this,N+M);var S=this.matrix.clone(),U=this.skew,K=this.node,Q,L=~F(this.attrs.fill).indexOf("-"),E=!F(this.attrs.fill).indexOf("url(");S.translate(-0.5,-0.5);if(E||L||this.type=="image"){U.matrix="1 0 0 1";U.offset="0 0";Q=S.split();if((L&&Q.noRotation)||!Q.isSimple){K.style.filter=S.toFilter();var P=this.getBBox(),J=this.getBBox(1),V=P.x-J.x,T=P.y-J.y;K.coordorigin=(V*-b)+k+(T*-b);p(this,1,1,V,T,0)}else{K.style.filter=q;p(this,Q.scalex,Q.scaley,Q.dx,Q.dy,Q.rotate)}}else{K.style.filter=q;U.matrix=F(S);U.offset=S.offset()}R&&(this._.transform=R);return this};m.rotate=function(J,E,L){if(this.removed){return this}if(J==null){return}J=F(J).split(i);if(J.length-1){E=n(J[1]);L=n(J[2])}J=n(J[0]);(L==null)&&(E=L);if(E==null||L==null){var K=this.getBBox(1);E=K.x+K.width/2;L=K.y+K.height/2}this._.dirtyT=1;this.transform(this._.transform.concat([["r",J,E,L]]));return this};m.translate=function(J,E){if(this.removed){return this}J=F(J).split(i);if(J.length-1){E=n(J[1])}J=n(J[0])||0;E=+E||0;if(this._.bbox){this._.bbox.x+=J;this._.bbox.y+=E}this.transform(this._.transform.concat([["t",J,E]]));return this};m.scale=function(M,K,E,L){if(this.removed){return this}M=F(M).split(i);if(M.length-1){K=n(M[1]);E=n(M[2]);L=n(M[3]);isNaN(E)&&(E=null);isNaN(L)&&(L=null)}M=n(M[0]);(K==null)&&(K=M);(L==null)&&(E=L);if(E==null||L==null){var J=this.getBBox(1)}E=E==null?J.x+J.width/2:E;L=L==null?J.y+J.height/2:L;this.transform(this._.transform.concat([["s",M,K,E,L]]));this._.dirtyT=1;return this};m.hide=function(){!this.removed&&(this.node.style.display="none");return this};m.show=function(){!this.removed&&(this.node.style.display=q);return this};m._getBBox=function(){if(this.removed){return{}}return{x:this.X+(this.bbx||0)-this.W/2,y:this.Y-this.H,width:this.W,height:this.H}};m.remove=function(){if(this.removed||!this.node.parentNode){return}this.paper.__set__&&this.paper.__set__.exclude(this);l.eve.unbind("raphael.*.*."+this.id);l._tear(this,this.paper);this.node.parentNode.removeChild(this.node);this.shape&&this.shape.parentNode.removeChild(this.shape);for(var E in this){this[E]=typeof this[E]=="function"?l._removedFactory(E):null}this.removed=true};m.attr=function(E,R){if(this.removed){return this}if(E==null){var O={};for(var Q in this.attrs){if(this.attrs[e](Q)){O[Q]=this.attrs[Q]}}O.gradient&&O.fill=="none"&&(O.fill=O.gradient)&&delete O.gradient;O.transform=this._.transform;return O}if(R==null&&l.is(E,"string")){if(E==v&&this.attrs.fill=="none"&&this.attrs.gradient){return this.attrs.gradient}var P=E.split(i),L={};for(var M=0,T=P.length;M<T;M++){E=P[M];if(E in this.attrs){L[E]=this.attrs[E]}else{if(l.is(this.paper.customAttributes[E],"function")){L[E]=this.paper.customAttributes[E].def}else{L[E]=l._availableAttrs[E]}}}return T-1?L:L[P[0]]}if(this.attrs&&R==null&&l.is(E,"array")){L={};for(M=0,T=E.length;M<T;M++){L[E[M]]=this.attr(E[M])}return L}var J;if(R!=null){J={};J[E]=R}R==null&&l.is(E,"object")&&(J=E);for(var S in J){A("raphael.attr."+S+"."+this.id,this,J[S])}if(J){for(S in this.paper.customAttributes){if(this.paper.customAttributes[e](S)&&J[e](S)&&l.is(this.paper.customAttributes[S],"function")){var N=this.paper.customAttributes[S].apply(this,[].concat(J[S]));this.attrs[S]=J[S];for(var K in N){if(N[e](K)){J[K]=N[K]}}}}if(J.text&&this.type=="text"){this.textpath.string=J.text}x(this,J)}return this};m.toFront=function(){!this.removed&&this.node.parentNode.appendChild(this.node);this.paper&&this.paper.top!=this&&l._tofront(this,this.paper);return this};m.toBack=function(){if(this.removed){return this}if(this.node.parentNode.firstChild!=this.node){this.node.parentNode.insertBefore(this.node,this.node.parentNode.firstChild);l._toback(this,this.paper)}return this};m.insertAfter=function(E){if(this.removed){return this}if(E.constructor==l.st.constructor){E=E[E.length-1]}if(E.node.nextSibling){E.node.parentNode.insertBefore(this.node,E.node.nextSibling)}else{E.node.parentNode.appendChild(this.node)}l._insertafter(this,E,this.paper);return this};m.insertBefore=function(E){if(this.removed){return this}if(E.constructor==l.st.constructor){E=E[0]}E.node.parentNode.insertBefore(this.node,E.node);l._insertbefore(this,E,this.paper);return this};m.blur=function(E){var J=this.node.runtimeStyle,K=J.filter;K=K.replace(t,q);if(+E!==0){this.attrs.blur=E;J.filter=K+k+w+".Blur(pixelradius="+(+E||1.5)+")";J.margin=l.format("-{0}px 0 0 -{0}px",B(+E||1.5))}else{J.filter=K;J.margin=0;delete this.attrs.blur}};l._engine.path=function(L,J){var M=G("shape");M.style.cssText=d;M.coordsize=b+k+b;M.coordorigin=J.coordorigin;var N=new u(M,J),E={fill:"none",stroke:"#000"};L&&(E.path=L);N.type="path";N.path=[];N.Path=q;x(N,E);J.canvas.appendChild(M);var K=G("skew");K.on=true;M.appendChild(K);N.skew=K;N.transform(q);return N};l._engine.rect=function(J,O,M,P,K,E){var Q=l._rectPath(O,M,P,K,E),L=J.path(Q),N=L.attrs;L.X=N.x=O;L.Y=N.y=M;L.W=N.width=P;L.H=N.height=K;N.r=E;N.path=Q;L.type="rect";return L};l._engine.ellipse=function(J,E,O,N,M){var L=J.path(),K=L.attrs;L.X=E-N;L.Y=O-M;L.W=N*2;L.H=M*2;L.type="ellipse";x(L,{cx:E,cy:O,rx:N,ry:M});return L};l._engine.circle=function(J,E,N,M){var L=J.path(),K=L.attrs;L.X=E-M;L.Y=N-M;L.W=L.H=M*2;L.type="circle";x(L,{cx:E,cy:N,r:M});return L};l._engine.image=function(J,E,P,N,Q,L){var S=l._rectPath(P,N,Q,L),M=J.path(S).attr({stroke:"none"}),O=M.attrs,K=M.node,R=K.getElementsByTagName(v)[0];O.src=E;M.X=O.x=P;M.Y=O.y=N;M.W=O.width=Q;M.H=O.height=L;O.path=S;M.type="image";R.parentNode==K&&K.removeChild(R);R.rotate=true;R.src=E;R.type="tile";M._.fillpos=[P,N];M._.fillsize=[Q,L];K.appendChild(R);p(M,1,1,0,0,0);return M};l._engine.text=function(E,O,N,P){var L=G("shape"),R=G("path"),K=G("textpath");O=O||0;N=N||0;P=P||"";R.v=l.format("m{0},{1}l{2},{1}",B(O*b),B(N*b),B(O*b)+1);R.textpathok=true;K.string=F(P);K.on=true;L.style.cssText=d;L.coordsize=b+k+b;L.coordorigin="0 0";var J=new u(L,E),M={fill:"#000",stroke:"none",font:l._availableAttrs.font,text:P};J.shape=L;J.path=R;J.textpath=K;J.type="text";J.attrs.text=F(P);J.attrs.x=O;J.attrs.y=N;J.attrs.w=1;J.attrs.h=1;x(J,M);L.appendChild(K);L.appendChild(R);E.canvas.appendChild(L);var Q=G("skew");Q.on=true;L.appendChild(Q);J.skew=Q;J.transform(q);return J};l._engine.setSize=function(K,E){var J=this.canvas.style;this.width=K;this.height=E;K==+K&&(K+="px");E==+E&&(E+="px");J.width=K;J.height=E;J.clip="rect(0 "+K+" "+E+" 0)";if(this._viewBox){l._engine.setViewBox.apply(this,this._viewBox)}return this};l._engine.setViewBox=function(N,M,O,K,L){l.eve("raphael.setViewBox",this,this._viewBox,[N,M,O,K,L]);var E=this.width,Q=this.height,R=1/I(O/E,K/Q),P,J;if(L){P=Q/K;J=E/O;if(O*P<E){N-=(E-O*P)/2/P}if(K*J<Q){M-=(Q-K*J)/2/J}}this._viewBox=[N,M,O,K,!!L];this._viewBoxShift={dx:-N,dy:-M,scale:R};this.forEach(function(S){S.transform("...")});return this};var G;l._engine.initWin=function(K){var J=K.document;J.createStyleSheet().addRule(".rvml","behavior:url(#default#VML)");try{!J.namespaces.rvml&&J.namespaces.add("rvml","urn:schemas-microsoft-com:vml");G=function(L){return J.createElement("<rvml:"+L+' class="rvml">')}}catch(E){G=function(L){return J.createElement("<"+L+' xmlns="urn:schemas-microsoft.com:vml" class="rvml">')}}};l._engine.initWin(l._g.win);l._engine.create=function(){var K=l._getContainer.apply(0,arguments),E=K.container,Q=K.height,R,J=K.width,P=K.x,O=K.y;if(!E){throw new Error("VML container not found.")}var M=new l._Paper,N=M.canvas=l._g.doc.createElement("div"),L=N.style;P=P||0;O=O||0;J=J||512;Q=Q||342;M.width=J;M.height=Q;J==+J&&(J+="px");Q==+Q&&(Q+="px");M.coordsize=b*1000+k+b*1000;M.coordorigin="0 0";M.span=l._g.doc.createElement("span");M.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;";N.appendChild(M.span);L.cssText=l.format("top:0;left:0;width:{0};height:{1};display:inline-block;position:relative;clip:rect(0 {0} {1} 0);overflow:hidden",J,Q);if(E==1){l._g.doc.body.appendChild(N);L.left=P+"px";L.top=O+"px";L.position="absolute"}else{if(E.firstChild){E.insertBefore(N,E.firstChild)}else{E.appendChild(N)}}M.renderfix=function(){};return M};l.prototype.clear=function(){l.eve("raphael.clear",this);this.canvas.innerHTML=q;this.span=l._g.doc.createElement("span");this.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;";this.canvas.appendChild(this.span);this.bottom=this.top=null};l.prototype.remove=function(){l.eve("raphael.remove",this);this.canvas.parentNode.removeChild(this.canvas);for(var E in this){this[E]=typeof this[E]=="function"?l._removedFactory(E):null}return true};var y=l.st;for(var g in m){if(m[e](g)&&!y[e](g)){y[g]=(function(E){return function(){var J=arguments;return this.forEach(function(K){K[E].apply(K,J)})}})(g)}}}(window.Raphael); /* jQuery UI - v1.8.24 - 2012-09-28 * https://github.com/jquery/jquery-ui * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.sortable.js, jquery.effects.core.js, jquery.effects.blind.js, jquery.effects.bounce.js, jquery.effects.clip.js, jquery.effects.drop.js, jquery.effects.explode.js, jquery.effects.fade.js, jquery.effects.fold.js, jquery.effects.highlight.js, jquery.effects.pulsate.js, jquery.effects.scale.js, jquery.effects.shake.js, jquery.effects.slide.js, jquery.effects.transfer.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.position.js, jquery.ui.progressbar.js, jquery.ui.slider.js, jquery.ui.tabs.js * Copyright (c) 2012 AUTHORS.txt; Licensed MIT, GPL */ (function(a,d){a.ui=a.ui||{};if(a.ui.version){return}a.extend(a.ui,{version:"1.8.24",keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});a.fn.extend({propAttr:a.fn.prop||a.fn.attr,_focus:a.fn.focus,focus:function(e,f){return typeof e==="number"?this.each(function(){var g=this;setTimeout(function(){a(g).focus();if(f){f.call(g)}},e)}):this._focus.apply(this,arguments)},scrollParent:function(){var e;if((a.browser.msie&&(/(static|relative)/).test(this.css("position")))||(/absolute/).test(this.css("position"))){e=this.parents().filter(function(){return(/(relative|absolute|fixed)/).test(a.curCSS(this,"position",1))&&(/(auto|scroll)/).test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0)}else{e=this.parents().filter(function(){return(/(auto|scroll)/).test(a.curCSS(this,"overflow",1)+a.curCSS(this,"overflow-y",1)+a.curCSS(this,"overflow-x",1))}).eq(0)}return(/fixed/).test(this.css("position"))||!e.length?a(document):e},zIndex:function(h){if(h!==d){return this.css("zIndex",h)}if(this.length){var f=a(this[0]),e,g;while(f.length&&f[0]!==document){e=f.css("position");if(e==="absolute"||e==="relative"||e==="fixed"){g=parseInt(f.css("zIndex"),10);if(!isNaN(g)&&g!==0){return g}}f=f.parent()}}return 0},disableSelection:function(){return this.bind((a.support.selectstart?"selectstart":"mousedown")+".ui-disableSelection",function(e){e.preventDefault()})},enableSelection:function(){return this.unbind(".ui-disableSelection")}});if(!a("<a>").outerWidth(1).jquery){a.each(["Width","Height"],function(g,e){var f=e==="Width"?["Left","Right"]:["Top","Bottom"],h=e.toLowerCase(),k={innerWidth:a.fn.innerWidth,innerHeight:a.fn.innerHeight,outerWidth:a.fn.outerWidth,outerHeight:a.fn.outerHeight};function j(m,l,i,n){a.each(f,function(){l-=parseFloat(a.curCSS(m,"padding"+this,true))||0;if(i){l-=parseFloat(a.curCSS(m,"border"+this+"Width",true))||0}if(n){l-=parseFloat(a.curCSS(m,"margin"+this,true))||0}});return l}a.fn["inner"+e]=function(i){if(i===d){return k["inner"+e].call(this)}return this.each(function(){a(this).css(h,j(this,i)+"px")})};a.fn["outer"+e]=function(i,l){if(typeof i!=="number"){return k["outer"+e].call(this,i)}return this.each(function(){a(this).css(h,j(this,i,true,l)+"px")})}})}function c(g,e){var j=g.nodeName.toLowerCase();if("area"===j){var i=g.parentNode,h=i.name,f;if(!g.href||!h||i.nodeName.toLowerCase()!=="map"){return false}f=a("img[usemap=#"+h+"]")[0];return !!f&&b(f)}return(/input|select|textarea|button|object/.test(j)?!g.disabled:"a"==j?g.href||e:e)&&b(g)}function b(e){return !a(e).parents().andSelf().filter(function(){return a.curCSS(this,"visibility")==="hidden"||a.expr.filters.hidden(this)}).length}a.extend(a.expr[":"],{data:a.expr.createPseudo?a.expr.createPseudo(function(e){return function(f){return !!a.data(f,e)}}):function(g,f,e){return !!a.data(g,e[3])},focusable:function(e){return c(e,!isNaN(a.attr(e,"tabindex")))},tabbable:function(g){var e=a.attr(g,"tabindex"),f=isNaN(e);return(f||e>=0)&&c(g,!f)}});a(function(){var e=document.body,f=e.appendChild(f=document.createElement("div"));f.offsetHeight;a.extend(f.style,{minHeight:"100px",height:"auto",padding:0,borderWidth:0});a.support.minHeight=f.offsetHeight===100;a.support.selectstart="onselectstart" in f;e.removeChild(f).style.display="none"});if(!a.curCSS){a.curCSS=a.css}a.extend(a.ui,{plugin:{add:function(f,g,j){var h=a.ui[f].prototype;for(var e in j){h.plugins[e]=h.plugins[e]||[];h.plugins[e].push([g,j[e]])}},call:function(e,g,f){var j=e.plugins[g];if(!j||!e.element[0].parentNode){return}for(var h=0;h<j.length;h++){if(e.options[j[h][0]]){j[h][1].apply(e.element,f)}}}},contains:function(f,e){return document.compareDocumentPosition?f.compareDocumentPosition(e)&16:f!==e&&f.contains(e)},hasScroll:function(h,f){if(a(h).css("overflow")==="hidden"){return false}var e=(f&&f==="left")?"scrollLeft":"scrollTop",g=false;if(h[e]>0){return true}h[e]=1;g=(h[e]>0);h[e]=0;return g},isOverAxis:function(f,e,g){return(f>e)&&(f<(e+g))},isOver:function(j,f,i,h,e,g){return a.ui.isOverAxis(j,i,e)&&a.ui.isOverAxis(f,h,g)}})})(jQuery);(function(b,d){if(b.cleanData){var c=b.cleanData;b.cleanData=function(f){for(var g=0,h;(h=f[g])!=null;g++){try{b(h).triggerHandler("remove")}catch(j){}}c(f)}}else{var a=b.fn.remove;b.fn.remove=function(e,f){return this.each(function(){if(!f){if(!e||b.filter(e,[this]).length){b("*",this).add([this]).each(function(){try{b(this).triggerHandler("remove")}catch(g){}})}}return a.call(b(this),e,f)})}}b.widget=function(f,h,e){var g=f.split(".")[0],j;f=f.split(".")[1];j=g+"-"+f;if(!e){e=h;h=b.Widget}b.expr[":"][j]=function(k){return !!b.data(k,f)};b[g]=b[g]||{};b[g][f]=function(k,l){if(arguments.length){this._createWidget(k,l)}};var i=new h();i.options=b.extend(true,{},i.options);b[g][f].prototype=b.extend(true,i,{namespace:g,widgetName:f,widgetEventPrefix:b[g][f].prototype.widgetEventPrefix||f,widgetBaseClass:j},e);b.widget.bridge(f,b[g][f])};b.widget.bridge=function(f,e){b.fn[f]=function(i){var g=typeof i==="string",h=Array.prototype.slice.call(arguments,1),j=this;i=!g&&h.length?b.extend.apply(null,[true,i].concat(h)):i;if(g&&i.charAt(0)==="_"){return j}if(g){this.each(function(){var k=b.data(this,f),l=k&&b.isFunction(k[i])?k[i].apply(k,h):k;if(l!==k&&l!==d){j=l;return false}})}else{this.each(function(){var k=b.data(this,f);if(k){k.option(i||{})._init()}else{b.data(this,f,new e(i,this))}})}return j}};b.Widget=function(e,f){if(arguments.length){this._createWidget(e,f)}};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(f,g){b.data(g,this.widgetName,this);this.element=b(g);this.options=b.extend(true,{},this.options,this._getCreateOptions(),f);var e=this;this.element.bind("remove."+this.widgetName,function(){e.destroy()});this._create();this._trigger("create");this._init()},_getCreateOptions:function(){return b.metadata&&b.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(f,g){var e=f;if(arguments.length===0){return b.extend({},this.options)}if(typeof f==="string"){if(g===d){return this.options[f]}e={};e[f]=g}this._setOptions(e);return this},_setOptions:function(f){var e=this;b.each(f,function(g,h){e._setOption(g,h)});return this},_setOption:function(e,f){this.options[e]=f;if(e==="disabled"){this.widget()[f?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",f)}return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(e,f,g){var j,i,h=this.options[e];g=g||{};f=b.Event(f);f.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase();f.target=this.element[0];i=f.originalEvent;if(i){for(j in i){if(!(j in f)){f[j]=i[j]}}}this.element.trigger(f,g);return !(b.isFunction(h)&&h.call(this.element[0],f,g)===false||f.isDefaultPrevented())}}})(jQuery);(function(b,c){var a=false;b(document).mouseup(function(d){a=false});b.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var d=this;this.element.bind("mousedown."+this.widgetName,function(e){return d._mouseDown(e)}).bind("click."+this.widgetName,function(e){if(true===b.data(e.target,d.widgetName+".preventClickEvent")){b.removeData(e.target,d.widgetName+".preventClickEvent");e.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);if(this._mouseMoveDelegate){b(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)}},_mouseDown:function(f){if(a){return}(this._mouseStarted&&this._mouseUp(f));this._mouseDownEvent=f;var e=this,g=(f.which==1),d=(typeof this.options.cancel=="string"&&f.target.nodeName?b(f.target).closest(this.options.cancel).length:false);if(!g||d||!this._mouseCapture(f)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){e.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(f)&&this._mouseDelayMet(f)){this._mouseStarted=(this._mouseStart(f)!==false);if(!this._mouseStarted){f.preventDefault();return true}}if(true===b.data(f.target,this.widgetName+".preventClickEvent")){b.removeData(f.target,this.widgetName+".preventClickEvent")}this._mouseMoveDelegate=function(h){return e._mouseMove(h)};this._mouseUpDelegate=function(h){return e._mouseUp(h)};b(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);f.preventDefault();a=true;return true},_mouseMove:function(d){if(b.browser.msie&&!(document.documentMode>=9)&&!d.button){return this._mouseUp(d)}if(this._mouseStarted){this._mouseDrag(d);return d.preventDefault()}if(this._mouseDistanceMet(d)&&this._mouseDelayMet(d)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,d)!==false);(this._mouseStarted?this._mouseDrag(d):this._mouseUp(d))}return !this._mouseStarted},_mouseUp:function(d){b(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;if(d.target==this._mouseDownEvent.target){b.data(d.target,this.widgetName+".preventClickEvent",true)}this._mouseStop(d)}return false},_mouseDistanceMet:function(d){return(Math.max(Math.abs(this._mouseDownEvent.pageX-d.pageX),Math.abs(this._mouseDownEvent.pageY-d.pageY))>=this.options.distance)},_mouseDelayMet:function(d){return this.mouseDelayMet},_mouseStart:function(d){},_mouseDrag:function(d){},_mouseStop:function(d){},_mouseCapture:function(d){return true}})})(jQuery);(function(a,b){a.widget("ui.draggable",a.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false},_create:function(){if(this.options.helper=="original"&&!(/^(?:r|a|f)/).test(this.element.css("position"))){this.element[0].style.position="relative"}(this.options.addClasses&&this.element.addClass("ui-draggable"));(this.options.disabled&&this.element.addClass("ui-draggable-disabled"));this._mouseInit()},destroy:function(){if(!this.element.data("draggable")){return}this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy();return this},_mouseCapture:function(c){var d=this.options;if(this.helper||d.disabled||a(c.target).is(".ui-resizable-handle")){return false}this.handle=this._getHandle(c);if(!this.handle){return false}if(d.iframeFix){a(d.iframeFix===true?"iframe":d.iframeFix).each(function(){a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1000}).css(a(this).offset()).appendTo("body")})}return true},_mouseStart:function(c){var d=this.options;this.helper=this._createHelper(c);this.helper.addClass("ui-draggable-dragging");this._cacheHelperProportions();if(a.ui.ddmanager){a.ui.ddmanager.current=this}this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};a.extend(this.offset,{click:{left:c.pageX-this.offset.left,top:c.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(c);this.originalPageX=c.pageX;this.originalPageY=c.pageY;(d.cursorAt&&this._adjustOffsetFromHelper(d.cursorAt));if(d.containment){this._setContainment()}if(this._trigger("start",c)===false){this._clear();return false}this._cacheHelperProportions();if(a.ui.ddmanager&&!d.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,c)}this._mouseDrag(c,true);if(a.ui.ddmanager){a.ui.ddmanager.dragStart(this,c)}return true},_mouseDrag:function(c,e){this.position=this._generatePosition(c);this.positionAbs=this._convertPositionTo("absolute");if(!e){var d=this._uiHash();if(this._trigger("drag",c,d)===false){this._mouseUp({});return false}this.position=d.position}if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}if(a.ui.ddmanager){a.ui.ddmanager.drag(this,c)}return false},_mouseStop:function(e){var g=false;if(a.ui.ddmanager&&!this.options.dropBehaviour){g=a.ui.ddmanager.drop(this,e)}if(this.dropped){g=this.dropped;this.dropped=false}var d=this.element[0],f=false;while(d&&(d=d.parentNode)){if(d==document){f=true}}if(!f&&this.options.helper==="original"){return false}if((this.options.revert=="invalid"&&!g)||(this.options.revert=="valid"&&g)||this.options.revert===true||(a.isFunction(this.options.revert)&&this.options.revert.call(this.element,g))){var c=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){if(c._trigger("stop",e)!==false){c._clear()}})}else{if(this._trigger("stop",e)!==false){this._clear()}}return false},_mouseUp:function(c){a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)});if(a.ui.ddmanager){a.ui.ddmanager.dragStop(this,c)}return a.ui.mouse.prototype._mouseUp.call(this,c)},cancel:function(){if(this.helper.is(".ui-draggable-dragging")){this._mouseUp({})}else{this._clear()}return this},_getHandle:function(c){var d=!this.options.handle||!a(this.options.handle,this.element).length?true:false;a(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==c.target){d=true}});return d},_createHelper:function(d){var e=this.options;var c=a.isFunction(e.helper)?a(e.helper.apply(this.element[0],[d])):(e.helper=="clone"?this.element.clone().removeAttr("id"):this.element);if(!c.parents("body").length){c.appendTo((e.appendTo=="parent"?this.element[0].parentNode:e.appendTo))}if(c[0]!=this.element[0]&&!(/(fixed|absolute)/).test(c.css("position"))){c.css("position","absolute")}return c},_adjustOffsetFromHelper:function(c){if(typeof c=="string"){c=c.split(" ")}if(a.isArray(c)){c={left:+c[0],top:+c[1]||0}}if("left" in c){this.offset.click.left=c.left+this.margins.left}if("right" in c){this.offset.click.left=this.helperProportions.width-c.right+this.margins.left}if("top" in c){this.offset.click.top=c.top+this.margins.top}if("bottom" in c){this.offset.click.top=this.helperProportions.height-c.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var c=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){c.left+=this.scrollParent.scrollLeft();c.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){c={top:0,left:0}}return{top:c.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:c.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var c=this.element.position();return{top:c.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:c.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.element.css("marginLeft"),10)||0),top:(parseInt(this.element.css("marginTop"),10)||0),right:(parseInt(this.element.css("marginRight"),10)||0),bottom:(parseInt(this.element.css("marginBottom"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var g=this.options;if(g.containment=="parent"){g.containment=this.helper[0].parentNode}if(g.containment=="document"||g.containment=="window"){this.containment=[g.containment=="document"?0:a(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,g.containment=="document"?0:a(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(g.containment=="document"?0:a(window).scrollLeft())+a(g.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(g.containment=="document"?0:a(window).scrollTop())+(a(g.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(g.containment)&&g.containment.constructor!=Array){var h=a(g.containment);var e=h[0];if(!e){return}var f=h.offset();var d=(a(e).css("overflow")!="hidden");this.containment=[(parseInt(a(e).css("borderLeftWidth"),10)||0)+(parseInt(a(e).css("paddingLeft"),10)||0),(parseInt(a(e).css("borderTopWidth"),10)||0)+(parseInt(a(e).css("paddingTop"),10)||0),(d?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(a(e).css("borderLeftWidth"),10)||0)-(parseInt(a(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(d?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(a(e).css("borderTopWidth"),10)||0)-(parseInt(a(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom];this.relative_container=h}else{if(g.containment.constructor==Array){this.containment=g.containment}}},_convertPositionTo:function(g,i){if(!i){i=this.position}var e=g=="absolute"?1:-1;var f=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,h=(/(html|body)/i).test(c[0].tagName);return{top:(i.top+this.offset.relative.top*e+this.offset.parent.top*e-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(h?0:c.scrollTop()))*e)),left:(i.left+this.offset.relative.left*e+this.offset.parent.left*e-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():h?0:c.scrollLeft())*e))}},_generatePosition:function(d){var e=this.options,l=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,i=(/(html|body)/i).test(l[0].tagName);var h=d.pageX;var g=d.pageY;if(this.originalPosition){var c;if(this.containment){if(this.relative_container){var k=this.relative_container.offset();c=[this.containment[0]+k.left,this.containment[1]+k.top,this.containment[2]+k.left,this.containment[3]+k.top]}else{c=this.containment}if(d.pageX-this.offset.click.left<c[0]){h=c[0]+this.offset.click.left}if(d.pageY-this.offset.click.top<c[1]){g=c[1]+this.offset.click.top}if(d.pageX-this.offset.click.left>c[2]){h=c[2]+this.offset.click.left}if(d.pageY-this.offset.click.top>c[3]){g=c[3]+this.offset.click.top}}if(e.grid){var j=e.grid[1]?this.originalPageY+Math.round((g-this.originalPageY)/e.grid[1])*e.grid[1]:this.originalPageY;g=c?(!(j-this.offset.click.top<c[1]||j-this.offset.click.top>c[3])?j:(!(j-this.offset.click.top<c[1])?j-e.grid[1]:j+e.grid[1])):j;var f=e.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/e.grid[0])*e.grid[0]:this.originalPageX;h=c?(!(f-this.offset.click.left<c[0]||f-this.offset.click.left>c[2])?f:(!(f-this.offset.click.left<c[0])?f-e.grid[0]:f+e.grid[0])):f}}return{top:(g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(i?0:l.scrollTop())))),left:(h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:l.scrollLeft())))}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");if(this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval){this.helper.remove()}this.helper=null;this.cancelHelperRemoval=false},_trigger:function(c,d,e){e=e||this._uiHash();a.ui.plugin.call(this,c,[d,e]);if(c=="drag"){this.positionAbs=this._convertPositionTo("absolute")}return a.Widget.prototype._trigger.call(this,c,d,e)},plugins:{},_uiHash:function(c){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}});a.extend(a.ui.draggable,{version:"1.8.24"});a.ui.plugin.add("draggable","connectToSortable",{start:function(d,f){var e=a(this).data("draggable"),g=e.options,c=a.extend({},f,{item:e.element});e.sortables=[];a(g.connectToSortable).each(function(){var h=a.data(this,"sortable");if(h&&!h.options.disabled){e.sortables.push({instance:h,shouldRevert:h.options.revert});h.refreshPositions();h._trigger("activate",d,c)}})},stop:function(d,f){var e=a(this).data("draggable"),c=a.extend({},f,{item:e.element});a.each(e.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;e.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert){this.instance.options.revert=true}this.instance._mouseStop(d);this.instance.options.helper=this.instance.options._helper;if(e.options.helper=="original"){this.instance.currentItem.css({top:"auto",left:"auto"})}}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",d,c)}})},drag:function(d,g){var f=a(this).data("draggable"),c=this;var e=function(j){var p=this.offset.click.top,n=this.offset.click.left;var h=this.positionAbs.top,l=this.positionAbs.left;var k=j.height,m=j.width;var q=j.top,i=j.left;return a.ui.isOver(h+p,l+n,q,i,k,m)};a.each(f.sortables,function(h){this.instance.positionAbs=f.positionAbs;this.instance.helperProportions=f.helperProportions;this.instance.offset.click=f.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=a(c).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return g.helper[0]};d.target=this.instance.currentItem[0];this.instance._mouseCapture(d,true);this.instance._mouseStart(d,true,true);this.instance.offset.click.top=f.offset.click.top;this.instance.offset.click.left=f.offset.click.left;this.instance.offset.parent.left-=f.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=f.offset.parent.top-this.instance.offset.parent.top;f._trigger("toSortable",d);f.dropped=this.instance.element;f.currentItem=f.element;this.instance.fromOutside=f}if(this.instance.currentItem){this.instance._mouseDrag(d)}}else{if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",d,this.instance._uiHash(this.instance));this.instance._mouseStop(d,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();if(this.instance.placeholder){this.instance.placeholder.remove()}f._trigger("fromSortable",d);f.dropped=false}}})}});a.ui.plugin.add("draggable","cursor",{start:function(d,e){var c=a("body"),f=a(this).data("draggable").options;if(c.css("cursor")){f._cursor=c.css("cursor")}c.css("cursor",f.cursor)},stop:function(c,d){var e=a(this).data("draggable").options;if(e._cursor){a("body").css("cursor",e._cursor)}}});a.ui.plugin.add("draggable","opacity",{start:function(d,e){var c=a(e.helper),f=a(this).data("draggable").options;if(c.css("opacity")){f._opacity=c.css("opacity")}c.css("opacity",f.opacity)},stop:function(c,d){var e=a(this).data("draggable").options;if(e._opacity){a(d.helper).css("opacity",e._opacity)}}});a.ui.plugin.add("draggable","scroll",{start:function(d,e){var c=a(this).data("draggable");if(c.scrollParent[0]!=document&&c.scrollParent[0].tagName!="HTML"){c.overflowOffset=c.scrollParent.offset()}},drag:function(e,f){var d=a(this).data("draggable"),g=d.options,c=false;if(d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"){if(!g.axis||g.axis!="x"){if((d.overflowOffset.top+d.scrollParent[0].offsetHeight)-e.pageY<g.scrollSensitivity){d.scrollParent[0].scrollTop=c=d.scrollParent[0].scrollTop+g.scrollSpeed}else{if(e.pageY-d.overflowOffset.top<g.scrollSensitivity){d.scrollParent[0].scrollTop=c=d.scrollParent[0].scrollTop-g.scrollSpeed}}}if(!g.axis||g.axis!="y"){if((d.overflowOffset.left+d.scrollParent[0].offsetWidth)-e.pageX<g.scrollSensitivity){d.scrollParent[0].scrollLeft=c=d.scrollParent[0].scrollLeft+g.scrollSpeed}else{if(e.pageX-d.overflowOffset.left<g.scrollSensitivity){d.scrollParent[0].scrollLeft=c=d.scrollParent[0].scrollLeft-g.scrollSpeed}}}}else{if(!g.axis||g.axis!="x"){if(e.pageY-a(document).scrollTop()<g.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()-g.scrollSpeed)}else{if(a(window).height()-(e.pageY-a(document).scrollTop())<g.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()+g.scrollSpeed)}}}if(!g.axis||g.axis!="y"){if(e.pageX-a(document).scrollLeft()<g.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()-g.scrollSpeed)}else{if(a(window).width()-(e.pageX-a(document).scrollLeft())<g.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()+g.scrollSpeed)}}}}if(c!==false&&a.ui.ddmanager&&!g.dropBehaviour){a.ui.ddmanager.prepareOffsets(d,e)}}});a.ui.plugin.add("draggable","snap",{start:function(d,e){var c=a(this).data("draggable"),f=c.options;c.snapElements=[];a(f.snap.constructor!=String?(f.snap.items||":data(draggable)"):f.snap).each(function(){var h=a(this);var g=h.offset();if(this!=c.element[0]){c.snapElements.push({item:this,width:h.outerWidth(),height:h.outerHeight(),top:g.top,left:g.left})}})},drag:function(u,p){var g=a(this).data("draggable"),q=g.options;var y=q.snapTolerance;var x=p.offset.left,w=x+g.helperProportions.width,f=p.offset.top,e=f+g.helperProportions.height;for(var v=g.snapElements.length-1;v>=0;v--){var s=g.snapElements[v].left,n=s+g.snapElements[v].width,m=g.snapElements[v].top,A=m+g.snapElements[v].height;if(!((s-y<x&&x<n+y&&m-y<f&&f<A+y)||(s-y<x&&x<n+y&&m-y<e&&e<A+y)||(s-y<w&&w<n+y&&m-y<f&&f<A+y)||(s-y<w&&w<n+y&&m-y<e&&e<A+y))){if(g.snapElements[v].snapping){(g.options.snap.release&&g.options.snap.release.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=false;continue}if(q.snapMode!="inner"){var c=Math.abs(m-e)<=y;var z=Math.abs(A-f)<=y;var j=Math.abs(s-w)<=y;var k=Math.abs(n-x)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m-g.helperProportions.height,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s-g.helperProportions.width}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n}).left-g.margins.left}}var h=(c||z||j||k);if(q.snapMode!="outer"){var c=Math.abs(m-f)<=y;var z=Math.abs(A-e)<=y;var j=Math.abs(s-x)<=y;var k=Math.abs(n-w)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A-g.helperProportions.height,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n-g.helperProportions.width}).left-g.margins.left}}if(!g.snapElements[v].snapping&&(c||z||j||k||h)){(g.options.snap.snap&&g.options.snap.snap.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=(c||z||j||k||h)}}});a.ui.plugin.add("draggable","stack",{start:function(d,e){var g=a(this).data("draggable").options;var f=a.makeArray(a(g.stack)).sort(function(i,h){return(parseInt(a(i).css("zIndex"),10)||0)-(parseInt(a(h).css("zIndex"),10)||0)});if(!f.length){return}var c=parseInt(f[0].style.zIndex)||0;a(f).each(function(h){this.style.zIndex=c+h});this[0].style.zIndex=c+f.length}});a.ui.plugin.add("draggable","zIndex",{start:function(d,e){var c=a(e.helper),f=a(this).data("draggable").options;if(c.css("zIndex")){f._zIndex=c.css("zIndex")}c.css("zIndex",f.zIndex)},stop:function(c,d){var e=a(this).data("draggable").options;if(e._zIndex){a(d.helper).css("zIndex",e._zIndex)}}})})(jQuery);(function(a,b){a.widget("ui.droppable",{widgetEventPrefix:"drop",options:{accept:"*",activeClass:false,addClasses:true,greedy:false,hoverClass:false,scope:"default",tolerance:"intersect"},_create:function(){var d=this.options,c=d.accept;this.isover=0;this.isout=1;this.accept=a.isFunction(c)?c:function(e){return e.is(c)};this.proportions={width:this.element[0].offsetWidth,height:this.element[0].offsetHeight};a.ui.ddmanager.droppables[d.scope]=a.ui.ddmanager.droppables[d.scope]||[];a.ui.ddmanager.droppables[d.scope].push(this);(d.addClasses&&this.element.addClass("ui-droppable"))},destroy:function(){var c=a.ui.ddmanager.droppables[this.options.scope];for(var d=0;d<c.length;d++){if(c[d]==this){c.splice(d,1)}}this.element.removeClass("ui-droppable ui-droppable-disabled").removeData("droppable").unbind(".droppable");return this},_setOption:function(c,d){if(c=="accept"){this.accept=a.isFunction(d)?d:function(e){return e.is(d)}}a.Widget.prototype._setOption.apply(this,arguments)},_activate:function(d){var c=a.ui.ddmanager.current;if(this.options.activeClass){this.element.addClass(this.options.activeClass)}(c&&this._trigger("activate",d,this.ui(c)))},_deactivate:function(d){var c=a.ui.ddmanager.current;if(this.options.activeClass){this.element.removeClass(this.options.activeClass)}(c&&this._trigger("deactivate",d,this.ui(c)))},_over:function(d){var c=a.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0]){return}if(this.accept.call(this.element[0],(c.currentItem||c.element))){if(this.options.hoverClass){this.element.addClass(this.options.hoverClass)}this._trigger("over",d,this.ui(c))}},_out:function(d){var c=a.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0]){return}if(this.accept.call(this.element[0],(c.currentItem||c.element))){if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass)}this._trigger("out",d,this.ui(c))}},_drop:function(d,e){var c=e||a.ui.ddmanager.current;if(!c||(c.currentItem||c.element)[0]==this.element[0]){return false}var f=false;this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function(){var g=a.data(this,"droppable");if(g.options.greedy&&!g.options.disabled&&g.options.scope==c.options.scope&&g.accept.call(g.element[0],(c.currentItem||c.element))&&a.ui.intersect(c,a.extend(g,{offset:g.element.offset()}),g.options.tolerance)){f=true;return false}});if(f){return false}if(this.accept.call(this.element[0],(c.currentItem||c.element))){if(this.options.activeClass){this.element.removeClass(this.options.activeClass)}if(this.options.hoverClass){this.element.removeClass(this.options.hoverClass)}this._trigger("drop",d,this.ui(c));return this.element}return false},ui:function(d){return{draggable:(d.currentItem||d.element),helper:d.helper,position:d.position,offset:d.positionAbs}}});a.extend(a.ui.droppable,{version:"1.8.24"});a.ui.intersect=function(q,j,o){if(!j.offset){return false}var e=(q.positionAbs||q.position.absolute).left,d=e+q.helperProportions.width,n=(q.positionAbs||q.position.absolute).top,m=n+q.helperProportions.height;var g=j.offset.left,c=g+j.proportions.width,p=j.offset.top,k=p+j.proportions.height;switch(o){case"fit":return(g<=e&&d<=c&&p<=n&&m<=k);break;case"intersect":return(g<e+(q.helperProportions.width/2)&&d-(q.helperProportions.width/2)<c&&p<n+(q.helperProportions.height/2)&&m-(q.helperProportions.height/2)<k);break;case"pointer":var h=((q.positionAbs||q.position.absolute).left+(q.clickOffset||q.offset.click).left),i=((q.positionAbs||q.position.absolute).top+(q.clickOffset||q.offset.click).top),f=a.ui.isOver(i,h,p,g,j.proportions.height,j.proportions.width);return f;break;case"touch":return((n>=p&&n<=k)||(m>=p&&m<=k)||(n<p&&m>k))&&((e>=g&&e<=c)||(d>=g&&d<=c)||(e<g&&d>c));break;default:return false;break}};a.ui.ddmanager={current:null,droppables:{"default":[]},prepareOffsets:function(f,h){var c=a.ui.ddmanager.droppables[f.options.scope]||[];var g=h?h.type:null;var k=(f.currentItem||f.element).find(":data(droppable)").andSelf();droppablesLoop:for(var e=0;e<c.length;e++){if(c[e].options.disabled||(f&&!c[e].accept.call(c[e].element[0],(f.currentItem||f.element)))){continue}for(var d=0;d<k.length;d++){if(k[d]==c[e].element[0]){c[e].proportions.height=0;continue droppablesLoop}}c[e].visible=c[e].element.css("display")!="none";if(!c[e].visible){continue}if(g=="mousedown"){c[e]._activate.call(c[e],h)}c[e].offset=c[e].element.offset();c[e].proportions={width:c[e].element[0].offsetWidth,height:c[e].element[0].offsetHeight}}},drop:function(c,d){var e=false;a.each(a.ui.ddmanager.droppables[c.options.scope]||[],function(){if(!this.options){return}if(!this.options.disabled&&this.visible&&a.ui.intersect(c,this,this.options.tolerance)){e=this._drop.call(this,d)||e}if(!this.options.disabled&&this.visible&&this.accept.call(this.element[0],(c.currentItem||c.element))){this.isout=1;this.isover=0;this._deactivate.call(this,d)}});return e},dragStart:function(c,d){c.element.parents(":not(body,html)").bind("scroll.droppable",function(){if(!c.options.refreshPositions){a.ui.ddmanager.prepareOffsets(c,d)}})},drag:function(c,d){if(c.options.refreshPositions){a.ui.ddmanager.prepareOffsets(c,d)}a.each(a.ui.ddmanager.droppables[c.options.scope]||[],function(){if(this.options.disabled||this.greedyChild||!this.visible){return}var g=a.ui.intersect(c,this,this.options.tolerance);var i=!g&&this.isover==1?"isout":(g&&this.isover==0?"isover":null);if(!i){return}var h;if(this.options.greedy){var f=this.options.scope;var e=this.element.parents(":data(droppable)").filter(function(){return a.data(this,"droppable").options.scope===f});if(e.length){h=a.data(e[0],"droppable");h.greedyChild=(i=="isover"?1:0)}}if(h&&i=="isover"){h.isover=0;h.isout=1;h._out.call(h,d)}this[i]=1;this[i=="isout"?"isover":"isout"]=0;this[i=="isover"?"_over":"_out"].call(this,d);if(h&&i=="isout"){h.isout=0;h.isover=1;h._over.call(h,d)}})},dragStop:function(c,d){c.element.parents(":not(body,html)").unbind("scroll.droppable");if(!c.options.refreshPositions){a.ui.ddmanager.prepareOffsets(c,d)}}}})(jQuery);(function(c,d){c.widget("ui.resizable",c.ui.mouse,{widgetEventPrefix:"resize",options:{alsoResize:false,animate:false,animateDuration:"slow",animateEasing:"swing",aspectRatio:false,autoHide:false,containment:false,ghost:false,grid:false,handles:"e,s,se",helper:false,maxHeight:null,maxWidth:null,minHeight:10,minWidth:10,zIndex:1000},_create:function(){var f=this,k=this.options;this.element.addClass("ui-resizable");c.extend(this,{_aspectRatio:!!(k.aspectRatio),aspectRatio:k.aspectRatio,originalElement:this.element,_proportionallyResizeElements:[],_helper:k.helper||k.ghost||k.animate?k.helper||"ui-resizable-helper":null});if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)){this.element.wrap(c('<div class="ui-wrapper" style="overflow: hidden;"></div>').css({position:this.element.css("position"),width:this.element.outerWidth(),height:this.element.outerHeight(),top:this.element.css("top"),left:this.element.css("left")}));this.element=this.element.parent().data("resizable",this.element.data("resizable"));this.elementIsWrapper=true;this.element.css({marginLeft:this.originalElement.css("marginLeft"),marginTop:this.originalElement.css("marginTop"),marginRight:this.originalElement.css("marginRight"),marginBottom:this.originalElement.css("marginBottom")});this.originalElement.css({marginLeft:0,marginTop:0,marginRight:0,marginBottom:0});this.originalResizeStyle=this.originalElement.css("resize");this.originalElement.css("resize","none");this._proportionallyResizeElements.push(this.originalElement.css({position:"static",zoom:1,display:"block"}));this.originalElement.css({margin:this.originalElement.css("margin")});this._proportionallyResize()}this.handles=k.handles||(!c(".ui-resizable-handle",this.element).length?"e,s,se":{n:".ui-resizable-n",e:".ui-resizable-e",s:".ui-resizable-s",w:".ui-resizable-w",se:".ui-resizable-se",sw:".ui-resizable-sw",ne:".ui-resizable-ne",nw:".ui-resizable-nw"});if(this.handles.constructor==String){if(this.handles=="all"){this.handles="n,e,s,w,se,sw,ne,nw"}var l=this.handles.split(",");this.handles={};for(var g=0;g<l.length;g++){var j=c.trim(l[g]),e="ui-resizable-"+j;var h=c('<div class="ui-resizable-handle '+e+'"></div>');h.css({zIndex:k.zIndex});if("se"==j){h.addClass("ui-icon ui-icon-gripsmall-diagonal-se")}this.handles[j]=".ui-resizable-"+j;this.element.append(h)}}this._renderAxis=function(q){q=q||this.element;for(var n in this.handles){if(this.handles[n].constructor==String){this.handles[n]=c(this.handles[n],this.element).show()}if(this.elementIsWrapper&&this.originalElement[0].nodeName.match(/textarea|input|select|button/i)){var o=c(this.handles[n],this.element),p=0;p=/sw|ne|nw|se|n|s/.test(n)?o.outerHeight():o.outerWidth();var m=["padding",/ne|nw|n/.test(n)?"Top":/se|sw|s/.test(n)?"Bottom":/^e$/.test(n)?"Right":"Left"].join("");q.css(m,p);this._proportionallyResize()}if(!c(this.handles[n]).length){continue}}};this._renderAxis(this.element);this._handles=c(".ui-resizable-handle",this.element).disableSelection();this._handles.mouseover(function(){if(!f.resizing){if(this.className){var i=this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i)}f.axis=i&&i[1]?i[1]:"se"}});if(k.autoHide){this._handles.hide();c(this.element).addClass("ui-resizable-autohide").hover(function(){if(k.disabled){return}c(this).removeClass("ui-resizable-autohide");f._handles.show()},function(){if(k.disabled){return}if(!f.resizing){c(this).addClass("ui-resizable-autohide");f._handles.hide()}})}this._mouseInit()},destroy:function(){this._mouseDestroy();var e=function(g){c(g).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing").removeData("resizable").unbind(".resizable").find(".ui-resizable-handle").remove()};if(this.elementIsWrapper){e(this.element);var f=this.element;f.after(this.originalElement.css({position:f.css("position"),width:f.outerWidth(),height:f.outerHeight(),top:f.css("top"),left:f.css("left")})).remove()}this.originalElement.css("resize",this.originalResizeStyle);e(this.originalElement);return this},_mouseCapture:function(f){var g=false;for(var e in this.handles){if(c(this.handles[e])[0]==f.target){g=true}}return !this.options.disabled&&g},_mouseStart:function(g){var j=this.options,f=this.element.position(),e=this.element;this.resizing=true;this.documentScroll={top:c(document).scrollTop(),left:c(document).scrollLeft()};if(e.is(".ui-draggable")||(/absolute/).test(e.css("position"))){e.css({position:"absolute",top:f.top,left:f.left})}this._renderProxy();var k=b(this.helper.css("left")),h=b(this.helper.css("top"));if(j.containment){k+=c(j.containment).scrollLeft()||0;h+=c(j.containment).scrollTop()||0}this.offset=this.helper.offset();this.position={left:k,top:h};this.size=this._helper?{width:e.outerWidth(),height:e.outerHeight()}:{width:e.width(),height:e.height()};this.originalSize=this._helper?{width:e.outerWidth(),height:e.outerHeight()}:{width:e.width(),height:e.height()};this.originalPosition={left:k,top:h};this.sizeDiff={width:e.outerWidth()-e.width(),height:e.outerHeight()-e.height()};this.originalMousePosition={left:g.pageX,top:g.pageY};this.aspectRatio=(typeof j.aspectRatio=="number")?j.aspectRatio:((this.originalSize.width/this.originalSize.height)||1);var i=c(".ui-resizable-"+this.axis).css("cursor");c("body").css("cursor",i=="auto"?this.axis+"-resize":i);e.addClass("ui-resizable-resizing");this._propagate("start",g);return true},_mouseDrag:function(e){var h=this.helper,g=this.options,m={},q=this,j=this.originalMousePosition,n=this.axis;var r=(e.pageX-j.left)||0,p=(e.pageY-j.top)||0;var i=this._change[n];if(!i){return false}var l=i.apply(this,[e,r,p]),k=c.browser.msie&&c.browser.version<7,f=this.sizeDiff;this._updateVirtualBoundaries(e.shiftKey);if(this._aspectRatio||e.shiftKey){l=this._updateRatio(l,e)}l=this._respectSize(l,e);this._propagate("resize",e);h.css({top:this.position.top+"px",left:this.position.left+"px",width:this.size.width+"px",height:this.size.height+"px"});if(!this._helper&&this._proportionallyResizeElements.length){this._proportionallyResize()}this._updateCache(l);this._trigger("resize",e,this.ui());return false},_mouseStop:function(h){this.resizing=false;var i=this.options,m=this;if(this._helper){var g=this._proportionallyResizeElements,e=g.length&&(/textarea/i).test(g[0].nodeName),f=e&&c.ui.hasScroll(g[0],"left")?0:m.sizeDiff.height,k=e?0:m.sizeDiff.width;var n={width:(m.helper.width()-k),height:(m.helper.height()-f)},j=(parseInt(m.element.css("left"),10)+(m.position.left-m.originalPosition.left))||null,l=(parseInt(m.element.css("top"),10)+(m.position.top-m.originalPosition.top))||null;if(!i.animate){this.element.css(c.extend(n,{top:l,left:j}))}m.helper.height(m.size.height);m.helper.width(m.size.width);if(this._helper&&!i.animate){this._proportionallyResize()}}c("body").css("cursor","auto");this.element.removeClass("ui-resizable-resizing");this._propagate("stop",h);if(this._helper){this.helper.remove()}return false},_updateVirtualBoundaries:function(g){var j=this.options,i,h,f,k,e;e={minWidth:a(j.minWidth)?j.minWidth:0,maxWidth:a(j.maxWidth)?j.maxWidth:Infinity,minHeight:a(j.minHeight)?j.minHeight:0,maxHeight:a(j.maxHeight)?j.maxHeight:Infinity};if(this._aspectRatio||g){i=e.minHeight*this.aspectRatio;f=e.minWidth/this.aspectRatio;h=e.maxHeight*this.aspectRatio;k=e.maxWidth/this.aspectRatio;if(i>e.minWidth){e.minWidth=i}if(f>e.minHeight){e.minHeight=f}if(h<e.maxWidth){e.maxWidth=h}if(k<e.maxHeight){e.maxHeight=k}}this._vBoundaries=e},_updateCache:function(e){var f=this.options;this.offset=this.helper.offset();if(a(e.left)){this.position.left=e.left}if(a(e.top)){this.position.top=e.top}if(a(e.height)){this.size.height=e.height}if(a(e.width)){this.size.width=e.width}},_updateRatio:function(h,g){var i=this.options,j=this.position,f=this.size,e=this.axis;if(a(h.height)){h.width=(h.height*this.aspectRatio)}else{if(a(h.width)){h.height=(h.width/this.aspectRatio)}}if(e=="sw"){h.left=j.left+(f.width-h.width);h.top=null}if(e=="nw"){h.top=j.top+(f.height-h.height);h.left=j.left+(f.width-h.width)}return h},_respectSize:function(l,g){var j=this.helper,i=this._vBoundaries,r=this._aspectRatio||g.shiftKey,q=this.axis,t=a(l.width)&&i.maxWidth&&(i.maxWidth<l.width),m=a(l.height)&&i.maxHeight&&(i.maxHeight<l.height),h=a(l.width)&&i.minWidth&&(i.minWidth>l.width),s=a(l.height)&&i.minHeight&&(i.minHeight>l.height);if(h){l.width=i.minWidth}if(s){l.height=i.minHeight}if(t){l.width=i.maxWidth}if(m){l.height=i.maxHeight}var f=this.originalPosition.left+this.originalSize.width,p=this.position.top+this.size.height;var k=/sw|nw|w/.test(q),e=/nw|ne|n/.test(q);if(h&&k){l.left=f-i.minWidth}if(t&&k){l.left=f-i.maxWidth}if(s&&e){l.top=p-i.minHeight}if(m&&e){l.top=p-i.maxHeight}var n=!l.width&&!l.height;if(n&&!l.left&&l.top){l.top=null}else{if(n&&!l.top&&l.left){l.left=null}}return l},_proportionallyResize:function(){var k=this.options;if(!this._proportionallyResizeElements.length){return}var g=this.helper||this.element;for(var f=0;f<this._proportionallyResizeElements.length;f++){var h=this._proportionallyResizeElements[f];if(!this.borderDif){var e=[h.css("borderTopWidth"),h.css("borderRightWidth"),h.css("borderBottomWidth"),h.css("borderLeftWidth")],j=[h.css("paddingTop"),h.css("paddingRight"),h.css("paddingBottom"),h.css("paddingLeft")];this.borderDif=c.map(e,function(l,n){var m=parseInt(l,10)||0,o=parseInt(j[n],10)||0;return m+o})}if(c.browser.msie&&!(!(c(g).is(":hidden")||c(g).parents(":hidden").length))){continue}h.css({height:(g.height()-this.borderDif[0]-this.borderDif[2])||0,width:(g.width()-this.borderDif[1]-this.borderDif[3])||0})}},_renderProxy:function(){var f=this.element,i=this.options;this.elementOffset=f.offset();if(this._helper){this.helper=this.helper||c('<div style="overflow:hidden;"></div>');var e=c.browser.msie&&c.browser.version<7,g=(e?1:0),h=(e?2:-1);this.helper.addClass(this._helper).css({width:this.element.outerWidth()+h,height:this.element.outerHeight()+h,position:"absolute",left:this.elementOffset.left-g+"px",top:this.elementOffset.top-g+"px",zIndex:++i.zIndex});this.helper.appendTo("body").disableSelection()}else{this.helper=this.element}},_change:{e:function(g,f,e){return{width:this.originalSize.width+f}},w:function(h,f,e){var j=this.options,g=this.originalSize,i=this.originalPosition;return{left:i.left+f,width:g.width-f}},n:function(h,f,e){var j=this.options,g=this.originalSize,i=this.originalPosition;return{top:i.top+e,height:g.height-e}},s:function(g,f,e){return{height:this.originalSize.height+e}},se:function(g,f,e){return c.extend(this._change.s.apply(this,arguments),this._change.e.apply(this,[g,f,e]))},sw:function(g,f,e){return c.extend(this._change.s.apply(this,arguments),this._change.w.apply(this,[g,f,e]))},ne:function(g,f,e){return c.extend(this._change.n.apply(this,arguments),this._change.e.apply(this,[g,f,e]))},nw:function(g,f,e){return c.extend(this._change.n.apply(this,arguments),this._change.w.apply(this,[g,f,e]))}},_propagate:function(f,e){c.ui.plugin.call(this,f,[e,this.ui()]);(f!="resize"&&this._trigger(f,e,this.ui()))},plugins:{},ui:function(){return{originalElement:this.originalElement,element:this.element,helper:this.helper,position:this.position,size:this.size,originalSize:this.originalSize,originalPosition:this.originalPosition}}});c.extend(c.ui.resizable,{version:"1.8.24"});c.ui.plugin.add("resizable","alsoResize",{start:function(f,g){var e=c(this).data("resizable"),i=e.options;var h=function(j){c(j).each(function(){var k=c(this);k.data("resizable-alsoresize",{width:parseInt(k.width(),10),height:parseInt(k.height(),10),left:parseInt(k.css("left"),10),top:parseInt(k.css("top"),10)})})};if(typeof(i.alsoResize)=="object"&&!i.alsoResize.parentNode){if(i.alsoResize.length){i.alsoResize=i.alsoResize[0];h(i.alsoResize)}else{c.each(i.alsoResize,function(j){h(j)})}}else{h(i.alsoResize)}},resize:function(g,i){var f=c(this).data("resizable"),j=f.options,h=f.originalSize,l=f.originalPosition;var k={height:(f.size.height-h.height)||0,width:(f.size.width-h.width)||0,top:(f.position.top-l.top)||0,left:(f.position.left-l.left)||0},e=function(m,n){c(m).each(function(){var q=c(this),r=c(this).data("resizable-alsoresize"),p={},o=n&&n.length?n:q.parents(i.originalElement[0]).length?["width","height"]:["width","height","top","left"];c.each(o,function(s,u){var t=(r[u]||0)+(k[u]||0);if(t&&t>=0){p[u]=t||null}});q.css(p)})};if(typeof(j.alsoResize)=="object"&&!j.alsoResize.nodeType){c.each(j.alsoResize,function(m,n){e(m,n)})}else{e(j.alsoResize)}},stop:function(e,f){c(this).removeData("resizable-alsoresize")}});c.ui.plugin.add("resizable","animate",{stop:function(i,n){var p=c(this).data("resizable"),j=p.options;var h=p._proportionallyResizeElements,e=h.length&&(/textarea/i).test(h[0].nodeName),f=e&&c.ui.hasScroll(h[0],"left")?0:p.sizeDiff.height,l=e?0:p.sizeDiff.width;var g={width:(p.size.width-l),height:(p.size.height-f)},k=(parseInt(p.element.css("left"),10)+(p.position.left-p.originalPosition.left))||null,m=(parseInt(p.element.css("top"),10)+(p.position.top-p.originalPosition.top))||null;p.element.animate(c.extend(g,m&&k?{top:m,left:k}:{}),{duration:j.animateDuration,easing:j.animateEasing,step:function(){var o={width:parseInt(p.element.css("width"),10),height:parseInt(p.element.css("height"),10),top:parseInt(p.element.css("top"),10),left:parseInt(p.element.css("left"),10)};if(h&&h.length){c(h[0]).css({width:o.width,height:o.height})}p._updateCache(o);p._propagate("resize",i)}})}});c.ui.plugin.add("resizable","containment",{start:function(f,r){var t=c(this).data("resizable"),j=t.options,l=t.element;var g=j.containment,k=(g instanceof c)?g.get(0):(/parent/.test(g))?l.parent().get(0):g;if(!k){return}t.containerElement=c(k);if(/document/.test(g)||g==document){t.containerOffset={left:0,top:0};t.containerPosition={left:0,top:0};t.parentData={element:c(document),left:0,top:0,width:c(document).width(),height:c(document).height()||document.body.parentNode.scrollHeight}}else{var n=c(k),i=[];c(["Top","Right","Left","Bottom"]).each(function(p,o){i[p]=b(n.css("padding"+o))});t.containerOffset=n.offset();t.containerPosition=n.position();t.containerSize={height:(n.innerHeight()-i[3]),width:(n.innerWidth()-i[1])};var q=t.containerOffset,e=t.containerSize.height,m=t.containerSize.width,h=(c.ui.hasScroll(k,"left")?k.scrollWidth:m),s=(c.ui.hasScroll(k)?k.scrollHeight:e);t.parentData={element:k,left:q.left,top:q.top,width:h,height:s}}},resize:function(g,q){var t=c(this).data("resizable"),i=t.options,f=t.containerSize,p=t.containerOffset,m=t.size,n=t.position,r=t._aspectRatio||g.shiftKey,e={top:0,left:0},h=t.containerElement;if(h[0]!=document&&(/static/).test(h.css("position"))){e=p}if(n.left<(t._helper?p.left:0)){t.size.width=t.size.width+(t._helper?(t.position.left-p.left):(t.position.left-e.left));if(r){t.size.height=t.size.width/t.aspectRatio}t.position.left=i.helper?p.left:0}if(n.top<(t._helper?p.top:0)){t.size.height=t.size.height+(t._helper?(t.position.top-p.top):t.position.top);if(r){t.size.width=t.size.height*t.aspectRatio}t.position.top=t._helper?p.top:0}t.offset.left=t.parentData.left+t.position.left;t.offset.top=t.parentData.top+t.position.top;var l=Math.abs((t._helper?t.offset.left-e.left:(t.offset.left-e.left))+t.sizeDiff.width),s=Math.abs((t._helper?t.offset.top-e.top:(t.offset.top-p.top))+t.sizeDiff.height);var k=t.containerElement.get(0)==t.element.parent().get(0),j=/relative|absolute/.test(t.containerElement.css("position"));if(k&&j){l-=t.parentData.left}if(l+t.size.width>=t.parentData.width){t.size.width=t.parentData.width-l;if(r){t.size.height=t.size.width/t.aspectRatio}}if(s+t.size.height>=t.parentData.height){t.size.height=t.parentData.height-s;if(r){t.size.width=t.size.height*t.aspectRatio}}},stop:function(f,n){var q=c(this).data("resizable"),g=q.options,l=q.position,m=q.containerOffset,e=q.containerPosition,i=q.containerElement;var j=c(q.helper),r=j.offset(),p=j.outerWidth()-q.sizeDiff.width,k=j.outerHeight()-q.sizeDiff.height;if(q._helper&&!g.animate&&(/relative/).test(i.css("position"))){c(this).css({left:r.left-e.left-m.left,width:p,height:k})}if(q._helper&&!g.animate&&(/static/).test(i.css("position"))){c(this).css({left:r.left-e.left-m.left,width:p,height:k})}}});c.ui.plugin.add("resizable","ghost",{start:function(g,h){var e=c(this).data("resizable"),i=e.options,f=e.size;e.ghost=e.originalElement.clone();e.ghost.css({opacity:0.25,display:"block",position:"relative",height:f.height,width:f.width,margin:0,left:0,top:0}).addClass("ui-resizable-ghost").addClass(typeof i.ghost=="string"?i.ghost:"");e.ghost.appendTo(e.helper)},resize:function(f,g){var e=c(this).data("resizable"),h=e.options;if(e.ghost){e.ghost.css({position:"relative",height:e.size.height,width:e.size.width})}},stop:function(f,g){var e=c(this).data("resizable"),h=e.options;if(e.ghost&&e.helper){e.helper.get(0).removeChild(e.ghost.get(0))}}});c.ui.plugin.add("resizable","grid",{resize:function(e,m){var p=c(this).data("resizable"),h=p.options,k=p.size,i=p.originalSize,j=p.originalPosition,n=p.axis,l=h._aspectRatio||e.shiftKey;h.grid=typeof h.grid=="number"?[h.grid,h.grid]:h.grid;var g=Math.round((k.width-i.width)/(h.grid[0]||1))*(h.grid[0]||1),f=Math.round((k.height-i.height)/(h.grid[1]||1))*(h.grid[1]||1);if(/^(se|s|e)$/.test(n)){p.size.width=i.width+g;p.size.height=i.height+f}else{if(/^(ne)$/.test(n)){p.size.width=i.width+g;p.size.height=i.height+f;p.position.top=j.top-f}else{if(/^(sw)$/.test(n)){p.size.width=i.width+g;p.size.height=i.height+f;p.position.left=j.left-g}else{p.size.width=i.width+g;p.size.height=i.height+f;p.position.top=j.top-f;p.position.left=j.left-g}}}}});var b=function(e){return parseInt(e,10)||0};var a=function(e){return !isNaN(parseInt(e,10))}})(jQuery);(function(a,b){a.widget("ui.selectable",a.ui.mouse,{options:{appendTo:"body",autoRefresh:true,distance:0,filter:"*",tolerance:"touch"},_create:function(){var c=this;this.element.addClass("ui-selectable");this.dragged=false;var d;this.refresh=function(){d=a(c.options.filter,c.element[0]);d.addClass("ui-selectee");d.each(function(){var e=a(this);var f=e.offset();a.data(this,"selectable-item",{element:this,$element:e,left:f.left,top:f.top,right:f.left+e.outerWidth(),bottom:f.top+e.outerHeight(),startselected:false,selected:e.hasClass("ui-selected"),selecting:e.hasClass("ui-selecting"),unselecting:e.hasClass("ui-unselecting")})})};this.refresh();this.selectees=d.addClass("ui-selectee");this._mouseInit();this.helper=a("<div class='ui-selectable-helper'></div>")},destroy:function(){this.selectees.removeClass("ui-selectee").removeData("selectable-item");this.element.removeClass("ui-selectable ui-selectable-disabled").removeData("selectable").unbind(".selectable");this._mouseDestroy();return this},_mouseStart:function(e){var c=this;this.opos=[e.pageX,e.pageY];if(this.options.disabled){return}var d=this.options;this.selectees=a(d.filter,this.element[0]);this._trigger("start",e);a(d.appendTo).append(this.helper);this.helper.css({left:e.clientX,top:e.clientY,width:0,height:0});if(d.autoRefresh){this.refresh()}this.selectees.filter(".ui-selected").each(function(){var f=a.data(this,"selectable-item");f.startselected=true;if(!e.metaKey&&!e.ctrlKey){f.$element.removeClass("ui-selected");f.selected=false;f.$element.addClass("ui-unselecting");f.unselecting=true;c._trigger("unselecting",e,{unselecting:f.element})}});a(e.target).parents().andSelf().each(function(){var g=a.data(this,"selectable-item");if(g){var f=(!e.metaKey&&!e.ctrlKey)||!g.$element.hasClass("ui-selected");g.$element.removeClass(f?"ui-unselecting":"ui-selected").addClass(f?"ui-selecting":"ui-unselecting");g.unselecting=!f;g.selecting=f;g.selected=f;if(f){c._trigger("selecting",e,{selecting:g.element})}else{c._trigger("unselecting",e,{unselecting:g.element})}return false}})},_mouseDrag:function(j){var d=this;this.dragged=true;if(this.options.disabled){return}var f=this.options;var e=this.opos[0],i=this.opos[1],c=j.pageX,h=j.pageY;if(e>c){var g=c;c=e;e=g}if(i>h){var g=h;h=i;i=g}this.helper.css({left:e,top:i,width:c-e,height:h-i});this.selectees.each(function(){var k=a.data(this,"selectable-item");if(!k||k.element==d.element[0]){return}var l=false;if(f.tolerance=="touch"){l=(!(k.left>c||k.right<e||k.top>h||k.bottom<i))}else{if(f.tolerance=="fit"){l=(k.left>e&&k.right<c&&k.top>i&&k.bottom<h)}}if(l){if(k.selected){k.$element.removeClass("ui-selected");k.selected=false}if(k.unselecting){k.$element.removeClass("ui-unselecting");k.unselecting=false}if(!k.selecting){k.$element.addClass("ui-selecting");k.selecting=true;d._trigger("selecting",j,{selecting:k.element})}}else{if(k.selecting){if((j.metaKey||j.ctrlKey)&&k.startselected){k.$element.removeClass("ui-selecting");k.selecting=false;k.$element.addClass("ui-selected");k.selected=true}else{k.$element.removeClass("ui-selecting");k.selecting=false;if(k.startselected){k.$element.addClass("ui-unselecting");k.unselecting=true}d._trigger("unselecting",j,{unselecting:k.element})}}if(k.selected){if(!j.metaKey&&!j.ctrlKey&&!k.startselected){k.$element.removeClass("ui-selected");k.selected=false;k.$element.addClass("ui-unselecting");k.unselecting=true;d._trigger("unselecting",j,{unselecting:k.element})}}}});return false},_mouseStop:function(e){var c=this;this.dragged=false;var d=this.options;a(".ui-unselecting",this.element[0]).each(function(){var f=a.data(this,"selectable-item");f.$element.removeClass("ui-unselecting");f.unselecting=false;f.startselected=false;c._trigger("unselected",e,{unselected:f.element})});a(".ui-selecting",this.element[0]).each(function(){var f=a.data(this,"selectable-item");f.$element.removeClass("ui-selecting").addClass("ui-selected");f.selecting=false;f.selected=true;f.startselected=true;c._trigger("selected",e,{selected:f.element})});this._trigger("stop",e);this.helper.remove();return false}});a.extend(a.ui.selectable,{version:"1.8.24"})})(jQuery);(function(a,b){a.widget("ui.sortable",a.ui.mouse,{widgetEventPrefix:"sort",ready:false,options:{appendTo:"parent",axis:false,connectWith:false,containment:false,cursor:"auto",cursorAt:false,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1000},_create:function(){var c=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?c.axis==="x"||(/left|right/).test(this.items[0].item.css("float"))||(/inline|table-cell/).test(this.items[0].item.css("display")):false;this.offset=this.element.offset();this._mouseInit();this.ready=true},destroy:function(){a.Widget.prototype.destroy.call(this);this.element.removeClass("ui-sortable ui-sortable-disabled");this._mouseDestroy();for(var c=this.items.length-1;c>=0;c--){this.items[c].item.removeData(this.widgetName+"-item")}return this},_setOption:function(c,d){if(c==="disabled"){this.options[c]=d;this.widget()[d?"addClass":"removeClass"]("ui-sortable-disabled")}else{a.Widget.prototype._setOption.apply(this,arguments)}},_mouseCapture:function(g,h){var f=this;if(this.reverting){return false}if(this.options.disabled||this.options.type=="static"){return false}this._refreshItems(g);var e=null,d=this,c=a(g.target).parents().each(function(){if(a.data(this,f.widgetName+"-item")==d){e=a(this);return false}});if(a.data(g.target,f.widgetName+"-item")==d){e=a(g.target)}if(!e){return false}if(this.options.handle&&!h){var i=false;a(this.options.handle,e).find("*").andSelf().each(function(){if(this==g.target){i=true}});if(!i){return false}}this.currentItem=e;this._removeCurrentsFromItems();return true},_mouseStart:function(f,g,c){var h=this.options,d=this;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(f);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};a.extend(this.offset,{click:{left:f.pageX-this.offset.left,top:f.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");this.originalPosition=this._generatePosition(f);this.originalPageX=f.pageX;this.originalPageY=f.pageY;(h.cursorAt&&this._adjustOffsetFromHelper(h.cursorAt));this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};if(this.helper[0]!=this.currentItem[0]){this.currentItem.hide()}this._createPlaceholder();if(h.containment){this._setContainment()}if(h.cursor){if(a("body").css("cursor")){this._storedCursor=a("body").css("cursor")}a("body").css("cursor",h.cursor)}if(h.opacity){if(this.helper.css("opacity")){this._storedOpacity=this.helper.css("opacity")}this.helper.css("opacity",h.opacity)}if(h.zIndex){if(this.helper.css("zIndex")){this._storedZIndex=this.helper.css("zIndex")}this.helper.css("zIndex",h.zIndex)}if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){this.overflowOffset=this.scrollParent.offset()}this._trigger("start",f,this._uiHash());if(!this._preserveHelperProportions){this._cacheHelperProportions()}if(!c){for(var e=this.containers.length-1;e>=0;e--){this.containers[e]._trigger("activate",f,d._uiHash(this))}}if(a.ui.ddmanager){a.ui.ddmanager.current=this}if(a.ui.ddmanager&&!h.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,f)}this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(f);return true},_mouseDrag:function(g){this.position=this._generatePosition(g);this.positionAbs=this._convertPositionTo("absolute");if(!this.lastPositionAbs){this.lastPositionAbs=this.positionAbs}if(this.options.scroll){var h=this.options,c=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if((this.overflowOffset.top+this.scrollParent[0].offsetHeight)-g.pageY<h.scrollSensitivity){this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop+h.scrollSpeed}else{if(g.pageY-this.overflowOffset.top<h.scrollSensitivity){this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop-h.scrollSpeed}}if((this.overflowOffset.left+this.scrollParent[0].offsetWidth)-g.pageX<h.scrollSensitivity){this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft+h.scrollSpeed}else{if(g.pageX-this.overflowOffset.left<h.scrollSensitivity){this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft-h.scrollSpeed}}}else{if(g.pageY-a(document).scrollTop()<h.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()-h.scrollSpeed)}else{if(a(window).height()-(g.pageY-a(document).scrollTop())<h.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()+h.scrollSpeed)}}if(g.pageX-a(document).scrollLeft()<h.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()-h.scrollSpeed)}else{if(a(window).width()-(g.pageX-a(document).scrollLeft())<h.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()+h.scrollSpeed)}}}if(c!==false&&a.ui.ddmanager&&!h.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,g)}}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}for(var e=this.items.length-1;e>=0;e--){var f=this.items[e],d=f.item[0],j=this._intersectsWithPointer(f);if(!j){continue}if(f.instance!==this.currentContainer){continue}if(d!=this.currentItem[0]&&this.placeholder[j==1?"next":"prev"]()[0]!=d&&!a.ui.contains(this.placeholder[0],d)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],d):true)){this.direction=j==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(f)){this._rearrange(g,f)}else{break}this._trigger("change",g,this._uiHash());break}}this._contactContainers(g);if(a.ui.ddmanager){a.ui.ddmanager.drag(this,g)}this._trigger("sort",g,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(d,e){if(!d){return}if(a.ui.ddmanager&&!this.options.dropBehaviour){a.ui.ddmanager.drop(this,d)}if(this.options.revert){var c=this;var f=c.placeholder.offset();c.reverting=true;a(this.helper).animate({left:f.left-this.offset.parent.left-c.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:f.top-this.offset.parent.top-c.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){c._clear(d)})}else{this._clear(d,e)}return false},cancel:function(){var c=this;if(this.dragging){this._mouseUp({target:null});if(this.options.helper=="original"){this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}for(var d=this.containers.length-1;d>=0;d--){this.containers[d]._trigger("deactivate",null,c._uiHash(this));if(this.containers[d].containerCache.over){this.containers[d]._trigger("out",null,c._uiHash(this));this.containers[d].containerCache.over=0}}}if(this.placeholder){if(this.placeholder[0].parentNode){this.placeholder[0].parentNode.removeChild(this.placeholder[0])}if(this.options.helper!="original"&&this.helper&&this.helper[0].parentNode){this.helper.remove()}a.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});if(this.domPosition.prev){a(this.domPosition.prev).after(this.currentItem)}else{a(this.domPosition.parent).prepend(this.currentItem)}}return this},serialize:function(e){var c=this._getItemsAsjQuery(e&&e.connected);var d=[];e=e||{};a(c).each(function(){var f=(a(e.item||this).attr(e.attribute||"id")||"").match(e.expression||(/(.+)[-=_](.+)/));if(f){d.push((e.key||f[1]+"[]")+"="+(e.key&&e.expression?f[1]:f[2]))}});if(!d.length&&e.key){d.push(e.key+"=")}return d.join("&")},toArray:function(e){var c=this._getItemsAsjQuery(e&&e.connected);var d=[];e=e||{};c.each(function(){d.push(a(e.item||this).attr(e.attribute||"id")||"")});return d},_intersectsWith:function(m){var e=this.positionAbs.left,d=e+this.helperProportions.width,k=this.positionAbs.top,j=k+this.helperProportions.height;var f=m.left,c=f+m.width,n=m.top,i=n+m.height;var o=this.offset.click.top,h=this.offset.click.left;var g=(k+o)>n&&(k+o)<i&&(e+h)>f&&(e+h)<c;if(this.options.tolerance=="pointer"||this.options.forcePointerForContainers||(this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>m[this.floating?"width":"height"])){return g}else{return(f<e+(this.helperProportions.width/2)&&d-(this.helperProportions.width/2)<c&&n<k+(this.helperProportions.height/2)&&j-(this.helperProportions.height/2)<i)}},_intersectsWithPointer:function(e){var f=(this.options.axis==="x")||a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,e.top,e.height),d=(this.options.axis==="y")||a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,e.left,e.width),h=f&&d,c=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();if(!h){return false}return this.floating?(((g&&g=="right")||c=="down")?2:1):(c&&(c=="down"?2:1))},_intersectsWithSides:function(f){var d=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,f.top+(f.height/2),f.height),e=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,f.left+(f.width/2),f.width),c=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();if(this.floating&&g){return((g=="right"&&e)||(g=="left"&&!e))}else{return c&&((c=="down"&&d)||(c=="up"&&!d))}},_getDragVerticalDirection:function(){var c=this.positionAbs.top-this.lastPositionAbs.top;return c!=0&&(c>0?"down":"up")},_getDragHorizontalDirection:function(){var c=this.positionAbs.left-this.lastPositionAbs.left;return c!=0&&(c>0?"right":"left")},refresh:function(c){this._refreshItems(c);this.refreshPositions();return this},_connectWith:function(){var c=this.options;return c.connectWith.constructor==String?[c.connectWith]:c.connectWith},_getItemsAsjQuery:function(c){var m=this;var h=[];var f=[];var k=this._connectWith();if(k&&c){for(var e=k.length-1;e>=0;e--){var l=a(k[e]);for(var d=l.length-1;d>=0;d--){var g=a.data(l[d],this.widgetName);if(g&&g!=this&&!g.options.disabled){f.push([a.isFunction(g.options.items)?g.options.items.call(g.element):a(g.options.items,g.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),g])}}}}f.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var e=f.length-1;e>=0;e--){f[e][0].each(function(){h.push(this)})}return a(h)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");for(var d=0;d<this.items.length;d++){for(var c=0;c<e.length;c++){if(e[c]==this.items[d].item[0]){this.items.splice(d,1)}}}},_refreshItems:function(c){this.items=[];this.containers=[this];var k=this.items;var q=this;var g=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],c,{item:this.currentItem}):a(this.options.items,this.element),this]];var m=this._connectWith();if(m&&this.ready){for(var f=m.length-1;f>=0;f--){var n=a(m[f]);for(var e=n.length-1;e>=0;e--){var h=a.data(n[e],this.widgetName);if(h&&h!=this&&!h.options.disabled){g.push([a.isFunction(h.options.items)?h.options.items.call(h.element[0],c,{item:this.currentItem}):a(h.options.items,h.element),h]);this.containers.push(h)}}}}for(var f=g.length-1;f>=0;f--){var l=g[f][1];var d=g[f][0];for(var e=0,o=d.length;e<o;e++){var p=a(d[e]);p.data(this.widgetName+"-item",l);k.push({item:p,instance:l,width:0,height:0,left:0,top:0})}}},refreshPositions:function(c){if(this.offsetParent&&this.helper){this.offset.parent=this._getParentOffset()}for(var e=this.items.length-1;e>=0;e--){var f=this.items[e];if(f.instance!=this.currentContainer&&this.currentContainer&&f.item[0]!=this.currentItem[0]){continue}var d=this.options.toleranceElement?a(this.options.toleranceElement,f.item):f.item;if(!c){f.width=d.outerWidth();f.height=d.outerHeight()}var g=d.offset();f.left=g.left;f.top=g.top}if(this.options.custom&&this.options.custom.refreshContainers){this.options.custom.refreshContainers.call(this)}else{for(var e=this.containers.length-1;e>=0;e--){var g=this.containers[e].element.offset();this.containers[e].containerCache.left=g.left;this.containers[e].containerCache.top=g.top;this.containers[e].containerCache.width=this.containers[e].element.outerWidth();this.containers[e].containerCache.height=this.containers[e].element.outerHeight()}}return this},_createPlaceholder:function(e){var c=e||this,f=c.options;if(!f.placeholder||f.placeholder.constructor==String){var d=f.placeholder;f.placeholder={element:function(){var g=a(document.createElement(c.currentItem[0].nodeName)).addClass(d||c.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!d){g.style.visibility="hidden"}return g},update:function(g,h){if(d&&!f.forcePlaceholderSize){return}if(!h.height()){h.height(c.currentItem.innerHeight()-parseInt(c.currentItem.css("paddingTop")||0,10)-parseInt(c.currentItem.css("paddingBottom")||0,10))}if(!h.width()){h.width(c.currentItem.innerWidth()-parseInt(c.currentItem.css("paddingLeft")||0,10)-parseInt(c.currentItem.css("paddingRight")||0,10))}}}}c.placeholder=a(f.placeholder.element.call(c.element,c.currentItem));c.currentItem.after(c.placeholder);f.placeholder.update(c,c.placeholder)},_contactContainers:function(c){var e=null,l=null;for(var g=this.containers.length-1;g>=0;g--){if(a.ui.contains(this.currentItem[0],this.containers[g].element[0])){continue}if(this._intersectsWith(this.containers[g].containerCache)){if(e&&a.ui.contains(this.containers[g].element[0],e.element[0])){continue}e=this.containers[g];l=g}else{if(this.containers[g].containerCache.over){this.containers[g]._trigger("out",c,this._uiHash(this));this.containers[g].containerCache.over=0}}}if(!e){return}if(this.containers.length===1){this.containers[l]._trigger("over",c,this._uiHash(this));this.containers[l].containerCache.over=1}else{if(this.currentContainer!=this.containers[l]){var k=10000;var h=null;var d=this.positionAbs[this.containers[l].floating?"left":"top"];for(var f=this.items.length-1;f>=0;f--){if(!a.ui.contains(this.containers[l].element[0],this.items[f].item[0])){continue}var m=this.containers[l].floating?this.items[f].item.offset().left:this.items[f].item.offset().top;if(Math.abs(m-d)<k){k=Math.abs(m-d);h=this.items[f];this.direction=(m-d>0)?"down":"up"}}if(!h&&!this.options.dropOnEmpty){return}this.currentContainer=this.containers[l];h?this._rearrange(c,h,null,true):this._rearrange(c,null,this.containers[l].element,true);this._trigger("change",c,this._uiHash());this.containers[l]._trigger("change",c,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[l]._trigger("over",c,this._uiHash(this));this.containers[l].containerCache.over=1}}},_createHelper:function(d){var e=this.options;var c=a.isFunction(e.helper)?a(e.helper.apply(this.element[0],[d,this.currentItem])):(e.helper=="clone"?this.currentItem.clone():this.currentItem);if(!c.parents("body").length){a(e.appendTo!="parent"?e.appendTo:this.currentItem[0].parentNode)[0].appendChild(c[0])}if(c[0]==this.currentItem[0]){this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}}if(c[0].style.width==""||e.forceHelperSize){c.width(this.currentItem.width())}if(c[0].style.height==""||e.forceHelperSize){c.height(this.currentItem.height())}return c},_adjustOffsetFromHelper:function(c){if(typeof c=="string"){c=c.split(" ")}if(a.isArray(c)){c={left:+c[0],top:+c[1]||0}}if("left" in c){this.offset.click.left=c.left+this.margins.left}if("right" in c){this.offset.click.left=this.helperProportions.width-c.right+this.margins.left}if("top" in c){this.offset.click.top=c.top+this.margins.top}if("bottom" in c){this.offset.click.top=this.helperProportions.height-c.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var c=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){c.left+=this.scrollParent.scrollLeft();c.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){c={top:0,left:0}}return{top:c.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:c.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var c=this.currentItem.position();return{top:c.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:c.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.currentItem.css("marginLeft"),10)||0),top:(parseInt(this.currentItem.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var f=this.options;if(f.containment=="parent"){f.containment=this.helper[0].parentNode}if(f.containment=="document"||f.containment=="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(f.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(f.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(f.containment)){var d=a(f.containment)[0];var e=a(f.containment).offset();var c=(a(d).css("overflow")!="hidden");this.containment=[e.left+(parseInt(a(d).css("borderLeftWidth"),10)||0)+(parseInt(a(d).css("paddingLeft"),10)||0)-this.margins.left,e.top+(parseInt(a(d).css("borderTopWidth"),10)||0)+(parseInt(a(d).css("paddingTop"),10)||0)-this.margins.top,e.left+(c?Math.max(d.scrollWidth,d.offsetWidth):d.offsetWidth)-(parseInt(a(d).css("borderLeftWidth"),10)||0)-(parseInt(a(d).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,e.top+(c?Math.max(d.scrollHeight,d.offsetHeight):d.offsetHeight)-(parseInt(a(d).css("borderTopWidth"),10)||0)-(parseInt(a(d).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(g,i){if(!i){i=this.position}var e=g=="absolute"?1:-1;var f=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,h=(/(html|body)/i).test(c[0].tagName);return{top:(i.top+this.offset.relative.top*e+this.offset.parent.top*e-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(h?0:c.scrollTop()))*e)),left:(i.left+this.offset.relative.left*e+this.offset.parent.left*e-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():h?0:c.scrollLeft())*e))}},_generatePosition:function(f){var i=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,j=(/(html|body)/i).test(c[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}var e=f.pageX;var d=f.pageY;if(this.originalPosition){if(this.containment){if(f.pageX-this.offset.click.left<this.containment[0]){e=this.containment[0]+this.offset.click.left}if(f.pageY-this.offset.click.top<this.containment[1]){d=this.containment[1]+this.offset.click.top}if(f.pageX-this.offset.click.left>this.containment[2]){e=this.containment[2]+this.offset.click.left}if(f.pageY-this.offset.click.top>this.containment[3]){d=this.containment[3]+this.offset.click.top}}if(i.grid){var h=this.originalPageY+Math.round((d-this.originalPageY)/i.grid[1])*i.grid[1];d=this.containment?(!(h-this.offset.click.top<this.containment[1]||h-this.offset.click.top>this.containment[3])?h:(!(h-this.offset.click.top<this.containment[1])?h-i.grid[1]:h+i.grid[1])):h;var g=this.originalPageX+Math.round((e-this.originalPageX)/i.grid[0])*i.grid[0];e=this.containment?(!(g-this.offset.click.left<this.containment[0]||g-this.offset.click.left>this.containment[2])?g:(!(g-this.offset.click.left<this.containment[0])?g-i.grid[0]:g+i.grid[0])):g}}return{top:(d-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(j?0:c.scrollTop())))),left:(e-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():j?0:c.scrollLeft())))}},_rearrange:function(h,g,d,f){d?d[0].appendChild(this.placeholder[0]):g.item[0].parentNode.insertBefore(this.placeholder[0],(this.direction=="down"?g.item[0]:g.item[0].nextSibling));this.counter=this.counter?++this.counter:1;var e=this,c=this.counter;window.setTimeout(function(){if(c==e.counter){e.refreshPositions(!f)}},0)},_clear:function(e,f){this.reverting=false;var g=[],c=this;if(!this._noFinalSort&&this.currentItem.parent().length){this.placeholder.before(this.currentItem)}this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var d in this._storedCSS){if(this._storedCSS[d]=="auto"||this._storedCSS[d]=="static"){this._storedCSS[d]=""}}this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}if(this.fromOutside&&!f){g.push(function(h){this._trigger("receive",h,this._uiHash(this.fromOutside))})}if((this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!f){g.push(function(h){this._trigger("update",h,this._uiHash())})}if(this!==this.currentContainer){if(!f){g.push(function(h){this._trigger("remove",h,this._uiHash())});g.push((function(h){return function(i){h._trigger("receive",i,this._uiHash(this))}}).call(this,this.currentContainer));g.push((function(h){return function(i){h._trigger("update",i,this._uiHash(this))}}).call(this,this.currentContainer))}}for(var d=this.containers.length-1;d>=0;d--){if(!f){g.push((function(h){return function(i){h._trigger("deactivate",i,this._uiHash(this))}}).call(this,this.containers[d]))}if(this.containers[d].containerCache.over){g.push((function(h){return function(i){h._trigger("out",i,this._uiHash(this))}}).call(this,this.containers[d]));this.containers[d].containerCache.over=0}}if(this._storedCursor){a("body").css("cursor",this._storedCursor)}if(this._storedOpacity){this.helper.css("opacity",this._storedOpacity)}if(this._storedZIndex){this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex)}this.dragging=false;if(this.cancelHelperRemoval){if(!f){this._trigger("beforeStop",e,this._uiHash());for(var d=0;d<g.length;d++){g[d].call(this,e)}this._trigger("stop",e,this._uiHash())}this.fromOutside=false;return false}if(!f){this._trigger("beforeStop",e,this._uiHash())}this.placeholder[0].parentNode.removeChild(this.placeholder[0]);if(this.helper[0]!=this.currentItem[0]){this.helper.remove()}this.helper=null;if(!f){for(var d=0;d<g.length;d++){g[d].call(this,e)}this._trigger("stop",e,this._uiHash())}this.fromOutside=false;return true},_trigger:function(){if(a.Widget.prototype._trigger.apply(this,arguments)===false){this.cancel()}},_uiHash:function(d){var c=d||this;return{helper:c.helper,placeholder:c.placeholder||a([]),position:c.position,originalPosition:c.originalPosition,offset:c.positionAbs,item:c.currentItem,sender:d?d.element:null}}});a.extend(a.ui.sortable,{version:"1.8.24"})})(jQuery);jQuery.effects||(function(h,e){h.effects={};h.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","borderColor","color","outlineColor"],function(o,n){h.fx.step[n]=function(p){if(!p.colorInit){p.start=m(p.elem,n);p.end=k(p.end);p.colorInit=true}p.elem.style[n]="rgb("+Math.max(Math.min(parseInt((p.pos*(p.end[0]-p.start[0]))+p.start[0],10),255),0)+","+Math.max(Math.min(parseInt((p.pos*(p.end[1]-p.start[1]))+p.start[1],10),255),0)+","+Math.max(Math.min(parseInt((p.pos*(p.end[2]-p.start[2]))+p.start[2],10),255),0)+")"}});function k(o){var n;if(o&&o.constructor==Array&&o.length==3){return o}if(n=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(o)){return[parseInt(n[1],10),parseInt(n[2],10),parseInt(n[3],10)]}if(n=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(o)){return[parseFloat(n[1])*2.55,parseFloat(n[2])*2.55,parseFloat(n[3])*2.55]}if(n=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(o)){return[parseInt(n[1],16),parseInt(n[2],16),parseInt(n[3],16)]}if(n=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(o)){return[parseInt(n[1]+n[1],16),parseInt(n[2]+n[2],16),parseInt(n[3]+n[3],16)]}if(n=/rgba\(0, 0, 0, 0\)/.exec(o)){return a.transparent}return a[h.trim(o).toLowerCase()]}function m(p,n){var o;do{o=(h.curCSS||h.css)(p,n);if(o!=""&&o!="transparent"||h.nodeName(p,"body")){break}n="backgroundColor"}while(p=p.parentNode);return k(o)}var a={aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0],transparent:[255,255,255]};var f=["add","remove","toggle"],c={border:1,borderBottom:1,borderColor:1,borderLeft:1,borderRight:1,borderTop:1,borderWidth:1,margin:1,padding:1};function g(){var q=document.defaultView?document.defaultView.getComputedStyle(this,null):this.currentStyle,r={},o,p;if(q&&q.length&&q[0]&&q[q[0]]){var n=q.length;while(n--){o=q[n];if(typeof q[o]=="string"){p=o.replace(/\-(\w)/g,function(s,t){return t.toUpperCase()});r[p]=q[o]}}}else{for(o in q){if(typeof q[o]==="string"){r[o]=q[o]}}}return r}function b(o){var n,p;for(n in o){p=o[n];if(p==null||h.isFunction(p)||n in c||(/scrollbar/).test(n)||(!(/color/i).test(n)&&isNaN(parseFloat(p)))){delete o[n]}}return o}function i(n,p){var q={_:0},o;for(o in p){if(n[o]!=p[o]){q[o]=p[o]}}return q}h.effects.animateClass=function(n,o,q,p){if(h.isFunction(q)){p=q;q=null}return this.queue(function(){var u=h(this),r=u.attr("style")||" ",v=b(g.call(this)),t,s=u.attr("class")||"";h.each(f,function(w,x){if(n[x]){u[x+"Class"](n[x])}});t=b(g.call(this));u.attr("class",s);u.animate(i(v,t),{queue:false,duration:o,easing:q,complete:function(){h.each(f,function(w,x){if(n[x]){u[x+"Class"](n[x])}});if(typeof u.attr("style")=="object"){u.attr("style").cssText="";u.attr("style").cssText=r}else{u.attr("style",r)}if(p){p.apply(this,arguments)}h.dequeue(this)}})})};h.fn.extend({_addClass:h.fn.addClass,addClass:function(o,n,q,p){return n?h.effects.animateClass.apply(this,[{add:o},n,q,p]):this._addClass(o)},_removeClass:h.fn.removeClass,removeClass:function(o,n,q,p){return n?h.effects.animateClass.apply(this,[{remove:o},n,q,p]):this._removeClass(o)},_toggleClass:h.fn.toggleClass,toggleClass:function(p,o,n,r,q){if(typeof o=="boolean"||o===e){if(!n){return this._toggleClass(p,o)}else{return h.effects.animateClass.apply(this,[(o?{add:p}:{remove:p}),n,r,q])}}else{return h.effects.animateClass.apply(this,[{toggle:p},o,n,r])}},switchClass:function(n,p,o,r,q){return h.effects.animateClass.apply(this,[{add:p,remove:n},o,r,q])}});h.extend(h.effects,{version:"1.8.24",save:function(o,p){for(var n=0;n<p.length;n++){if(p[n]!==null){o.data("ec.storage."+p[n],o[0].style[p[n]])}}},restore:function(o,p){for(var n=0;n<p.length;n++){if(p[n]!==null){o.css(p[n],o.data("ec.storage."+p[n]))}}},setMode:function(n,o){if(o=="toggle"){o=n.is(":hidden")?"show":"hide"}return o},getBaseline:function(o,p){var q,n;switch(o[0]){case"top":q=0;break;case"middle":q=0.5;break;case"bottom":q=1;break;default:q=o[0]/p.height}switch(o[1]){case"left":n=0;break;case"center":n=0.5;break;case"right":n=1;break;default:n=o[1]/p.width}return{x:n,y:q}},createWrapper:function(n){if(n.parent().is(".ui-effects-wrapper")){return n.parent()}var o={width:n.outerWidth(true),height:n.outerHeight(true),"float":n.css("float")},r=h("<div></div>").addClass("ui-effects-wrapper").css({fontSize:"100%",background:"transparent",border:"none",margin:0,padding:0}),q=document.activeElement;try{q.id}catch(p){q=document.body}n.wrap(r);if(n[0]===q||h.contains(n[0],q)){h(q).focus()}r=n.parent();if(n.css("position")=="static"){r.css({position:"relative"});n.css({position:"relative"})}else{h.extend(o,{position:n.css("position"),zIndex:n.css("z-index")});h.each(["top","left","bottom","right"],function(s,t){o[t]=n.css(t);if(isNaN(parseInt(o[t],10))){o[t]="auto"}});n.css({position:"relative",top:0,left:0,right:"auto",bottom:"auto"})}return r.css(o).show()},removeWrapper:function(n){var o,p=document.activeElement;if(n.parent().is(".ui-effects-wrapper")){o=n.parent().replaceWith(n);if(n[0]===p||h.contains(n[0],p)){h(p).focus()}return o}return n},setTransition:function(o,q,n,p){p=p||{};h.each(q,function(s,r){var t=o.cssUnit(r);if(t[0]>0){p[r]=t[0]*n+t[1]}});return p}});function d(o,n,p,q){if(typeof o=="object"){q=n;p=null;n=o;o=n.effect}if(h.isFunction(n)){q=n;p=null;n={}}if(typeof n=="number"||h.fx.speeds[n]){q=p;p=n;n={}}if(h.isFunction(p)){q=p;p=null}n=n||{};p=p||n.duration;p=h.fx.off?0:typeof p=="number"?p:p in h.fx.speeds?h.fx.speeds[p]:h.fx.speeds._default;q=q||n.complete;return[o,n,p,q]}function l(n){if(!n||typeof n==="number"||h.fx.speeds[n]){return true}if(typeof n==="string"&&!h.effects[n]){return true}return false}h.fn.extend({effect:function(q,p,s,u){var o=d.apply(this,arguments),r={options:o[1],duration:o[2],callback:o[3]},t=r.options.mode,n=h.effects[q];if(h.fx.off||!n){if(t){return this[t](r.duration,r.callback)}else{return this.each(function(){if(r.callback){r.callback.call(this)}})}}return n.call(this,r)},_show:h.fn.show,show:function(o){if(l(o)){return this._show.apply(this,arguments)}else{var n=d.apply(this,arguments);n[1].mode="show";return this.effect.apply(this,n)}},_hide:h.fn.hide,hide:function(o){if(l(o)){return this._hide.apply(this,arguments)}else{var n=d.apply(this,arguments);n[1].mode="hide";return this.effect.apply(this,n)}},__toggle:h.fn.toggle,toggle:function(o){if(l(o)||typeof o==="boolean"||h.isFunction(o)){return this.__toggle.apply(this,arguments)}else{var n=d.apply(this,arguments);n[1].mode="toggle";return this.effect.apply(this,n)}},cssUnit:function(n){var o=this.css(n),p=[];h.each(["em","px","%","pt"],function(q,r){if(o.indexOf(r)>0){p=[parseFloat(o),r]}});return p}});var j={};h.each(["Quad","Cubic","Quart","Quint","Expo"],function(o,n){j[n]=function(q){return Math.pow(q,o+2)}});h.extend(j,{Sine:function(n){return 1-Math.cos(n*Math.PI/2)},Circ:function(n){return 1-Math.sqrt(1-n*n)},Elastic:function(n){return n===0||n===1?n:-Math.pow(2,8*(n-1))*Math.sin(((n-1)*80-7.5)*Math.PI/15)},Back:function(n){return n*n*(3*n-2)},Bounce:function(q){var n,o=4;while(q<((n=Math.pow(2,--o))-1)/11){}return 1/Math.pow(4,3-o)-7.5625*Math.pow((n*3-2)/22-q,2)}});h.each(j,function(o,n){h.easing["easeIn"+o]=n;h.easing["easeOut"+o]=function(q){return 1-n(1-q)};h.easing["easeInOut"+o]=function(q){return q<0.5?n(q*2)/2:n(q*-2+2)/-2+1}})})(jQuery);(function(a,b){a.effects.blind=function(c){return this.queue(function(){var e=a(this),d=["position","top","bottom","left","right"];var i=a.effects.setMode(e,c.options.mode||"hide");var h=c.options.direction||"vertical";a.effects.save(e,d);e.show();var k=a.effects.createWrapper(e).css({overflow:"hidden"});var f=(h=="vertical")?"height":"width";var j=(h=="vertical")?k.height():k.width();if(i=="show"){k.css(f,0)}var g={};g[f]=i=="show"?j:0;k.animate(g,c.duration,c.options.easing,function(){if(i=="hide"){e.hide()}a.effects.restore(e,d);a.effects.removeWrapper(e);if(c.callback){c.callback.apply(e[0],arguments)}e.dequeue()})})}})(jQuery);(function(a,b){a.effects.bounce=function(c){return this.queue(function(){var f=a(this),m=["position","top","bottom","left","right"];var l=a.effects.setMode(f,c.options.mode||"effect");var o=c.options.direction||"up";var d=c.options.distance||20;var e=c.options.times||5;var h=c.duration||250;if(/show|hide/.test(l)){m.push("opacity")}a.effects.save(f,m);f.show();a.effects.createWrapper(f);var g=(o=="up"||o=="down")?"top":"left";var q=(o=="up"||o=="left")?"pos":"neg";var d=c.options.distance||(g=="top"?f.outerHeight(true)/3:f.outerWidth(true)/3);if(l=="show"){f.css("opacity",0).css(g,q=="pos"?-d:d)}if(l=="hide"){d=d/(e*2)}if(l!="hide"){e--}if(l=="show"){var j={opacity:1};j[g]=(q=="pos"?"+=":"-=")+d;f.animate(j,h/2,c.options.easing);d=d/2;e--}for(var k=0;k<e;k++){var p={},n={};p[g]=(q=="pos"?"-=":"+=")+d;n[g]=(q=="pos"?"+=":"-=")+d;f.animate(p,h/2,c.options.easing).animate(n,h/2,c.options.easing);d=(l=="hide")?d*2:d/2}if(l=="hide"){var j={opacity:0};j[g]=(q=="pos"?"-=":"+=")+d;f.animate(j,h/2,c.options.easing,function(){f.hide();a.effects.restore(f,m);a.effects.removeWrapper(f);if(c.callback){c.callback.apply(this,arguments)}})}else{var p={},n={};p[g]=(q=="pos"?"-=":"+=")+d;n[g]=(q=="pos"?"+=":"-=")+d;f.animate(p,h/2,c.options.easing).animate(n,h/2,c.options.easing,function(){a.effects.restore(f,m);a.effects.removeWrapper(f);if(c.callback){c.callback.apply(this,arguments)}})}f.queue("fx",function(){f.dequeue()});f.dequeue()})}})(jQuery);(function(a,b){a.effects.clip=function(c){return this.queue(function(){var g=a(this),k=["position","top","bottom","left","right","height","width"];var j=a.effects.setMode(g,c.options.mode||"hide");var l=c.options.direction||"vertical";a.effects.save(g,k);g.show();var d=a.effects.createWrapper(g).css({overflow:"hidden"});var f=g[0].tagName=="IMG"?d:g;var h={size:(l=="vertical")?"height":"width",position:(l=="vertical")?"top":"left"};var e=(l=="vertical")?f.height():f.width();if(j=="show"){f.css(h.size,0);f.css(h.position,e/2)}var i={};i[h.size]=j=="show"?e:0;i[h.position]=j=="show"?0:e/2;f.animate(i,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){if(j=="hide"){g.hide()}a.effects.restore(g,k);a.effects.removeWrapper(g);if(c.callback){c.callback.apply(g[0],arguments)}g.dequeue()}})})}})(jQuery);(function(a,b){a.effects.drop=function(c){return this.queue(function(){var f=a(this),e=["position","top","bottom","left","right","opacity"];var j=a.effects.setMode(f,c.options.mode||"hide");var i=c.options.direction||"left";a.effects.save(f,e);f.show();a.effects.createWrapper(f);var g=(i=="up"||i=="down")?"top":"left";var d=(i=="up"||i=="left")?"pos":"neg";var k=c.options.distance||(g=="top"?f.outerHeight(true)/2:f.outerWidth(true)/2);if(j=="show"){f.css("opacity",0).css(g,d=="pos"?-k:k)}var h={opacity:j=="show"?1:0};h[g]=(j=="show"?(d=="pos"?"+=":"-="):(d=="pos"?"-=":"+="))+k;f.animate(h,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){if(j=="hide"){f.hide()}a.effects.restore(f,e);a.effects.removeWrapper(f);if(c.callback){c.callback.apply(this,arguments)}f.dequeue()}})})}})(jQuery);(function(a,b){a.effects.explode=function(c){return this.queue(function(){var l=c.options.pieces?Math.round(Math.sqrt(c.options.pieces)):3;var f=c.options.pieces?Math.round(Math.sqrt(c.options.pieces)):3;c.options.mode=c.options.mode=="toggle"?(a(this).is(":visible")?"hide":"show"):c.options.mode;var k=a(this).show().css("visibility","hidden");var m=k.offset();m.top-=parseInt(k.css("marginTop"),10)||0;m.left-=parseInt(k.css("marginLeft"),10)||0;var h=k.outerWidth(true);var d=k.outerHeight(true);for(var g=0;g<l;g++){for(var e=0;e<f;e++){k.clone().appendTo("body").wrap("<div></div>").css({position:"absolute",visibility:"visible",left:-e*(h/f),top:-g*(d/l)}).parent().addClass("ui-effects-explode").css({position:"absolute",overflow:"hidden",width:h/f,height:d/l,left:m.left+e*(h/f)+(c.options.mode=="show"?(e-Math.floor(f/2))*(h/f):0),top:m.top+g*(d/l)+(c.options.mode=="show"?(g-Math.floor(l/2))*(d/l):0),opacity:c.options.mode=="show"?0:1}).animate({left:m.left+e*(h/f)+(c.options.mode=="show"?0:(e-Math.floor(f/2))*(h/f)),top:m.top+g*(d/l)+(c.options.mode=="show"?0:(g-Math.floor(l/2))*(d/l)),opacity:c.options.mode=="show"?1:0},c.duration||500)}}setTimeout(function(){c.options.mode=="show"?k.css({visibility:"visible"}):k.css({visibility:"visible"}).hide();if(c.callback){c.callback.apply(k[0])}k.dequeue();a("div.ui-effects-explode").remove()},c.duration||500)})}})(jQuery);(function(a,b){a.effects.fade=function(c){return this.queue(function(){var d=a(this),e=a.effects.setMode(d,c.options.mode||"hide");d.animate({opacity:e},{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){(c.callback&&c.callback.apply(this,arguments));d.dequeue()}})})}})(jQuery);(function(a,b){a.effects.fold=function(c){return this.queue(function(){var f=a(this),l=["position","top","bottom","left","right"];var i=a.effects.setMode(f,c.options.mode||"hide");var p=c.options.size||15;var o=!(!c.options.horizFirst);var h=c.duration?c.duration/2:a.fx.speeds._default/2;a.effects.save(f,l);f.show();var e=a.effects.createWrapper(f).css({overflow:"hidden"});var j=((i=="show")!=o);var g=j?["width","height"]:["height","width"];var d=j?[e.width(),e.height()]:[e.height(),e.width()];var k=/([0-9]+)%/.exec(p);if(k){p=parseInt(k[1],10)/100*d[i=="hide"?0:1]}if(i=="show"){e.css(o?{height:0,width:p}:{height:p,width:0})}var n={},m={};n[g[0]]=i=="show"?d[0]:p;m[g[1]]=i=="show"?d[1]:0;e.animate(n,h,c.options.easing).animate(m,h,c.options.easing,function(){if(i=="hide"){f.hide()}a.effects.restore(f,l);a.effects.removeWrapper(f);if(c.callback){c.callback.apply(f[0],arguments)}f.dequeue()})})}})(jQuery);(function(a,b){a.effects.highlight=function(c){return this.queue(function(){var e=a(this),d=["backgroundImage","backgroundColor","opacity"],g=a.effects.setMode(e,c.options.mode||"show"),f={backgroundColor:e.css("backgroundColor")};if(g=="hide"){f.opacity=0}a.effects.save(e,d);e.show().css({backgroundImage:"none",backgroundColor:c.options.color||"#ffff99"}).animate(f,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){(g=="hide"&&e.hide());a.effects.restore(e,d);(g=="show"&&!a.support.opacity&&this.style.removeAttribute("filter"));(c.callback&&c.callback.apply(this,arguments));e.dequeue()}})})}})(jQuery);(function(a,b){a.effects.pulsate=function(c){return this.queue(function(){var g=a(this),k=a.effects.setMode(g,c.options.mode||"show"),j=((c.options.times||5)*2)-1,h=c.duration?c.duration/2:a.fx.speeds._default/2,d=g.is(":visible"),e=0;if(!d){g.css("opacity",0).show();e=1}if((k=="hide"&&d)||(k=="show"&&!d)){j--}for(var f=0;f<j;f++){g.animate({opacity:e},h,c.options.easing);e=(e+1)%2}g.animate({opacity:e},h,c.options.easing,function(){if(e==0){g.hide()}(c.callback&&c.callback.apply(this,arguments))});g.queue("fx",function(){g.dequeue()}).dequeue()})}})(jQuery);(function(a,b){a.effects.puff=function(c){return this.queue(function(){var g=a(this),h=a.effects.setMode(g,c.options.mode||"hide"),f=parseInt(c.options.percent,10)||150,e=f/100,d={height:g.height(),width:g.width()};a.extend(c.options,{fade:true,mode:h,percent:h=="hide"?f:100,from:h=="hide"?d:{height:d.height*e,width:d.width*e}});g.effect("scale",c.options,c.duration,c.callback);g.dequeue()})};a.effects.scale=function(c){return this.queue(function(){var h=a(this);var e=a.extend(true,{},c.options);var k=a.effects.setMode(h,c.options.mode||"effect");var i=parseInt(c.options.percent,10)||(parseInt(c.options.percent,10)==0?0:(k=="hide"?0:100));var j=c.options.direction||"both";var d=c.options.origin;if(k!="effect"){e.origin=d||["middle","center"];e.restore=true}var g={height:h.height(),width:h.width()};h.from=c.options.from||(k=="show"?{height:0,width:0}:g);var f={y:j!="horizontal"?(i/100):1,x:j!="vertical"?(i/100):1};h.to={height:g.height*f.y,width:g.width*f.x};if(c.options.fade){if(k=="show"){h.from.opacity=0;h.to.opacity=1}if(k=="hide"){h.from.opacity=1;h.to.opacity=0}}e.from=h.from;e.to=h.to;e.mode=k;h.effect("size",e,c.duration,c.callback);h.dequeue()})};a.effects.size=function(c){return this.queue(function(){var d=a(this),o=["position","top","bottom","left","right","width","height","overflow","opacity"];var n=["position","top","bottom","left","right","overflow","opacity"];var k=["width","height","overflow"];var q=["fontSize"];var l=["borderTopWidth","borderBottomWidth","paddingTop","paddingBottom"];var g=["borderLeftWidth","borderRightWidth","paddingLeft","paddingRight"];var h=a.effects.setMode(d,c.options.mode||"effect");var j=c.options.restore||false;var f=c.options.scale||"both";var p=c.options.origin;var e={height:d.height(),width:d.width()};d.from=c.options.from||e;d.to=c.options.to||e;if(p){var i=a.effects.getBaseline(p,e);d.from.top=(e.height-d.from.height)*i.y;d.from.left=(e.width-d.from.width)*i.x;d.to.top=(e.height-d.to.height)*i.y;d.to.left=(e.width-d.to.width)*i.x}var m={from:{y:d.from.height/e.height,x:d.from.width/e.width},to:{y:d.to.height/e.height,x:d.to.width/e.width}};if(f=="box"||f=="both"){if(m.from.y!=m.to.y){o=o.concat(l);d.from=a.effects.setTransition(d,l,m.from.y,d.from);d.to=a.effects.setTransition(d,l,m.to.y,d.to)}if(m.from.x!=m.to.x){o=o.concat(g);d.from=a.effects.setTransition(d,g,m.from.x,d.from);d.to=a.effects.setTransition(d,g,m.to.x,d.to)}}if(f=="content"||f=="both"){if(m.from.y!=m.to.y){o=o.concat(q);d.from=a.effects.setTransition(d,q,m.from.y,d.from);d.to=a.effects.setTransition(d,q,m.to.y,d.to)}}a.effects.save(d,j?o:n);d.show();a.effects.createWrapper(d);d.css("overflow","hidden").css(d.from);if(f=="content"||f=="both"){l=l.concat(["marginTop","marginBottom"]).concat(q);g=g.concat(["marginLeft","marginRight"]);k=o.concat(l).concat(g);d.find("*[width]").each(function(){var s=a(this);if(j){a.effects.save(s,k)}var r={height:s.height(),width:s.width()};s.from={height:r.height*m.from.y,width:r.width*m.from.x};s.to={height:r.height*m.to.y,width:r.width*m.to.x};if(m.from.y!=m.to.y){s.from=a.effects.setTransition(s,l,m.from.y,s.from);s.to=a.effects.setTransition(s,l,m.to.y,s.to)}if(m.from.x!=m.to.x){s.from=a.effects.setTransition(s,g,m.from.x,s.from);s.to=a.effects.setTransition(s,g,m.to.x,s.to)}s.css(s.from);s.animate(s.to,c.duration,c.options.easing,function(){if(j){a.effects.restore(s,k)}})})}d.animate(d.to,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){if(d.to.opacity===0){d.css("opacity",d.from.opacity)}if(h=="hide"){d.hide()}a.effects.restore(d,j?o:n);a.effects.removeWrapper(d);if(c.callback){c.callback.apply(this,arguments)}d.dequeue()}})})}})(jQuery);(function(a,b){a.effects.shake=function(c){return this.queue(function(){var f=a(this),m=["position","top","bottom","left","right"];var l=a.effects.setMode(f,c.options.mode||"effect");var o=c.options.direction||"left";var d=c.options.distance||20;var e=c.options.times||3;var h=c.duration||c.options.duration||140;a.effects.save(f,m);f.show();a.effects.createWrapper(f);var g=(o=="up"||o=="down")?"top":"left";var q=(o=="up"||o=="left")?"pos":"neg";var j={},p={},n={};j[g]=(q=="pos"?"-=":"+=")+d;p[g]=(q=="pos"?"+=":"-=")+d*2;n[g]=(q=="pos"?"-=":"+=")+d*2;f.animate(j,h,c.options.easing);for(var k=1;k<e;k++){f.animate(p,h,c.options.easing).animate(n,h,c.options.easing)}f.animate(p,h,c.options.easing).animate(j,h/2,c.options.easing,function(){a.effects.restore(f,m);a.effects.removeWrapper(f);if(c.callback){c.callback.apply(this,arguments)}});f.queue("fx",function(){f.dequeue()});f.dequeue()})}})(jQuery);(function(a,b){a.effects.slide=function(c){return this.queue(function(){var f=a(this),e=["position","top","bottom","left","right"];var j=a.effects.setMode(f,c.options.mode||"show");var i=c.options.direction||"left";a.effects.save(f,e);f.show();a.effects.createWrapper(f).css({overflow:"hidden"});var g=(i=="up"||i=="down")?"top":"left";var d=(i=="up"||i=="left")?"pos":"neg";var k=c.options.distance||(g=="top"?f.outerHeight(true):f.outerWidth(true));if(j=="show"){f.css(g,d=="pos"?(isNaN(k)?"-"+k:-k):k)}var h={};h[g]=(j=="show"?(d=="pos"?"+=":"-="):(d=="pos"?"-=":"+="))+k;f.animate(h,{queue:false,duration:c.duration,easing:c.options.easing,complete:function(){if(j=="hide"){f.hide()}a.effects.restore(f,e);a.effects.removeWrapper(f);if(c.callback){c.callback.apply(this,arguments)}f.dequeue()}})})}})(jQuery);(function(a,b){a.effects.transfer=function(c){return this.queue(function(){var g=a(this),i=a(c.options.to),f=i.offset(),h={top:f.top,left:f.left,height:i.innerHeight(),width:i.innerWidth()},e=g.offset(),d=a('<div class="ui-effects-transfer"></div>').appendTo(document.body).addClass(c.options.className).css({top:e.top,left:e.left,height:g.innerHeight(),width:g.innerWidth(),position:"absolute"}).animate(h,c.duration,c.options.easing,function(){d.remove();(c.callback&&c.callback.apply(g[0],arguments));g.dequeue()})})}})(jQuery);(function(a,b){a.widget("ui.accordion",{options:{active:0,animated:"slide",autoHeight:true,clearStyle:false,collapsible:false,event:"click",fillSpace:false,header:"> li > :first-child,> :not(li):even",icons:{header:"ui-icon-triangle-1-e",headerSelected:"ui-icon-triangle-1-s"},navigation:false,navigationFilter:function(){return this.href.toLowerCase()===location.href.toLowerCase()}},_create:function(){var c=this,d=c.options;c.running=0;c.element.addClass("ui-accordion ui-widget ui-helper-reset").children("li").addClass("ui-accordion-li-fix");c.headers=c.element.find(d.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all").bind("mouseenter.accordion",function(){if(d.disabled){return}a(this).addClass("ui-state-hover")}).bind("mouseleave.accordion",function(){if(d.disabled){return}a(this).removeClass("ui-state-hover")}).bind("focus.accordion",function(){if(d.disabled){return}a(this).addClass("ui-state-focus")}).bind("blur.accordion",function(){if(d.disabled){return}a(this).removeClass("ui-state-focus")});c.headers.next().addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom");if(d.navigation){var e=c.element.find("a").filter(d.navigationFilter).eq(0);if(e.length){var f=e.closest(".ui-accordion-header");if(f.length){c.active=f}else{c.active=e.closest(".ui-accordion-content").prev()}}}c.active=c._findActive(c.active||d.active).addClass("ui-state-default ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top");c.active.next().addClass("ui-accordion-content-active");c._createIcons();c.resize();c.element.attr("role","tablist");c.headers.attr("role","tab").bind("keydown.accordion",function(g){return c._keydown(g)}).next().attr("role","tabpanel");c.headers.not(c.active||"").attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).next().hide();if(!c.active.length){c.headers.eq(0).attr("tabIndex",0)}else{c.active.attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0})}if(!a.browser.safari){c.headers.find("a").attr("tabIndex",-1)}if(d.event){c.headers.bind(d.event.split(" ").join(".accordion ")+".accordion",function(g){c._clickHandler.call(c,g,this);g.preventDefault()})}},_createIcons:function(){var c=this.options;if(c.icons){a("<span></span>").addClass("ui-icon "+c.icons.header).prependTo(this.headers);this.active.children(".ui-icon").toggleClass(c.icons.header).toggleClass(c.icons.headerSelected);this.element.addClass("ui-accordion-icons")}},_destroyIcons:function(){this.headers.children(".ui-icon").remove();this.element.removeClass("ui-accordion-icons")},destroy:function(){var c=this.options;this.element.removeClass("ui-accordion ui-widget ui-helper-reset").removeAttr("role");this.headers.unbind(".accordion").removeClass("ui-accordion-header ui-accordion-disabled ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top").removeAttr("role").removeAttr("aria-expanded").removeAttr("aria-selected").removeAttr("tabIndex");this.headers.find("a").removeAttr("tabIndex");this._destroyIcons();var d=this.headers.next().css("display","").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-accordion-disabled ui-state-disabled");if(c.autoHeight||c.fillHeight){d.css("height","")}return a.Widget.prototype.destroy.call(this)},_setOption:function(c,d){a.Widget.prototype._setOption.apply(this,arguments);if(c=="active"){this.activate(d)}if(c=="icons"){this._destroyIcons();if(d){this._createIcons()}}if(c=="disabled"){this.headers.add(this.headers.next())[d?"addClass":"removeClass"]("ui-accordion-disabled ui-state-disabled")}},_keydown:function(f){if(this.options.disabled||f.altKey||f.ctrlKey){return}var g=a.ui.keyCode,e=this.headers.length,c=this.headers.index(f.target),d=false;switch(f.keyCode){case g.RIGHT:case g.DOWN:d=this.headers[(c+1)%e];break;case g.LEFT:case g.UP:d=this.headers[(c-1+e)%e];break;case g.SPACE:case g.ENTER:this._clickHandler({target:f.target},f.target);f.preventDefault()}if(d){a(f.target).attr("tabIndex",-1);a(d).attr("tabIndex",0);d.focus();return false}return true},resize:function(){var c=this.options,e;if(c.fillSpace){if(a.browser.msie){var d=this.element.parent().css("overflow");this.element.parent().css("overflow","hidden")}e=this.element.parent().height();if(a.browser.msie){this.element.parent().css("overflow",d)}this.headers.each(function(){e-=a(this).outerHeight(true)});this.headers.next().each(function(){a(this).height(Math.max(0,e-a(this).innerHeight()+a(this).height()))}).css("overflow","auto")}else{if(c.autoHeight){e=0;this.headers.next().each(function(){e=Math.max(e,a(this).height("").height())}).height(e)}}return this},activate:function(c){this.options.active=c;var d=this._findActive(c)[0];this._clickHandler({target:d},d);return this},_findActive:function(c){return c?typeof c==="number"?this.headers.filter(":eq("+c+")"):this.headers.not(this.headers.not(c)):c===false?a([]):this.headers.filter(":eq(0)")},_clickHandler:function(c,g){var l=this.options;if(l.disabled){return}if(!c.target){if(!l.collapsible){return}this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(l.icons.headerSelected).addClass(l.icons.header);this.active.next().addClass("ui-accordion-content-active");var i=this.active.next(),f={options:l,newHeader:a([]),oldHeader:l.active,newContent:a([]),oldContent:i},d=(this.active=a([]));this._toggle(d,i,f);return}var h=a(c.currentTarget||g),j=h[0]===this.active[0];l.active=l.collapsible&&j?false:this.headers.index(h);if(this.running||(!l.collapsible&&j)){return}var e=this.active,d=h.next(),i=this.active.next(),f={options:l,newHeader:j&&l.collapsible?a([]):h,oldHeader:this.active,newContent:j&&l.collapsible?a([]):d,oldContent:i},k=this.headers.index(this.active[0])>this.headers.index(h[0]);this.active=j?a([]):h;this._toggle(d,i,f,j,k);e.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all").children(".ui-icon").removeClass(l.icons.headerSelected).addClass(l.icons.header);if(!j){h.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top").children(".ui-icon").removeClass(l.icons.header).addClass(l.icons.headerSelected);h.next().addClass("ui-accordion-content-active")}return},_toggle:function(c,i,g,j,k){var m=this,n=m.options;m.toShow=c;m.toHide=i;m.data=g;var d=function(){if(!m){return}return m._completed.apply(m,arguments)};m._trigger("changestart",null,m.data);m.running=i.size()===0?c.size():i.size();if(n.animated){var f={};if(n.collapsible&&j){f={toShow:a([]),toHide:i,complete:d,down:k,autoHeight:n.autoHeight||n.fillSpace}}else{f={toShow:c,toHide:i,complete:d,down:k,autoHeight:n.autoHeight||n.fillSpace}}if(!n.proxied){n.proxied=n.animated}if(!n.proxiedDuration){n.proxiedDuration=n.duration}n.animated=a.isFunction(n.proxied)?n.proxied(f):n.proxied;n.duration=a.isFunction(n.proxiedDuration)?n.proxiedDuration(f):n.proxiedDuration;var l=a.ui.accordion.animations,e=n.duration,h=n.animated;if(h&&!l[h]&&!a.easing[h]){h="slide"}if(!l[h]){l[h]=function(o){this.slide(o,{easing:h,duration:e||700})}}l[h](f)}else{if(n.collapsible&&j){c.toggle()}else{i.hide();c.show()}d(true)}i.prev().attr({"aria-expanded":"false","aria-selected":"false",tabIndex:-1}).blur();c.prev().attr({"aria-expanded":"true","aria-selected":"true",tabIndex:0}).focus()},_completed:function(c){this.running=c?0:--this.running;if(this.running){return}if(this.options.clearStyle){this.toShow.add(this.toHide).css({height:"",overflow:""})}this.toHide.removeClass("ui-accordion-content-active");if(this.toHide.length){this.toHide.parent()[0].className=this.toHide.parent()[0].className}this._trigger("change",null,this.data)}});a.extend(a.ui.accordion,{version:"1.8.24",animations:{slide:function(k,i){k=a.extend({easing:"swing",duration:300},k,i);if(!k.toHide.size()){k.toShow.animate({height:"show",paddingTop:"show",paddingBottom:"show"},k);return}if(!k.toShow.size()){k.toHide.animate({height:"hide",paddingTop:"hide",paddingBottom:"hide"},k);return}var d=k.toShow.css("overflow"),h=0,e={},g={},f=["height","paddingTop","paddingBottom"],c;var j=k.toShow;c=j[0].style.width;j.width(j.parent().width()-parseFloat(j.css("paddingLeft"))-parseFloat(j.css("paddingRight"))-(parseFloat(j.css("borderLeftWidth"))||0)-(parseFloat(j.css("borderRightWidth"))||0));a.each(f,function(l,n){g[n]="hide";var m=(""+a.css(k.toShow[0],n)).match(/^([\d+-.]+)(.*)$/);e[n]={value:m[1],unit:m[2]||"px"}});k.toShow.css({height:0,overflow:"hidden"}).show();k.toHide.filter(":hidden").each(k.complete).end().filter(":visible").animate(g,{step:function(l,m){if(m.prop=="height"){h=(m.end-m.start===0)?0:(m.now-m.start)/(m.end-m.start)}k.toShow[0].style[m.prop]=(h*e[m.prop].value)+e[m.prop].unit},duration:k.duration,easing:k.easing,complete:function(){if(!k.autoHeight){k.toShow.css("height","")}k.toShow.css({width:c,overflow:d});k.complete()}})},bounceslide:function(c){this.slide(c,{easing:c.down?"easeOutBounce":"swing",duration:c.down?1000:200})}}})})(jQuery);(function(a,b){var c=0;a.widget("ui.autocomplete",{options:{appendTo:"body",autoFocus:false,delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null},pending:0,_create:function(){var d=this,f=this.element[0].ownerDocument,e;this.isMultiLine=this.element.is("textarea");this.element.addClass("ui-autocomplete-input").attr("autocomplete","off").attr({role:"textbox","aria-autocomplete":"list","aria-haspopup":"true"}).bind("keydown.autocomplete",function(g){if(d.options.disabled||d.element.propAttr("readOnly")){return}e=false;var h=a.ui.keyCode;switch(g.keyCode){case h.PAGE_UP:d._move("previousPage",g);break;case h.PAGE_DOWN:d._move("nextPage",g);break;case h.UP:d._keyEvent("previous",g);break;case h.DOWN:d._keyEvent("next",g);break;case h.ENTER:case h.NUMPAD_ENTER:if(d.menu.active){e=true;g.preventDefault()}case h.TAB:if(!d.menu.active){return}d.menu.select(g);break;case h.ESCAPE:d.element.val(d.term);d.close(g);break;default:clearTimeout(d.searching);d.searching=setTimeout(function(){if(d.term!=d.element.val()){d.selectedItem=null;d.search(null,g)}},d.options.delay);break}}).bind("keypress.autocomplete",function(g){if(e){e=false;g.preventDefault()}}).bind("focus.autocomplete",function(){if(d.options.disabled){return}d.selectedItem=null;d.previous=d.element.val()}).bind("blur.autocomplete",function(g){if(d.options.disabled){return}clearTimeout(d.searching);d.closing=setTimeout(function(){d.close(g);d._change(g)},150)});this._initSource();this.menu=a("<ul></ul>").addClass("ui-autocomplete").appendTo(a(this.options.appendTo||"body",f)[0]).mousedown(function(g){var h=d.menu.element[0];if(!a(g.target).closest(".ui-menu-item").length){setTimeout(function(){a(document).one("mousedown",function(i){if(i.target!==d.element[0]&&i.target!==h&&!a.ui.contains(h,i.target)){d.close()}})},1)}setTimeout(function(){clearTimeout(d.closing)},13)}).menu({focus:function(h,i){var g=i.item.data("item.autocomplete");if(false!==d._trigger("focus",h,{item:g})){if(/^key/.test(h.originalEvent.type)){d.element.val(g.value)}}},selected:function(i,j){var h=j.item.data("item.autocomplete"),g=d.previous;if(d.element[0]!==f.activeElement){d.element.focus();d.previous=g;setTimeout(function(){d.previous=g;d.selectedItem=h},1)}if(false!==d._trigger("select",i,{item:h})){d.element.val(h.value)}d.term=d.element.val();d.close(i);d.selectedItem=h},blur:function(g,h){if(d.menu.element.is(":visible")&&(d.element.val()!==d.term)){d.element.val(d.term)}}}).zIndex(this.element.zIndex()+1).css({top:0,left:0}).hide().data("menu");if(a.fn.bgiframe){this.menu.element.bgiframe()}d.beforeunloadHandler=function(){d.element.removeAttr("autocomplete")};a(window).bind("beforeunload",d.beforeunloadHandler)},destroy:function(){this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete").removeAttr("role").removeAttr("aria-autocomplete").removeAttr("aria-haspopup");this.menu.element.remove();a(window).unbind("beforeunload",this.beforeunloadHandler);a.Widget.prototype.destroy.call(this)},_setOption:function(d,e){a.Widget.prototype._setOption.apply(this,arguments);if(d==="source"){this._initSource()}if(d==="appendTo"){this.menu.element.appendTo(a(e||"body",this.element[0].ownerDocument)[0])}if(d==="disabled"&&e&&this.xhr){this.xhr.abort()}},_initSource:function(){var d=this,f,e;if(a.isArray(this.options.source)){f=this.options.source;this.source=function(h,g){g(a.ui.autocomplete.filter(f,h.term))}}else{if(typeof this.options.source==="string"){e=this.options.source;this.source=function(h,g){if(d.xhr){d.xhr.abort()}d.xhr=a.ajax({url:e,data:h,dataType:"json",success:function(j,i){g(j)},error:function(){g([])}})}}else{this.source=this.options.source}}},search:function(e,d){e=e!=null?e:this.element.val();this.term=this.element.val();if(e.length<this.options.minLength){return this.close(d)}clearTimeout(this.closing);if(this._trigger("search",d)===false){return}return this._search(e)},_search:function(d){this.pending++;this.element.addClass("ui-autocomplete-loading");this.source({term:d},this._response())},_response:function(){var e=this,d=++c;return function(f){if(d===c){e.__response(f)}e.pending--;if(!e.pending){e.element.removeClass("ui-autocomplete-loading")}}},__response:function(d){if(!this.options.disabled&&d&&d.length){d=this._normalize(d);this._suggest(d);this._trigger("open")}else{this.close()}},close:function(d){clearTimeout(this.closing);if(this.menu.element.is(":visible")){this.menu.element.hide();this.menu.deactivate();this._trigger("close",d)}},_change:function(d){if(this.previous!==this.element.val()){this._trigger("change",d,{item:this.selectedItem})}},_normalize:function(d){if(d.length&&d[0].label&&d[0].value){return d}return a.map(d,function(e){if(typeof e==="string"){return{label:e,value:e}}return a.extend({label:e.label||e.value,value:e.value||e.label},e)})},_suggest:function(d){var e=this.menu.element.empty().zIndex(this.element.zIndex()+1);this._renderMenu(e,d);this.menu.deactivate();this.menu.refresh();e.show();this._resizeMenu();e.position(a.extend({of:this.element},this.options.position));if(this.options.autoFocus){this.menu.next(new a.Event("mouseover"))}},_resizeMenu:function(){var d=this.menu.element;d.outerWidth(Math.max(d.width("").outerWidth()+1,this.element.outerWidth()))},_renderMenu:function(f,e){var d=this;a.each(e,function(g,h){d._renderItem(f,h)})},_renderItem:function(d,e){return a("<li></li>").data("item.autocomplete",e).append(a("<a></a>").text(e.label)).appendTo(d)},_move:function(e,d){if(!this.menu.element.is(":visible")){this.search(null,d);return}if(this.menu.first()&&/^previous/.test(e)||this.menu.last()&&/^next/.test(e)){this.element.val(this.term);this.menu.deactivate();return}this.menu[e](d)},widget:function(){return this.menu.element},_keyEvent:function(e,d){if(!this.isMultiLine||this.menu.element.is(":visible")){this._move(e,d);d.preventDefault()}}});a.extend(a.ui.autocomplete,{escapeRegex:function(d){return d.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")},filter:function(f,d){var e=new RegExp(a.ui.autocomplete.escapeRegex(d),"i");return a.grep(f,function(g){return e.test(g.label||g.value||g)})}})}(jQuery));(function(a){a.widget("ui.menu",{_create:function(){var b=this;this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr({role:"listbox","aria-activedescendant":"ui-active-menuitem"}).click(function(c){if(!a(c.target).closest(".ui-menu-item a").length){return}c.preventDefault();b.select(c)});this.refresh()},refresh:function(){var c=this;var b=this.element.children("li:not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","menuitem");b.children("a").addClass("ui-corner-all").attr("tabindex",-1).mouseenter(function(d){c.activate(d,a(this).parent())}).mouseleave(function(){c.deactivate()})},activate:function(e,d){this.deactivate();if(this.hasScroll()){var f=d.offset().top-this.element.offset().top,b=this.element.scrollTop(),c=this.element.height();if(f<0){this.element.scrollTop(b+f)}else{if(f>=c){this.element.scrollTop(b+f-c+d.height())}}}this.active=d.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-menuitem").end();this._trigger("focus",e,{item:d})},deactivate:function(){if(!this.active){return}this.active.children("a").removeClass("ui-state-hover").removeAttr("id");this._trigger("blur");this.active=null},next:function(b){this.move("next",".ui-menu-item:first",b)},previous:function(b){this.move("prev",".ui-menu-item:last",b)},first:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},last:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},move:function(e,d,c){if(!this.active){this.activate(c,this.element.children(d));return}var b=this.active[e+"All"](".ui-menu-item").eq(0);if(b.length){this.activate(c,b)}else{this.activate(c,this.element.children(d))}},nextPage:function(d){if(this.hasScroll()){if(!this.active||this.last()){this.activate(d,this.element.children(".ui-menu-item:first"));return}var e=this.active.offset().top,c=this.element.height(),b=this.element.children(".ui-menu-item").filter(function(){var f=a(this).offset().top-e-c+a(this).height();return f<10&&f>-10});if(!b.length){b=this.element.children(".ui-menu-item:last")}this.activate(d,b)}else{this.activate(d,this.element.children(".ui-menu-item").filter(!this.active||this.last()?":first":":last"))}},previousPage:function(d){if(this.hasScroll()){if(!this.active||this.first()){this.activate(d,this.element.children(".ui-menu-item:last"));return}var e=this.active.offset().top,c=this.element.height(),b=this.element.children(".ui-menu-item").filter(function(){var f=a(this).offset().top-e+c-a(this).height();return f<10&&f>-10});if(!b.length){b=this.element.children(".ui-menu-item:first")}this.activate(d,b)}else{this.activate(d,this.element.children(".ui-menu-item").filter(!this.active||this.first()?":last":":first"))}},hasScroll:function(){return this.element.height()<this.element[a.fn.prop?"prop":"attr"]("scrollHeight")},select:function(b){this._trigger("selected",b,{item:this.active})}})}(jQuery));(function(f,b){var k,e,a,h,i="ui-button ui-widget ui-state-default ui-corner-all",c="ui-state-hover ui-state-active ",g="ui-button-icons-only ui-button-icon-only ui-button-text-icons ui-button-text-icon-primary ui-button-text-icon-secondary ui-button-text-only",j=function(){var l=f(this).find(":ui-button");setTimeout(function(){l.button("refresh")},1)},d=function(m){var l=m.name,n=m.form,o=f([]);if(l){if(n){o=f(n).find("[name='"+l+"']")}else{o=f("[name='"+l+"']",m.ownerDocument).filter(function(){return !this.form})}}return o};f.widget("ui.button",{options:{disabled:null,text:true,label:null,icons:{primary:null,secondary:null}},_create:function(){this.element.closest("form").unbind("reset.button").bind("reset.button",j);if(typeof this.options.disabled!=="boolean"){this.options.disabled=!!this.element.propAttr("disabled")}else{this.element.propAttr("disabled",this.options.disabled)}this._determineButtonType();this.hasTitle=!!this.buttonElement.attr("title");var l=this,n=this.options,o=this.type==="checkbox"||this.type==="radio",p="ui-state-hover"+(!o?" ui-state-active":""),m="ui-state-focus";if(n.label===null){n.label=this.buttonElement.html()}this.buttonElement.addClass(i).attr("role","button").bind("mouseenter.button",function(){if(n.disabled){return}f(this).addClass("ui-state-hover");if(this===k){f(this).addClass("ui-state-active")}}).bind("mouseleave.button",function(){if(n.disabled){return}f(this).removeClass(p)}).bind("click.button",function(q){if(n.disabled){q.preventDefault();q.stopImmediatePropagation()}});this.element.bind("focus.button",function(){l.buttonElement.addClass(m)}).bind("blur.button",function(){l.buttonElement.removeClass(m)});if(o){this.element.bind("change.button",function(){if(h){return}l.refresh()});this.buttonElement.bind("mousedown.button",function(q){if(n.disabled){return}h=false;e=q.pageX;a=q.pageY}).bind("mouseup.button",function(q){if(n.disabled){return}if(e!==q.pageX||a!==q.pageY){h=true}})}if(this.type==="checkbox"){this.buttonElement.bind("click.button",function(){if(n.disabled||h){return false}f(this).toggleClass("ui-state-active");l.buttonElement.attr("aria-pressed",l.element[0].checked)})}else{if(this.type==="radio"){this.buttonElement.bind("click.button",function(){if(n.disabled||h){return false}f(this).addClass("ui-state-active");l.buttonElement.attr("aria-pressed","true");var q=l.element[0];d(q).not(q).map(function(){return f(this).button("widget")[0]}).removeClass("ui-state-active").attr("aria-pressed","false")})}else{this.buttonElement.bind("mousedown.button",function(){if(n.disabled){return false}f(this).addClass("ui-state-active");k=this;f(document).one("mouseup",function(){k=null})}).bind("mouseup.button",function(){if(n.disabled){return false}f(this).removeClass("ui-state-active")}).bind("keydown.button",function(q){if(n.disabled){return false}if(q.keyCode==f.ui.keyCode.SPACE||q.keyCode==f.ui.keyCode.ENTER){f(this).addClass("ui-state-active")}}).bind("keyup.button",function(){f(this).removeClass("ui-state-active")});if(this.buttonElement.is("a")){this.buttonElement.keyup(function(q){if(q.keyCode===f.ui.keyCode.SPACE){f(this).click()}})}}}this._setOption("disabled",n.disabled);this._resetButton()},_determineButtonType:function(){if(this.element.is(":checkbox")){this.type="checkbox"}else{if(this.element.is(":radio")){this.type="radio"}else{if(this.element.is("input")){this.type="input"}else{this.type="button"}}}if(this.type==="checkbox"||this.type==="radio"){var l=this.element.parents().filter(":last"),n="label[for='"+this.element.attr("id")+"']";this.buttonElement=l.find(n);if(!this.buttonElement.length){l=l.length?l.siblings():this.element.siblings();this.buttonElement=l.filter(n);if(!this.buttonElement.length){this.buttonElement=l.find(n)}}this.element.addClass("ui-helper-hidden-accessible");var m=this.element.is(":checked");if(m){this.buttonElement.addClass("ui-state-active")}this.buttonElement.attr("aria-pressed",m)}else{this.buttonElement=this.element}},widget:function(){return this.buttonElement},destroy:function(){this.element.removeClass("ui-helper-hidden-accessible");this.buttonElement.removeClass(i+" "+c+" "+g).removeAttr("role").removeAttr("aria-pressed").html(this.buttonElement.find(".ui-button-text").html());if(!this.hasTitle){this.buttonElement.removeAttr("title")}f.Widget.prototype.destroy.call(this)},_setOption:function(l,m){f.Widget.prototype._setOption.apply(this,arguments);if(l==="disabled"){if(m){this.element.propAttr("disabled",true)}else{this.element.propAttr("disabled",false)}return}this._resetButton()},refresh:function(){var l=this.element.is(":disabled");if(l!==this.options.disabled){this._setOption("disabled",l)}if(this.type==="radio"){d(this.element[0]).each(function(){if(f(this).is(":checked")){f(this).button("widget").addClass("ui-state-active").attr("aria-pressed","true")}else{f(this).button("widget").removeClass("ui-state-active").attr("aria-pressed","false")}})}else{if(this.type==="checkbox"){if(this.element.is(":checked")){this.buttonElement.addClass("ui-state-active").attr("aria-pressed","true")}else{this.buttonElement.removeClass("ui-state-active").attr("aria-pressed","false")}}}},_resetButton:function(){if(this.type==="input"){if(this.options.label){this.element.val(this.options.label)}return}var p=this.buttonElement.removeClass(g),n=f("<span></span>",this.element[0].ownerDocument).addClass("ui-button-text").html(this.options.label).appendTo(p.empty()).text(),m=this.options.icons,l=m.primary&&m.secondary,o=[];if(m.primary||m.secondary){if(this.options.text){o.push("ui-button-text-icon"+(l?"s":(m.primary?"-primary":"-secondary")))}if(m.primary){p.prepend("<span class='ui-button-icon-primary ui-icon "+m.primary+"'></span>")}if(m.secondary){p.append("<span class='ui-button-icon-secondary ui-icon "+m.secondary+"'></span>")}if(!this.options.text){o.push(l?"ui-button-icons-only":"ui-button-icon-only");if(!this.hasTitle){p.attr("title",n)}}}else{o.push("ui-button-text-only")}p.addClass(o.join(" "))}});f.widget("ui.buttonset",{options:{items:":button, :submit, :reset, :checkbox, :radio, a, :data(button)"},_create:function(){this.element.addClass("ui-buttonset")},_init:function(){this.refresh()},_setOption:function(l,m){if(l==="disabled"){this.buttons.button("option",l,m)}f.Widget.prototype._setOption.apply(this,arguments)},refresh:function(){var l=this.element.css("direction")==="rtl";this.buttons=this.element.find(this.options.items).filter(":ui-button").button("refresh").end().not(":ui-button").button().end().map(function(){return f(this).button("widget")[0]}).removeClass("ui-corner-all ui-corner-left ui-corner-right").filter(":first").addClass(l?"ui-corner-right":"ui-corner-left").end().filter(":last").addClass(l?"ui-corner-left":"ui-corner-right").end().end()},destroy:function(){this.element.removeClass("ui-buttonset");this.buttons.map(function(){return f(this).button("widget")[0]}).removeClass("ui-corner-left ui-corner-right").end().button("destroy");f.Widget.prototype.destroy.call(this)}})}(jQuery));(function($,undefined){$.extend($.ui,{datepicker:{version:"1.8.24"}});var PROP_NAME="datepicker";var dpuuid=new Date().getTime();var instActive;function Datepicker(){this.debug=false;this._curInst=null;this._keyEvent=false;this._disabledInputs=[];this._datepickerShowing=false;this._inDialog=false;this._mainDivId="ui-datepicker-div";this._inlineClass="ui-datepicker-inline";this._appendClass="ui-datepicker-append";this._triggerClass="ui-datepicker-trigger";this._dialogClass="ui-datepicker-dialog";this._disableClass="ui-datepicker-disabled";this._unselectableClass="ui-datepicker-unselectable";this._currentClass="ui-datepicker-current-day";this._dayOverClass="ui-datepicker-days-cell-over";this.regional=[];this.regional[""]={closeText:"Done",prevText:"Prev",nextText:"Next",currentText:"Today",monthNames:["January","February","March","April","May","June","July","August","September","October","November","December"],monthNamesShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],dayNames:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],dayNamesShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],dayNamesMin:["Su","Mo","Tu","We","Th","Fr","Sa"],weekHeader:"Wk",dateFormat:"mm/dd/yy",firstDay:0,isRTL:false,showMonthAfterYear:false,yearSuffix:""};this._defaults={showOn:"focus",showAnim:"fadeIn",showOptions:{},defaultDate:null,appendText:"",buttonText:"...",buttonImage:"",buttonImageOnly:false,hideIfNoPrevNext:false,navigationAsDateFormat:false,gotoCurrent:false,changeMonth:false,changeYear:false,yearRange:"c-10:c+10",showOtherMonths:false,selectOtherMonths:false,showWeek:false,calculateWeek:this.iso8601Week,shortYearCutoff:"+10",minDate:null,maxDate:null,duration:"fast",beforeShowDay:null,beforeShow:null,onSelect:null,onChangeMonthYear:null,onClose:null,numberOfMonths:1,showCurrentAtPos:0,stepMonths:1,stepBigMonths:12,altField:"",altFormat:"",constrainInput:true,showButtonPanel:false,autoSize:false,disabled:false};$.extend(this._defaults,this.regional[""]);this.dpDiv=bindHover($('<div id="'+this._mainDivId+'" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'))}$.extend(Datepicker.prototype,{markerClassName:"hasDatepicker",maxRows:4,log:function(){if(this.debug){console.log.apply("",arguments)}},_widgetDatepicker:function(){return this.dpDiv},setDefaults:function(settings){extendRemove(this._defaults,settings||{});return this},_attachDatepicker:function(target,settings){var inlineSettings=null;for(var attrName in this._defaults){var attrValue=target.getAttribute("date:"+attrName);if(attrValue){inlineSettings=inlineSettings||{};try{inlineSettings[attrName]=eval(attrValue)}catch(err){inlineSettings[attrName]=attrValue}}}var nodeName=target.nodeName.toLowerCase();var inline=(nodeName=="div"||nodeName=="span");if(!target.id){this.uuid+=1;target.id="dp"+this.uuid}var inst=this._newInst($(target),inline);inst.settings=$.extend({},settings||{},inlineSettings||{});if(nodeName=="input"){this._connectDatepicker(target,inst)}else{if(inline){this._inlineDatepicker(target,inst)}}},_newInst:function(target,inline){var id=target[0].id.replace(/([^A-Za-z0-9_-])/g,"\\\\$1");return{id:id,input:target,selectedDay:0,selectedMonth:0,selectedYear:0,drawMonth:0,drawYear:0,inline:inline,dpDiv:(!inline?this.dpDiv:bindHover($('<div class="'+this._inlineClass+' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')))}},_connectDatepicker:function(target,inst){var input=$(target);inst.append=$([]);inst.trigger=$([]);if(input.hasClass(this.markerClassName)){return}this._attachments(input,inst);input.addClass(this.markerClassName).keydown(this._doKeyDown).keypress(this._doKeyPress).keyup(this._doKeyUp).bind("setData.datepicker",function(event,key,value){inst.settings[key]=value}).bind("getData.datepicker",function(event,key){return this._get(inst,key)});this._autoSize(inst);$.data(target,PROP_NAME,inst);if(inst.settings.disabled){this._disableDatepicker(target)}},_attachments:function(input,inst){var appendText=this._get(inst,"appendText");var isRTL=this._get(inst,"isRTL");if(inst.append){inst.append.remove()}if(appendText){inst.append=$('<span class="'+this._appendClass+'">'+appendText+"</span>");input[isRTL?"before":"after"](inst.append)}input.unbind("focus",this._showDatepicker);if(inst.trigger){inst.trigger.remove()}var showOn=this._get(inst,"showOn");if(showOn=="focus"||showOn=="both"){input.focus(this._showDatepicker)}if(showOn=="button"||showOn=="both"){var buttonText=this._get(inst,"buttonText");var buttonImage=this._get(inst,"buttonImage");inst.trigger=$(this._get(inst,"buttonImageOnly")?$("<img/>").addClass(this._triggerClass).attr({src:buttonImage,alt:buttonText,title:buttonText}):$('<button type="button"></button>').addClass(this._triggerClass).html(buttonImage==""?buttonText:$("<img/>").attr({src:buttonImage,alt:buttonText,title:buttonText})));input[isRTL?"before":"after"](inst.trigger);inst.trigger.click(function(){if($.datepicker._datepickerShowing&&$.datepicker._lastInput==input[0]){$.datepicker._hideDatepicker()}else{if($.datepicker._datepickerShowing&&$.datepicker._lastInput!=input[0]){$.datepicker._hideDatepicker();$.datepicker._showDatepicker(input[0])}else{$.datepicker._showDatepicker(input[0])}}return false})}},_autoSize:function(inst){if(this._get(inst,"autoSize")&&!inst.inline){var date=new Date(2009,12-1,20);var dateFormat=this._get(inst,"dateFormat");if(dateFormat.match(/[DM]/)){var findMax=function(names){var max=0;var maxI=0;for(var i=0;i<names.length;i++){if(names[i].length>max){max=names[i].length;maxI=i}}return maxI};date.setMonth(findMax(this._get(inst,(dateFormat.match(/MM/)?"monthNames":"monthNamesShort"))));date.setDate(findMax(this._get(inst,(dateFormat.match(/DD/)?"dayNames":"dayNamesShort")))+20-date.getDay())}inst.input.attr("size",this._formatDate(inst,date).length)}},_inlineDatepicker:function(target,inst){var divSpan=$(target);if(divSpan.hasClass(this.markerClassName)){return}divSpan.addClass(this.markerClassName).append(inst.dpDiv).bind("setData.datepicker",function(event,key,value){inst.settings[key]=value}).bind("getData.datepicker",function(event,key){return this._get(inst,key)});$.data(target,PROP_NAME,inst);this._setDate(inst,this._getDefaultDate(inst),true);this._updateDatepicker(inst);this._updateAlternate(inst);if(inst.settings.disabled){this._disableDatepicker(target)}inst.dpDiv.css("display","block")},_dialogDatepicker:function(input,date,onSelect,settings,pos){var inst=this._dialogInst;if(!inst){this.uuid+=1;var id="dp"+this.uuid;this._dialogInput=$('<input type="text" id="'+id+'" style="position: absolute; top: -100px; width: 0px;"/>');this._dialogInput.keydown(this._doKeyDown);$("body").append(this._dialogInput);inst=this._dialogInst=this._newInst(this._dialogInput,false);inst.settings={};$.data(this._dialogInput[0],PROP_NAME,inst)}extendRemove(inst.settings,settings||{});date=(date&&date.constructor==Date?this._formatDate(inst,date):date);this._dialogInput.val(date);this._pos=(pos?(pos.length?pos:[pos.pageX,pos.pageY]):null);if(!this._pos){var browserWidth=document.documentElement.clientWidth;var browserHeight=document.documentElement.clientHeight;var scrollX=document.documentElement.scrollLeft||document.body.scrollLeft;var scrollY=document.documentElement.scrollTop||document.body.scrollTop;this._pos=[(browserWidth/2)-100+scrollX,(browserHeight/2)-150+scrollY]}this._dialogInput.css("left",(this._pos[0]+20)+"px").css("top",this._pos[1]+"px");inst.settings.onSelect=onSelect;this._inDialog=true;this.dpDiv.addClass(this._dialogClass);this._showDatepicker(this._dialogInput[0]);if($.blockUI){$.blockUI(this.dpDiv)}$.data(this._dialogInput[0],PROP_NAME,inst);return this},_destroyDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();$.removeData(target,PROP_NAME);if(nodeName=="input"){inst.append.remove();inst.trigger.remove();$target.removeClass(this.markerClassName).unbind("focus",this._showDatepicker).unbind("keydown",this._doKeyDown).unbind("keypress",this._doKeyPress).unbind("keyup",this._doKeyUp)}else{if(nodeName=="div"||nodeName=="span"){$target.removeClass(this.markerClassName).empty()}}},_enableDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();if(nodeName=="input"){target.disabled=false;inst.trigger.filter("button").each(function(){this.disabled=false}).end().filter("img").css({opacity:"1.0",cursor:""})}else{if(nodeName=="div"||nodeName=="span"){var inline=$target.children("."+this._inlineClass);inline.children().removeClass("ui-state-disabled");inline.find("select.ui-datepicker-month, select.ui-datepicker-year").removeAttr("disabled")}}this._disabledInputs=$.map(this._disabledInputs,function(value){return(value==target?null:value)})},_disableDatepicker:function(target){var $target=$(target);var inst=$.data(target,PROP_NAME);if(!$target.hasClass(this.markerClassName)){return}var nodeName=target.nodeName.toLowerCase();if(nodeName=="input"){target.disabled=true;inst.trigger.filter("button").each(function(){this.disabled=true}).end().filter("img").css({opacity:"0.5",cursor:"default"})}else{if(nodeName=="div"||nodeName=="span"){var inline=$target.children("."+this._inlineClass);inline.children().addClass("ui-state-disabled");inline.find("select.ui-datepicker-month, select.ui-datepicker-year").attr("disabled","disabled")}}this._disabledInputs=$.map(this._disabledInputs,function(value){return(value==target?null:value)});this._disabledInputs[this._disabledInputs.length]=target},_isDisabledDatepicker:function(target){if(!target){return false}for(var i=0;i<this._disabledInputs.length;i++){if(this._disabledInputs[i]==target){return true}}return false},_getInst:function(target){try{return $.data(target,PROP_NAME)}catch(err){throw"Missing instance data for this datepicker"}},_optionDatepicker:function(target,name,value){var inst=this._getInst(target);if(arguments.length==2&&typeof name=="string"){return(name=="defaults"?$.extend({},$.datepicker._defaults):(inst?(name=="all"?$.extend({},inst.settings):this._get(inst,name)):null))}var settings=name||{};if(typeof name=="string"){settings={};settings[name]=value}if(inst){if(this._curInst==inst){this._hideDatepicker()}var date=this._getDateDatepicker(target,true);var minDate=this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");extendRemove(inst.settings,settings);if(minDate!==null&&settings.dateFormat!==undefined&&settings.minDate===undefined){inst.settings.minDate=this._formatDate(inst,minDate)}if(maxDate!==null&&settings.dateFormat!==undefined&&settings.maxDate===undefined){inst.settings.maxDate=this._formatDate(inst,maxDate)}this._attachments($(target),inst);this._autoSize(inst);this._setDate(inst,date);this._updateAlternate(inst);this._updateDatepicker(inst)}},_changeDatepicker:function(target,name,value){this._optionDatepicker(target,name,value)},_refreshDatepicker:function(target){var inst=this._getInst(target);if(inst){this._updateDatepicker(inst)}},_setDateDatepicker:function(target,date){var inst=this._getInst(target);if(inst){this._setDate(inst,date);this._updateDatepicker(inst);this._updateAlternate(inst)}},_getDateDatepicker:function(target,noDefault){var inst=this._getInst(target);if(inst&&!inst.inline){this._setDateFromField(inst,noDefault)}return(inst?this._getDate(inst):null)},_doKeyDown:function(event){var inst=$.datepicker._getInst(event.target);var handled=true;var isRTL=inst.dpDiv.is(".ui-datepicker-rtl");inst._keyEvent=true;if($.datepicker._datepickerShowing){switch(event.keyCode){case 9:$.datepicker._hideDatepicker();handled=false;break;case 13:var sel=$("td."+$.datepicker._dayOverClass+":not(."+$.datepicker._currentClass+")",inst.dpDiv);if(sel[0]){$.datepicker._selectDay(event.target,inst.selectedMonth,inst.selectedYear,sel[0])}var onSelect=$.datepicker._get(inst,"onSelect");if(onSelect){var dateStr=$.datepicker._formatDate(inst);onSelect.apply((inst.input?inst.input[0]:null),[dateStr,inst])}else{$.datepicker._hideDatepicker()}return false;break;case 27:$.datepicker._hideDatepicker();break;case 33:$.datepicker._adjustDate(event.target,(event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths")),"M");break;case 34:$.datepicker._adjustDate(event.target,(event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths")),"M");break;case 35:if(event.ctrlKey||event.metaKey){$.datepicker._clearDate(event.target)}handled=event.ctrlKey||event.metaKey;break;case 36:if(event.ctrlKey||event.metaKey){$.datepicker._gotoToday(event.target)}handled=event.ctrlKey||event.metaKey;break;case 37:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,(isRTL?+1:-1),"D")}handled=event.ctrlKey||event.metaKey;if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,(event.ctrlKey?-$.datepicker._get(inst,"stepBigMonths"):-$.datepicker._get(inst,"stepMonths")),"M")}break;case 38:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,-7,"D")}handled=event.ctrlKey||event.metaKey;break;case 39:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,(isRTL?-1:+1),"D")}handled=event.ctrlKey||event.metaKey;if(event.originalEvent.altKey){$.datepicker._adjustDate(event.target,(event.ctrlKey?+$.datepicker._get(inst,"stepBigMonths"):+$.datepicker._get(inst,"stepMonths")),"M")}break;case 40:if(event.ctrlKey||event.metaKey){$.datepicker._adjustDate(event.target,+7,"D")}handled=event.ctrlKey||event.metaKey;break;default:handled=false}}else{if(event.keyCode==36&&event.ctrlKey){$.datepicker._showDatepicker(this)}else{handled=false}}if(handled){event.preventDefault();event.stopPropagation()}},_doKeyPress:function(event){var inst=$.datepicker._getInst(event.target);if($.datepicker._get(inst,"constrainInput")){var chars=$.datepicker._possibleChars($.datepicker._get(inst,"dateFormat"));var chr=String.fromCharCode(event.charCode==undefined?event.keyCode:event.charCode);return event.ctrlKey||event.metaKey||(chr<" "||!chars||chars.indexOf(chr)>-1)}},_doKeyUp:function(event){var inst=$.datepicker._getInst(event.target);if(inst.input.val()!=inst.lastVal){try{var date=$.datepicker.parseDate($.datepicker._get(inst,"dateFormat"),(inst.input?inst.input.val():null),$.datepicker._getFormatConfig(inst));if(date){$.datepicker._setDateFromField(inst);$.datepicker._updateAlternate(inst);$.datepicker._updateDatepicker(inst)}}catch(err){$.datepicker.log(err)}}return true},_showDatepicker:function(input){input=input.target||input;if(input.nodeName.toLowerCase()!="input"){input=$("input",input.parentNode)[0]}if($.datepicker._isDisabledDatepicker(input)||$.datepicker._lastInput==input){return}var inst=$.datepicker._getInst(input);if($.datepicker._curInst&&$.datepicker._curInst!=inst){$.datepicker._curInst.dpDiv.stop(true,true);if(inst&&$.datepicker._datepickerShowing){$.datepicker._hideDatepicker($.datepicker._curInst.input[0])}}var beforeShow=$.datepicker._get(inst,"beforeShow");var beforeShowSettings=beforeShow?beforeShow.apply(input,[input,inst]):{};if(beforeShowSettings===false){return}extendRemove(inst.settings,beforeShowSettings);inst.lastVal=null;$.datepicker._lastInput=input;$.datepicker._setDateFromField(inst);if($.datepicker._inDialog){input.value=""}if(!$.datepicker._pos){$.datepicker._pos=$.datepicker._findPos(input);$.datepicker._pos[1]+=input.offsetHeight}var isFixed=false;$(input).parents().each(function(){isFixed|=$(this).css("position")=="fixed";return !isFixed});if(isFixed&&$.browser.opera){$.datepicker._pos[0]-=document.documentElement.scrollLeft;$.datepicker._pos[1]-=document.documentElement.scrollTop}var offset={left:$.datepicker._pos[0],top:$.datepicker._pos[1]};$.datepicker._pos=null;inst.dpDiv.empty();inst.dpDiv.css({position:"absolute",display:"block",top:"-1000px"});$.datepicker._updateDatepicker(inst);offset=$.datepicker._checkOffset(inst,offset,isFixed);inst.dpDiv.css({position:($.datepicker._inDialog&&$.blockUI?"static":(isFixed?"fixed":"absolute")),display:"none",left:offset.left+"px",top:offset.top+"px"});if(!inst.inline){var showAnim=$.datepicker._get(inst,"showAnim");var duration=$.datepicker._get(inst,"duration");var postProcess=function(){var cover=inst.dpDiv.find("iframe.ui-datepicker-cover");if(!!cover.length){var borders=$.datepicker._getBorders(inst.dpDiv);cover.css({left:-borders[0],top:-borders[1],width:inst.dpDiv.outerWidth(),height:inst.dpDiv.outerHeight()})}};inst.dpDiv.zIndex($(input).zIndex()+1);$.datepicker._datepickerShowing=true;if($.effects&&$.effects[showAnim]){inst.dpDiv.show(showAnim,$.datepicker._get(inst,"showOptions"),duration,postProcess)}else{inst.dpDiv[showAnim||"show"]((showAnim?duration:null),postProcess)}if(!showAnim||!duration){postProcess()}if(inst.input.is(":visible")&&!inst.input.is(":disabled")){inst.input.focus()}$.datepicker._curInst=inst}},_updateDatepicker:function(inst){var self=this;self.maxRows=4;var borders=$.datepicker._getBorders(inst.dpDiv);instActive=inst;inst.dpDiv.empty().append(this._generateHTML(inst));this._attachHandlers(inst);var cover=inst.dpDiv.find("iframe.ui-datepicker-cover");if(!!cover.length){cover.css({left:-borders[0],top:-borders[1],width:inst.dpDiv.outerWidth(),height:inst.dpDiv.outerHeight()})}inst.dpDiv.find("."+this._dayOverClass+" a").mouseover();var numMonths=this._getNumberOfMonths(inst);var cols=numMonths[1];var width=17;inst.dpDiv.removeClass("ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4").width("");if(cols>1){inst.dpDiv.addClass("ui-datepicker-multi-"+cols).css("width",(width*cols)+"em")}inst.dpDiv[(numMonths[0]!=1||numMonths[1]!=1?"add":"remove")+"Class"]("ui-datepicker-multi");inst.dpDiv[(this._get(inst,"isRTL")?"add":"remove")+"Class"]("ui-datepicker-rtl");if(inst==$.datepicker._curInst&&$.datepicker._datepickerShowing&&inst.input&&inst.input.is(":visible")&&!inst.input.is(":disabled")&&inst.input[0]!=document.activeElement){inst.input.focus()}if(inst.yearshtml){var origyearshtml=inst.yearshtml;setTimeout(function(){if(origyearshtml===inst.yearshtml&&inst.yearshtml){inst.dpDiv.find("select.ui-datepicker-year:first").replaceWith(inst.yearshtml)}origyearshtml=inst.yearshtml=null},0)}},_getBorders:function(elem){var convert=function(value){return{thin:1,medium:2,thick:3}[value]||value};return[parseFloat(convert(elem.css("border-left-width"))),parseFloat(convert(elem.css("border-top-width")))]},_checkOffset:function(inst,offset,isFixed){var dpWidth=inst.dpDiv.outerWidth();var dpHeight=inst.dpDiv.outerHeight();var inputWidth=inst.input?inst.input.outerWidth():0;var inputHeight=inst.input?inst.input.outerHeight():0;var viewWidth=document.documentElement.clientWidth+(isFixed?0:$(document).scrollLeft());var viewHeight=document.documentElement.clientHeight+(isFixed?0:$(document).scrollTop());offset.left-=(this._get(inst,"isRTL")?(dpWidth-inputWidth):0);offset.left-=(isFixed&&offset.left==inst.input.offset().left)?$(document).scrollLeft():0;offset.top-=(isFixed&&offset.top==(inst.input.offset().top+inputHeight))?$(document).scrollTop():0;offset.left-=Math.min(offset.left,(offset.left+dpWidth>viewWidth&&viewWidth>dpWidth)?Math.abs(offset.left+dpWidth-viewWidth):0);offset.top-=Math.min(offset.top,(offset.top+dpHeight>viewHeight&&viewHeight>dpHeight)?Math.abs(dpHeight+inputHeight):0);return offset},_findPos:function(obj){var inst=this._getInst(obj);var isRTL=this._get(inst,"isRTL");while(obj&&(obj.type=="hidden"||obj.nodeType!=1||$.expr.filters.hidden(obj))){obj=obj[isRTL?"previousSibling":"nextSibling"]}var position=$(obj).offset();return[position.left,position.top]},_hideDatepicker:function(input){var inst=this._curInst;if(!inst||(input&&inst!=$.data(input,PROP_NAME))){return}if(this._datepickerShowing){var showAnim=this._get(inst,"showAnim");var duration=this._get(inst,"duration");var postProcess=function(){$.datepicker._tidyDialog(inst)};if($.effects&&$.effects[showAnim]){inst.dpDiv.hide(showAnim,$.datepicker._get(inst,"showOptions"),duration,postProcess)}else{inst.dpDiv[(showAnim=="slideDown"?"slideUp":(showAnim=="fadeIn"?"fadeOut":"hide"))]((showAnim?duration:null),postProcess)}if(!showAnim){postProcess()}this._datepickerShowing=false;var onClose=this._get(inst,"onClose");if(onClose){onClose.apply((inst.input?inst.input[0]:null),[(inst.input?inst.input.val():""),inst])}this._lastInput=null;if(this._inDialog){this._dialogInput.css({position:"absolute",left:"0",top:"-100px"});if($.blockUI){$.unblockUI();$("body").append(this.dpDiv)}}this._inDialog=false}},_tidyDialog:function(inst){inst.dpDiv.removeClass(this._dialogClass).unbind(".ui-datepicker-calendar")},_checkExternalClick:function(event){if(!$.datepicker._curInst){return}var $target=$(event.target),inst=$.datepicker._getInst($target[0]);if((($target[0].id!=$.datepicker._mainDivId&&$target.parents("#"+$.datepicker._mainDivId).length==0&&!$target.hasClass($.datepicker.markerClassName)&&!$target.closest("."+$.datepicker._triggerClass).length&&$.datepicker._datepickerShowing&&!($.datepicker._inDialog&&$.blockUI)))||($target.hasClass($.datepicker.markerClassName)&&$.datepicker._curInst!=inst)){$.datepicker._hideDatepicker()}},_adjustDate:function(id,offset,period){var target=$(id);var inst=this._getInst(target[0]);if(this._isDisabledDatepicker(target[0])){return}this._adjustInstDate(inst,offset+(period=="M"?this._get(inst,"showCurrentAtPos"):0),period);this._updateDatepicker(inst)},_gotoToday:function(id){var target=$(id);var inst=this._getInst(target[0]);if(this._get(inst,"gotoCurrent")&&inst.currentDay){inst.selectedDay=inst.currentDay;inst.drawMonth=inst.selectedMonth=inst.currentMonth;inst.drawYear=inst.selectedYear=inst.currentYear}else{var date=new Date();inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear()}this._notifyChange(inst);this._adjustDate(target)},_selectMonthYear:function(id,select,period){var target=$(id);var inst=this._getInst(target[0]);inst["selected"+(period=="M"?"Month":"Year")]=inst["draw"+(period=="M"?"Month":"Year")]=parseInt(select.options[select.selectedIndex].value,10);this._notifyChange(inst);this._adjustDate(target)},_selectDay:function(id,month,year,td){var target=$(id);if($(td).hasClass(this._unselectableClass)||this._isDisabledDatepicker(target[0])){return}var inst=this._getInst(target[0]);inst.selectedDay=inst.currentDay=$("a",td).html();inst.selectedMonth=inst.currentMonth=month;inst.selectedYear=inst.currentYear=year;this._selectDate(id,this._formatDate(inst,inst.currentDay,inst.currentMonth,inst.currentYear))},_clearDate:function(id){var target=$(id);var inst=this._getInst(target[0]);this._selectDate(target,"")},_selectDate:function(id,dateStr){var target=$(id);var inst=this._getInst(target[0]);dateStr=(dateStr!=null?dateStr:this._formatDate(inst));if(inst.input){inst.input.val(dateStr)}this._updateAlternate(inst);var onSelect=this._get(inst,"onSelect");if(onSelect){onSelect.apply((inst.input?inst.input[0]:null),[dateStr,inst])}else{if(inst.input){inst.input.trigger("change")}}if(inst.inline){this._updateDatepicker(inst)}else{this._hideDatepicker();this._lastInput=inst.input[0];if(typeof(inst.input[0])!="object"){inst.input.focus()}this._lastInput=null}},_updateAlternate:function(inst){var altField=this._get(inst,"altField");if(altField){var altFormat=this._get(inst,"altFormat")||this._get(inst,"dateFormat");var date=this._getDate(inst);var dateStr=this.formatDate(altFormat,date,this._getFormatConfig(inst));$(altField).each(function(){$(this).val(dateStr)})}},noWeekends:function(date){var day=date.getDay();return[(day>0&&day<6),""]},iso8601Week:function(date){var checkDate=new Date(date.getTime());checkDate.setDate(checkDate.getDate()+4-(checkDate.getDay()||7));var time=checkDate.getTime();checkDate.setMonth(0);checkDate.setDate(1);return Math.floor(Math.round((time-checkDate)/86400000)/7)+1},parseDate:function(format,value,settings){if(format==null||value==null){throw"Invalid arguments"}value=(typeof value=="object"?value.toString():value+"");if(value==""){return null}var shortYearCutoff=(settings?settings.shortYearCutoff:null)||this._defaults.shortYearCutoff;shortYearCutoff=(typeof shortYearCutoff!="string"?shortYearCutoff:new Date().getFullYear()%100+parseInt(shortYearCutoff,10));var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var year=-1;var month=-1;var day=-1;var doy=-1;var literal=false;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var getNumber=function(match){var isDoubled=lookAhead(match);var size=(match=="@"?14:(match=="!"?20:(match=="y"&&isDoubled?4:(match=="o"?3:2))));var digits=new RegExp("^\\d{1,"+size+"}");var num=value.substring(iValue).match(digits);if(!num){throw"Missing number at position "+iValue}iValue+=num[0].length;return parseInt(num[0],10)};var getName=function(match,shortNames,longNames){var names=$.map(lookAhead(match)?longNames:shortNames,function(v,k){return[[k,v]]}).sort(function(a,b){return -(a[1].length-b[1].length)});var index=-1;$.each(names,function(i,pair){var name=pair[1];if(value.substr(iValue,name.length).toLowerCase()==name.toLowerCase()){index=pair[0];iValue+=name.length;return false}});if(index!=-1){return index+1}else{throw"Unknown name at position "+iValue}};var checkLiteral=function(){if(value.charAt(iValue)!=format.charAt(iFormat)){throw"Unexpected literal at position "+iValue}iValue++};var iValue=0;for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{checkLiteral()}}else{switch(format.charAt(iFormat)){case"d":day=getNumber("d");break;case"D":getName("D",dayNamesShort,dayNames);break;case"o":doy=getNumber("o");break;case"m":month=getNumber("m");break;case"M":month=getName("M",monthNamesShort,monthNames);break;case"y":year=getNumber("y");break;case"@":var date=new Date(getNumber("@"));year=date.getFullYear();month=date.getMonth()+1;day=date.getDate();break;case"!":var date=new Date((getNumber("!")-this._ticksTo1970)/10000);year=date.getFullYear();month=date.getMonth()+1;day=date.getDate();break;case"'":if(lookAhead("'")){checkLiteral()}else{literal=true}break;default:checkLiteral()}}}if(iValue<value.length){throw"Extra/unparsed characters found in date: "+value.substring(iValue)}if(year==-1){year=new Date().getFullYear()}else{if(year<100){year+=new Date().getFullYear()-new Date().getFullYear()%100+(year<=shortYearCutoff?0:-100)}}if(doy>-1){month=1;day=doy;do{var dim=this._getDaysInMonth(year,month-1);if(day<=dim){break}month++;day-=dim}while(true)}var date=this._daylightSavingAdjust(new Date(year,month-1,day));if(date.getFullYear()!=year||date.getMonth()+1!=month||date.getDate()!=day){throw"Invalid date"}return date},ATOM:"yy-mm-dd",COOKIE:"D, dd M yy",ISO_8601:"yy-mm-dd",RFC_822:"D, d M y",RFC_850:"DD, dd-M-y",RFC_1036:"D, d M y",RFC_1123:"D, d M yy",RFC_2822:"D, d M yy",RSS:"D, d M y",TICKS:"!",TIMESTAMP:"@",W3C:"yy-mm-dd",_ticksTo1970:(((1970-1)*365+Math.floor(1970/4)-Math.floor(1970/100)+Math.floor(1970/400))*24*60*60*10000000),formatDate:function(format,date,settings){if(!date){return""}var dayNamesShort=(settings?settings.dayNamesShort:null)||this._defaults.dayNamesShort;var dayNames=(settings?settings.dayNames:null)||this._defaults.dayNames;var monthNamesShort=(settings?settings.monthNamesShort:null)||this._defaults.monthNamesShort;var monthNames=(settings?settings.monthNames:null)||this._defaults.monthNames;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};var formatNumber=function(match,value,len){var num=""+value;if(lookAhead(match)){while(num.length<len){num="0"+num}}return num};var formatName=function(match,value,shortNames,longNames){return(lookAhead(match)?longNames[value]:shortNames[value])};var output="";var literal=false;if(date){for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{output+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d":output+=formatNumber("d",date.getDate(),2);break;case"D":output+=formatName("D",date.getDay(),dayNamesShort,dayNames);break;case"o":output+=formatNumber("o",Math.round((new Date(date.getFullYear(),date.getMonth(),date.getDate()).getTime()-new Date(date.getFullYear(),0,0).getTime())/86400000),3);break;case"m":output+=formatNumber("m",date.getMonth()+1,2);break;case"M":output+=formatName("M",date.getMonth(),monthNamesShort,monthNames);break;case"y":output+=(lookAhead("y")?date.getFullYear():(date.getYear()%100<10?"0":"")+date.getYear()%100);break;case"@":output+=date.getTime();break;case"!":output+=date.getTime()*10000+this._ticksTo1970;break;case"'":if(lookAhead("'")){output+="'"}else{literal=true}break;default:output+=format.charAt(iFormat)}}}}return output},_possibleChars:function(format){var chars="";var literal=false;var lookAhead=function(match){var matches=(iFormat+1<format.length&&format.charAt(iFormat+1)==match);if(matches){iFormat++}return matches};for(var iFormat=0;iFormat<format.length;iFormat++){if(literal){if(format.charAt(iFormat)=="'"&&!lookAhead("'")){literal=false}else{chars+=format.charAt(iFormat)}}else{switch(format.charAt(iFormat)){case"d":case"m":case"y":case"@":chars+="0123456789";break;case"D":case"M":return null;case"'":if(lookAhead("'")){chars+="'"}else{literal=true}break;default:chars+=format.charAt(iFormat)}}}return chars},_get:function(inst,name){return inst.settings[name]!==undefined?inst.settings[name]:this._defaults[name]},_setDateFromField:function(inst,noDefault){if(inst.input.val()==inst.lastVal){return}var dateFormat=this._get(inst,"dateFormat");var dates=inst.lastVal=inst.input?inst.input.val():null;var date,defaultDate;date=defaultDate=this._getDefaultDate(inst);var settings=this._getFormatConfig(inst);try{date=this.parseDate(dateFormat,dates,settings)||defaultDate}catch(event){this.log(event);dates=(noDefault?"":dates)}inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();inst.currentDay=(dates?date.getDate():0);inst.currentMonth=(dates?date.getMonth():0);inst.currentYear=(dates?date.getFullYear():0);this._adjustInstDate(inst)},_getDefaultDate:function(inst){return this._restrictMinMax(inst,this._determineDate(inst,this._get(inst,"defaultDate"),new Date()))},_determineDate:function(inst,date,defaultDate){var offsetNumeric=function(offset){var date=new Date();date.setDate(date.getDate()+offset);return date};var offsetString=function(offset){try{return $.datepicker.parseDate($.datepicker._get(inst,"dateFormat"),offset,$.datepicker._getFormatConfig(inst))}catch(e){}var date=(offset.toLowerCase().match(/^c/)?$.datepicker._getDate(inst):null)||new Date();var year=date.getFullYear();var month=date.getMonth();var day=date.getDate();var pattern=/([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;var matches=pattern.exec(offset);while(matches){switch(matches[2]||"d"){case"d":case"D":day+=parseInt(matches[1],10);break;case"w":case"W":day+=parseInt(matches[1],10)*7;break;case"m":case"M":month+=parseInt(matches[1],10);day=Math.min(day,$.datepicker._getDaysInMonth(year,month));break;case"y":case"Y":year+=parseInt(matches[1],10);day=Math.min(day,$.datepicker._getDaysInMonth(year,month));break}matches=pattern.exec(offset)}return new Date(year,month,day)};var newDate=(date==null||date===""?defaultDate:(typeof date=="string"?offsetString(date):(typeof date=="number"?(isNaN(date)?defaultDate:offsetNumeric(date)):new Date(date.getTime()))));newDate=(newDate&&newDate.toString()=="Invalid Date"?defaultDate:newDate);if(newDate){newDate.setHours(0);newDate.setMinutes(0);newDate.setSeconds(0);newDate.setMilliseconds(0)}return this._daylightSavingAdjust(newDate)},_daylightSavingAdjust:function(date){if(!date){return null}date.setHours(date.getHours()>12?date.getHours()+2:0);return date},_setDate:function(inst,date,noChange){var clear=!date;var origMonth=inst.selectedMonth;var origYear=inst.selectedYear;var newDate=this._restrictMinMax(inst,this._determineDate(inst,date,new Date()));inst.selectedDay=inst.currentDay=newDate.getDate();inst.drawMonth=inst.selectedMonth=inst.currentMonth=newDate.getMonth();inst.drawYear=inst.selectedYear=inst.currentYear=newDate.getFullYear();if((origMonth!=inst.selectedMonth||origYear!=inst.selectedYear)&&!noChange){this._notifyChange(inst)}this._adjustInstDate(inst);if(inst.input){inst.input.val(clear?"":this._formatDate(inst))}},_getDate:function(inst){var startDate=(!inst.currentYear||(inst.input&&inst.input.val()=="")?null:this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));return startDate},_attachHandlers:function(inst){var stepMonths=this._get(inst,"stepMonths");var id="#"+inst.id.replace(/\\\\/g,"\\");inst.dpDiv.find("[data-handler]").map(function(){var handler={prev:function(){window["DP_jQuery_"+dpuuid].datepicker._adjustDate(id,-stepMonths,"M")},next:function(){window["DP_jQuery_"+dpuuid].datepicker._adjustDate(id,+stepMonths,"M")},hide:function(){window["DP_jQuery_"+dpuuid].datepicker._hideDatepicker()},today:function(){window["DP_jQuery_"+dpuuid].datepicker._gotoToday(id)},selectDay:function(){window["DP_jQuery_"+dpuuid].datepicker._selectDay(id,+this.getAttribute("data-month"),+this.getAttribute("data-year"),this);return false},selectMonth:function(){window["DP_jQuery_"+dpuuid].datepicker._selectMonthYear(id,this,"M");return false},selectYear:function(){window["DP_jQuery_"+dpuuid].datepicker._selectMonthYear(id,this,"Y");return false}};$(this).bind(this.getAttribute("data-event"),handler[this.getAttribute("data-handler")])})},_generateHTML:function(inst){var today=new Date();today=this._daylightSavingAdjust(new Date(today.getFullYear(),today.getMonth(),today.getDate()));var isRTL=this._get(inst,"isRTL");var showButtonPanel=this._get(inst,"showButtonPanel");var hideIfNoPrevNext=this._get(inst,"hideIfNoPrevNext");var navigationAsDateFormat=this._get(inst,"navigationAsDateFormat");var numMonths=this._getNumberOfMonths(inst);var showCurrentAtPos=this._get(inst,"showCurrentAtPos");var stepMonths=this._get(inst,"stepMonths");var isMultiMonth=(numMonths[0]!=1||numMonths[1]!=1);var currentDate=this._daylightSavingAdjust((!inst.currentDay?new Date(9999,9,9):new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));var minDate=this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");var drawMonth=inst.drawMonth-showCurrentAtPos;var drawYear=inst.drawYear;if(drawMonth<0){drawMonth+=12;drawYear--}if(maxDate){var maxDraw=this._daylightSavingAdjust(new Date(maxDate.getFullYear(),maxDate.getMonth()-(numMonths[0]*numMonths[1])+1,maxDate.getDate()));maxDraw=(minDate&&maxDraw<minDate?minDate:maxDraw);while(this._daylightSavingAdjust(new Date(drawYear,drawMonth,1))>maxDraw){drawMonth--;if(drawMonth<0){drawMonth=11;drawYear--}}}inst.drawMonth=drawMonth;inst.drawYear=drawYear;var prevText=this._get(inst,"prevText");prevText=(!navigationAsDateFormat?prevText:this.formatDate(prevText,this._daylightSavingAdjust(new Date(drawYear,drawMonth-stepMonths,1)),this._getFormatConfig(inst)));var prev=(this._canAdjustMonth(inst,-1,drawYear,drawMonth)?'<a class="ui-datepicker-prev ui-corner-all" data-handler="prev" data-event="click" title="'+prevText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"e":"w")+'">'+prevText+"</span></a>":(hideIfNoPrevNext?"":'<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+prevText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"e":"w")+'">'+prevText+"</span></a>"));var nextText=this._get(inst,"nextText");nextText=(!navigationAsDateFormat?nextText:this.formatDate(nextText,this._daylightSavingAdjust(new Date(drawYear,drawMonth+stepMonths,1)),this._getFormatConfig(inst)));var next=(this._canAdjustMonth(inst,+1,drawYear,drawMonth)?'<a class="ui-datepicker-next ui-corner-all" data-handler="next" data-event="click" title="'+nextText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"w":"e")+'">'+nextText+"</span></a>":(hideIfNoPrevNext?"":'<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+nextText+'"><span class="ui-icon ui-icon-circle-triangle-'+(isRTL?"w":"e")+'">'+nextText+"</span></a>"));var currentText=this._get(inst,"currentText");var gotoDate=(this._get(inst,"gotoCurrent")&&inst.currentDay?currentDate:today);currentText=(!navigationAsDateFormat?currentText:this.formatDate(currentText,gotoDate,this._getFormatConfig(inst)));var controls=(!inst.inline?'<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">'+this._get(inst,"closeText")+"</button>":"");var buttonPanel=(showButtonPanel)?'<div class="ui-datepicker-buttonpane ui-widget-content">'+(isRTL?controls:"")+(this._isInRange(inst,gotoDate)?'<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" data-handler="today" data-event="click">'+currentText+"</button>":"")+(isRTL?"":controls)+"</div>":"";var firstDay=parseInt(this._get(inst,"firstDay"),10);firstDay=(isNaN(firstDay)?0:firstDay);var showWeek=this._get(inst,"showWeek");var dayNames=this._get(inst,"dayNames");var dayNamesShort=this._get(inst,"dayNamesShort");var dayNamesMin=this._get(inst,"dayNamesMin");var monthNames=this._get(inst,"monthNames");var monthNamesShort=this._get(inst,"monthNamesShort");var beforeShowDay=this._get(inst,"beforeShowDay");var showOtherMonths=this._get(inst,"showOtherMonths");var selectOtherMonths=this._get(inst,"selectOtherMonths");var calculateWeek=this._get(inst,"calculateWeek")||this.iso8601Week;var defaultDate=this._getDefaultDate(inst);var html="";for(var row=0;row<numMonths[0];row++){var group="";this.maxRows=4;for(var col=0;col<numMonths[1];col++){var selectedDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,inst.selectedDay));var cornerClass=" ui-corner-all";var calender="";if(isMultiMonth){calender+='<div class="ui-datepicker-group';if(numMonths[1]>1){switch(col){case 0:calender+=" ui-datepicker-group-first";cornerClass=" ui-corner-"+(isRTL?"right":"left");break;case numMonths[1]-1:calender+=" ui-datepicker-group-last";cornerClass=" ui-corner-"+(isRTL?"left":"right");break;default:calender+=" ui-datepicker-group-middle";cornerClass="";break}}calender+='">'}calender+='<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix'+cornerClass+'">'+(/all|left/.test(cornerClass)&&row==0?(isRTL?next:prev):"")+(/all|right/.test(cornerClass)&&row==0?(isRTL?prev:next):"")+this._generateMonthYearHeader(inst,drawMonth,drawYear,minDate,maxDate,row>0||col>0,monthNames,monthNamesShort)+'</div><table class="ui-datepicker-calendar"><thead><tr>';var thead=(showWeek?'<th class="ui-datepicker-week-col">'+this._get(inst,"weekHeader")+"</th>":"");for(var dow=0;dow<7;dow++){var day=(dow+firstDay)%7;thead+="<th"+((dow+firstDay+6)%7>=5?' class="ui-datepicker-week-end"':"")+'><span title="'+dayNames[day]+'">'+dayNamesMin[day]+"</span></th>"}calender+=thead+"</tr></thead><tbody>";var daysInMonth=this._getDaysInMonth(drawYear,drawMonth);if(drawYear==inst.selectedYear&&drawMonth==inst.selectedMonth){inst.selectedDay=Math.min(inst.selectedDay,daysInMonth)}var leadDays=(this._getFirstDayOfMonth(drawYear,drawMonth)-firstDay+7)%7;var curRows=Math.ceil((leadDays+daysInMonth)/7);var numRows=(isMultiMonth?this.maxRows>curRows?this.maxRows:curRows:curRows);this.maxRows=numRows;var printDate=this._daylightSavingAdjust(new Date(drawYear,drawMonth,1-leadDays));for(var dRow=0;dRow<numRows;dRow++){calender+="<tr>";var tbody=(!showWeek?"":'<td class="ui-datepicker-week-col">'+this._get(inst,"calculateWeek")(printDate)+"</td>");for(var dow=0;dow<7;dow++){var daySettings=(beforeShowDay?beforeShowDay.apply((inst.input?inst.input[0]:null),[printDate]):[true,""]);var otherMonth=(printDate.getMonth()!=drawMonth);var unselectable=(otherMonth&&!selectOtherMonths)||!daySettings[0]||(minDate&&printDate<minDate)||(maxDate&&printDate>maxDate);tbody+='<td class="'+((dow+firstDay+6)%7>=5?" ui-datepicker-week-end":"")+(otherMonth?" ui-datepicker-other-month":"")+((printDate.getTime()==selectedDate.getTime()&&drawMonth==inst.selectedMonth&&inst._keyEvent)||(defaultDate.getTime()==printDate.getTime()&&defaultDate.getTime()==selectedDate.getTime())?" "+this._dayOverClass:"")+(unselectable?" "+this._unselectableClass+" ui-state-disabled":"")+(otherMonth&&!showOtherMonths?"":" "+daySettings[1]+(printDate.getTime()==currentDate.getTime()?" "+this._currentClass:"")+(printDate.getTime()==today.getTime()?" ui-datepicker-today":""))+'"'+((!otherMonth||showOtherMonths)&&daySettings[2]?' title="'+daySettings[2]+'"':"")+(unselectable?"":' data-handler="selectDay" data-event="click" data-month="'+printDate.getMonth()+'" data-year="'+printDate.getFullYear()+'"')+">"+(otherMonth&&!showOtherMonths?"&#xa0;":(unselectable?'<span class="ui-state-default">'+printDate.getDate()+"</span>":'<a class="ui-state-default'+(printDate.getTime()==today.getTime()?" ui-state-highlight":"")+(printDate.getTime()==currentDate.getTime()?" ui-state-active":"")+(otherMonth?" ui-priority-secondary":"")+'" href="#">'+printDate.getDate()+"</a>"))+"</td>";printDate.setDate(printDate.getDate()+1);printDate=this._daylightSavingAdjust(printDate)}calender+=tbody+"</tr>"}drawMonth++;if(drawMonth>11){drawMonth=0;drawYear++}calender+="</tbody></table>"+(isMultiMonth?"</div>"+((numMonths[0]>0&&col==numMonths[1]-1)?'<div class="ui-datepicker-row-break"></div>':""):"");group+=calender}html+=group}html+=buttonPanel+($.browser.msie&&parseInt($.browser.version,10)<7&&!inst.inline?'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>':"");inst._keyEvent=false;return html},_generateMonthYearHeader:function(inst,drawMonth,drawYear,minDate,maxDate,secondary,monthNames,monthNamesShort){var changeMonth=this._get(inst,"changeMonth");var changeYear=this._get(inst,"changeYear");var showMonthAfterYear=this._get(inst,"showMonthAfterYear");var html='<div class="ui-datepicker-title">';var monthHtml="";if(secondary||!changeMonth){monthHtml+='<span class="ui-datepicker-month">'+monthNames[drawMonth]+"</span>"}else{var inMinYear=(minDate&&minDate.getFullYear()==drawYear);var inMaxYear=(maxDate&&maxDate.getFullYear()==drawYear);monthHtml+='<select class="ui-datepicker-month" data-handler="selectMonth" data-event="change">';for(var month=0;month<12;month++){if((!inMinYear||month>=minDate.getMonth())&&(!inMaxYear||month<=maxDate.getMonth())){monthHtml+='<option value="'+month+'"'+(month==drawMonth?' selected="selected"':"")+">"+monthNamesShort[month]+"</option>"}}monthHtml+="</select>"}if(!showMonthAfterYear){html+=monthHtml+(secondary||!(changeMonth&&changeYear)?"&#xa0;":"")}if(!inst.yearshtml){inst.yearshtml="";if(secondary||!changeYear){html+='<span class="ui-datepicker-year">'+drawYear+"</span>"}else{var years=this._get(inst,"yearRange").split(":");var thisYear=new Date().getFullYear();var determineYear=function(value){var year=(value.match(/c[+-].*/)?drawYear+parseInt(value.substring(1),10):(value.match(/[+-].*/)?thisYear+parseInt(value,10):parseInt(value,10)));return(isNaN(year)?thisYear:year)};var year=determineYear(years[0]);var endYear=Math.max(year,determineYear(years[1]||""));year=(minDate?Math.max(year,minDate.getFullYear()):year);endYear=(maxDate?Math.min(endYear,maxDate.getFullYear()):endYear);inst.yearshtml+='<select class="ui-datepicker-year" data-handler="selectYear" data-event="change">';for(;year<=endYear;year++){inst.yearshtml+='<option value="'+year+'"'+(year==drawYear?' selected="selected"':"")+">"+year+"</option>"}inst.yearshtml+="</select>";html+=inst.yearshtml;inst.yearshtml=null}}html+=this._get(inst,"yearSuffix");if(showMonthAfterYear){html+=(secondary||!(changeMonth&&changeYear)?"&#xa0;":"")+monthHtml}html+="</div>";return html},_adjustInstDate:function(inst,offset,period){var year=inst.drawYear+(period=="Y"?offset:0);var month=inst.drawMonth+(period=="M"?offset:0);var day=Math.min(inst.selectedDay,this._getDaysInMonth(year,month))+(period=="D"?offset:0);var date=this._restrictMinMax(inst,this._daylightSavingAdjust(new Date(year,month,day)));inst.selectedDay=date.getDate();inst.drawMonth=inst.selectedMonth=date.getMonth();inst.drawYear=inst.selectedYear=date.getFullYear();if(period=="M"||period=="Y"){this._notifyChange(inst)}},_restrictMinMax:function(inst,date){var minDate=this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");var newDate=(minDate&&date<minDate?minDate:date);newDate=(maxDate&&newDate>maxDate?maxDate:newDate);return newDate},_notifyChange:function(inst){var onChange=this._get(inst,"onChangeMonthYear");if(onChange){onChange.apply((inst.input?inst.input[0]:null),[inst.selectedYear,inst.selectedMonth+1,inst])}},_getNumberOfMonths:function(inst){var numMonths=this._get(inst,"numberOfMonths");return(numMonths==null?[1,1]:(typeof numMonths=="number"?[1,numMonths]:numMonths))},_getMinMaxDate:function(inst,minMax){return this._determineDate(inst,this._get(inst,minMax+"Date"),null)},_getDaysInMonth:function(year,month){return 32-this._daylightSavingAdjust(new Date(year,month,32)).getDate()},_getFirstDayOfMonth:function(year,month){return new Date(year,month,1).getDay()},_canAdjustMonth:function(inst,offset,curYear,curMonth){var numMonths=this._getNumberOfMonths(inst);var date=this._daylightSavingAdjust(new Date(curYear,curMonth+(offset<0?offset:numMonths[0]*numMonths[1]),1));if(offset<0){date.setDate(this._getDaysInMonth(date.getFullYear(),date.getMonth()))}return this._isInRange(inst,date)},_isInRange:function(inst,date){var minDate=this._getMinMaxDate(inst,"min");var maxDate=this._getMinMaxDate(inst,"max");return((!minDate||date.getTime()>=minDate.getTime())&&(!maxDate||date.getTime()<=maxDate.getTime()))},_getFormatConfig:function(inst){var shortYearCutoff=this._get(inst,"shortYearCutoff");shortYearCutoff=(typeof shortYearCutoff!="string"?shortYearCutoff:new Date().getFullYear()%100+parseInt(shortYearCutoff,10));return{shortYearCutoff:shortYearCutoff,dayNamesShort:this._get(inst,"dayNamesShort"),dayNames:this._get(inst,"dayNames"),monthNamesShort:this._get(inst,"monthNamesShort"),monthNames:this._get(inst,"monthNames")}},_formatDate:function(inst,day,month,year){if(!day){inst.currentDay=inst.selectedDay;inst.currentMonth=inst.selectedMonth;inst.currentYear=inst.selectedYear}var date=(day?(typeof day=="object"?day:this._daylightSavingAdjust(new Date(year,month,day))):this._daylightSavingAdjust(new Date(inst.currentYear,inst.currentMonth,inst.currentDay)));return this.formatDate(this._get(inst,"dateFormat"),date,this._getFormatConfig(inst))}});function bindHover(dpDiv){var selector="button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a";return dpDiv.bind("mouseout",function(event){var elem=$(event.target).closest(selector);if(!elem.length){return}elem.removeClass("ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover")}).bind("mouseover",function(event){var elem=$(event.target).closest(selector);if($.datepicker._isDisabledDatepicker(instActive.inline?dpDiv.parent()[0]:instActive.input[0])||!elem.length){return}elem.parents(".ui-datepicker-calendar").find("a").removeClass("ui-state-hover");elem.addClass("ui-state-hover");if(elem.hasClass("ui-datepicker-prev")){elem.addClass("ui-datepicker-prev-hover")}if(elem.hasClass("ui-datepicker-next")){elem.addClass("ui-datepicker-next-hover")}})}function extendRemove(target,props){$.extend(target,props);for(var name in props){if(props[name]==null||props[name]==undefined){target[name]=props[name]}}return target}function isArray(a){return(a&&(($.browser.safari&&typeof a=="object"&&a.length)||(a.constructor&&a.constructor.toString().match(/\Array\(\)/))))}$.fn.datepicker=function(options){if(!this.length){return this}if(!$.datepicker.initialized){$(document).mousedown($.datepicker._checkExternalClick).find("body").append($.datepicker.dpDiv);$.datepicker.initialized=true}var otherArgs=Array.prototype.slice.call(arguments,1);if(typeof options=="string"&&(options=="isDisabled"||options=="getDate"||options=="widget")){return $.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this[0]].concat(otherArgs))}if(options=="option"&&arguments.length==2&&typeof arguments[1]=="string"){return $.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this[0]].concat(otherArgs))}return this.each(function(){typeof options=="string"?$.datepicker["_"+options+"Datepicker"].apply($.datepicker,[this].concat(otherArgs)):$.datepicker._attachDatepicker(this,options)})};$.datepicker=new Datepicker();$.datepicker.initialized=false;$.datepicker.uuid=new Date().getTime();$.datepicker.version="1.8.24";window["DP_jQuery_"+dpuuid]=$})(jQuery);(function(d,e){var b="ui-dialog ui-widget ui-widget-content ui-corner-all ",a={buttons:true,height:true,maxHeight:true,maxWidth:true,minHeight:true,minWidth:true,width:true},c={maxHeight:true,maxWidth:true,minHeight:true,minWidth:true};d.widget("ui.dialog",{options:{autoOpen:true,buttons:{},closeOnEscape:true,closeText:"close",dialogClass:"",draggable:true,hide:null,height:"auto",maxHeight:false,maxWidth:false,minHeight:150,minWidth:150,modal:false,position:{my:"center",at:"center",collision:"fit",using:function(g){var f=d(this).css(g).offset().top;if(f<0){d(this).css("top",g.top-f)}}},resizable:true,show:null,stack:true,title:"",width:300,zIndex:1000},_create:function(){this.originalTitle=this.element.attr("title");if(typeof this.originalTitle!=="string"){this.originalTitle=""}this.options.title=this.options.title||this.originalTitle;var n=this,o=n.options,l=o.title||"&#160;",g=d.ui.dialog.getTitleId(n.element),m=(n.uiDialog=d("<div></div>")).appendTo(document.body).hide().addClass(b+o.dialogClass).css({zIndex:o.zIndex}).attr("tabIndex",-1).css("outline",0).keydown(function(p){if(o.closeOnEscape&&!p.isDefaultPrevented()&&p.keyCode&&p.keyCode===d.ui.keyCode.ESCAPE){n.close(p);p.preventDefault()}}).attr({role:"dialog","aria-labelledby":g}).mousedown(function(p){n.moveToTop(false,p)}),i=n.element.show().removeAttr("title").addClass("ui-dialog-content ui-widget-content").appendTo(m),h=(n.uiDialogTitlebar=d("<div></div>")).addClass("ui-dialog-titlebar ui-widget-header ui-corner-all ui-helper-clearfix").prependTo(m),k=d('<a href="#"></a>').addClass("ui-dialog-titlebar-close ui-corner-all").attr("role","button").hover(function(){k.addClass("ui-state-hover")},function(){k.removeClass("ui-state-hover")}).focus(function(){k.addClass("ui-state-focus")}).blur(function(){k.removeClass("ui-state-focus")}).click(function(p){n.close(p);return false}).appendTo(h),j=(n.uiDialogTitlebarCloseText=d("<span></span>")).addClass("ui-icon ui-icon-closethick").text(o.closeText).appendTo(k),f=d("<span></span>").addClass("ui-dialog-title").attr("id",g).html(l).prependTo(h);if(d.isFunction(o.beforeclose)&&!d.isFunction(o.beforeClose)){o.beforeClose=o.beforeclose}h.find("*").add(h).disableSelection();if(o.draggable&&d.fn.draggable){n._makeDraggable()}if(o.resizable&&d.fn.resizable){n._makeResizable()}n._createButtons(o.buttons);n._isOpen=false;if(d.fn.bgiframe){m.bgiframe()}},_init:function(){if(this.options.autoOpen){this.open()}},destroy:function(){var f=this;if(f.overlay){f.overlay.destroy()}f.uiDialog.hide();f.element.unbind(".dialog").removeData("dialog").removeClass("ui-dialog-content ui-widget-content").hide().appendTo("body");f.uiDialog.remove();if(f.originalTitle){f.element.attr("title",f.originalTitle)}return f},widget:function(){return this.uiDialog},close:function(i){var f=this,h,g;if(false===f._trigger("beforeClose",i)){return}if(f.overlay){f.overlay.destroy()}f.uiDialog.unbind("keypress.ui-dialog");f._isOpen=false;if(f.options.hide){f.uiDialog.hide(f.options.hide,function(){f._trigger("close",i)})}else{f.uiDialog.hide();f._trigger("close",i)}d.ui.dialog.overlay.resize();if(f.options.modal){h=0;d(".ui-dialog").each(function(){if(this!==f.uiDialog[0]){g=d(this).css("z-index");if(!isNaN(g)){h=Math.max(h,g)}}});d.ui.dialog.maxZ=h}return f},isOpen:function(){return this._isOpen},moveToTop:function(j,i){var f=this,h=f.options,g;if((h.modal&&!j)||(!h.stack&&!h.modal)){return f._trigger("focus",i)}if(h.zIndex>d.ui.dialog.maxZ){d.ui.dialog.maxZ=h.zIndex}if(f.overlay){d.ui.dialog.maxZ+=1;f.overlay.$el.css("z-index",d.ui.dialog.overlay.maxZ=d.ui.dialog.maxZ)}g={scrollTop:f.element.scrollTop(),scrollLeft:f.element.scrollLeft()};d.ui.dialog.maxZ+=1;f.uiDialog.css("z-index",d.ui.dialog.maxZ);f.element.attr(g);f._trigger("focus",i);return f},open:function(){if(this._isOpen){return}var g=this,h=g.options,f=g.uiDialog;g.overlay=h.modal?new d.ui.dialog.overlay(g):null;g._size();g._position(h.position);f.show(h.show);g.moveToTop(true);if(h.modal){f.bind("keydown.ui-dialog",function(k){if(k.keyCode!==d.ui.keyCode.TAB){return}var j=d(":tabbable",this),l=j.filter(":first"),i=j.filter(":last");if(k.target===i[0]&&!k.shiftKey){l.focus(1);return false}else{if(k.target===l[0]&&k.shiftKey){i.focus(1);return false}}})}d(g.element.find(":tabbable").get().concat(f.find(".ui-dialog-buttonpane :tabbable").get().concat(f.get()))).eq(0).focus();g._isOpen=true;g._trigger("open");return g},_createButtons:function(i){var h=this,f=false,g=d("<div></div>").addClass("ui-dialog-buttonpane ui-widget-content ui-helper-clearfix"),j=d("<div></div>").addClass("ui-dialog-buttonset").appendTo(g);h.uiDialog.find(".ui-dialog-buttonpane").remove();if(typeof i==="object"&&i!==null){d.each(i,function(){return !(f=true)})}if(f){d.each(i,function(k,m){m=d.isFunction(m)?{click:m,text:k}:m;var l=d('<button type="button"></button>').click(function(){m.click.apply(h.element[0],arguments)}).appendTo(j);d.each(m,function(n,o){if(n==="click"){return}if(n in l){l[n](o)}else{l.attr(n,o)}});if(d.fn.button){l.button()}});g.appendTo(h.uiDialog)}},_makeDraggable:function(){var f=this,i=f.options,j=d(document),h;function g(k){return{position:k.position,offset:k.offset}}f.uiDialog.draggable({cancel:".ui-dialog-content, .ui-dialog-titlebar-close",handle:".ui-dialog-titlebar",containment:"document",start:function(k,l){h=i.height==="auto"?"auto":d(this).height();d(this).height(d(this).height()).addClass("ui-dialog-dragging");f._trigger("dragStart",k,g(l))},drag:function(k,l){f._trigger("drag",k,g(l))},stop:function(k,l){i.position=[l.position.left-j.scrollLeft(),l.position.top-j.scrollTop()];d(this).removeClass("ui-dialog-dragging").height(h);f._trigger("dragStop",k,g(l));d.ui.dialog.overlay.resize()}})},_makeResizable:function(k){k=(k===e?this.options.resizable:k);var g=this,j=g.options,f=g.uiDialog.css("position"),i=(typeof k==="string"?k:"n,e,s,w,se,sw,ne,nw");function h(l){return{originalPosition:l.originalPosition,originalSize:l.originalSize,position:l.position,size:l.size}}g.uiDialog.resizable({cancel:".ui-dialog-content",containment:"document",alsoResize:g.element,maxWidth:j.maxWidth,maxHeight:j.maxHeight,minWidth:j.minWidth,minHeight:g._minHeight(),handles:i,start:function(l,m){d(this).addClass("ui-dialog-resizing");g._trigger("resizeStart",l,h(m))},resize:function(l,m){g._trigger("resize",l,h(m))},stop:function(l,m){d(this).removeClass("ui-dialog-resizing");j.height=d(this).height();j.width=d(this).width();g._trigger("resizeStop",l,h(m));d.ui.dialog.overlay.resize()}}).css("position",f).find(".ui-resizable-se").addClass("ui-icon ui-icon-grip-diagonal-se")},_minHeight:function(){var f=this.options;if(f.height==="auto"){return f.minHeight}else{return Math.min(f.minHeight,f.height)}},_position:function(g){var h=[],i=[0,0],f;if(g){if(typeof g==="string"||(typeof g==="object"&&"0" in g)){h=g.split?g.split(" "):[g[0],g[1]];if(h.length===1){h[1]=h[0]}d.each(["left","top"],function(k,j){if(+h[k]===h[k]){i[k]=h[k];h[k]=j}});g={my:h.join(" "),at:h.join(" "),offset:i.join(" ")}}g=d.extend({},d.ui.dialog.prototype.options.position,g)}else{g=d.ui.dialog.prototype.options.position}f=this.uiDialog.is(":visible");if(!f){this.uiDialog.show()}this.uiDialog.css({top:0,left:0}).position(d.extend({of:window},g));if(!f){this.uiDialog.hide()}},_setOptions:function(i){var g=this,f={},h=false;d.each(i,function(j,k){g._setOption(j,k);if(j in a){h=true}if(j in c){f[j]=k}});if(h){this._size()}if(this.uiDialog.is(":data(resizable)")){this.uiDialog.resizable("option",f)}},_setOption:function(i,j){var g=this,f=g.uiDialog;switch(i){case"beforeclose":i="beforeClose";break;case"buttons":g._createButtons(j);break;case"closeText":g.uiDialogTitlebarCloseText.text(""+j);break;case"dialogClass":f.removeClass(g.options.dialogClass).addClass(b+j);break;case"disabled":if(j){f.addClass("ui-dialog-disabled")}else{f.removeClass("ui-dialog-disabled")}break;case"draggable":var h=f.is(":data(draggable)");if(h&&!j){f.draggable("destroy")}if(!h&&j){g._makeDraggable()}break;case"position":g._position(j);break;case"resizable":var k=f.is(":data(resizable)");if(k&&!j){f.resizable("destroy")}if(k&&typeof j==="string"){f.resizable("option","handles",j)}if(!k&&j!==false){g._makeResizable(j)}break;case"title":d(".ui-dialog-title",g.uiDialogTitlebar).html(""+(j||"&#160;"));break}d.Widget.prototype._setOption.apply(g,arguments)},_size:function(){var j=this.options,g,i,f=this.uiDialog.is(":visible");this.element.show().css({width:"auto",minHeight:0,height:0});if(j.minWidth>j.width){j.width=j.minWidth}g=this.uiDialog.css({height:"auto",width:j.width}).height();i=Math.max(0,j.minHeight-g);if(j.height==="auto"){if(d.support.minHeight){this.element.css({minHeight:i,height:"auto"})}else{this.uiDialog.show();var h=this.element.css("height","auto").height();if(!f){this.uiDialog.hide()}this.element.height(Math.max(h,i))}}else{this.element.height(Math.max(j.height-g,0))}if(this.uiDialog.is(":data(resizable)")){this.uiDialog.resizable("option","minHeight",this._minHeight())}}});d.extend(d.ui.dialog,{version:"1.8.24",uuid:0,maxZ:0,getTitleId:function(f){var g=f.attr("id");if(!g){this.uuid+=1;g=this.uuid}return"ui-dialog-title-"+g},overlay:function(f){this.$el=d.ui.dialog.overlay.create(f)}});d.extend(d.ui.dialog.overlay,{instances:[],oldInstances:[],maxZ:0,events:d.map("focus,mousedown,mouseup,keydown,keypress,click".split(","),function(f){return f+".dialog-overlay"}).join(" "),create:function(g){if(this.instances.length===0){setTimeout(function(){if(d.ui.dialog.overlay.instances.length){d(document).bind(d.ui.dialog.overlay.events,function(h){if(d(h.target).zIndex()<d.ui.dialog.overlay.maxZ){return false}})}},1);d(document).bind("keydown.dialog-overlay",function(h){if(g.options.closeOnEscape&&!h.isDefaultPrevented()&&h.keyCode&&h.keyCode===d.ui.keyCode.ESCAPE){g.close(h);h.preventDefault()}});d(window).bind("resize.dialog-overlay",d.ui.dialog.overlay.resize)}var f=(this.oldInstances.pop()||d("<div></div>").addClass("ui-widget-overlay")).appendTo(document.body).css({width:this.width(),height:this.height()});if(d.fn.bgiframe){f.bgiframe()}this.instances.push(f);return f},destroy:function(f){var g=d.inArray(f,this.instances);if(g!=-1){this.oldInstances.push(this.instances.splice(g,1)[0])}if(this.instances.length===0){d([document,window]).unbind(".dialog-overlay")}f.remove();var h=0;d.each(this.instances,function(){h=Math.max(h,this.css("z-index"))});this.maxZ=h},height:function(){var g,f;if(d.browser.msie&&d.browser.version<7){g=Math.max(document.documentElement.scrollHeight,document.body.scrollHeight);f=Math.max(document.documentElement.offsetHeight,document.body.offsetHeight);if(g<f){return d(window).height()+"px"}else{return g+"px"}}else{return d(document).height()+"px"}},width:function(){var f,g;if(d.browser.msie){f=Math.max(document.documentElement.scrollWidth,document.body.scrollWidth);g=Math.max(document.documentElement.offsetWidth,document.body.offsetWidth);if(f<g){return d(window).width()+"px"}else{return f+"px"}}else{return d(document).width()+"px"}},resize:function(){var f=d([]);d.each(d.ui.dialog.overlay.instances,function(){f=f.add(this)});f.css({width:0,height:0}).css({width:d.ui.dialog.overlay.width(),height:d.ui.dialog.overlay.height()})}});d.extend(d.ui.dialog.overlay.prototype,{destroy:function(){d.ui.dialog.overlay.destroy(this.$el)}})}(jQuery));(function(g,h){g.ui=g.ui||{};var d=/left|center|right/,e=/top|center|bottom/,a="center",f={},b=g.fn.position,c=g.fn.offset;g.fn.position=function(j){if(!j||!j.of){return b.apply(this,arguments)}j=g.extend({},j);var n=g(j.of),m=n[0],p=(j.collision||"flip").split(" "),o=j.offset?j.offset.split(" "):[0,0],l,i,k;if(m.nodeType===9){l=n.width();i=n.height();k={top:0,left:0}}else{if(m.setTimeout){l=n.width();i=n.height();k={top:n.scrollTop(),left:n.scrollLeft()}}else{if(m.preventDefault){j.at="left top";l=i=0;k={top:j.of.pageY,left:j.of.pageX}}else{l=n.outerWidth();i=n.outerHeight();k=n.offset()}}}g.each(["my","at"],function(){var q=(j[this]||"").split(" ");if(q.length===1){q=d.test(q[0])?q.concat([a]):e.test(q[0])?[a].concat(q):[a,a]}q[0]=d.test(q[0])?q[0]:a;q[1]=e.test(q[1])?q[1]:a;j[this]=q});if(p.length===1){p[1]=p[0]}o[0]=parseInt(o[0],10)||0;if(o.length===1){o[1]=o[0]}o[1]=parseInt(o[1],10)||0;if(j.at[0]==="right"){k.left+=l}else{if(j.at[0]===a){k.left+=l/2}}if(j.at[1]==="bottom"){k.top+=i}else{if(j.at[1]===a){k.top+=i/2}}k.left+=o[0];k.top+=o[1];return this.each(function(){var t=g(this),v=t.outerWidth(),s=t.outerHeight(),u=parseInt(g.curCSS(this,"marginLeft",true))||0,r=parseInt(g.curCSS(this,"marginTop",true))||0,x=v+u+(parseInt(g.curCSS(this,"marginRight",true))||0),y=s+r+(parseInt(g.curCSS(this,"marginBottom",true))||0),w=g.extend({},k),q;if(j.my[0]==="right"){w.left-=v}else{if(j.my[0]===a){w.left-=v/2}}if(j.my[1]==="bottom"){w.top-=s}else{if(j.my[1]===a){w.top-=s/2}}if(!f.fractions){w.left=Math.round(w.left);w.top=Math.round(w.top)}q={left:w.left-u,top:w.top-r};g.each(["left","top"],function(A,z){if(g.ui.position[p[A]]){g.ui.position[p[A]][z](w,{targetWidth:l,targetHeight:i,elemWidth:v,elemHeight:s,collisionPosition:q,collisionWidth:x,collisionHeight:y,offset:o,my:j.my,at:j.at})}});if(g.fn.bgiframe){t.bgiframe()}t.offset(g.extend(w,{using:j.using}))})};g.ui.position={fit:{left:function(i,j){var l=g(window),k=j.collisionPosition.left+j.collisionWidth-l.width()-l.scrollLeft();i.left=k>0?i.left-k:Math.max(i.left-j.collisionPosition.left,i.left)},top:function(i,j){var l=g(window),k=j.collisionPosition.top+j.collisionHeight-l.height()-l.scrollTop();i.top=k>0?i.top-k:Math.max(i.top-j.collisionPosition.top,i.top)}},flip:{left:function(j,l){if(l.at[0]===a){return}var n=g(window),m=l.collisionPosition.left+l.collisionWidth-n.width()-n.scrollLeft(),i=l.my[0]==="left"?-l.elemWidth:l.my[0]==="right"?l.elemWidth:0,k=l.at[0]==="left"?l.targetWidth:-l.targetWidth,o=-2*l.offset[0];j.left+=l.collisionPosition.left<0?i+k+o:m>0?i+k+o:0},top:function(j,l){if(l.at[1]===a){return}var n=g(window),m=l.collisionPosition.top+l.collisionHeight-n.height()-n.scrollTop(),i=l.my[1]==="top"?-l.elemHeight:l.my[1]==="bottom"?l.elemHeight:0,k=l.at[1]==="top"?l.targetHeight:-l.targetHeight,o=-2*l.offset[1];j.top+=l.collisionPosition.top<0?i+k+o:m>0?i+k+o:0}}};if(!g.offset.setOffset){g.offset.setOffset=function(m,j){if(/static/.test(g.curCSS(m,"position"))){m.style.position="relative"}var l=g(m),o=l.offset(),i=parseInt(g.curCSS(m,"top",true),10)||0,n=parseInt(g.curCSS(m,"left",true),10)||0,k={top:(j.top-o.top)+i,left:(j.left-o.left)+n};if("using" in j){j.using.call(m,k)}else{l.css(k)}};g.fn.offset=function(i){var j=this[0];if(!j||!j.ownerDocument){return null}if(i){if(g.isFunction(i)){return this.each(function(k){g(this).offset(i.call(this,k,g(this).offset()))})}return this.each(function(){g.offset.setOffset(this,i)})}return c.call(this)}}if(!g.curCSS){g.curCSS=g.css}(function(){var j=document.getElementsByTagName("body")[0],q=document.createElement("div"),n,p,k,o,m;n=document.createElement(j?"div":"body");k={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"};if(j){g.extend(k,{position:"absolute",left:"-1000px",top:"-1000px"})}for(var l in k){n.style[l]=k[l]}n.appendChild(q);p=j||document.documentElement;p.insertBefore(n,p.firstChild);q.style.cssText="position: absolute; left: 10.7432222px; top: 10.432325px; height: 30px; width: 201px;";o=g(q).offset(function(i,r){return r}).offset();n.innerHTML="";p.removeChild(n);m=o.top+o.left+(j?2000:0);f.fractions=m>21&&m<22})()}(jQuery));(function(a,b){a.widget("ui.progressbar",{options:{value:0,max:100},min:0,_create:function(){this.element.addClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").attr({role:"progressbar","aria-valuemin":this.min,"aria-valuemax":this.options.max,"aria-valuenow":this._value()});this.valueDiv=a("<div class='ui-progressbar-value ui-widget-header ui-corner-left'></div>").appendTo(this.element);this.oldValue=this._value();this._refreshValue()},destroy:function(){this.element.removeClass("ui-progressbar ui-widget ui-widget-content ui-corner-all").removeAttr("role").removeAttr("aria-valuemin").removeAttr("aria-valuemax").removeAttr("aria-valuenow");this.valueDiv.remove();a.Widget.prototype.destroy.apply(this,arguments)},value:function(c){if(c===b){return this._value()}this._setOption("value",c);return this},_setOption:function(c,d){if(c==="value"){this.options.value=d;this._refreshValue();if(this._value()===this.options.max){this._trigger("complete")}}a.Widget.prototype._setOption.apply(this,arguments)},_value:function(){var c=this.options.value;if(typeof c!=="number"){c=0}return Math.min(this.options.max,Math.max(this.min,c))},_percentage:function(){return 100*this._value()/this.options.max},_refreshValue:function(){var d=this.value();var c=this._percentage();if(this.oldValue!==d){this.oldValue=d;this._trigger("change")}this.valueDiv.toggle(d>this.min).toggleClass("ui-corner-right",d===this.options.max).width(c.toFixed(0)+"%");this.element.attr("aria-valuenow",d)}});a.extend(a.ui.progressbar,{version:"1.8.24"})})(jQuery);(function(b,c){var a=5;b.widget("ui.slider",b.ui.mouse,{widgetEventPrefix:"slide",options:{animate:false,distance:0,max:100,min:0,orientation:"horizontal",range:false,step:1,value:0,values:null},_create:function(){var e=this,k=this.options,j=this.element.find(".ui-slider-handle").addClass("ui-state-default ui-corner-all"),h="<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>",d=(k.values&&k.values.length)||1,g=[];this._keySliding=false;this._mouseSliding=false;this._animateOff=true;this._handleIndex=null;this._detectOrientation();this._mouseInit();this.element.addClass("ui-slider ui-slider-"+this.orientation+" ui-widget ui-widget-content ui-corner-all"+(k.disabled?" ui-slider-disabled ui-disabled":""));this.range=b([]);if(k.range){if(k.range===true){if(!k.values){k.values=[this._valueMin(),this._valueMin()]}if(k.values.length&&k.values.length!==2){k.values=[k.values[0],k.values[0]]}}this.range=b("<div></div>").appendTo(this.element).addClass("ui-slider-range ui-widget-header"+((k.range==="min"||k.range==="max")?" ui-slider-range-"+k.range:""))}for(var f=j.length;f<d;f+=1){g.push(h)}this.handles=j.add(b(g.join("")).appendTo(e.element));this.handle=this.handles.eq(0);this.handles.add(this.range).filter("a").click(function(i){i.preventDefault()}).hover(function(){if(!k.disabled){b(this).addClass("ui-state-hover")}},function(){b(this).removeClass("ui-state-hover")}).focus(function(){if(!k.disabled){b(".ui-slider .ui-state-focus").removeClass("ui-state-focus");b(this).addClass("ui-state-focus")}else{b(this).blur()}}).blur(function(){b(this).removeClass("ui-state-focus")});this.handles.each(function(l){b(this).data("index.ui-slider-handle",l)});this.handles.keydown(function(o){var l=b(this).data("index.ui-slider-handle"),p,m,i,n;if(e.options.disabled){return}switch(o.keyCode){case b.ui.keyCode.HOME:case b.ui.keyCode.END:case b.ui.keyCode.PAGE_UP:case b.ui.keyCode.PAGE_DOWN:case b.ui.keyCode.UP:case b.ui.keyCode.RIGHT:case b.ui.keyCode.DOWN:case b.ui.keyCode.LEFT:o.preventDefault();if(!e._keySliding){e._keySliding=true;b(this).addClass("ui-state-active");p=e._start(o,l);if(p===false){return}}break}n=e.options.step;if(e.options.values&&e.options.values.length){m=i=e.values(l)}else{m=i=e.value()}switch(o.keyCode){case b.ui.keyCode.HOME:i=e._valueMin();break;case b.ui.keyCode.END:i=e._valueMax();break;case b.ui.keyCode.PAGE_UP:i=e._trimAlignValue(m+((e._valueMax()-e._valueMin())/a));break;case b.ui.keyCode.PAGE_DOWN:i=e._trimAlignValue(m-((e._valueMax()-e._valueMin())/a));break;case b.ui.keyCode.UP:case b.ui.keyCode.RIGHT:if(m===e._valueMax()){return}i=e._trimAlignValue(m+n);break;case b.ui.keyCode.DOWN:case b.ui.keyCode.LEFT:if(m===e._valueMin()){return}i=e._trimAlignValue(m-n);break}e._slide(o,l,i)}).keyup(function(l){var i=b(this).data("index.ui-slider-handle");if(e._keySliding){e._keySliding=false;e._stop(l,i);e._change(l,i);b(this).removeClass("ui-state-active")}});this._refreshValue();this._animateOff=false},destroy:function(){this.handles.remove();this.range.remove();this.element.removeClass("ui-slider ui-slider-horizontal ui-slider-vertical ui-slider-disabled ui-widget ui-widget-content ui-corner-all").removeData("slider").unbind(".slider");this._mouseDestroy();return this},_mouseCapture:function(f){var g=this.options,j,l,e,h,n,k,m,i,d;if(g.disabled){return false}this.elementSize={width:this.element.outerWidth(),height:this.element.outerHeight()};this.elementOffset=this.element.offset();j={x:f.pageX,y:f.pageY};l=this._normValueFromMouse(j);e=this._valueMax()-this._valueMin()+1;n=this;this.handles.each(function(o){var p=Math.abs(l-n.values(o));if(e>p){e=p;h=b(this);k=o}});if(g.range===true&&this.values(1)===g.min){k+=1;h=b(this.handles[k])}m=this._start(f,k);if(m===false){return false}this._mouseSliding=true;n._handleIndex=k;h.addClass("ui-state-active").focus();i=h.offset();d=!b(f.target).parents().andSelf().is(".ui-slider-handle");this._clickOffset=d?{left:0,top:0}:{left:f.pageX-i.left-(h.width()/2),top:f.pageY-i.top-(h.height()/2)-(parseInt(h.css("borderTopWidth"),10)||0)-(parseInt(h.css("borderBottomWidth"),10)||0)+(parseInt(h.css("marginTop"),10)||0)};if(!this.handles.hasClass("ui-state-hover")){this._slide(f,k,l)}this._animateOff=true;return true},_mouseStart:function(d){return true},_mouseDrag:function(f){var d={x:f.pageX,y:f.pageY},e=this._normValueFromMouse(d);this._slide(f,this._handleIndex,e);return false},_mouseStop:function(d){this.handles.removeClass("ui-state-active");this._mouseSliding=false;this._stop(d,this._handleIndex);this._change(d,this._handleIndex);this._handleIndex=null;this._clickOffset=null;this._animateOff=false;return false},_detectOrientation:function(){this.orientation=(this.options.orientation==="vertical")?"vertical":"horizontal"},_normValueFromMouse:function(e){var d,h,g,f,i;if(this.orientation==="horizontal"){d=this.elementSize.width;h=e.x-this.elementOffset.left-(this._clickOffset?this._clickOffset.left:0)}else{d=this.elementSize.height;h=e.y-this.elementOffset.top-(this._clickOffset?this._clickOffset.top:0)}g=(h/d);if(g>1){g=1}if(g<0){g=0}if(this.orientation==="vertical"){g=1-g}f=this._valueMax()-this._valueMin();i=this._valueMin()+g*f;return this._trimAlignValue(i)},_start:function(f,e){var d={handle:this.handles[e],value:this.value()};if(this.options.values&&this.options.values.length){d.value=this.values(e);d.values=this.values()}return this._trigger("start",f,d)},_slide:function(h,g,f){var d,e,i;if(this.options.values&&this.options.values.length){d=this.values(g?0:1);if((this.options.values.length===2&&this.options.range===true)&&((g===0&&f>d)||(g===1&&f<d))){f=d}if(f!==this.values(g)){e=this.values();e[g]=f;i=this._trigger("slide",h,{handle:this.handles[g],value:f,values:e});d=this.values(g?0:1);if(i!==false){this.values(g,f,true)}}}else{if(f!==this.value()){i=this._trigger("slide",h,{handle:this.handles[g],value:f});if(i!==false){this.value(f)}}}},_stop:function(f,e){var d={handle:this.handles[e],value:this.value()};if(this.options.values&&this.options.values.length){d.value=this.values(e);d.values=this.values()}this._trigger("stop",f,d)},_change:function(f,e){if(!this._keySliding&&!this._mouseSliding){var d={handle:this.handles[e],value:this.value()};if(this.options.values&&this.options.values.length){d.value=this.values(e);d.values=this.values()}this._trigger("change",f,d)}},value:function(d){if(arguments.length){this.options.value=this._trimAlignValue(d);this._refreshValue();this._change(null,0);return}return this._value()},values:function(e,h){var g,d,f;if(arguments.length>1){this.options.values[e]=this._trimAlignValue(h);this._refreshValue();this._change(null,e);return}if(arguments.length){if(b.isArray(arguments[0])){g=this.options.values;d=arguments[0];for(f=0;f<g.length;f+=1){g[f]=this._trimAlignValue(d[f]);this._change(null,f)}this._refreshValue()}else{if(this.options.values&&this.options.values.length){return this._values(e)}else{return this.value()}}}else{return this._values()}},_setOption:function(e,f){var d,g=0;if(b.isArray(this.options.values)){g=this.options.values.length}b.Widget.prototype._setOption.apply(this,arguments);switch(e){case"disabled":if(f){this.handles.filter(".ui-state-focus").blur();this.handles.removeClass("ui-state-hover");this.handles.propAttr("disabled",true);this.element.addClass("ui-disabled")}else{this.handles.propAttr("disabled",false);this.element.removeClass("ui-disabled")}break;case"orientation":this._detectOrientation();this.element.removeClass("ui-slider-horizontal ui-slider-vertical").addClass("ui-slider-"+this.orientation);this._refreshValue();break;case"value":this._animateOff=true;this._refreshValue();this._change(null,0);this._animateOff=false;break;case"values":this._animateOff=true;this._refreshValue();for(d=0;d<g;d+=1){this._change(null,d)}this._animateOff=false;break}},_value:function(){var d=this.options.value;d=this._trimAlignValue(d);return d},_values:function(d){var g,f,e;if(arguments.length){g=this.options.values[d];g=this._trimAlignValue(g);return g}else{f=this.options.values.slice();for(e=0;e<f.length;e+=1){f[e]=this._trimAlignValue(f[e])}return f}},_trimAlignValue:function(g){if(g<=this._valueMin()){return this._valueMin()}if(g>=this._valueMax()){return this._valueMax()}var d=(this.options.step>0)?this.options.step:1,f=(g-this._valueMin())%d,e=g-f;if(Math.abs(f)*2>=d){e+=(f>0)?d:(-d)}return parseFloat(e.toFixed(5))},_valueMin:function(){return this.options.min},_valueMax:function(){return this.options.max},_refreshValue:function(){var g=this.options.range,f=this.options,m=this,e=(!this._animateOff)?f.animate:false,h,d={},i,k,j,l;if(this.options.values&&this.options.values.length){this.handles.each(function(o,n){h=(m.values(o)-m._valueMin())/(m._valueMax()-m._valueMin())*100;d[m.orientation==="horizontal"?"left":"bottom"]=h+"%";b(this).stop(1,1)[e?"animate":"css"](d,f.animate);if(m.options.range===true){if(m.orientation==="horizontal"){if(o===0){m.range.stop(1,1)[e?"animate":"css"]({left:h+"%"},f.animate)}if(o===1){m.range[e?"animate":"css"]({width:(h-i)+"%"},{queue:false,duration:f.animate})}}else{if(o===0){m.range.stop(1,1)[e?"animate":"css"]({bottom:(h)+"%"},f.animate)}if(o===1){m.range[e?"animate":"css"]({height:(h-i)+"%"},{queue:false,duration:f.animate})}}}i=h})}else{k=this.value();j=this._valueMin();l=this._valueMax();h=(l!==j)?(k-j)/(l-j)*100:0;d[m.orientation==="horizontal"?"left":"bottom"]=h+"%";this.handle.stop(1,1)[e?"animate":"css"](d,f.animate);if(g==="min"&&this.orientation==="horizontal"){this.range.stop(1,1)[e?"animate":"css"]({width:h+"%"},f.animate)}if(g==="max"&&this.orientation==="horizontal"){this.range[e?"animate":"css"]({width:(100-h)+"%"},{queue:false,duration:f.animate})}if(g==="min"&&this.orientation==="vertical"){this.range.stop(1,1)[e?"animate":"css"]({height:h+"%"},f.animate)}if(g==="max"&&this.orientation==="vertical"){this.range[e?"animate":"css"]({height:(100-h)+"%"},{queue:false,duration:f.animate})}}}});b.extend(b.ui.slider,{version:"1.8.24"})}(jQuery));(function(d,f){var c=0,b=0;function e(){return ++c}function a(){return ++b}d.widget("ui.tabs",{options:{add:null,ajaxOptions:null,cache:false,cookie:null,collapsible:false,disable:null,disabled:[],enable:null,event:"click",fx:null,idPrefix:"ui-tabs-",load:null,panelTemplate:"<div></div>",remove:null,select:null,show:null,spinner:"<em>Loading&#8230;</em>",tabTemplate:"<li><a href='#{href}'><span>#{label}</span></a></li>"},_create:function(){this._tabify(true)},_setOption:function(g,h){if(g=="selected"){if(this.options.collapsible&&h==this.options.selected){return}this.select(h)}else{this.options[g]=h;this._tabify()}},_tabId:function(g){return g.title&&g.title.replace(/\s/g,"_").replace(/[^\w\u00c0-\uFFFF-]/g,"")||this.options.idPrefix+e()},_sanitizeSelector:function(g){return g.replace(/:/g,"\\:")},_cookie:function(){var g=this.cookie||(this.cookie=this.options.cookie.name||"ui-tabs-"+a());return d.cookie.apply(null,[g].concat(d.makeArray(arguments)))},_ui:function(h,g){return{tab:h,panel:g,index:this.anchors.index(h)}},_cleanup:function(){this.lis.filter(".ui-state-processing").removeClass("ui-state-processing").find("span:data(label.tabs)").each(function(){var g=d(this);g.html(g.data("label.tabs")).removeData("label.tabs")})},_tabify:function(t){var u=this,j=this.options,h=/^#.+/;this.list=this.element.find("ol,ul").eq(0);this.lis=d(" > li:has(a[href])",this.list);this.anchors=this.lis.map(function(){return d("a",this)[0]});this.panels=d([]);this.anchors.each(function(w,o){var v=d(o).attr("href");var x=v.split("#")[0],y;if(x&&(x===location.toString().split("#")[0]||(y=d("base")[0])&&x===y.href)){v=o.hash;o.href=v}if(h.test(v)){u.panels=u.panels.add(u.element.find(u._sanitizeSelector(v)))}else{if(v&&v!=="#"){d.data(o,"href.tabs",v);d.data(o,"load.tabs",v.replace(/#.*$/,""));var A=u._tabId(o);o.href="#"+A;var z=u.element.find("#"+A);if(!z.length){z=d(j.panelTemplate).attr("id",A).addClass("ui-tabs-panel ui-widget-content ui-corner-bottom").insertAfter(u.panels[w-1]||u.list);z.data("destroy.tabs",true)}u.panels=u.panels.add(z)}else{j.disabled.push(w)}}});if(t){this.element.addClass("ui-tabs ui-widget ui-widget-content ui-corner-all");this.list.addClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.lis.addClass("ui-state-default ui-corner-top");this.panels.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom");if(j.selected===f){if(location.hash){this.anchors.each(function(v,o){if(o.hash==location.hash){j.selected=v;return false}})}if(typeof j.selected!=="number"&&j.cookie){j.selected=parseInt(u._cookie(),10)}if(typeof j.selected!=="number"&&this.lis.filter(".ui-tabs-selected").length){j.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))}j.selected=j.selected||(this.lis.length?0:-1)}else{if(j.selected===null){j.selected=-1}}j.selected=((j.selected>=0&&this.anchors[j.selected])||j.selected<0)?j.selected:0;j.disabled=d.unique(j.disabled.concat(d.map(this.lis.filter(".ui-state-disabled"),function(v,o){return u.lis.index(v)}))).sort();if(d.inArray(j.selected,j.disabled)!=-1){j.disabled.splice(d.inArray(j.selected,j.disabled),1)}this.panels.addClass("ui-tabs-hide");this.lis.removeClass("ui-tabs-selected ui-state-active");if(j.selected>=0&&this.anchors.length){u.element.find(u._sanitizeSelector(u.anchors[j.selected].hash)).removeClass("ui-tabs-hide");this.lis.eq(j.selected).addClass("ui-tabs-selected ui-state-active");u.element.queue("tabs",function(){u._trigger("show",null,u._ui(u.anchors[j.selected],u.element.find(u._sanitizeSelector(u.anchors[j.selected].hash))[0]))});this.load(j.selected)}d(window).bind("unload",function(){u.lis.add(u.anchors).unbind(".tabs");u.lis=u.anchors=u.panels=null})}else{j.selected=this.lis.index(this.lis.filter(".ui-tabs-selected"))}this.element[j.collapsible?"addClass":"removeClass"]("ui-tabs-collapsible");if(j.cookie){this._cookie(j.selected,j.cookie)}for(var m=0,s;(s=this.lis[m]);m++){d(s)[d.inArray(m,j.disabled)!=-1&&!d(s).hasClass("ui-tabs-selected")?"addClass":"removeClass"]("ui-state-disabled")}if(j.cache===false){this.anchors.removeData("cache.tabs")}this.lis.add(this.anchors).unbind(".tabs");if(j.event!=="mouseover"){var l=function(o,i){if(i.is(":not(.ui-state-disabled)")){i.addClass("ui-state-"+o)}};var p=function(o,i){i.removeClass("ui-state-"+o)};this.lis.bind("mouseover.tabs",function(){l("hover",d(this))});this.lis.bind("mouseout.tabs",function(){p("hover",d(this))});this.anchors.bind("focus.tabs",function(){l("focus",d(this).closest("li"))});this.anchors.bind("blur.tabs",function(){p("focus",d(this).closest("li"))})}var g,n;if(j.fx){if(d.isArray(j.fx)){g=j.fx[0];n=j.fx[1]}else{g=n=j.fx}}function k(i,o){i.css("display","");if(!d.support.opacity&&o.opacity){i[0].style.removeAttribute("filter")}}var q=n?function(i,o){d(i).closest("li").addClass("ui-tabs-selected ui-state-active");o.hide().removeClass("ui-tabs-hide").animate(n,n.duration||"normal",function(){k(o,n);u._trigger("show",null,u._ui(i,o[0]))})}:function(i,o){d(i).closest("li").addClass("ui-tabs-selected ui-state-active");o.removeClass("ui-tabs-hide");u._trigger("show",null,u._ui(i,o[0]))};var r=g?function(o,i){i.animate(g,g.duration||"normal",function(){u.lis.removeClass("ui-tabs-selected ui-state-active");i.addClass("ui-tabs-hide");k(i,g);u.element.dequeue("tabs")})}:function(o,i,v){u.lis.removeClass("ui-tabs-selected ui-state-active");i.addClass("ui-tabs-hide");u.element.dequeue("tabs")};this.anchors.bind(j.event+".tabs",function(){var o=this,w=d(o).closest("li"),i=u.panels.filter(":not(.ui-tabs-hide)"),v=u.element.find(u._sanitizeSelector(o.hash));if((w.hasClass("ui-tabs-selected")&&!j.collapsible)||w.hasClass("ui-state-disabled")||w.hasClass("ui-state-processing")||u.panels.filter(":animated").length||u._trigger("select",null,u._ui(this,v[0]))===false){this.blur();return false}j.selected=u.anchors.index(this);u.abort();if(j.collapsible){if(w.hasClass("ui-tabs-selected")){j.selected=-1;if(j.cookie){u._cookie(j.selected,j.cookie)}u.element.queue("tabs",function(){r(o,i)}).dequeue("tabs");this.blur();return false}else{if(!i.length){if(j.cookie){u._cookie(j.selected,j.cookie)}u.element.queue("tabs",function(){q(o,v)});u.load(u.anchors.index(this));this.blur();return false}}}if(j.cookie){u._cookie(j.selected,j.cookie)}if(v.length){if(i.length){u.element.queue("tabs",function(){r(o,i)})}u.element.queue("tabs",function(){q(o,v)});u.load(u.anchors.index(this))}else{throw"jQuery UI Tabs: Mismatching fragment identifier."}if(d.browser.msie){this.blur()}});this.anchors.bind("click.tabs",function(){return false})},_getIndex:function(g){if(typeof g=="string"){g=this.anchors.index(this.anchors.filter("[href$='"+g+"']"))}return g},destroy:function(){var g=this.options;this.abort();this.element.unbind(".tabs").removeClass("ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible").removeData("tabs");this.list.removeClass("ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all");this.anchors.each(function(){var h=d.data(this,"href.tabs");if(h){this.href=h}var i=d(this).unbind(".tabs");d.each(["href","load","cache"],function(j,k){i.removeData(k+".tabs")})});this.lis.unbind(".tabs").add(this.panels).each(function(){if(d.data(this,"destroy.tabs")){d(this).remove()}else{d(this).removeClass(["ui-state-default","ui-corner-top","ui-tabs-selected","ui-state-active","ui-state-hover","ui-state-focus","ui-state-disabled","ui-tabs-panel","ui-widget-content","ui-corner-bottom","ui-tabs-hide"].join(" "))}});if(g.cookie){this._cookie(null,g.cookie)}return this},add:function(j,i,h){if(h===f){h=this.anchors.length}var g=this,l=this.options,n=d(l.tabTemplate.replace(/#\{href\}/g,j).replace(/#\{label\}/g,i)),m=!j.indexOf("#")?j.replace("#",""):this._tabId(d("a",n)[0]);n.addClass("ui-state-default ui-corner-top").data("destroy.tabs",true);var k=g.element.find("#"+m);if(!k.length){k=d(l.panelTemplate).attr("id",m).data("destroy.tabs",true)}k.addClass("ui-tabs-panel ui-widget-content ui-corner-bottom ui-tabs-hide");if(h>=this.lis.length){n.appendTo(this.list);k.appendTo(this.list[0].parentNode)}else{n.insertBefore(this.lis[h]);k.insertBefore(this.panels[h])}l.disabled=d.map(l.disabled,function(p,o){return p>=h?++p:p});this._tabify();if(this.anchors.length==1){l.selected=0;n.addClass("ui-tabs-selected ui-state-active");k.removeClass("ui-tabs-hide");this.element.queue("tabs",function(){g._trigger("show",null,g._ui(g.anchors[0],g.panels[0]))});this.load(0)}this._trigger("add",null,this._ui(this.anchors[h],this.panels[h]));return this},remove:function(g){g=this._getIndex(g);var i=this.options,j=this.lis.eq(g).remove(),h=this.panels.eq(g).remove();if(j.hasClass("ui-tabs-selected")&&this.anchors.length>1){this.select(g+(g+1<this.anchors.length?1:-1))}i.disabled=d.map(d.grep(i.disabled,function(l,k){return l!=g}),function(l,k){return l>=g?--l:l});this._tabify();this._trigger("remove",null,this._ui(j.find("a")[0],h[0]));return this},enable:function(g){g=this._getIndex(g);var h=this.options;if(d.inArray(g,h.disabled)==-1){return}this.lis.eq(g).removeClass("ui-state-disabled");h.disabled=d.grep(h.disabled,function(k,j){return k!=g});this._trigger("enable",null,this._ui(this.anchors[g],this.panels[g]));return this},disable:function(h){h=this._getIndex(h);var g=this,i=this.options;if(h!=i.selected){this.lis.eq(h).addClass("ui-state-disabled");i.disabled.push(h);i.disabled.sort();this._trigger("disable",null,this._ui(this.anchors[h],this.panels[h]))}return this},select:function(g){g=this._getIndex(g);if(g==-1){if(this.options.collapsible&&this.options.selected!=-1){g=this.options.selected}else{return this}}this.anchors.eq(g).trigger(this.options.event+".tabs");return this},load:function(j){j=this._getIndex(j);var h=this,l=this.options,g=this.anchors.eq(j)[0],i=d.data(g,"load.tabs");this.abort();if(!i||this.element.queue("tabs").length!==0&&d.data(g,"cache.tabs")){this.element.dequeue("tabs");return}this.lis.eq(j).addClass("ui-state-processing");if(l.spinner){var k=d("span",g);k.data("label.tabs",k.html()).html(l.spinner)}this.xhr=d.ajax(d.extend({},l.ajaxOptions,{url:i,success:function(n,m){h.element.find(h._sanitizeSelector(g.hash)).html(n);h._cleanup();if(l.cache){d.data(g,"cache.tabs",true)}h._trigger("load",null,h._ui(h.anchors[j],h.panels[j]));try{l.ajaxOptions.success(n,m)}catch(o){}},error:function(o,m,n){h._cleanup();h._trigger("load",null,h._ui(h.anchors[j],h.panels[j]));try{l.ajaxOptions.error(o,m,j,g)}catch(n){}}}));h.element.dequeue("tabs");return this},abort:function(){this.element.queue([]);this.panels.stop(false,true);this.element.queue("tabs",this.element.queue("tabs").splice(-2,2));if(this.xhr){this.xhr.abort();delete this.xhr}this._cleanup();return this},url:function(h,g){this.anchors.eq(h).removeData("cache.tabs").data("load.tabs",g);return this},length:function(){return this.anchors.length}});d.extend(d.ui.tabs,{version:"1.8.24"});d.extend(d.ui.tabs.prototype,{rotation:null,rotate:function(i,k){var g=this,l=this.options;var h=g._rotate||(g._rotate=function(m){clearTimeout(g.rotation);g.rotation=setTimeout(function(){var n=l.selected;g.select(++n<g.anchors.length?n:0)},i);if(m){m.stopPropagation()}});var j=g._unrotate||(g._unrotate=!k?function(m){if(m.clientX){g.rotate(null)}}:function(m){h()});if(i){this.element.bind("tabsshow",h);this.anchors.bind(l.event+".tabs",j);h()}else{clearTimeout(g.rotation);this.element.unbind("tabsshow",h);this.anchors.unbind(l.event+".tabs",j);delete this._rotate;delete this._unrotate}return this}})})(jQuery); /* * jQuery UI Draggable 1.8.24 * * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Draggables * * Depends: * jquery.ui.core.js * jquery.ui.mouse.js * jquery.ui.widget.js */ (function(a,b){a.widget("ui.draggable",a.ui.mouse,{widgetEventPrefix:"drag",options:{addClasses:true,appendTo:"parent",axis:false,connectToSortable:false,containment:false,cursor:"auto",cursorAt:false,grid:false,handle:false,helper:"original",iframeFix:false,opacity:false,refreshPositions:false,revert:false,revertDuration:500,scope:"default",scroll:true,scrollSensitivity:20,scrollSpeed:20,snap:false,snapMode:"both",snapTolerance:20,stack:false,zIndex:false},_create:function(){if(this.options.helper=="original"&&!(/^(?:r|a|f)/).test(this.element.css("position"))){this.element[0].style.position="relative"}(this.options.addClasses&&this.element.addClass("ui-draggable"));(this.options.disabled&&this.element.addClass("ui-draggable-disabled"));this._mouseInit()},destroy:function(){if(!this.element.data("draggable")){return}this.element.removeData("draggable").unbind(".draggable").removeClass("ui-draggable ui-draggable-dragging ui-draggable-disabled");this._mouseDestroy();return this},_mouseCapture:function(c){var d=this.options;if(this.helper||d.disabled||a(c.target).is(".ui-resizable-handle")){return false}this.handle=this._getHandle(c);if(!this.handle){return false}if(d.iframeFix){a(d.iframeFix===true?"iframe":d.iframeFix).each(function(){a('<div class="ui-draggable-iframeFix" style="background: #fff;"></div>').css({width:this.offsetWidth+"px",height:this.offsetHeight+"px",position:"absolute",opacity:"0.001",zIndex:1000}).css(a(this).offset()).appendTo("body")})}return true},_mouseStart:function(c){var d=this.options;this.helper=this._createHelper(c);this.helper.addClass("ui-draggable-dragging");this._cacheHelperProportions();if(a.ui.ddmanager){a.ui.ddmanager.current=this}this._cacheMargins();this.cssPosition=this.helper.css("position");this.scrollParent=this.helper.scrollParent();this.offset=this.positionAbs=this.element.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};a.extend(this.offset,{click:{left:c.pageX-this.offset.left,top:c.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.originalPosition=this.position=this._generatePosition(c);this.originalPageX=c.pageX;this.originalPageY=c.pageY;(d.cursorAt&&this._adjustOffsetFromHelper(d.cursorAt));if(d.containment){this._setContainment()}if(this._trigger("start",c)===false){this._clear();return false}this._cacheHelperProportions();if(a.ui.ddmanager&&!d.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,c)}this._mouseDrag(c,true);if(a.ui.ddmanager){a.ui.ddmanager.dragStart(this,c)}return true},_mouseDrag:function(c,e){this.position=this._generatePosition(c);this.positionAbs=this._convertPositionTo("absolute");if(!e){var d=this._uiHash();if(this._trigger("drag",c,d)===false){this._mouseUp({});return false}this.position=d.position}if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}if(a.ui.ddmanager){a.ui.ddmanager.drag(this,c)}return false},_mouseStop:function(e){var g=false;if(a.ui.ddmanager&&!this.options.dropBehaviour){g=a.ui.ddmanager.drop(this,e)}if(this.dropped){g=this.dropped;this.dropped=false}var d=this.element[0],f=false;while(d&&(d=d.parentNode)){if(d==document){f=true}}if(!f&&this.options.helper==="original"){return false}if((this.options.revert=="invalid"&&!g)||(this.options.revert=="valid"&&g)||this.options.revert===true||(a.isFunction(this.options.revert)&&this.options.revert.call(this.element,g))){var c=this;a(this.helper).animate(this.originalPosition,parseInt(this.options.revertDuration,10),function(){if(c._trigger("stop",e)!==false){c._clear()}})}else{if(this._trigger("stop",e)!==false){this._clear()}}return false},_mouseUp:function(c){a("div.ui-draggable-iframeFix").each(function(){this.parentNode.removeChild(this)});if(a.ui.ddmanager){a.ui.ddmanager.dragStop(this,c)}return a.ui.mouse.prototype._mouseUp.call(this,c)},cancel:function(){if(this.helper.is(".ui-draggable-dragging")){this._mouseUp({})}else{this._clear()}return this},_getHandle:function(c){var d=!this.options.handle||!a(this.options.handle,this.element).length?true:false;a(this.options.handle,this.element).find("*").andSelf().each(function(){if(this==c.target){d=true}});return d},_createHelper:function(d){var e=this.options;var c=a.isFunction(e.helper)?a(e.helper.apply(this.element[0],[d])):(e.helper=="clone"?this.element.clone().removeAttr("id"):this.element);if(!c.parents("body").length){c.appendTo((e.appendTo=="parent"?this.element[0].parentNode:e.appendTo))}if(c[0]!=this.element[0]&&!(/(fixed|absolute)/).test(c.css("position"))){c.css("position","absolute")}return c},_adjustOffsetFromHelper:function(c){if(typeof c=="string"){c=c.split(" ")}if(a.isArray(c)){c={left:+c[0],top:+c[1]||0}}if("left" in c){this.offset.click.left=c.left+this.margins.left}if("right" in c){this.offset.click.left=this.helperProportions.width-c.right+this.margins.left}if("top" in c){this.offset.click.top=c.top+this.margins.top}if("bottom" in c){this.offset.click.top=this.helperProportions.height-c.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var c=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){c.left+=this.scrollParent.scrollLeft();c.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){c={top:0,left:0}}return{top:c.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:c.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var c=this.element.position();return{top:c.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:c.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.element.css("marginLeft"),10)||0),top:(parseInt(this.element.css("marginTop"),10)||0),right:(parseInt(this.element.css("marginRight"),10)||0),bottom:(parseInt(this.element.css("marginBottom"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var g=this.options;if(g.containment=="parent"){g.containment=this.helper[0].parentNode}if(g.containment=="document"||g.containment=="window"){this.containment=[g.containment=="document"?0:a(window).scrollLeft()-this.offset.relative.left-this.offset.parent.left,g.containment=="document"?0:a(window).scrollTop()-this.offset.relative.top-this.offset.parent.top,(g.containment=="document"?0:a(window).scrollLeft())+a(g.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(g.containment=="document"?0:a(window).scrollTop())+(a(g.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(g.containment)&&g.containment.constructor!=Array){var h=a(g.containment);var e=h[0];if(!e){return}var f=h.offset();var d=(a(e).css("overflow")!="hidden");this.containment=[(parseInt(a(e).css("borderLeftWidth"),10)||0)+(parseInt(a(e).css("paddingLeft"),10)||0),(parseInt(a(e).css("borderTopWidth"),10)||0)+(parseInt(a(e).css("paddingTop"),10)||0),(d?Math.max(e.scrollWidth,e.offsetWidth):e.offsetWidth)-(parseInt(a(e).css("borderLeftWidth"),10)||0)-(parseInt(a(e).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left-this.margins.right,(d?Math.max(e.scrollHeight,e.offsetHeight):e.offsetHeight)-(parseInt(a(e).css("borderTopWidth"),10)||0)-(parseInt(a(e).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top-this.margins.bottom];this.relative_container=h}else{if(g.containment.constructor==Array){this.containment=g.containment}}},_convertPositionTo:function(g,i){if(!i){i=this.position}var e=g=="absolute"?1:-1;var f=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,h=(/(html|body)/i).test(c[0].tagName);return{top:(i.top+this.offset.relative.top*e+this.offset.parent.top*e-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(h?0:c.scrollTop()))*e)),left:(i.left+this.offset.relative.left*e+this.offset.parent.left*e-(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():h?0:c.scrollLeft())*e))}},_generatePosition:function(d){var e=this.options,l=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,i=(/(html|body)/i).test(l[0].tagName);var h=d.pageX;var g=d.pageY;if(this.originalPosition){var c;if(this.containment){if(this.relative_container){var k=this.relative_container.offset();c=[this.containment[0]+k.left,this.containment[1]+k.top,this.containment[2]+k.left,this.containment[3]+k.top]}else{c=this.containment}if(d.pageX-this.offset.click.left<c[0]){h=c[0]+this.offset.click.left}if(d.pageY-this.offset.click.top<c[1]){g=c[1]+this.offset.click.top}if(d.pageX-this.offset.click.left>c[2]){h=c[2]+this.offset.click.left}if(d.pageY-this.offset.click.top>c[3]){g=c[3]+this.offset.click.top}}if(e.grid){var j=e.grid[1]?this.originalPageY+Math.round((g-this.originalPageY)/e.grid[1])*e.grid[1]:this.originalPageY;g=c?(!(j-this.offset.click.top<c[1]||j-this.offset.click.top>c[3])?j:(!(j-this.offset.click.top<c[1])?j-e.grid[1]:j+e.grid[1])):j;var f=e.grid[0]?this.originalPageX+Math.round((h-this.originalPageX)/e.grid[0])*e.grid[0]:this.originalPageX;h=c?(!(f-this.offset.click.left<c[0]||f-this.offset.click.left>c[2])?f:(!(f-this.offset.click.left<c[0])?f-e.grid[0]:f+e.grid[0])):f}}return{top:(g-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(i?0:l.scrollTop())))),left:(h-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&a.browser.version<526&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():i?0:l.scrollLeft())))}},_clear:function(){this.helper.removeClass("ui-draggable-dragging");if(this.helper[0]!=this.element[0]&&!this.cancelHelperRemoval){this.helper.remove()}this.helper=null;this.cancelHelperRemoval=false},_trigger:function(c,d,e){e=e||this._uiHash();a.ui.plugin.call(this,c,[d,e]);if(c=="drag"){this.positionAbs=this._convertPositionTo("absolute")}return a.Widget.prototype._trigger.call(this,c,d,e)},plugins:{},_uiHash:function(c){return{helper:this.helper,position:this.position,originalPosition:this.originalPosition,offset:this.positionAbs}}});a.extend(a.ui.draggable,{version:"1.8.24"});a.ui.plugin.add("draggable","connectToSortable",{start:function(d,f){var e=a(this).data("draggable"),g=e.options,c=a.extend({},f,{item:e.element});e.sortables=[];a(g.connectToSortable).each(function(){var h=a.data(this,"sortable");if(h&&!h.options.disabled){e.sortables.push({instance:h,shouldRevert:h.options.revert});h.refreshPositions();h._trigger("activate",d,c)}})},stop:function(d,f){var e=a(this).data("draggable"),c=a.extend({},f,{item:e.element});a.each(e.sortables,function(){if(this.instance.isOver){this.instance.isOver=0;e.cancelHelperRemoval=true;this.instance.cancelHelperRemoval=false;if(this.shouldRevert){this.instance.options.revert=true}this.instance._mouseStop(d);this.instance.options.helper=this.instance.options._helper;if(e.options.helper=="original"){this.instance.currentItem.css({top:"auto",left:"auto"})}}else{this.instance.cancelHelperRemoval=false;this.instance._trigger("deactivate",d,c)}})},drag:function(d,g){var f=a(this).data("draggable"),c=this;var e=function(j){var p=this.offset.click.top,n=this.offset.click.left;var h=this.positionAbs.top,l=this.positionAbs.left;var k=j.height,m=j.width;var q=j.top,i=j.left;return a.ui.isOver(h+p,l+n,q,i,k,m)};a.each(f.sortables,function(h){this.instance.positionAbs=f.positionAbs;this.instance.helperProportions=f.helperProportions;this.instance.offset.click=f.offset.click;if(this.instance._intersectsWith(this.instance.containerCache)){if(!this.instance.isOver){this.instance.isOver=1;this.instance.currentItem=a(c).clone().removeAttr("id").appendTo(this.instance.element).data("sortable-item",true);this.instance.options._helper=this.instance.options.helper;this.instance.options.helper=function(){return g.helper[0]};d.target=this.instance.currentItem[0];this.instance._mouseCapture(d,true);this.instance._mouseStart(d,true,true);this.instance.offset.click.top=f.offset.click.top;this.instance.offset.click.left=f.offset.click.left;this.instance.offset.parent.left-=f.offset.parent.left-this.instance.offset.parent.left;this.instance.offset.parent.top-=f.offset.parent.top-this.instance.offset.parent.top;f._trigger("toSortable",d);f.dropped=this.instance.element;f.currentItem=f.element;this.instance.fromOutside=f}if(this.instance.currentItem){this.instance._mouseDrag(d)}}else{if(this.instance.isOver){this.instance.isOver=0;this.instance.cancelHelperRemoval=true;this.instance.options.revert=false;this.instance._trigger("out",d,this.instance._uiHash(this.instance));this.instance._mouseStop(d,true);this.instance.options.helper=this.instance.options._helper;this.instance.currentItem.remove();if(this.instance.placeholder){this.instance.placeholder.remove()}f._trigger("fromSortable",d);f.dropped=false}}})}});a.ui.plugin.add("draggable","cursor",{start:function(d,e){var c=a("body"),f=a(this).data("draggable").options;if(c.css("cursor")){f._cursor=c.css("cursor")}c.css("cursor",f.cursor)},stop:function(c,d){var e=a(this).data("draggable").options;if(e._cursor){a("body").css("cursor",e._cursor)}}});a.ui.plugin.add("draggable","opacity",{start:function(d,e){var c=a(e.helper),f=a(this).data("draggable").options;if(c.css("opacity")){f._opacity=c.css("opacity")}c.css("opacity",f.opacity)},stop:function(c,d){var e=a(this).data("draggable").options;if(e._opacity){a(d.helper).css("opacity",e._opacity)}}});a.ui.plugin.add("draggable","scroll",{start:function(d,e){var c=a(this).data("draggable");if(c.scrollParent[0]!=document&&c.scrollParent[0].tagName!="HTML"){c.overflowOffset=c.scrollParent.offset()}},drag:function(e,f){var d=a(this).data("draggable"),g=d.options,c=false;if(d.scrollParent[0]!=document&&d.scrollParent[0].tagName!="HTML"){if(!g.axis||g.axis!="x"){if((d.overflowOffset.top+d.scrollParent[0].offsetHeight)-e.pageY<g.scrollSensitivity){d.scrollParent[0].scrollTop=c=d.scrollParent[0].scrollTop+g.scrollSpeed}else{if(e.pageY-d.overflowOffset.top<g.scrollSensitivity){d.scrollParent[0].scrollTop=c=d.scrollParent[0].scrollTop-g.scrollSpeed}}}if(!g.axis||g.axis!="y"){if((d.overflowOffset.left+d.scrollParent[0].offsetWidth)-e.pageX<g.scrollSensitivity){d.scrollParent[0].scrollLeft=c=d.scrollParent[0].scrollLeft+g.scrollSpeed}else{if(e.pageX-d.overflowOffset.left<g.scrollSensitivity){d.scrollParent[0].scrollLeft=c=d.scrollParent[0].scrollLeft-g.scrollSpeed}}}}else{if(!g.axis||g.axis!="x"){if(e.pageY-a(document).scrollTop()<g.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()-g.scrollSpeed)}else{if(a(window).height()-(e.pageY-a(document).scrollTop())<g.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()+g.scrollSpeed)}}}if(!g.axis||g.axis!="y"){if(e.pageX-a(document).scrollLeft()<g.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()-g.scrollSpeed)}else{if(a(window).width()-(e.pageX-a(document).scrollLeft())<g.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()+g.scrollSpeed)}}}}if(c!==false&&a.ui.ddmanager&&!g.dropBehaviour){a.ui.ddmanager.prepareOffsets(d,e)}}});a.ui.plugin.add("draggable","snap",{start:function(d,e){var c=a(this).data("draggable"),f=c.options;c.snapElements=[];a(f.snap.constructor!=String?(f.snap.items||":data(draggable)"):f.snap).each(function(){var h=a(this);var g=h.offset();if(this!=c.element[0]){c.snapElements.push({item:this,width:h.outerWidth(),height:h.outerHeight(),top:g.top,left:g.left})}})},drag:function(u,p){var g=a(this).data("draggable"),q=g.options;var y=q.snapTolerance;var x=p.offset.left,w=x+g.helperProportions.width,f=p.offset.top,e=f+g.helperProportions.height;for(var v=g.snapElements.length-1;v>=0;v--){var s=g.snapElements[v].left,n=s+g.snapElements[v].width,m=g.snapElements[v].top,A=m+g.snapElements[v].height;if(!((s-y<x&&x<n+y&&m-y<f&&f<A+y)||(s-y<x&&x<n+y&&m-y<e&&e<A+y)||(s-y<w&&w<n+y&&m-y<f&&f<A+y)||(s-y<w&&w<n+y&&m-y<e&&e<A+y))){if(g.snapElements[v].snapping){(g.options.snap.release&&g.options.snap.release.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=false;continue}if(q.snapMode!="inner"){var c=Math.abs(m-e)<=y;var z=Math.abs(A-f)<=y;var j=Math.abs(s-w)<=y;var k=Math.abs(n-x)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m-g.helperProportions.height,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s-g.helperProportions.width}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n}).left-g.margins.left}}var h=(c||z||j||k);if(q.snapMode!="outer"){var c=Math.abs(m-f)<=y;var z=Math.abs(A-e)<=y;var j=Math.abs(s-x)<=y;var k=Math.abs(n-w)<=y;if(c){p.position.top=g._convertPositionTo("relative",{top:m,left:0}).top-g.margins.top}if(z){p.position.top=g._convertPositionTo("relative",{top:A-g.helperProportions.height,left:0}).top-g.margins.top}if(j){p.position.left=g._convertPositionTo("relative",{top:0,left:s}).left-g.margins.left}if(k){p.position.left=g._convertPositionTo("relative",{top:0,left:n-g.helperProportions.width}).left-g.margins.left}}if(!g.snapElements[v].snapping&&(c||z||j||k||h)){(g.options.snap.snap&&g.options.snap.snap.call(g.element,u,a.extend(g._uiHash(),{snapItem:g.snapElements[v].item})))}g.snapElements[v].snapping=(c||z||j||k||h)}}});a.ui.plugin.add("draggable","stack",{start:function(d,e){var g=a(this).data("draggable").options;var f=a.makeArray(a(g.stack)).sort(function(i,h){return(parseInt(a(i).css("zIndex"),10)||0)-(parseInt(a(h).css("zIndex"),10)||0)});if(!f.length){return}var c=parseInt(f[0].style.zIndex)||0;a(f).each(function(h){this.style.zIndex=c+h});this[0].style.zIndex=c+f.length}});a.ui.plugin.add("draggable","zIndex",{start:function(d,e){var c=a(e.helper),f=a(this).data("draggable").options;if(c.css("zIndex")){f._zIndex=c.css("zIndex")}c.css("zIndex",f.zIndex)},stop:function(c,d){var e=a(this).data("draggable").options;if(e._zIndex){a(d.helper).css("zIndex",e._zIndex)}}})})(jQuery); /* * jQuery UI Mouse 1.8.24 * * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Mouse * * Depends: * jquery.ui.widget.js */ (function(b,c){var a=false;b(document).mouseup(function(d){a=false});b.widget("ui.mouse",{options:{cancel:":input,option",distance:1,delay:0},_mouseInit:function(){var d=this;this.element.bind("mousedown."+this.widgetName,function(e){return d._mouseDown(e)}).bind("click."+this.widgetName,function(e){if(true===b.data(e.target,d.widgetName+".preventClickEvent")){b.removeData(e.target,d.widgetName+".preventClickEvent");e.stopImmediatePropagation();return false}});this.started=false},_mouseDestroy:function(){this.element.unbind("."+this.widgetName);if(this._mouseMoveDelegate){b(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate)}},_mouseDown:function(f){if(a){return}(this._mouseStarted&&this._mouseUp(f));this._mouseDownEvent=f;var e=this,g=(f.which==1),d=(typeof this.options.cancel=="string"&&f.target.nodeName?b(f.target).closest(this.options.cancel).length:false);if(!g||d||!this._mouseCapture(f)){return true}this.mouseDelayMet=!this.options.delay;if(!this.mouseDelayMet){this._mouseDelayTimer=setTimeout(function(){e.mouseDelayMet=true},this.options.delay)}if(this._mouseDistanceMet(f)&&this._mouseDelayMet(f)){this._mouseStarted=(this._mouseStart(f)!==false);if(!this._mouseStarted){f.preventDefault();return true}}if(true===b.data(f.target,this.widgetName+".preventClickEvent")){b.removeData(f.target,this.widgetName+".preventClickEvent")}this._mouseMoveDelegate=function(h){return e._mouseMove(h)};this._mouseUpDelegate=function(h){return e._mouseUp(h)};b(document).bind("mousemove."+this.widgetName,this._mouseMoveDelegate).bind("mouseup."+this.widgetName,this._mouseUpDelegate);f.preventDefault();a=true;return true},_mouseMove:function(d){if(b.browser.msie&&!(document.documentMode>=9)&&!d.button){return this._mouseUp(d)}if(this._mouseStarted){this._mouseDrag(d);return d.preventDefault()}if(this._mouseDistanceMet(d)&&this._mouseDelayMet(d)){this._mouseStarted=(this._mouseStart(this._mouseDownEvent,d)!==false);(this._mouseStarted?this._mouseDrag(d):this._mouseUp(d))}return !this._mouseStarted},_mouseUp:function(d){b(document).unbind("mousemove."+this.widgetName,this._mouseMoveDelegate).unbind("mouseup."+this.widgetName,this._mouseUpDelegate);if(this._mouseStarted){this._mouseStarted=false;if(d.target==this._mouseDownEvent.target){b.data(d.target,this.widgetName+".preventClickEvent",true)}this._mouseStop(d)}return false},_mouseDistanceMet:function(d){return(Math.max(Math.abs(this._mouseDownEvent.pageX-d.pageX),Math.abs(this._mouseDownEvent.pageY-d.pageY))>=this.options.distance)},_mouseDelayMet:function(d){return this.mouseDelayMet},_mouseStart:function(d){},_mouseDrag:function(d){},_mouseStop:function(d){},_mouseCapture:function(d){return true}})})(jQuery); /* * jQuery UI Sortable 1.8.24 * * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Sortables * * Depends: * jquery.ui.core.js * jquery.ui.mouse.js * jquery.ui.widget.js */ (function(a,b){a.widget("ui.sortable",a.ui.mouse,{widgetEventPrefix:"sort",ready:false,options:{appendTo:"parent",axis:false,connectWith:false,containment:false,cursor:"auto",cursorAt:false,dropOnEmpty:true,forcePlaceholderSize:false,forceHelperSize:false,grid:false,handle:false,helper:"original",items:"> *",opacity:false,placeholder:false,revert:false,scroll:true,scrollSensitivity:20,scrollSpeed:20,scope:"default",tolerance:"intersect",zIndex:1000},_create:function(){var c=this.options;this.containerCache={};this.element.addClass("ui-sortable");this.refresh();this.floating=this.items.length?c.axis==="x"||(/left|right/).test(this.items[0].item.css("float"))||(/inline|table-cell/).test(this.items[0].item.css("display")):false;this.offset=this.element.offset();this._mouseInit();this.ready=true},destroy:function(){a.Widget.prototype.destroy.call(this);this.element.removeClass("ui-sortable ui-sortable-disabled");this._mouseDestroy();for(var c=this.items.length-1;c>=0;c--){this.items[c].item.removeData(this.widgetName+"-item")}return this},_setOption:function(c,d){if(c==="disabled"){this.options[c]=d;this.widget()[d?"addClass":"removeClass"]("ui-sortable-disabled")}else{a.Widget.prototype._setOption.apply(this,arguments)}},_mouseCapture:function(g,h){var f=this;if(this.reverting){return false}if(this.options.disabled||this.options.type=="static"){return false}this._refreshItems(g);var e=null,d=this,c=a(g.target).parents().each(function(){if(a.data(this,f.widgetName+"-item")==d){e=a(this);return false}});if(a.data(g.target,f.widgetName+"-item")==d){e=a(g.target)}if(!e){return false}if(this.options.handle&&!h){var i=false;a(this.options.handle,e).find("*").andSelf().each(function(){if(this==g.target){i=true}});if(!i){return false}}this.currentItem=e;this._removeCurrentsFromItems();return true},_mouseStart:function(f,g,c){var h=this.options,d=this;this.currentContainer=this;this.refreshPositions();this.helper=this._createHelper(f);this._cacheHelperProportions();this._cacheMargins();this.scrollParent=this.helper.scrollParent();this.offset=this.currentItem.offset();this.offset={top:this.offset.top-this.margins.top,left:this.offset.left-this.margins.left};a.extend(this.offset,{click:{left:f.pageX-this.offset.left,top:f.pageY-this.offset.top},parent:this._getParentOffset(),relative:this._getRelativeOffset()});this.helper.css("position","absolute");this.cssPosition=this.helper.css("position");this.originalPosition=this._generatePosition(f);this.originalPageX=f.pageX;this.originalPageY=f.pageY;(h.cursorAt&&this._adjustOffsetFromHelper(h.cursorAt));this.domPosition={prev:this.currentItem.prev()[0],parent:this.currentItem.parent()[0]};if(this.helper[0]!=this.currentItem[0]){this.currentItem.hide()}this._createPlaceholder();if(h.containment){this._setContainment()}if(h.cursor){if(a("body").css("cursor")){this._storedCursor=a("body").css("cursor")}a("body").css("cursor",h.cursor)}if(h.opacity){if(this.helper.css("opacity")){this._storedOpacity=this.helper.css("opacity")}this.helper.css("opacity",h.opacity)}if(h.zIndex){if(this.helper.css("zIndex")){this._storedZIndex=this.helper.css("zIndex")}this.helper.css("zIndex",h.zIndex)}if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){this.overflowOffset=this.scrollParent.offset()}this._trigger("start",f,this._uiHash());if(!this._preserveHelperProportions){this._cacheHelperProportions()}if(!c){for(var e=this.containers.length-1;e>=0;e--){this.containers[e]._trigger("activate",f,d._uiHash(this))}}if(a.ui.ddmanager){a.ui.ddmanager.current=this}if(a.ui.ddmanager&&!h.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,f)}this.dragging=true;this.helper.addClass("ui-sortable-helper");this._mouseDrag(f);return true},_mouseDrag:function(g){this.position=this._generatePosition(g);this.positionAbs=this._convertPositionTo("absolute");if(!this.lastPositionAbs){this.lastPositionAbs=this.positionAbs}if(this.options.scroll){var h=this.options,c=false;if(this.scrollParent[0]!=document&&this.scrollParent[0].tagName!="HTML"){if((this.overflowOffset.top+this.scrollParent[0].offsetHeight)-g.pageY<h.scrollSensitivity){this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop+h.scrollSpeed}else{if(g.pageY-this.overflowOffset.top<h.scrollSensitivity){this.scrollParent[0].scrollTop=c=this.scrollParent[0].scrollTop-h.scrollSpeed}}if((this.overflowOffset.left+this.scrollParent[0].offsetWidth)-g.pageX<h.scrollSensitivity){this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft+h.scrollSpeed}else{if(g.pageX-this.overflowOffset.left<h.scrollSensitivity){this.scrollParent[0].scrollLeft=c=this.scrollParent[0].scrollLeft-h.scrollSpeed}}}else{if(g.pageY-a(document).scrollTop()<h.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()-h.scrollSpeed)}else{if(a(window).height()-(g.pageY-a(document).scrollTop())<h.scrollSensitivity){c=a(document).scrollTop(a(document).scrollTop()+h.scrollSpeed)}}if(g.pageX-a(document).scrollLeft()<h.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()-h.scrollSpeed)}else{if(a(window).width()-(g.pageX-a(document).scrollLeft())<h.scrollSensitivity){c=a(document).scrollLeft(a(document).scrollLeft()+h.scrollSpeed)}}}if(c!==false&&a.ui.ddmanager&&!h.dropBehaviour){a.ui.ddmanager.prepareOffsets(this,g)}}this.positionAbs=this._convertPositionTo("absolute");if(!this.options.axis||this.options.axis!="y"){this.helper[0].style.left=this.position.left+"px"}if(!this.options.axis||this.options.axis!="x"){this.helper[0].style.top=this.position.top+"px"}for(var e=this.items.length-1;e>=0;e--){var f=this.items[e],d=f.item[0],j=this._intersectsWithPointer(f);if(!j){continue}if(f.instance!==this.currentContainer){continue}if(d!=this.currentItem[0]&&this.placeholder[j==1?"next":"prev"]()[0]!=d&&!a.ui.contains(this.placeholder[0],d)&&(this.options.type=="semi-dynamic"?!a.ui.contains(this.element[0],d):true)){this.direction=j==1?"down":"up";if(this.options.tolerance=="pointer"||this._intersectsWithSides(f)){this._rearrange(g,f)}else{break}this._trigger("change",g,this._uiHash());break}}this._contactContainers(g);if(a.ui.ddmanager){a.ui.ddmanager.drag(this,g)}this._trigger("sort",g,this._uiHash());this.lastPositionAbs=this.positionAbs;return false},_mouseStop:function(d,e){if(!d){return}if(a.ui.ddmanager&&!this.options.dropBehaviour){a.ui.ddmanager.drop(this,d)}if(this.options.revert){var c=this;var f=c.placeholder.offset();c.reverting=true;a(this.helper).animate({left:f.left-this.offset.parent.left-c.margins.left+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollLeft),top:f.top-this.offset.parent.top-c.margins.top+(this.offsetParent[0]==document.body?0:this.offsetParent[0].scrollTop)},parseInt(this.options.revert,10)||500,function(){c._clear(d)})}else{this._clear(d,e)}return false},cancel:function(){var c=this;if(this.dragging){this._mouseUp({target:null});if(this.options.helper=="original"){this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}for(var d=this.containers.length-1;d>=0;d--){this.containers[d]._trigger("deactivate",null,c._uiHash(this));if(this.containers[d].containerCache.over){this.containers[d]._trigger("out",null,c._uiHash(this));this.containers[d].containerCache.over=0}}}if(this.placeholder){if(this.placeholder[0].parentNode){this.placeholder[0].parentNode.removeChild(this.placeholder[0])}if(this.options.helper!="original"&&this.helper&&this.helper[0].parentNode){this.helper.remove()}a.extend(this,{helper:null,dragging:false,reverting:false,_noFinalSort:null});if(this.domPosition.prev){a(this.domPosition.prev).after(this.currentItem)}else{a(this.domPosition.parent).prepend(this.currentItem)}}return this},serialize:function(e){var c=this._getItemsAsjQuery(e&&e.connected);var d=[];e=e||{};a(c).each(function(){var f=(a(e.item||this).attr(e.attribute||"id")||"").match(e.expression||(/(.+)[-=_](.+)/));if(f){d.push((e.key||f[1]+"[]")+"="+(e.key&&e.expression?f[1]:f[2]))}});if(!d.length&&e.key){d.push(e.key+"=")}return d.join("&")},toArray:function(e){var c=this._getItemsAsjQuery(e&&e.connected);var d=[];e=e||{};c.each(function(){d.push(a(e.item||this).attr(e.attribute||"id")||"")});return d},_intersectsWith:function(m){var e=this.positionAbs.left,d=e+this.helperProportions.width,k=this.positionAbs.top,j=k+this.helperProportions.height;var f=m.left,c=f+m.width,n=m.top,i=n+m.height;var o=this.offset.click.top,h=this.offset.click.left;var g=(k+o)>n&&(k+o)<i&&(e+h)>f&&(e+h)<c;if(this.options.tolerance=="pointer"||this.options.forcePointerForContainers||(this.options.tolerance!="pointer"&&this.helperProportions[this.floating?"width":"height"]>m[this.floating?"width":"height"])){return g}else{return(f<e+(this.helperProportions.width/2)&&d-(this.helperProportions.width/2)<c&&n<k+(this.helperProportions.height/2)&&j-(this.helperProportions.height/2)<i)}},_intersectsWithPointer:function(e){var f=(this.options.axis==="x")||a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,e.top,e.height),d=(this.options.axis==="y")||a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,e.left,e.width),h=f&&d,c=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();if(!h){return false}return this.floating?(((g&&g=="right")||c=="down")?2:1):(c&&(c=="down"?2:1))},_intersectsWithSides:function(f){var d=a.ui.isOverAxis(this.positionAbs.top+this.offset.click.top,f.top+(f.height/2),f.height),e=a.ui.isOverAxis(this.positionAbs.left+this.offset.click.left,f.left+(f.width/2),f.width),c=this._getDragVerticalDirection(),g=this._getDragHorizontalDirection();if(this.floating&&g){return((g=="right"&&e)||(g=="left"&&!e))}else{return c&&((c=="down"&&d)||(c=="up"&&!d))}},_getDragVerticalDirection:function(){var c=this.positionAbs.top-this.lastPositionAbs.top;return c!=0&&(c>0?"down":"up")},_getDragHorizontalDirection:function(){var c=this.positionAbs.left-this.lastPositionAbs.left;return c!=0&&(c>0?"right":"left")},refresh:function(c){this._refreshItems(c);this.refreshPositions();return this},_connectWith:function(){var c=this.options;return c.connectWith.constructor==String?[c.connectWith]:c.connectWith},_getItemsAsjQuery:function(c){var m=this;var h=[];var f=[];var k=this._connectWith();if(k&&c){for(var e=k.length-1;e>=0;e--){var l=a(k[e]);for(var d=l.length-1;d>=0;d--){var g=a.data(l[d],this.widgetName);if(g&&g!=this&&!g.options.disabled){f.push([a.isFunction(g.options.items)?g.options.items.call(g.element):a(g.options.items,g.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),g])}}}}f.push([a.isFunction(this.options.items)?this.options.items.call(this.element,null,{options:this.options,item:this.currentItem}):a(this.options.items,this.element).not(".ui-sortable-helper").not(".ui-sortable-placeholder"),this]);for(var e=f.length-1;e>=0;e--){f[e][0].each(function(){h.push(this)})}return a(h)},_removeCurrentsFromItems:function(){var e=this.currentItem.find(":data("+this.widgetName+"-item)");for(var d=0;d<this.items.length;d++){for(var c=0;c<e.length;c++){if(e[c]==this.items[d].item[0]){this.items.splice(d,1)}}}},_refreshItems:function(c){this.items=[];this.containers=[this];var k=this.items;var q=this;var g=[[a.isFunction(this.options.items)?this.options.items.call(this.element[0],c,{item:this.currentItem}):a(this.options.items,this.element),this]];var m=this._connectWith();if(m&&this.ready){for(var f=m.length-1;f>=0;f--){var n=a(m[f]);for(var e=n.length-1;e>=0;e--){var h=a.data(n[e],this.widgetName);if(h&&h!=this&&!h.options.disabled){g.push([a.isFunction(h.options.items)?h.options.items.call(h.element[0],c,{item:this.currentItem}):a(h.options.items,h.element),h]);this.containers.push(h)}}}}for(var f=g.length-1;f>=0;f--){var l=g[f][1];var d=g[f][0];for(var e=0,o=d.length;e<o;e++){var p=a(d[e]);p.data(this.widgetName+"-item",l);k.push({item:p,instance:l,width:0,height:0,left:0,top:0})}}},refreshPositions:function(c){if(this.offsetParent&&this.helper){this.offset.parent=this._getParentOffset()}for(var e=this.items.length-1;e>=0;e--){var f=this.items[e];if(f.instance!=this.currentContainer&&this.currentContainer&&f.item[0]!=this.currentItem[0]){continue}var d=this.options.toleranceElement?a(this.options.toleranceElement,f.item):f.item;if(!c){f.width=d.outerWidth();f.height=d.outerHeight()}var g=d.offset();f.left=g.left;f.top=g.top}if(this.options.custom&&this.options.custom.refreshContainers){this.options.custom.refreshContainers.call(this)}else{for(var e=this.containers.length-1;e>=0;e--){var g=this.containers[e].element.offset();this.containers[e].containerCache.left=g.left;this.containers[e].containerCache.top=g.top;this.containers[e].containerCache.width=this.containers[e].element.outerWidth();this.containers[e].containerCache.height=this.containers[e].element.outerHeight()}}return this},_createPlaceholder:function(e){var c=e||this,f=c.options;if(!f.placeholder||f.placeholder.constructor==String){var d=f.placeholder;f.placeholder={element:function(){var g=a(document.createElement(c.currentItem[0].nodeName)).addClass(d||c.currentItem[0].className+" ui-sortable-placeholder").removeClass("ui-sortable-helper")[0];if(!d){g.style.visibility="hidden"}return g},update:function(g,h){if(d&&!f.forcePlaceholderSize){return}if(!h.height()){h.height(c.currentItem.innerHeight()-parseInt(c.currentItem.css("paddingTop")||0,10)-parseInt(c.currentItem.css("paddingBottom")||0,10))}if(!h.width()){h.width(c.currentItem.innerWidth()-parseInt(c.currentItem.css("paddingLeft")||0,10)-parseInt(c.currentItem.css("paddingRight")||0,10))}}}}c.placeholder=a(f.placeholder.element.call(c.element,c.currentItem));c.currentItem.after(c.placeholder);f.placeholder.update(c,c.placeholder)},_contactContainers:function(c){var e=null,l=null;for(var g=this.containers.length-1;g>=0;g--){if(a.ui.contains(this.currentItem[0],this.containers[g].element[0])){continue}if(this._intersectsWith(this.containers[g].containerCache)){if(e&&a.ui.contains(this.containers[g].element[0],e.element[0])){continue}e=this.containers[g];l=g}else{if(this.containers[g].containerCache.over){this.containers[g]._trigger("out",c,this._uiHash(this));this.containers[g].containerCache.over=0}}}if(!e){return}if(this.containers.length===1){this.containers[l]._trigger("over",c,this._uiHash(this));this.containers[l].containerCache.over=1}else{if(this.currentContainer!=this.containers[l]){var k=10000;var h=null;var d=this.positionAbs[this.containers[l].floating?"left":"top"];for(var f=this.items.length-1;f>=0;f--){if(!a.ui.contains(this.containers[l].element[0],this.items[f].item[0])){continue}var m=this.containers[l].floating?this.items[f].item.offset().left:this.items[f].item.offset().top;if(Math.abs(m-d)<k){k=Math.abs(m-d);h=this.items[f];this.direction=(m-d>0)?"down":"up"}}if(!h&&!this.options.dropOnEmpty){return}this.currentContainer=this.containers[l];h?this._rearrange(c,h,null,true):this._rearrange(c,null,this.containers[l].element,true);this._trigger("change",c,this._uiHash());this.containers[l]._trigger("change",c,this._uiHash(this));this.options.placeholder.update(this.currentContainer,this.placeholder);this.containers[l]._trigger("over",c,this._uiHash(this));this.containers[l].containerCache.over=1}}},_createHelper:function(d){var e=this.options;var c=a.isFunction(e.helper)?a(e.helper.apply(this.element[0],[d,this.currentItem])):(e.helper=="clone"?this.currentItem.clone():this.currentItem);if(!c.parents("body").length){a(e.appendTo!="parent"?e.appendTo:this.currentItem[0].parentNode)[0].appendChild(c[0])}if(c[0]==this.currentItem[0]){this._storedCSS={width:this.currentItem[0].style.width,height:this.currentItem[0].style.height,position:this.currentItem.css("position"),top:this.currentItem.css("top"),left:this.currentItem.css("left")}}if(c[0].style.width==""||e.forceHelperSize){c.width(this.currentItem.width())}if(c[0].style.height==""||e.forceHelperSize){c.height(this.currentItem.height())}return c},_adjustOffsetFromHelper:function(c){if(typeof c=="string"){c=c.split(" ")}if(a.isArray(c)){c={left:+c[0],top:+c[1]||0}}if("left" in c){this.offset.click.left=c.left+this.margins.left}if("right" in c){this.offset.click.left=this.helperProportions.width-c.right+this.margins.left}if("top" in c){this.offset.click.top=c.top+this.margins.top}if("bottom" in c){this.offset.click.top=this.helperProportions.height-c.bottom+this.margins.top}},_getParentOffset:function(){this.offsetParent=this.helper.offsetParent();var c=this.offsetParent.offset();if(this.cssPosition=="absolute"&&this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0])){c.left+=this.scrollParent.scrollLeft();c.top+=this.scrollParent.scrollTop()}if((this.offsetParent[0]==document.body)||(this.offsetParent[0].tagName&&this.offsetParent[0].tagName.toLowerCase()=="html"&&a.browser.msie)){c={top:0,left:0}}return{top:c.top+(parseInt(this.offsetParent.css("borderTopWidth"),10)||0),left:c.left+(parseInt(this.offsetParent.css("borderLeftWidth"),10)||0)}},_getRelativeOffset:function(){if(this.cssPosition=="relative"){var c=this.currentItem.position();return{top:c.top-(parseInt(this.helper.css("top"),10)||0)+this.scrollParent.scrollTop(),left:c.left-(parseInt(this.helper.css("left"),10)||0)+this.scrollParent.scrollLeft()}}else{return{top:0,left:0}}},_cacheMargins:function(){this.margins={left:(parseInt(this.currentItem.css("marginLeft"),10)||0),top:(parseInt(this.currentItem.css("marginTop"),10)||0)}},_cacheHelperProportions:function(){this.helperProportions={width:this.helper.outerWidth(),height:this.helper.outerHeight()}},_setContainment:function(){var f=this.options;if(f.containment=="parent"){f.containment=this.helper[0].parentNode}if(f.containment=="document"||f.containment=="window"){this.containment=[0-this.offset.relative.left-this.offset.parent.left,0-this.offset.relative.top-this.offset.parent.top,a(f.containment=="document"?document:window).width()-this.helperProportions.width-this.margins.left,(a(f.containment=="document"?document:window).height()||document.body.parentNode.scrollHeight)-this.helperProportions.height-this.margins.top]}if(!(/^(document|window|parent)$/).test(f.containment)){var d=a(f.containment)[0];var e=a(f.containment).offset();var c=(a(d).css("overflow")!="hidden");this.containment=[e.left+(parseInt(a(d).css("borderLeftWidth"),10)||0)+(parseInt(a(d).css("paddingLeft"),10)||0)-this.margins.left,e.top+(parseInt(a(d).css("borderTopWidth"),10)||0)+(parseInt(a(d).css("paddingTop"),10)||0)-this.margins.top,e.left+(c?Math.max(d.scrollWidth,d.offsetWidth):d.offsetWidth)-(parseInt(a(d).css("borderLeftWidth"),10)||0)-(parseInt(a(d).css("paddingRight"),10)||0)-this.helperProportions.width-this.margins.left,e.top+(c?Math.max(d.scrollHeight,d.offsetHeight):d.offsetHeight)-(parseInt(a(d).css("borderTopWidth"),10)||0)-(parseInt(a(d).css("paddingBottom"),10)||0)-this.helperProportions.height-this.margins.top]}},_convertPositionTo:function(g,i){if(!i){i=this.position}var e=g=="absolute"?1:-1;var f=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,h=(/(html|body)/i).test(c[0].tagName);return{top:(i.top+this.offset.relative.top*e+this.offset.parent.top*e-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(h?0:c.scrollTop()))*e)),left:(i.left+this.offset.relative.left*e+this.offset.parent.left*e-(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():h?0:c.scrollLeft())*e))}},_generatePosition:function(f){var i=this.options,c=this.cssPosition=="absolute"&&!(this.scrollParent[0]!=document&&a.ui.contains(this.scrollParent[0],this.offsetParent[0]))?this.offsetParent:this.scrollParent,j=(/(html|body)/i).test(c[0].tagName);if(this.cssPosition=="relative"&&!(this.scrollParent[0]!=document&&this.scrollParent[0]!=this.offsetParent[0])){this.offset.relative=this._getRelativeOffset()}var e=f.pageX;var d=f.pageY;if(this.originalPosition){if(this.containment){if(f.pageX-this.offset.click.left<this.containment[0]){e=this.containment[0]+this.offset.click.left}if(f.pageY-this.offset.click.top<this.containment[1]){d=this.containment[1]+this.offset.click.top}if(f.pageX-this.offset.click.left>this.containment[2]){e=this.containment[2]+this.offset.click.left}if(f.pageY-this.offset.click.top>this.containment[3]){d=this.containment[3]+this.offset.click.top}}if(i.grid){var h=this.originalPageY+Math.round((d-this.originalPageY)/i.grid[1])*i.grid[1];d=this.containment?(!(h-this.offset.click.top<this.containment[1]||h-this.offset.click.top>this.containment[3])?h:(!(h-this.offset.click.top<this.containment[1])?h-i.grid[1]:h+i.grid[1])):h;var g=this.originalPageX+Math.round((e-this.originalPageX)/i.grid[0])*i.grid[0];e=this.containment?(!(g-this.offset.click.left<this.containment[0]||g-this.offset.click.left>this.containment[2])?g:(!(g-this.offset.click.left<this.containment[0])?g-i.grid[0]:g+i.grid[0])):g}}return{top:(d-this.offset.click.top-this.offset.relative.top-this.offset.parent.top+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollTop():(j?0:c.scrollTop())))),left:(e-this.offset.click.left-this.offset.relative.left-this.offset.parent.left+(a.browser.safari&&this.cssPosition=="fixed"?0:(this.cssPosition=="fixed"?-this.scrollParent.scrollLeft():j?0:c.scrollLeft())))}},_rearrange:function(h,g,d,f){d?d[0].appendChild(this.placeholder[0]):g.item[0].parentNode.insertBefore(this.placeholder[0],(this.direction=="down"?g.item[0]:g.item[0].nextSibling));this.counter=this.counter?++this.counter:1;var e=this,c=this.counter;window.setTimeout(function(){if(c==e.counter){e.refreshPositions(!f)}},0)},_clear:function(e,f){this.reverting=false;var g=[],c=this;if(!this._noFinalSort&&this.currentItem.parent().length){this.placeholder.before(this.currentItem)}this._noFinalSort=null;if(this.helper[0]==this.currentItem[0]){for(var d in this._storedCSS){if(this._storedCSS[d]=="auto"||this._storedCSS[d]=="static"){this._storedCSS[d]=""}}this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper")}else{this.currentItem.show()}if(this.fromOutside&&!f){g.push(function(h){this._trigger("receive",h,this._uiHash(this.fromOutside))})}if((this.fromOutside||this.domPosition.prev!=this.currentItem.prev().not(".ui-sortable-helper")[0]||this.domPosition.parent!=this.currentItem.parent()[0])&&!f){g.push(function(h){this._trigger("update",h,this._uiHash())})}if(this!==this.currentContainer){if(!f){g.push(function(h){this._trigger("remove",h,this._uiHash())});g.push((function(h){return function(i){h._trigger("receive",i,this._uiHash(this))}}).call(this,this.currentContainer));g.push((function(h){return function(i){h._trigger("update",i,this._uiHash(this))}}).call(this,this.currentContainer))}}for(var d=this.containers.length-1;d>=0;d--){if(!f){g.push((function(h){return function(i){h._trigger("deactivate",i,this._uiHash(this))}}).call(this,this.containers[d]))}if(this.containers[d].containerCache.over){g.push((function(h){return function(i){h._trigger("out",i,this._uiHash(this))}}).call(this,this.containers[d]));this.containers[d].containerCache.over=0}}if(this._storedCursor){a("body").css("cursor",this._storedCursor)}if(this._storedOpacity){this.helper.css("opacity",this._storedOpacity)}if(this._storedZIndex){this.helper.css("zIndex",this._storedZIndex=="auto"?"":this._storedZIndex)}this.dragging=false;if(this.cancelHelperRemoval){if(!f){this._trigger("beforeStop",e,this._uiHash());for(var d=0;d<g.length;d++){g[d].call(this,e)}this._trigger("stop",e,this._uiHash())}this.fromOutside=false;return false}if(!f){this._trigger("beforeStop",e,this._uiHash())}this.placeholder[0].parentNode.removeChild(this.placeholder[0]);if(this.helper[0]!=this.currentItem[0]){this.helper.remove()}this.helper=null;if(!f){for(var d=0;d<g.length;d++){g[d].call(this,e)}this._trigger("stop",e,this._uiHash())}this.fromOutside=false;return true},_trigger:function(){if(a.Widget.prototype._trigger.apply(this,arguments)===false){this.cancel()}},_uiHash:function(d){var c=d||this;return{helper:c.helper,placeholder:c.placeholder||a([]),position:c.position,originalPosition:c.originalPosition,offset:c.positionAbs,item:c.currentItem,sender:d?d.element:null}}});a.extend(a.ui.sortable,{version:"1.8.24"})})(jQuery); /* * jQuery UI Widget 1.8.24 * * Copyright 2012, AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT or GPL Version 2 licenses. * http://jquery.org/license * * http://docs.jquery.com/UI/Widget */ (function(b,d){if(b.cleanData){var c=b.cleanData;b.cleanData=function(f){for(var g=0,h;(h=f[g])!=null;g++){try{b(h).triggerHandler("remove")}catch(j){}}c(f)}}else{var a=b.fn.remove;b.fn.remove=function(e,f){return this.each(function(){if(!f){if(!e||b.filter(e,[this]).length){b("*",this).add([this]).each(function(){try{b(this).triggerHandler("remove")}catch(g){}})}}return a.call(b(this),e,f)})}}b.widget=function(f,h,e){var g=f.split(".")[0],j;f=f.split(".")[1];j=g+"-"+f;if(!e){e=h;h=b.Widget}b.expr[":"][j]=function(k){return !!b.data(k,f)};b[g]=b[g]||{};b[g][f]=function(k,l){if(arguments.length){this._createWidget(k,l)}};var i=new h();i.options=b.extend(true,{},i.options);b[g][f].prototype=b.extend(true,i,{namespace:g,widgetName:f,widgetEventPrefix:b[g][f].prototype.widgetEventPrefix||f,widgetBaseClass:j},e);b.widget.bridge(f,b[g][f])};b.widget.bridge=function(f,e){b.fn[f]=function(i){var g=typeof i==="string",h=Array.prototype.slice.call(arguments,1),j=this;i=!g&&h.length?b.extend.apply(null,[true,i].concat(h)):i;if(g&&i.charAt(0)==="_"){return j}if(g){this.each(function(){var k=b.data(this,f),l=k&&b.isFunction(k[i])?k[i].apply(k,h):k;if(l!==k&&l!==d){j=l;return false}})}else{this.each(function(){var k=b.data(this,f);if(k){k.option(i||{})._init()}else{b.data(this,f,new e(i,this))}})}return j}};b.Widget=function(e,f){if(arguments.length){this._createWidget(e,f)}};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(f,g){b.data(g,this.widgetName,this);this.element=b(g);this.options=b.extend(true,{},this.options,this._getCreateOptions(),f);var e=this;this.element.bind("remove."+this.widgetName,function(){e.destroy()});this._create();this._trigger("create");this._init()},_getCreateOptions:function(){return b.metadata&&b.metadata.get(this.element[0])[this.widgetName]},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(f,g){var e=f;if(arguments.length===0){return b.extend({},this.options)}if(typeof f==="string"){if(g===d){return this.options[f]}e={};e[f]=g}this._setOptions(e);return this},_setOptions:function(f){var e=this;b.each(f,function(g,h){e._setOption(g,h)});return this},_setOption:function(e,f){this.options[e]=f;if(e==="disabled"){this.widget()[f?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",f)}return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(e,f,g){var j,i,h=this.options[e];g=g||{};f=b.Event(f);f.type=(e===this.widgetEventPrefix?e:this.widgetEventPrefix+e).toLowerCase();f.target=this.element[0];i=f.originalEvent;if(i){for(j in i){if(!(j in f)){f[j]=i[j]}}}this.element.trigger(f,g);return !(b.isFunction(h)&&h.call(this.element[0],f,g)===false||f.isDefaultPrevented())}}})(jQuery);
app/components/Explore.js
stitux/OpenObjectMarker
import React from 'react'; import ExploreStore from '../stores/ExploreStore'; import ExploreActions from '../actions/ExploreActions' import ImageLoader from 'react-imageloader' class Explore extends React.Component { constructor(props) { super(props); this.state = ExploreStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { //this.updateCanvas(); ExploreStore.listen(this.onChange); } componentWillUnmount() { //this.updateCanvas(); ExploreStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } /* update the class and call updateCanvas*/ handleSubmit(event) { event.preventDefault(); var images = ExploreActions.exploreByClass(); this.updateCanvas(images); } updateCanvas(images) { var c = document.getElementById("drawCanvas"); const ctx = c.getContext('2d'); c.width = 600; c.height = Math.ceil(images.length / 2) * 300; for (var i = 0; i < images.length; i++) { var topMap = new Image(); console.log('uploads/' + images[i].image_id); topMap.src = 'uploads/' + images[i].image_id; ctx.drawImage(topMap, (i % 2) * 300 , Math.floor(i / 2) * 300 , 300, 300); ctx.strokeStyle="red"; ctx.rect((i % 2) * 300 + 50, Math.floor(i / 2) * 300 + 50, 200, 200); ctx.stroke(); } } render() { return ( <div className='container'> <h1> Open Object Marker </h1> <ul> <li><a href="/home">Home</a></li> <li><a href="/upload">Upload</a></li> <li><a className="active" href="/explore">Explore</a></li> <li><a href="">Login</a></li> </ul> <hr></hr> <div className='row flipInX animated'> <div className='col-sm-8'> <div className='panel panel-default'> <div className='panel-heading'>Explore</div> <div className='panel-body'> <form onSubmit={this.handleSubmit.bind(this)}> <canvas id="drawCanvas" width={600} height={600}/> <button type='submit' className='btn btn-primary'>Submit</button> </form> </div> </div> </div> </div> </div> ); } } export default Explore;
pkg/interface/publish/src/js/components/lib/sidebar-invite.js
jfranklin9000/urbit
import React, { Component } from 'react'; import classnames from 'classnames'; import _ from 'lodash'; export class SidebarInvite extends Component { onAccept() { let action = { accept: { path: '/publish', uid: this.props.uid, } } window.api.action("invite-store", "invite-action", action); } onDecline() { let action = { decline: { path: '/publish', uid: this.props.uid, } } window.api.action("invite-store", "invite-action", action); } render() { const { props } = this; return ( <div className='pa3 bb b--gray4 b--gray1-d'> <div className='w-100 v-mid'> <p className="dib f9 mono gray4-d"> {props.invite.text} </p> </div> <a className="dib pointer pa2 f9 bg-green2 white mt4" onClick={this.onAccept.bind(this)}> Accept Invite </a> <a className="dib pointer ml4 pa2 f9 bg-black bg-gray0-d white mt4" onClick={this.onDecline.bind(this)}> Decline </a> </div> ) } }
packages/flyout/src/presenters/PointerWrapperPresenter.js
Autodesk/hig
import React from "react"; import PropTypes from "prop-types"; import { css, cx } from "emotion"; import { createCustomClassNames } from "@hig/utils"; import stylesheet from "./stylesheet"; import { AVAILABLE_ANCHOR_POINTS } from "../anchorPoints"; export default function PointerWrapperPresenter({ children, innerRef, style, anchorPoint, stylesheet: customStylesheet, ...otherProps }) { const styles = stylesheet({ transitionStatus: null, anchorPoint, stylesheet: customStylesheet, }); const { className } = otherProps; const pointerWrapperClassName = createCustomClassNames( className, "pointer-wrapper" ); return ( <div aria-hidden="true" className={cx(css(styles.pointerWrapper), pointerWrapperClassName)} ref={innerRef} role="presentation" style={style} > {children} </div> ); } PointerWrapperPresenter.propTypes = { children: PropTypes.node, innerRef: PropTypes.func, /* eslint-disable-next-line react/forbid-prop-types */ style: PropTypes.object, anchorPoint: PropTypes.oneOf(AVAILABLE_ANCHOR_POINTS), stylesheet: PropTypes.func, };
src/svg-icons/action/chrome-reader-mode.js
hai-cea/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionChromeReaderMode = (props) => ( <SvgIcon {...props}> <path d="M13 12h7v1.5h-7zm0-2.5h7V11h-7zm0 5h7V16h-7zM21 4H3c-1.1 0-2 .9-2 2v13c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 15h-9V6h9v13z"/> </SvgIcon> ); ActionChromeReaderMode = pure(ActionChromeReaderMode); ActionChromeReaderMode.displayName = 'ActionChromeReaderMode'; ActionChromeReaderMode.muiName = 'SvgIcon'; export default ActionChromeReaderMode;
src/svg-icons/RadioButtonChecked.js
AndriusBil/material-ui
// @flow import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../SvgIcon'; /** * @ignore - internal component. */ let RadioButtonChecked = props => ( <SvgIcon {...props}> <path d="M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zm0-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z" /> </SvgIcon> ); RadioButtonChecked = pure(RadioButtonChecked); RadioButtonChecked.muiName = 'SvgIcon'; export default RadioButtonChecked;
packages/material-ui-icons/src/SatelliteOutlined.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14z" /><path d="M8.57 6H6v2.58c1.42 0 2.57-1.16 2.57-2.58zM12 6h-1.71c0 2.36-1.92 4.29-4.29 4.29V12c3.32 0 6-2.69 6-6zM14.14 11.86l-3 3.87L9 13.15 6 17h12z" /></React.Fragment> , 'SatelliteOutlined');
src/pages/Home.js
mtomcal/reactjs-hooligans-tv
import React, { Component } from 'react'; import { Jumbotron, Button } from 'react-bootstrap'; import Player from '../player'; import { Containers } from '../data'; import { Card } from '../cards'; import {api_url} from '../config.js'; var Home = React.createClass({ propTypes: { queryData: React.PropTypes.object.isRequired }, render() { var style = {}; const videos = this.props.queryData.data.map(function (res, index) { return (<div className="col-lg-4"> <Player key={index} source={res.snippet.resourceId.videoId} title={res.snippet.title} autoplay={true} imageURL={res.snippet.thumbnails.high.url} /> </div>); }); const offense = videos.filter((item, index) => { return index < 6; }); const defense = videos.filter((item, index) => { return index >= 6 && index < 12; }); return ( <div> <div className="container-fluid" style={style}> <div className="row"> <div className="col-lg-12"> <Card title="Home" /> </div> </div> <div className="row"> <div className="col-lg-6"> <Card title="Offense"> {offense} </Card> </div> <div className="col-lg-6"> <Card title="Defense"> {defense} </Card> </div> </div> <div className="row"> <div className="col-lg-6"> <Card title="Offense"> {offense} </Card> </div> <div className="col-lg-6"> <Card title="Defense"> {defense} </Card> </div> </div> </div> </div> ); } }); export default Containers.query.createContainer(Home, { method: 'get', route: api_url + '/videos', })
app/hocs/CurrentUser/index.js
zebbra-repos/Zeiterfassung-medi
/* * * CurrentUser * */ import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { makeSelectUsername, makeSelectFirstName, makeSelectLastName, makeSelectRoles, makeSelectOriginRoles, makeSelectOriginUsername, makeSelectTeams, } from 'hocs/Session/selectors'; export default function CurrentUser(Component) { function PersonalisedComponent(props) { const isImpersonated = props.roles.includes('impersonated'); const isUser = props.roles.includes('user'); const isAdmin = props.roles.includes('admin'); const isSuperAdmin = props.roles.includes('super-admin') || props.originRoles.includes('super-admin'); const isTeamleader = props.roles.includes('teamleader') || props.originRoles.includes('teamleader'); return (<Component {...props} isImpersonated={isImpersonated} isUser={isUser} isTeamleader={isTeamleader} isAdmin={isAdmin} isSuperAdmin={isSuperAdmin} />); } PersonalisedComponent.propTypes = { roles: ImmutablePropTypes.list.isRequired, originRoles: ImmutablePropTypes.list.isRequired, }; PersonalisedComponent.defaultProps = { // properties username: '', firstName: '', lastName: '', originUsername: '', isUser: false, isTeamleader: false, isAdmin: false, isSuperAdmin: false, teams: [], }; const mapStateToProps = createStructuredSelector({ username: makeSelectUsername(), firstName: makeSelectFirstName(), lastName: makeSelectLastName(), roles: makeSelectRoles(), originRoles: makeSelectOriginRoles(), originUsername: makeSelectOriginUsername(), teams: makeSelectTeams(), }); return connect(mapStateToProps)(PersonalisedComponent); }
ajax/libs/react-virtualized/4.6.2/react-virtualized.js
cdnjs/cdnjs
!function(root, factory) { "object" == typeof exports && "object" == typeof module ? module.exports = factory(require("react")) : "function" == typeof define && define.amd ? define([ "react" ], factory) : "object" == typeof exports ? exports["react-virtualized"] = factory(require("react")) : root["react-virtualized"] = factory(root.React); }(this, function(__WEBPACK_EXTERNAL_MODULE_4__) { /******/ return function(modules) { /******/ /******/ // 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: !1 }; /******/ /******/ // Return the exports of the module /******/ /******/ /******/ // Execute the module function /******/ /******/ /******/ // Flag the module as loaded /******/ return modules[moduleId].call(module.exports, module, module.exports, __webpack_require__), module.loaded = !0, module.exports; } // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // Load entry module and return exports /******/ /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ /******/ /******/ // expose the module cache /******/ /******/ /******/ // __webpack_public_path__ /******/ return __webpack_require__.m = modules, __webpack_require__.c = installedModules, __webpack_require__.p = "", __webpack_require__(0); }([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: !0 }); var _AutoSizer = __webpack_require__(1); Object.defineProperty(exports, "AutoSizer", { enumerable: !0, get: function() { return _AutoSizer.AutoSizer; } }); var _FlexTable = __webpack_require__(8); Object.defineProperty(exports, "FlexTable", { enumerable: !0, get: function() { return _FlexTable.FlexTable; } }), Object.defineProperty(exports, "FlexColumn", { enumerable: !0, get: function() { return _FlexTable.FlexColumn; } }), Object.defineProperty(exports, "SortDirection", { enumerable: !0, get: function() { return _FlexTable.SortDirection; } }), Object.defineProperty(exports, "SortIndicator", { enumerable: !0, get: function() { return _FlexTable.SortIndicator; } }); var _Grid = __webpack_require__(19); Object.defineProperty(exports, "Grid", { enumerable: !0, get: function() { return _Grid.Grid; } }); var _InfiniteLoader = __webpack_require__(21); Object.defineProperty(exports, "InfiniteLoader", { enumerable: !0, get: function() { return _InfiniteLoader.InfiniteLoader; } }); var _VirtualScroll = __webpack_require__(11); Object.defineProperty(exports, "VirtualScroll", { enumerable: !0, get: function() { return _VirtualScroll.VirtualScroll; } }); }, /* 1 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _AutoSizer2 = __webpack_require__(2), _AutoSizer3 = _interopRequireDefault(_AutoSizer2); exports["default"] = _AutoSizer3["default"]; var _AutoSizer4 = _interopRequireDefault(_AutoSizer2); exports.AutoSizer = _AutoSizer4["default"]; }, /* 2 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) keys.indexOf(i) >= 0 || Object.prototype.hasOwnProperty.call(obj, i) && (target[i] = obj[i]); return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _get = function(_x, _x2, _x3) { for (var _again = !0; _again; ) { var object = _x, property = _x2, receiver = _x3; _again = !1, null === object && (object = Function.prototype); var desc = Object.getOwnPropertyDescriptor(object, property); if (void 0 !== desc) { if ("value" in desc) return desc.value; var getter = desc.get; if (void 0 === getter) return; return getter.call(receiver); } var parent = Object.getPrototypeOf(object); if (null === parent) return; _x = parent, _x2 = property, _x3 = receiver, _again = !0, desc = parent = void 0; } }, _classnames = __webpack_require__(3), _classnames2 = _interopRequireDefault(_classnames), _react = __webpack_require__(4), _react2 = _interopRequireDefault(_react), _reactPureRenderFunction = __webpack_require__(5), _reactPureRenderFunction2 = _interopRequireDefault(_reactPureRenderFunction), AutoSizer = function(_Component) { function AutoSizer(props) { _classCallCheck(this, AutoSizer), _get(Object.getPrototypeOf(AutoSizer.prototype), "constructor", this).call(this, props), this.shouldComponentUpdate = _reactPureRenderFunction2["default"], this.state = { height: 0, width: 0 }, this._onResize = this._onResize.bind(this), this._setRef = this._setRef.bind(this); } return _inherits(AutoSizer, _Component), _createClass(AutoSizer, null, [ { key: "propTypes", value: { /** Component to manage width/height of */ children: _react.PropTypes.element, /** Optional CSS class name */ className: _react.PropTypes.string, /** Disable dynamic :height property */ disableHeight: _react.PropTypes.bool, /** Disable dynamic :width property */ disableWidth: _react.PropTypes.bool }, enumerable: !0 } ]), _createClass(AutoSizer, [ { key: "componentDidMount", value: function() { // Defer requiring resize handler in order to support server-side rendering. // See issue #41 this._detectElementResize = __webpack_require__(7), this._detectElementResize.addResizeListener(this._parentNode, this._onResize), this._onResize(); } }, { key: "componentWillUnmount", value: function() { this._detectElementResize.removeResizeListener(this._parentNode, this._onResize); } }, { key: "render", value: function() { var _props = this.props, children = _props.children, className = _props.className, disableHeight = _props.disableHeight, disableWidth = _props.disableWidth, _state = (_objectWithoutProperties(_props, [ "children", "className", "disableHeight", "disableWidth" ]), this.state), height = _state.height, width = _state.width, childProps = {}; disableHeight || (childProps.height = height), disableWidth || (childProps.width = width); var child = _react2["default"].Children.only(children); return child = _react2["default"].cloneElement(child, childProps), _react2["default"].createElement("div", { ref: this._setRef, className: (0, _classnames2["default"])("AutoSizer", className), style: { width: "100%", height: "100%" } }, child); } }, { key: "_onResize", value: function() { var _parentNode$getBoundingClientRect = this._parentNode.getBoundingClientRect(), height = _parentNode$getBoundingClientRect.height, width = _parentNode$getBoundingClientRect.width; this.setState({ height: height, width: width }); } }, { key: "_setRef", value: function(autoSizer) { // In case the component has been unmounted this._parentNode = autoSizer && autoSizer.parentNode; } } ]), AutoSizer; }(_react.Component); exports["default"] = AutoSizer, module.exports = exports["default"]; }, /* 3 */ /***/ 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"; function classNames() { for (var classes = [], i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { var argType = typeof arg; if ("string" === argType || "number" === argType) classes.push(arg); else if (Array.isArray(arg)) classes.push(classNames.apply(null, arg)); else if ("object" === argType) for (var key in arg) hasOwn.call(arg, key) && arg[key] && classes.push(key); } } return classes.join(" "); } var hasOwn = {}.hasOwnProperty; "undefined" != typeof module && module.exports ? module.exports = classNames : (__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), !(void 0 !== __WEBPACK_AMD_DEFINE_RESULT__ && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))); }(); }, /* 4 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; }, /* 5 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function shouldPureComponentUpdate(nextProps, nextState) { return !(0, _shallowEqual2["default"])(this.props, nextProps) || !(0, _shallowEqual2["default"])(this.state, nextState); } exports.__esModule = !0, exports["default"] = shouldPureComponentUpdate; var _shallowEqual = __webpack_require__(6), _shallowEqual2 = _interopRequireDefault(_shallowEqual); module.exports = exports["default"]; }, /* 6 */ /***/ function(module, exports) { "use strict"; function shallowEqual(objA, objB) { if (objA === objB) return !0; if ("object" != typeof objA || null === objA || "object" != typeof objB || null === objB) return !1; var keysA = Object.keys(objA), keysB = Object.keys(objB); if (keysA.length !== keysB.length) return !1; for (var bHasOwnProperty = Object.prototype.hasOwnProperty.bind(objB), i = 0; i < keysA.length; i++) if (!bHasOwnProperty(keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) return !1; return !0; } exports.__esModule = !0, exports["default"] = shallowEqual, module.exports = exports["default"]; }, /* 7 */ /***/ function(module, exports) { /** * Detect Element Resize. * Forked in order to guard against unsafe 'window' and 'document' references. * * https://github.com/sdecima/javascript-detect-element-resize * Sebastian Decima * * version: 0.5.3 **/ // Check `document` and `window` in case of server-side rendering "use strict"; var _window; _window = "undefined" != typeof window ? window : "undefined" != typeof self ? self : void 0; var attachEvent = "undefined" != typeof document && document.attachEvent, stylesCreated = !1; if (!attachEvent) { var requestFrame = function() { var raf = _window.requestAnimationFrame || _window.mozRequestAnimationFrame || _window.webkitRequestAnimationFrame || function(fn) { return _window.setTimeout(fn, 20); }; return function(fn) { return raf(fn); }; }(), cancelFrame = function() { var cancel = _window.cancelAnimationFrame || _window.mozCancelAnimationFrame || _window.webkitCancelAnimationFrame || _window.clearTimeout; return function(id) { return cancel(id); }; }(), resetTriggers = function(element) { var triggers = element.__resizeTriggers__, expand = triggers.firstElementChild, contract = triggers.lastElementChild, expandChild = expand.firstElementChild; contract.scrollLeft = contract.scrollWidth, contract.scrollTop = contract.scrollHeight, expandChild.style.width = expand.offsetWidth + 1 + "px", expandChild.style.height = expand.offsetHeight + 1 + "px", expand.scrollLeft = expand.scrollWidth, expand.scrollTop = expand.scrollHeight; }, checkTriggers = function(element) { return element.offsetWidth != element.__resizeLast__.width || element.offsetHeight != element.__resizeLast__.height; }, scrollListener = function(e) { var element = this; resetTriggers(this), this.__resizeRAF__ && cancelFrame(this.__resizeRAF__), this.__resizeRAF__ = requestFrame(function() { checkTriggers(element) && (element.__resizeLast__.width = element.offsetWidth, element.__resizeLast__.height = element.offsetHeight, element.__resizeListeners__.forEach(function(fn) { fn.call(element, e); })); }); }, animation = !1, animationstring = "animation", keyframeprefix = "", animationstartevent = "animationstart", domPrefixes = "Webkit Moz O ms".split(" "), startEvents = "webkitAnimationStart animationstart oAnimationStart MSAnimationStart".split(" "), pfx = "", elm = document.createElement("fakeelement"); if (void 0 !== elm.style.animationName && (animation = !0), animation === !1) for (var i = 0; i < domPrefixes.length; i++) if (void 0 !== elm.style[domPrefixes[i] + "AnimationName"]) { pfx = domPrefixes[i], animationstring = pfx + "Animation", keyframeprefix = "-" + pfx.toLowerCase() + "-", animationstartevent = startEvents[i], animation = !0; break; } var animationName = "resizeanim", animationKeyframes = "@" + keyframeprefix + "keyframes " + animationName + " { from { opacity: 0; } to { opacity: 0; } } ", animationStyle = keyframeprefix + "animation: 1ms " + animationName + "; "; } var createStyles = function() { if (!stylesCreated) { //opacity:0 works around a chrome bug https://code.google.com/p/chromium/issues/detail?id=286360 var css = (animationKeyframes ? animationKeyframes : "") + ".resize-triggers { " + (animationStyle ? animationStyle : "") + 'visibility: hidden; opacity: 0; } .resize-triggers, .resize-triggers > div, .contract-trigger:before { content: " "; display: block; position: absolute; top: 0; left: 0; height: 100%; width: 100%; overflow: hidden; } .resize-triggers > div { background: #eee; overflow: auto; } .contract-trigger:before { width: 200%; height: 200%; }', head = document.head || document.getElementsByTagName("head")[0], style = document.createElement("style"); style.type = "text/css", style.styleSheet ? style.styleSheet.cssText = css : style.appendChild(document.createTextNode(css)), head.appendChild(style), stylesCreated = !0; } }, addResizeListener = function(element, fn) { attachEvent ? element.attachEvent("onresize", fn) : (element.__resizeTriggers__ || ("static" == getComputedStyle(element).position && (element.style.position = "relative"), createStyles(), element.__resizeLast__ = {}, element.__resizeListeners__ = [], (element.__resizeTriggers__ = document.createElement("div")).className = "resize-triggers", element.__resizeTriggers__.innerHTML = '<div class="expand-trigger"><div></div></div><div class="contract-trigger"></div>', element.appendChild(element.__resizeTriggers__), resetTriggers(element), element.addEventListener("scroll", scrollListener, !0), /* Listen for a css animation to detect element display/re-attach */ animationstartevent && element.__resizeTriggers__.addEventListener(animationstartevent, function(e) { e.animationName == animationName && resetTriggers(element); })), element.__resizeListeners__.push(fn)); }, removeResizeListener = function(element, fn) { attachEvent ? element.detachEvent("onresize", fn) : (element.__resizeListeners__.splice(element.__resizeListeners__.indexOf(fn), 1), element.__resizeListeners__.length || (element.removeEventListener("scroll", scrollListener), element.__resizeTriggers__ = !element.removeChild(element.__resizeTriggers__))); }; module.exports = { addResizeListener: addResizeListener, removeResizeListener: removeResizeListener }; }, /* 8 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _FlexTable2 = __webpack_require__(9), _FlexTable3 = _interopRequireDefault(_FlexTable2); exports["default"] = _FlexTable3["default"]; var _FlexTable4 = _interopRequireDefault(_FlexTable2); exports.FlexTable = _FlexTable4["default"], Object.defineProperty(exports, "SortDirection", { enumerable: !0, get: function() { return _FlexTable2.SortDirection; } }), Object.defineProperty(exports, "SortIndicator", { enumerable: !0, get: function() { return _FlexTable2.SortIndicator; } }); var _FlexColumn2 = __webpack_require__(10), _FlexColumn3 = _interopRequireDefault(_FlexColumn2); exports.FlexColumn = _FlexColumn3["default"]; }, /* 9 */ /***/ function(module, exports, __webpack_require__) { "use strict"; 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 ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } function SortIndicator(_ref) { var sortDirection = _ref.sortDirection, classNames = (0, _classnames2["default"])("FlexTable__sortableHeaderIcon", { "FlexTable__sortableHeaderIcon--ASC": sortDirection === SortDirection.ASC, "FlexTable__sortableHeaderIcon--DESC": sortDirection === SortDirection.DESC }); return _react2["default"].createElement("svg", { className: classNames, width: 18, height: 18, viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg" }, sortDirection === SortDirection.ASC ? _react2["default"].createElement("path", { d: "M7 14l5-5 5 5z" }) : _react2["default"].createElement("path", { d: "M7 10l5 5 5-5z" }), _react2["default"].createElement("path", { d: "M0 0h24v24H0z", fill: "none" })); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _get = function(_x, _x2, _x3) { for (var _again = !0; _again; ) { var object = _x, property = _x2, receiver = _x3; _again = !1, null === object && (object = Function.prototype); var desc = Object.getOwnPropertyDescriptor(object, property); if (void 0 !== desc) { if ("value" in desc) return desc.value; var getter = desc.get; if (void 0 === getter) return; return getter.call(receiver); } var parent = Object.getPrototypeOf(object); if (null === parent) return; _x = parent, _x2 = property, _x3 = receiver, _again = !0, desc = parent = void 0; } }; exports.SortIndicator = SortIndicator; var _classnames = __webpack_require__(3), _classnames2 = _interopRequireDefault(_classnames), _FlexColumn = __webpack_require__(10), _FlexColumn2 = _interopRequireDefault(_FlexColumn), _react = __webpack_require__(4), _react2 = _interopRequireDefault(_react), _reactPureRenderFunction = __webpack_require__(5), _reactPureRenderFunction2 = _interopRequireDefault(_reactPureRenderFunction), _VirtualScroll = __webpack_require__(11), _VirtualScroll2 = _interopRequireDefault(_VirtualScroll), SortDirection = { /** * Sort items in ascending order. * This means arranging from the lowest value to the highest (e.g. a-z, 0-9). */ ASC: "ASC", /** * Sort items in descending order. * This means arranging from the highest value to the lowest (e.g. z-a, 9-0). */ DESC: "DESC" }; exports.SortDirection = SortDirection; /** * Table component with fixed headers and virtualized rows for improved performance with large data sets. * This component expects explicit width, height, and padding parameters. */ var FlexTable = function(_Component) { function FlexTable(props) { _classCallCheck(this, FlexTable), _get(Object.getPrototypeOf(FlexTable.prototype), "constructor", this).call(this, props), this.shouldComponentUpdate = _reactPureRenderFunction2["default"], this._createRow = this._createRow.bind(this); } /** * Displayed beside a header to indicate that a FlexTable is currently sorted by this column. */ /** * See VirtualScroll#recomputeRowHeights */ return _inherits(FlexTable, _Component), _createClass(FlexTable, null, [ { key: "propTypes", value: { /** One or more FlexColumns describing the data displayed in this row */ children: function children(props, propName, componentName) { for (var children = _react2["default"].Children.toArray(props.children), i = 0; i < children.length; i++) if (children[i].type !== _FlexColumn2["default"]) return new Error("FlexTable only accepts children of type FlexColumn"); }, /** Optional CSS class name */ className: _react.PropTypes.string, /** Disable rendering the header at all */ disableHeader: _react.PropTypes.bool, /** Optional CSS class to apply to all column headers */ headerClassName: _react.PropTypes.string, /** Fixed height of header row */ headerHeight: _react.PropTypes.number.isRequired, /** Fixed/available height for out DOM element */ height: _react.PropTypes.number.isRequired, /** Horizontal padding of outer DOM element */ horizontalPadding: _react.PropTypes.number, /** Optional renderer to be used in place of table body rows when rowsCount is 0 */ noRowsRenderer: _react.PropTypes.func, /** * Optional callback when a column's header is clicked. * (dataKey: string): void */ onHeaderClick: _react.PropTypes.func, /** * Callback invoked when a user clicks on a table row. * (rowIndex: number): void */ onRowClick: _react.PropTypes.func, /** * Callback invoked with information about the slice of rows that were just rendered. * ({ startIndex, stopIndex }): void */ onRowsRendered: _react.PropTypes.func, /** * Callback invoked whenever the scroll offset changes within the inner scrollable region. * This callback can be used to sync scrolling between lists, tables, or grids. * ({ scrollTop }): void */ onScroll: _react.PropTypes.func.isRequired, /** * Optional CSS class to apply to all table rows (including the header row). * This property can be a CSS class name (string) or a function that returns a class name. * If a function is provided its signature should be: (rowIndex: number): string */ rowClassName: _react.PropTypes.oneOfType([ _react.PropTypes.string, _react.PropTypes.func ]), /** * Callback responsible for returning a data row given an index. * (index: number): any */ rowGetter: _react.PropTypes.func.isRequired, /** * Either a fixed row height (number) or a function that returns the height of a row given its index. * (index: number): number */ rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, /** Number of rows in table. */ rowsCount: _react.PropTypes.number.isRequired, /** * Sort function to be called if a sortable header is clicked. * (dataKey: string, sortDirection: SortDirection): void */ sort: _react.PropTypes.func, /** FlexTable data is currently sorted by this :dataKey (if it is sorted at all) */ sortBy: _react.PropTypes.string, /** FlexTable data is currently sorted in this direction (if it is sorted at all) */ sortDirection: _react.PropTypes.oneOf([ SortDirection.ASC, SortDirection.DESC ]), /** Vertical padding of outer DOM element */ verticalPadding: _react.PropTypes.number }, enumerable: !0 }, { key: "defaultProps", value: { disableHeader: !1, horizontalPadding: 0, noRowsRenderer: function() { return null; }, onHeaderClick: function() { return null; }, onRowClick: function() { return null; }, onRowsRendered: function() { return null; }, onScroll: function() { return null; }, verticalPadding: 0 }, enumerable: !0 } ]), _createClass(FlexTable, [ { key: "recomputeRowHeights", value: function() { this.refs.VirtualScroll.recomputeRowHeights(); } }, { key: "scrollToRow", value: function(scrollToIndex) { this.refs.VirtualScroll.scrollToRow(scrollToIndex); } }, { key: "setScrollTop", value: function(scrollTop) { this.refs.VirtualScroll.setScrollTop(scrollTop); } }, { key: "render", value: function() { var _this = this, _props = this.props, className = _props.className, disableHeader = _props.disableHeader, headerHeight = _props.headerHeight, height = _props.height, noRowsRenderer = _props.noRowsRenderer, onRowsRendered = _props.onRowsRendered, onScroll = _props.onScroll, rowClassName = _props.rowClassName, rowHeight = _props.rowHeight, rowsCount = _props.rowsCount, verticalPadding = _props.verticalPadding, availableRowsHeight = height - headerHeight - verticalPadding, rowRenderer = function(index) { return _this._createRow(index); }, rowClass = rowClassName instanceof Function ? rowClassName(-1) : rowClassName; return _react2["default"].createElement("div", { className: (0, _classnames2["default"])("FlexTable", className) }, !disableHeader && _react2["default"].createElement("div", { className: (0, _classnames2["default"])("FlexTable__headerRow", rowClass), style: { height: headerHeight } }, this._getRenderedHeaderRow()), _react2["default"].createElement(_VirtualScroll2["default"], { ref: "VirtualScroll", height: availableRowsHeight, noRowsRenderer: noRowsRenderer, onRowsRendered: onRowsRendered, onScroll: onScroll, rowHeight: rowHeight, rowRenderer: rowRenderer, rowsCount: rowsCount })); } }, { key: "_createColumn", value: function(column, columnIndex, rowData, rowIndex) { var _column$props = column.props, cellClassName = _column$props.cellClassName, cellDataGetter = _column$props.cellDataGetter, columnData = _column$props.columnData, dataKey = _column$props.dataKey, cellRenderer = _column$props.cellRenderer, cellData = cellDataGetter(dataKey, rowData, columnData), renderedCell = cellRenderer(cellData, dataKey, rowData, rowIndex, columnData), style = this._getFlexStyleForColumn(column), title = "string" == typeof renderedCell ? renderedCell : null; return _react2["default"].createElement("div", { key: "Row" + rowIndex + "-Col" + columnIndex, className: (0, _classnames2["default"])("FlexTable__rowColumn", cellClassName), style: style }, _react2["default"].createElement("div", { className: "FlexTable__truncatedColumnText", title: title }, renderedCell)); } }, { key: "_createHeader", value: function(column, columnIndex) { var _props2 = this.props, headerClassName = _props2.headerClassName, onHeaderClick = _props2.onHeaderClick, sort = _props2.sort, sortBy = _props2.sortBy, sortDirection = _props2.sortDirection, _column$props2 = column.props, dataKey = _column$props2.dataKey, disableSort = _column$props2.disableSort, label = _column$props2.label, columnData = _column$props2.columnData, showSortIndicator = sortBy === dataKey, sortEnabled = !disableSort && sort, classNames = (0, _classnames2["default"])("FlexTable__headerColumn", headerClassName, column.props.headerClassName, { FlexTable__sortableHeaderColumn: sortEnabled }), style = this._getFlexStyleForColumn(column), newSortDirection = sortBy !== dataKey || sortDirection === SortDirection.DESC ? SortDirection.ASC : SortDirection.DESC, onClick = function() { sortEnabled && sort(dataKey, newSortDirection), onHeaderClick(dataKey, columnData); }; return _react2["default"].createElement("div", { key: "Header-Col" + columnIndex, className: classNames, style: style, onClick: onClick }, _react2["default"].createElement("div", { className: "FlexTable__headerTruncatedText", title: label }, label), showSortIndicator && _react2["default"].createElement(SortIndicator, { sortDirection: sortDirection })); } }, { key: "_createRow", value: function(rowIndex) { var _this2 = this, _props3 = this.props, children = _props3.children, onRowClick = _props3.onRowClick, rowClassName = _props3.rowClassName, rowGetter = _props3.rowGetter, rowClass = rowClassName instanceof Function ? rowClassName(rowIndex) : rowClassName, renderedRow = _react2["default"].Children.map(children, function(column, columnIndex) { return _this2._createColumn(column, columnIndex, rowGetter(rowIndex), rowIndex); }); return _react2["default"].createElement("div", { key: rowIndex, className: (0, _classnames2["default"])("FlexTable__row", rowClass), onClick: function() { return onRowClick(rowIndex); }, style: { height: this._getRowHeight(rowIndex) } }, renderedRow); } }, { key: "_getFlexStyleForColumn", value: function(column) { var flex = []; flex.push(column.props.flexGrow), flex.push(column.props.flexShrink), flex.push(column.props.width ? column.props.width + "px" : "auto"); var flexValue = flex.join(" "); return { flex: flexValue, msFlex: flexValue, WebkitFlex: flexValue }; } }, { key: "_getRenderedHeaderRow", value: function() { var _this3 = this, _props4 = this.props, children = _props4.children, disableHeader = _props4.disableHeader, items = disableHeader ? [] : children; return _react2["default"].Children.map(items, function(column, columnIndex) { return _this3._createHeader(column, columnIndex); }); } }, { key: "_getRowHeight", value: function(rowIndex) { var rowHeight = this.props.rowHeight; return rowHeight instanceof Function ? rowHeight(rowIndex) : rowHeight; } } ]), FlexTable; }(_react.Component); exports["default"] = FlexTable, SortIndicator.propTypes = { sortDirection: _react.PropTypes.oneOf([ SortDirection.ASC, SortDirection.DESC ]) }; }, /* 10 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } /** * Default cell renderer that displays an attribute as a simple string * You should override the column's cellRenderer if your data is some other type of object. */ function defaultCellRenderer(cellData, cellDataKey, rowData, rowIndex, columnData) { return null === cellData || void 0 === cellData ? "" : String(cellData); } /** * Default accessor for returning a cell value for a given attribute. * This function expects to operate on either a vanilla Object or an Immutable Map. * You should override the column's cellDataGetter if your data is some other type of object. */ function defaultCellDataGetter(dataKey, rowData, columnData) { return rowData.get instanceof Function ? rowData.get(dataKey) : rowData[dataKey]; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _get = function(_x, _x2, _x3) { for (var _again = !0; _again; ) { var object = _x, property = _x2, receiver = _x3; _again = !1, null === object && (object = Function.prototype); var desc = Object.getOwnPropertyDescriptor(object, property); if (void 0 !== desc) { if ("value" in desc) return desc.value; var getter = desc.get; if (void 0 === getter) return; return getter.call(receiver); } var parent = Object.getPrototypeOf(object); if (null === parent) return; _x = parent, _x2 = property, _x3 = receiver, _again = !0, desc = parent = void 0; } }; exports.defaultCellRenderer = defaultCellRenderer, exports.defaultCellDataGetter = defaultCellDataGetter; var _react = __webpack_require__(4), Column = function(_Component) { function Column() { _classCallCheck(this, Column), _get(Object.getPrototypeOf(Column.prototype), "constructor", this).apply(this, arguments); } return _inherits(Column, _Component), _createClass(Column, null, [ { key: "defaultProps", value: { cellDataGetter: defaultCellDataGetter, cellRenderer: defaultCellRenderer, flexGrow: 0, flexShrink: 1 }, enumerable: !0 }, { key: "propTypes", value: { /** Optional CSS class to apply to cell */ cellClassName: _react.PropTypes.string, /** * Callback responsible for returning a cell's data, given its :dataKey * (dataKey: string, rowData: any): any */ cellDataGetter: _react.PropTypes.func, /** * Callback responsible for rendering a cell's contents. * (cellData: any, cellDataKey: string, rowData: any, rowIndex: number, columnData: any): element */ cellRenderer: _react.PropTypes.func, /** Optional additional data passed to this column's :cellDataGetter */ columnData: _react.PropTypes.object, /** Uniquely identifies the row-data attribute correspnding to this cell */ dataKey: _react.PropTypes.any.isRequired, /** If sort is enabled for the table at large, disable it for this column */ disableSort: _react.PropTypes.bool, /** Flex grow style; defaults to 0 */ flexGrow: _react.PropTypes.number, /** Flex shrink style; defaults to 1 */ flexShrink: _react.PropTypes.number, /** Optional CSS class to apply to this column's header */ headerClassName: _react.PropTypes.string, /** Header label for this column */ label: _react.PropTypes.string, /** Optional fixed width for this column */ width: _react.PropTypes.number }, enumerable: !0 } ]), Column; }(_react.Component); exports["default"] = Column; }, /* 11 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _VirtualScroll2 = __webpack_require__(12), _VirtualScroll3 = _interopRequireDefault(_VirtualScroll2); exports["default"] = _VirtualScroll3["default"]; var _VirtualScroll4 = _interopRequireDefault(_VirtualScroll2); exports.VirtualScroll = _VirtualScroll4["default"]; }, /* 12 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(setImmediate, clearImmediate) { "use strict"; 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 ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _get = function(_x, _x2, _x3) { for (var _again = !0; _again; ) { var object = _x, property = _x2, receiver = _x3; _again = !1, null === object && (object = Function.prototype); var desc = Object.getOwnPropertyDescriptor(object, property); if (void 0 !== desc) { if ("value" in desc) return desc.value; var getter = desc.get; if (void 0 === getter) return; return getter.call(receiver); } var parent = Object.getPrototypeOf(object); if (null === parent) return; _x = parent, _x2 = property, _x3 = receiver, _again = !0, desc = parent = void 0; } }, _utils = __webpack_require__(15), _classnames = __webpack_require__(3), _classnames2 = _interopRequireDefault(_classnames), _raf = __webpack_require__(16), _raf2 = _interopRequireDefault(_raf), _react = __webpack_require__(4), _react2 = _interopRequireDefault(_react), _reactPureRenderFunction = __webpack_require__(5), _reactPureRenderFunction2 = _interopRequireDefault(_reactPureRenderFunction), IS_SCROLLING_TIMEOUT = 150, VirtualScroll = function(_Component) { function VirtualScroll(props, context) { _classCallCheck(this, VirtualScroll), _get(Object.getPrototypeOf(VirtualScroll.prototype), "constructor", this).call(this, props, context), this.shouldComponentUpdate = _reactPureRenderFunction2["default"], this.state = { computeCellMetadataOnNextUpdate: !1, isScrolling: !1, scrollTop: 0 }, // Invokes onRowsRendered callback only when start/stop row indices change this._onRowsRenderedMemoizer = (0, _utils.createCallbackMemoizer)(), this._onScrollMemoizer = (0, _utils.createCallbackMemoizer)(!1), // Bind functions to instance so they don't lose context when passed around this._computeCellMetadata = this._computeCellMetadata.bind(this), this._invokeOnRowsRenderedHelper = this._invokeOnRowsRenderedHelper.bind(this), this._onKeyPress = this._onKeyPress.bind(this), this._onScroll = this._onScroll.bind(this), this._onWheel = this._onWheel.bind(this), this._updateScrollTopForScrollToIndex = this._updateScrollTopForScrollToIndex.bind(this); } /** * Forced recompute of row heights. * This function should be called if dynamic row heights have changed but nothing else has. * Since VirtualScroll receives a :rowsCount it has no way of knowing if the underlying list data has changed. */ return _inherits(VirtualScroll, _Component), _createClass(VirtualScroll, null, [ { key: "propTypes", value: { /** Optional CSS class name */ className: _react.PropTypes.string, /** Height constraint for list (determines how many actual rows are rendered) */ height: _react.PropTypes.number.isRequired, /** Optional renderer to be used in place of rows when rowsCount is 0 */ noRowsRenderer: _react.PropTypes.func.isRequired, /** * Callback invoked with information about the slice of rows that were just rendered. * ({ startIndex, stopIndex }): void */ onRowsRendered: _react.PropTypes.func.isRequired, /** * Callback invoked whenever the scroll offset changes within the inner scrollable region. * This callback can be used to sync scrolling between lists, tables, or grids. * ({ scrollTop }): void */ onScroll: _react.PropTypes.func.isRequired, /** * Either a fixed row height (number) or a function that returns the height of a row given its index. * (index: number): number */ rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, /** Responsbile for rendering a row given an index */ rowRenderer: _react.PropTypes.func.isRequired, /** Number of rows in list. */ rowsCount: _react.PropTypes.number.isRequired, /** Row index to ensure visible (by forcefully scrolling if necessary) */ scrollToIndex: _react.PropTypes.number }, enumerable: !0 }, { key: "defaultProps", value: { noRowsRenderer: function() { return null; }, onRowsRendered: function() { return null; }, onScroll: function() { return null; } }, enumerable: !0 } ]), _createClass(VirtualScroll, [ { key: "recomputeRowHeights", value: function() { this.setState({ computeCellMetadataOnNextUpdate: !0 }); } }, { key: "scrollToRow", value: function(scrollToIndex) { this._updateScrollTopForScrollToIndex(scrollToIndex); } }, { key: "setScrollTop", value: function(scrollTop) { scrollTop = Number.isNaN(scrollTop) ? 0 : scrollTop, this.setState({ scrollTop: scrollTop }); } }, { key: "componentDidMount", value: function() { var _this = this, scrollToIndex = this.props.scrollToIndex; scrollToIndex >= 0 && (// Without setImmediate() the initial scrollingContainer.scrollTop assignment doesn't work this._scrollTopId = setImmediate(function() { _this._scrollTopId = null, _this._updateScrollTopForScrollToIndex(); })), // Update onRowsRendered callback this._invokeOnRowsRenderedHelper(); } }, { key: "componentDidUpdate", value: function(prevProps, prevState) { var _props = this.props, height = _props.height, rowsCount = _props.rowsCount, rowHeight = _props.rowHeight, scrollToIndex = _props.scrollToIndex, scrollTop = this.state.scrollTop; // Make sure any changes to :scrollTop (from :scrollToIndex) get applied scrollTop >= 0 && scrollTop !== prevState.scrollTop && (this.refs.scrollingContainer.scrollTop = scrollTop), // Update scrollTop if appropriate (0, _utils.updateScrollIndexHelper)({ cellMetadata: this._cellMetadata, cellsCount: rowsCount, cellSize: rowHeight, previousCellsCount: prevProps.rowsCount, previousCellSize: prevProps.rowHeight, previousScrollToIndex: prevProps.scrollToIndex, previousSize: prevProps.height, scrollOffset: scrollTop, scrollToIndex: scrollToIndex, size: height, updateScrollIndexCallback: this._updateScrollTopForScrollToIndex }), // Update onRowsRendered callback if start/stop indices have changed this._invokeOnRowsRenderedHelper(); } }, { key: "componentWillMount", value: function() { this._computeCellMetadata(this.props); } }, { key: "componentWillUnmount", value: function() { this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._scrollTopId && clearImmediate(this._scrollTopId), this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId); } }, { key: "componentWillUpdate", value: function(nextProps, nextState) { 0 === nextProps.rowsCount && 0 !== nextState.scrollTop && this.setState({ scrollTop: 0 }), (0, _utils.computeCellMetadataAndUpdateScrollOffsetHelper)({ cellsCount: this.props.rowsCount, cellSize: this.props.rowHeight, computeMetadataCallback: this._computeCellMetadata, computeMetadataCallbackProps: nextProps, computeMetadataOnNextUpdate: nextState.computeCellMetadataOnNextUpdate, nextCellsCount: nextProps.rowsCount, nextCellSize: nextProps.rowHeight, nextScrollToIndex: nextProps.scrollToIndex, scrollToIndex: this.props.scrollToIndex, updateScrollOffsetForScrollToIndex: this._updateScrollTopForScrollToIndex }), this.setState({ computeCellMetadataOnNextUpdate: !1 }); } }, { key: "render", value: function() { var _props2 = this.props, className = _props2.className, height = _props2.height, noRowsRenderer = _props2.noRowsRenderer, rowsCount = _props2.rowsCount, rowRenderer = _props2.rowRenderer, _state = this.state, isScrolling = _state.isScrolling, scrollTop = _state.scrollTop, childrenToDisplay = []; // Render only enough rows to cover the visible (vertical) area of the table. if (height > 0) { var _getVisibleCellIndices = (0, _utils.getVisibleCellIndices)({ cellCount: rowsCount, cellMetadata: this._cellMetadata, containerSize: height, currentOffset: scrollTop }), start = _getVisibleCellIndices.start, _stop = _getVisibleCellIndices.stop; // Store for onRowsRendered callback in componentDidUpdate this._renderedStartIndex = start, this._renderedStopIndex = _stop; for (var i = start; _stop >= i; i++) { var datum = this._cellMetadata[i], child = rowRenderer(i); child = _react2["default"].createElement("div", { key: i, className: "VirtualScroll__row", style: { top: datum.offset, width: "100%", height: this._getRowHeight(i) } }, child), childrenToDisplay.push(child); } } return _react2["default"].createElement("div", { ref: "scrollingContainer", className: (0, _classnames2["default"])("VirtualScroll", className), onKeyDown: this._onKeyPress, onScroll: this._onScroll, onWheel: this._onWheel, tabIndex: 0, style: { height: height } }, rowsCount > 0 && _react2["default"].createElement("div", { className: "VirtualScroll__innerScrollContainer", style: { height: this._getTotalRowsHeight(), maxHeight: this._getTotalRowsHeight(), pointerEvents: isScrolling ? "none" : "auto" } }, childrenToDisplay), 0 === rowsCount && noRowsRenderer()); } }, { key: "_computeCellMetadata", value: function(props) { var rowHeight = props.rowHeight, rowsCount = props.rowsCount; this._cellMetadata = (0, _utils.initCellMetadata)({ cellCount: rowsCount, size: rowHeight }); } }, { key: "_getRowHeight", value: function(index) { var rowHeight = this.props.rowHeight; return rowHeight instanceof Function ? rowHeight(index) : rowHeight; } }, { key: "_getTotalRowsHeight", value: function() { if (0 === this._cellMetadata.length) return 0; var datum = this._cellMetadata[this._cellMetadata.length - 1]; return datum.offset + datum.size; } }, { key: "_invokeOnRowsRenderedHelper", value: function() { var onRowsRendered = this.props.onRowsRendered; this._onRowsRenderedMemoizer({ callback: onRowsRendered, indices: { startIndex: this._renderedStartIndex, stopIndex: this._renderedStopIndex } }); } }, { key: "_setNextState", value: function(state) { var _this2 = this; this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId), this._setNextStateAnimationFrameId = (0, _raf2["default"])(function() { _this2._setNextStateAnimationFrameId = null, _this2.setState(state); }); } }, { key: "_setNextStateForScrollHelper", value: function(_ref) { var scrollTop = _ref.scrollTop; // Certain devices (like Apple touchpad) rapid-fire duplicate events. // Don't force a re-render if this is the case. this.state.scrollTop !== scrollTop && (// Prevent pointer events from interrupting a smooth scroll this._temporarilyDisablePointerEvents(), // The mouse may move faster then the animation frame does. // Use requestAnimationFrame to avoid over-updating. this._setNextState({ isScrolling: !0, scrollTop: scrollTop })); } }, { key: "_stopEvent", value: function(event) { event.preventDefault(); } }, { key: "_temporarilyDisablePointerEvents", value: function() { var _this3 = this; this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._disablePointerEventsTimeoutId = setTimeout(function() { _this3._disablePointerEventsTimeoutId = null, _this3.setState({ isScrolling: !1 }); }, IS_SCROLLING_TIMEOUT); } }, { key: "_updateScrollTopForScrollToIndex", value: function(scrollToIndexOverride) { var scrollToIndex = void 0 !== scrollToIndexOverride ? scrollToIndexOverride : this.props.scrollToIndex, height = this.props.height, scrollTop = this.state.scrollTop; if (scrollToIndex >= 0) { var calculatedScrollTop = (0, _utils.getUpdatedOffsetForIndex)({ cellMetadata: this._cellMetadata, containerSize: height, currentOffset: scrollTop, targetIndex: scrollToIndex }); scrollTop !== calculatedScrollTop && this.setState({ scrollTop: calculatedScrollTop }); } } }, { key: "_onKeyPress", value: function(event) { var _props3 = this.props, height = _props3.height, rowsCount = _props3.rowsCount, scrollTop = this.state.scrollTop, start = void 0, datum = void 0, newScrollTop = void 0; if (0 !== rowsCount) switch (event.key) { case "ArrowDown": this._stopEvent(event), // Prevent key from also scrolling surrounding window start = (0, _utils.getVisibleCellIndices)({ cellCount: rowsCount, cellMetadata: this._cellMetadata, containerSize: height, currentOffset: scrollTop }).start, datum = this._cellMetadata[start], newScrollTop = Math.min(this._getTotalRowsHeight() - height, scrollTop + datum.size), this.setState({ scrollTop: newScrollTop }); break; case "ArrowUp": this._stopEvent(event), // Prevent key from also scrolling surrounding window start = (0, _utils.getVisibleCellIndices)({ cellCount: rowsCount, cellMetadata: this._cellMetadata, containerSize: height, currentOffset: scrollTop }).start, this.scrollToRow(Math.max(0, start - 1)); } } }, { key: "_onScroll", value: function(event) { // In certain edge-cases React dispatches an onScroll event with an invalid target.scrollTop. // This invalid event can be detected by comparing event.target to this component's scrollable DOM element. // See issue #404 for more information. if (event.target === this.refs.scrollingContainer) { // When this component is shrunk drastically, React dispatches a series of back-to-back scroll events, // Gradually converging on a scrollTop that is within the bounds of the new, smaller height. // This causes a series of rapid renders that is slow for long lists. // We can avoid that by doing some simple bounds checking to ensure that scrollTop never exceeds the total height. var _props4 = this.props, height = _props4.height, onScroll = _props4.onScroll, totalRowsHeight = this._getTotalRowsHeight(), scrollTop = Math.min(totalRowsHeight - height, event.target.scrollTop); this._setNextStateForScrollHelper({ scrollTop: scrollTop }), this._onScrollMemoizer({ callback: onScroll, indices: { scrollTop: scrollTop } }); } } }, { key: "_onWheel", value: function(event) { var onScroll = this.props.onScroll, scrollTop = this.refs.scrollingContainer.scrollTop; this._setNextStateForScrollHelper({ scrollTop: scrollTop }), this._onScrollMemoizer({ callback: onScroll, indices: { scrollTop: scrollTop } }); } } ]), VirtualScroll; }(_react.Component); exports["default"] = VirtualScroll, module.exports = exports["default"]; }).call(exports, __webpack_require__(13).setImmediate, __webpack_require__(13).clearImmediate); }, /* 13 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(setImmediate, clearImmediate) { function Timeout(id, clearFn) { this._id = id, this._clearFn = clearFn; } var nextTick = __webpack_require__(14).nextTick, apply = Function.prototype.apply, slice = Array.prototype.slice, immediateIds = {}, nextImmediateId = 0; // DOM APIs, for completeness exports.setTimeout = function() { return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); }, exports.setInterval = function() { return new Timeout(apply.call(setInterval, window, arguments), clearInterval); }, exports.clearTimeout = exports.clearInterval = function(timeout) { timeout.close(); }, Timeout.prototype.unref = Timeout.prototype.ref = function() {}, Timeout.prototype.close = function() { this._clearFn.call(window, this._id); }, // Does not start the time, just sets up the members needed. exports.enroll = function(item, msecs) { clearTimeout(item._idleTimeoutId), item._idleTimeout = msecs; }, exports.unenroll = function(item) { clearTimeout(item._idleTimeoutId), item._idleTimeout = -1; }, exports._unrefActive = exports.active = function(item) { clearTimeout(item._idleTimeoutId); var msecs = item._idleTimeout; msecs >= 0 && (item._idleTimeoutId = setTimeout(function() { item._onTimeout && item._onTimeout(); }, msecs)); }, // That's not how node.js implements it but the exposed api is the same. exports.setImmediate = "function" == typeof setImmediate ? setImmediate : function(fn) { var id = nextImmediateId++, args = arguments.length < 2 ? !1 : slice.call(arguments, 1); return immediateIds[id] = !0, nextTick(function() { immediateIds[id] && (// fn.call() is faster so we optimize for the common use-case // @see http://jsperf.com/call-apply-segu args ? fn.apply(null, args) : fn.call(null), // Prevent ids from leaking exports.clearImmediate(id)); }), id; }, exports.clearImmediate = "function" == typeof clearImmediate ? clearImmediate : function(id) { delete immediateIds[id]; }; }).call(exports, __webpack_require__(13).setImmediate, __webpack_require__(13).clearImmediate); }, /* 14 */ /***/ function(module, exports) { function cleanUpNextTick() { draining = !1, currentQueue.length ? queue = currentQueue.concat(queue) : queueIndex = -1, queue.length && drainQueue(); } function drainQueue() { if (!draining) { var timeout = setTimeout(cleanUpNextTick); draining = !0; for (var len = queue.length; len; ) { for (currentQueue = queue, queue = []; ++queueIndex < len; ) currentQueue && currentQueue[queueIndex].run(); queueIndex = -1, len = queue.length; } currentQueue = null, draining = !1, clearTimeout(timeout); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun, this.array = array; } function noop() {} // shim for using process in browser var currentQueue, process = module.exports = {}, queue = [], draining = !1, queueIndex = -1; 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)), 1 !== queue.length || draining || setTimeout(drainQueue, 0); }, Item.prototype.run = function() { this.fun.apply(null, this.array); }, process.title = "browser", process.browser = !0, process.env = {}, process.argv = [], process.version = "", // empty string to avoid regexp issues process.versions = {}, 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; }; }, /* 15 */ /***/ function(module, exports) { /** * Helper method that determines when to recalculate row or column metadata. * * @param cellsCount Number of rows or columns in the current axis * @param cellsSize Width or height of cells for the current axis * @param computeMetadataCallback Method to invoke if cell metadata should be recalculated * @param computeMetadataCallbackProps Parameters to pass to :computeMetadataCallback * @param computeMetadataOnNextUpdate Flag specifying that metadata should be recalculated * @param nextCellsCount Newly updated number of rows or columns in the current axis * @param nextCellsSize Newly updated width or height of cells for the current axis * @param nextScrollToIndex Newly updated scroll-to-index * @param scrollToIndex Scroll-to-index * @param updateScrollOffsetForScrollToIndex Callback to invoke if the scroll position should be recalculated */ "use strict"; function computeCellMetadataAndUpdateScrollOffsetHelper(_ref) { var cellsCount = _ref.cellsCount, cellSize = _ref.cellSize, computeMetadataCallback = _ref.computeMetadataCallback, computeMetadataCallbackProps = _ref.computeMetadataCallbackProps, computeMetadataOnNextUpdate = _ref.computeMetadataOnNextUpdate, nextCellsCount = _ref.nextCellsCount, nextCellSize = _ref.nextCellSize, nextScrollToIndex = _ref.nextScrollToIndex, scrollToIndex = _ref.scrollToIndex, updateScrollOffsetForScrollToIndex = _ref.updateScrollOffsetForScrollToIndex; // Don't compare cell sizes if they are functions because inline functions would cause infinite loops. // In that event users should use the manual recompute methods to inform of changes. (computeMetadataOnNextUpdate || cellsCount !== nextCellsCount || ("number" == typeof cellSize || "number" == typeof nextCellSize) && cellSize !== nextCellSize) && (computeMetadataCallback(computeMetadataCallbackProps), // Updated cell metadata may have hidden the previous scrolled-to item. // In this case we should also update the scrollTop to ensure it stays visible. scrollToIndex >= 0 && scrollToIndex === nextScrollToIndex && updateScrollOffsetForScrollToIndex()); } /** * Helper utility that updates the specified callback whenever any of the specified indices have changed. */ function createCallbackMemoizer() { var requireAllKeys = arguments.length <= 0 || void 0 === arguments[0] ? !0 : arguments[0], cachedIndices = {}; return function(_ref2) { var callback = _ref2.callback, indices = _ref2.indices, keys = Object.keys(indices), allInitialized = !requireAllKeys || keys.every(function(key) { return indices[key] >= 0; }), indexChanged = keys.some(function(key) { return cachedIndices[key] !== indices[key]; }); cachedIndices = indices, allInitialized && indexChanged && callback(indices); }; } /** * Binary search function inspired by react-infinite. */ function findNearestCell(_ref3) { // TODO Add better guards here against NaN offset for (var cellMetadata = _ref3.cellMetadata, mode = _ref3.mode, offset = _ref3.offset, high = cellMetadata.length - 1, low = 0, middle = void 0, currentOffset = void 0; high >= low; ) { if (middle = low + Math.floor((high - low) / 2), currentOffset = cellMetadata[middle].offset, currentOffset === offset) return middle; offset > currentOffset ? low = middle + 1 : currentOffset > offset && (high = middle - 1); } return mode === findNearestCell.EQUAL_OR_LOWER && low > 0 ? low - 1 : mode === findNearestCell.EQUAL_OR_HIGHER && high < cellMetadata.length - 1 ? high + 1 : void 0; } /** * Determines a new offset that ensures a certain cell is visible, given the current offset. * If the cell is already visible then the current offset will be returned. * If the current offset is too great or small, it will be adjusted just enough to ensure the specified index is visible. * * @param cellMetadata Metadata initially computed by initCellMetadata() * @param containerSize Total size (width or height) of the container * @param currentOffset Container's current (x or y) offset * @param targetIndex Index of target cell * @return Offset to use to ensure the specified cell is visible */ function getUpdatedOffsetForIndex(_ref4) { var cellMetadata = _ref4.cellMetadata, containerSize = _ref4.containerSize, currentOffset = _ref4.currentOffset, targetIndex = _ref4.targetIndex; if (0 === cellMetadata.length) return 0; targetIndex = Math.max(0, Math.min(cellMetadata.length - 1, targetIndex)); var datum = cellMetadata[targetIndex], maxOffset = datum.offset, minOffset = maxOffset - containerSize + datum.size, newOffset = Math.max(minOffset, Math.min(maxOffset, currentOffset)); return newOffset; } /** * Determines the range of cells to display for a given offset in order to fill the specified container. * * @param cellCount Total number of cells. * @param cellMetadata Metadata initially computed by initCellMetadata() * @param containerSize Total size (width or height) of the container * @param currentOffset Container's current (x or y) offset * @return An object containing :start and :stop attributes, each specifying a cell index */ function getVisibleCellIndices(_ref5) { var cellCount = _ref5.cellCount, cellMetadata = _ref5.cellMetadata, containerSize = _ref5.containerSize, currentOffset = _ref5.currentOffset; if (0 === cellCount) return {}; currentOffset = Math.max(0, currentOffset); var maxOffset = currentOffset + containerSize, start = findNearestCell({ cellMetadata: cellMetadata, mode: findNearestCell.EQUAL_OR_LOWER, offset: currentOffset }), datum = cellMetadata[start]; currentOffset = datum.offset + datum.size; for (var stop = start; maxOffset > currentOffset && cellCount - 1 > stop; ) stop++, currentOffset += cellMetadata[stop].size; return { start: start, stop: stop }; } /** * Initializes metadata for an axis and its cells. * This data is used to determine which cells are visible given a container size and scroll position. * * @param cellCount Total number of cells. * @param size Either a fixed size or a function that returns the size for a given given an index. * @return Object mapping cell index to cell metadata (size, offset) */ function initCellMetadata(_ref6) { for (var cellCount = _ref6.cellCount, size = _ref6.size, sizeGetter = size instanceof Function ? size : function(index) { return size; }, cellMetadata = [], offset = 0, i = 0; cellCount > i; i++) { var _size = sizeGetter(i); if (null == _size || isNaN(_size)) throw Error("Invalid size returned for cell " + i + " of value " + _size); cellMetadata[i] = { size: _size, offset: offset }, offset += _size; } return cellMetadata; } /** * Helper function that determines when to update scroll offsets to ensure that a scroll-to-index remains visible. * * @param cellMetadata Metadata initially computed by initCellMetadata() * @param cellsCount Number of rows or columns in the current axis * @param cellsSize Width or height of cells for the current axis * @param previousCellsCount Previous number of rows or columns * @param previousCellsSize Previous width or height of cells * @param previousScrollToIndex Previous scroll-to-index * @param previousSize Previous width or height of the virtualized container * @param scrollOffset Current scrollLeft or scrollTop * @param scrollToIndex Scroll-to-index * @param size Width or height of the virtualized container * @param updateScrollIndexCallback Callback to invoke with an optional scroll-to-index override */ function updateScrollIndexHelper(_ref7) { var cellMetadata = _ref7.cellMetadata, cellsCount = _ref7.cellsCount, cellSize = _ref7.cellSize, previousCellsCount = _ref7.previousCellsCount, previousCellSize = _ref7.previousCellSize, previousScrollToIndex = _ref7.previousScrollToIndex, previousSize = _ref7.previousSize, scrollOffset = _ref7.scrollOffset, scrollToIndex = _ref7.scrollToIndex, size = _ref7.size, updateScrollIndexCallback = _ref7.updateScrollIndexCallback, hasScrollToIndex = scrollToIndex >= 0 && cellsCount > scrollToIndex, sizeHasChanged = size !== previousSize || !previousCellSize || "number" == typeof cellSize && cellSize !== previousCellSize; // If we have a new scroll target OR if height/row-height has changed, // We should ensure that the scroll target is visible. if (hasScrollToIndex && (sizeHasChanged || scrollToIndex !== previousScrollToIndex)) updateScrollIndexCallback(); else if (!hasScrollToIndex && (previousSize > size || previousCellsCount > cellsCount)) { var calculatedScrollOffset = getUpdatedOffsetForIndex({ cellMetadata: cellMetadata, containerSize: size, currentOffset: scrollOffset, targetIndex: cellsCount - 1 }); // Only adjust the scroll position if we've scrolled below the last set of rows. scrollOffset > calculatedScrollOffset && updateScrollIndexCallback(cellsCount - 1); } } Object.defineProperty(exports, "__esModule", { value: !0 }), exports.computeCellMetadataAndUpdateScrollOffsetHelper = computeCellMetadataAndUpdateScrollOffsetHelper, exports.createCallbackMemoizer = createCallbackMemoizer, exports.findNearestCell = findNearestCell, exports.getUpdatedOffsetForIndex = getUpdatedOffsetForIndex, exports.getVisibleCellIndices = getVisibleCellIndices, exports.initCellMetadata = initCellMetadata, exports.updateScrollIndexHelper = updateScrollIndexHelper, findNearestCell.EQUAL_OR_LOWER = 1, findNearestCell.EQUAL_OR_HIGHER = 2; }, /* 16 */ /***/ function(module, exports, __webpack_require__) { for (var now = __webpack_require__(17), global = "undefined" == typeof window ? {} : window, vendors = [ "moz", "webkit" ], suffix = "AnimationFrame", raf = global["request" + suffix], caf = global["cancel" + suffix] || global["cancelRequest" + suffix], i = 0; i < vendors.length && !raf; i++) raf = global[vendors[i] + "Request" + suffix], caf = global[vendors[i] + "Cancel" + suffix] || global[vendors[i] + "CancelRequest" + suffix]; // Some versions of FF have rAF but not cAF if (!raf || !caf) { var last = 0, id = 0, queue = [], frameDuration = 1e3 / 60; raf = function(callback) { if (0 === queue.length) { var _now = now(), next = Math.max(0, frameDuration - (_now - last)); last = next + _now, setTimeout(function() { var cp = queue.slice(0); // Clear queue here to prevent // callbacks from appending listeners // to the current frame's queue queue.length = 0; for (var i = 0; i < cp.length; i++) if (!cp[i].cancelled) try { cp[i].callback(last); } catch (e) { setTimeout(function() { throw e; }, 0); } }, Math.round(next)); } return queue.push({ handle: ++id, callback: callback, cancelled: !1 }), id; }, caf = function(handle) { for (var i = 0; i < queue.length; i++) queue[i].handle === handle && (queue[i].cancelled = !0); }; } module.exports = function(fn) { // Wrap in a new function to prevent // `cancel` potentially being assigned // to the native rAF function return raf.call(global, fn); }, module.exports.cancel = function() { caf.apply(global, arguments); }; }, /* 17 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(process) { // Generated by CoffeeScript 1.7.1 (function() { var getNanoSeconds, hrtime, loadTime; "undefined" != typeof performance && null !== performance && performance.now ? module.exports = function() { return performance.now(); } : "undefined" != typeof process && null !== process && process.hrtime ? (module.exports = function() { return (getNanoSeconds() - loadTime) / 1e6; }, hrtime = process.hrtime, getNanoSeconds = function() { var hr; return hr = hrtime(), 1e9 * hr[0] + hr[1]; }, loadTime = getNanoSeconds()) : Date.now ? (module.exports = function() { return Date.now() - loadTime; }, loadTime = Date.now()) : (module.exports = function() { return new Date().getTime() - loadTime; }, loadTime = new Date().getTime()); }).call(this); }).call(exports, __webpack_require__(18)); }, /* 18 */ /***/ function(module, exports) { function cleanUpNextTick() { draining = !1, currentQueue.length ? queue = currentQueue.concat(queue) : queueIndex = -1, queue.length && drainQueue(); } function drainQueue() { if (!draining) { var timeout = setTimeout(cleanUpNextTick); draining = !0; for (var len = queue.length; len; ) { for (currentQueue = queue, queue = []; ++queueIndex < len; ) currentQueue && currentQueue[queueIndex].run(); queueIndex = -1, len = queue.length; } currentQueue = null, draining = !1, clearTimeout(timeout); } } // v8 likes predictible objects function Item(fun, array) { this.fun = fun, this.array = array; } function noop() {} // shim for using process in browser var currentQueue, process = module.exports = {}, queue = [], draining = !1, queueIndex = -1; 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)), 1 !== queue.length || draining || setTimeout(drainQueue, 0); }, Item.prototype.run = function() { this.fun.apply(null, this.array); }, process.title = "browser", process.browser = !0, process.env = {}, process.argv = [], process.version = "", // empty string to avoid regexp issues process.versions = {}, 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, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _Grid2 = __webpack_require__(20), _Grid3 = _interopRequireDefault(_Grid2); exports["default"] = _Grid3["default"]; var _Grid4 = _interopRequireDefault(_Grid2); exports.Grid = _Grid4["default"]; }, /* 20 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */ (function(setImmediate, clearImmediate) { "use strict"; 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 ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _get = function(_x, _x2, _x3) { for (var _again = !0; _again; ) { var object = _x, property = _x2, receiver = _x3; _again = !1, null === object && (object = Function.prototype); var desc = Object.getOwnPropertyDescriptor(object, property); if (void 0 !== desc) { if ("value" in desc) return desc.value; var getter = desc.get; if (void 0 === getter) return; return getter.call(receiver); } var parent = Object.getPrototypeOf(object); if (null === parent) return; _x = parent, _x2 = property, _x3 = receiver, _again = !0, desc = parent = void 0; } }, _utils = __webpack_require__(15), _classnames = __webpack_require__(3), _classnames2 = _interopRequireDefault(_classnames), _raf = __webpack_require__(16), _raf2 = _interopRequireDefault(_raf), _react = __webpack_require__(4), _react2 = _interopRequireDefault(_react), _reactPureRenderFunction = __webpack_require__(5), _reactPureRenderFunction2 = _interopRequireDefault(_reactPureRenderFunction), IS_SCROLLING_TIMEOUT = 150, Grid = function(_Component) { function Grid(props, context) { _classCallCheck(this, Grid), _get(Object.getPrototypeOf(Grid.prototype), "constructor", this).call(this, props, context), this.shouldComponentUpdate = _reactPureRenderFunction2["default"], this.state = { computeGridMetadataOnNextUpdate: !1, isScrolling: !1, scrollLeft: 0, scrollTop: 0 }, // Invokes onSectionRendered callback only when start/stop row or column indices change this._onGridRenderedMemoizer = (0, _utils.createCallbackMemoizer)(), this._onScrollMemoizer = (0, _utils.createCallbackMemoizer)(!1), // Bind functions to instance so they don't lose context when passed around this._computeGridMetadata = this._computeGridMetadata.bind(this), this._invokeOnGridRenderedHelper = this._invokeOnGridRenderedHelper.bind(this), this._onKeyPress = this._onKeyPress.bind(this), this._onScroll = this._onScroll.bind(this), this._onWheel = this._onWheel.bind(this), this._updateScrollLeftForScrollToColumn = this._updateScrollLeftForScrollToColumn.bind(this), this._updateScrollTopForScrollToRow = this._updateScrollTopForScrollToRow.bind(this); } /** * Forced recompute of row heights and column widths. * This function should be called if dynamic column or row sizes have changed but nothing else has. * Since Grid only receives :columnsCount and :rowsCount it has no way of detecting when the underlying data changes. */ return _inherits(Grid, _Component), _createClass(Grid, null, [ { key: "propTypes", value: { /** * Optional custom CSS class name to attach to root Grid element. */ className: _react.PropTypes.string, /** * Number of columns in grid. */ columnsCount: _react.PropTypes.number.isRequired, /** * Either a fixed column width (number) or a function that returns the width of a column given its index. * Should implement the following interface: (index: number): number */ columnWidth: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, /** * Height of Grid; this property determines the number of visible (vs virtualized) rows. */ height: _react.PropTypes.number.isRequired, /** * Optional renderer to be used in place of rows when either :rowsCount or :columnsCount is 0. */ noContentRenderer: _react.PropTypes.func.isRequired, /** * Callback invoked whenever the scroll offset changes within the inner scrollable region. * This callback can be used to sync scrolling between lists, tables, or grids. * ({ scrollLeft, scrollTop }): void */ onScroll: _react.PropTypes.func.isRequired, /** * Callback invoked with information about the section of the Grid that was just rendered. * ({ columnStartIndex, columnStopIndex, rowStartIndex, rowStopIndex }): void */ onSectionRendered: _react.PropTypes.func.isRequired, /** * Responsible for rendering a cell given an row and column index. * Should implement the following interface: ({ columnIndex: number, rowIndex: number }): PropTypes.node */ renderCell: _react.PropTypes.func.isRequired, /** * Either a fixed row height (number) or a function that returns the height of a row given its index. * Should implement the following interface: (index: number): number */ rowHeight: _react.PropTypes.oneOfType([ _react.PropTypes.number, _react.PropTypes.func ]).isRequired, /** * Number of rows in grid. */ rowsCount: _react.PropTypes.number.isRequired, /** * Column index to ensure visible (by forcefully scrolling if necessary) */ scrollToColumn: _react.PropTypes.number, /** * Row index to ensure visible (by forcefully scrolling if necessary) */ scrollToRow: _react.PropTypes.number, /** * Width of Grid; this property determines the number of visible (vs virtualized) columns. */ width: _react.PropTypes.number.isRequired }, enumerable: !0 }, { key: "defaultProps", value: { noContentRenderer: function() { return null; }, onScroll: function() { return null; }, onSectionRendered: function() { return null; } }, enumerable: !0 } ]), _createClass(Grid, [ { key: "recomputeGridSize", value: function() { this.setState({ computeGridMetadataOnNextUpdate: !0 }); } }, { key: "scrollToCell", value: function(_ref) { var scrollToColumn = _ref.scrollToColumn, scrollToRow = _ref.scrollToRow; this._updateScrollLeftForScrollToColumn(scrollToColumn), this._updateScrollTopForScrollToRow(scrollToRow); } }, { key: "setScrollPosition", value: function(_ref2) { var scrollLeft = _ref2.scrollLeft, scrollTop = _ref2.scrollTop, props = {}; scrollLeft >= 0 && (props.scrollLeft = scrollLeft), scrollTop >= 0 && (props.scrollTop = scrollTop), (scrollLeft >= 0 && scrollLeft !== this.state.scrollLeft || scrollTop >= 0 && scrollTop !== this.state.scrollTop) && this.setState(props); } }, { key: "componentDidMount", value: function() { var _this = this, _props = this.props, scrollToColumn = _props.scrollToColumn, scrollToRow = _props.scrollToRow; (scrollToColumn >= 0 || scrollToRow >= 0) && (// Without setImmediate() the initial scrollingContainer.scrollTop assignment doesn't work this._setImmediateId = setImmediate(function() { _this._setImmediateId = null, _this._updateScrollLeftForScrollToColumn(), _this._updateScrollTopForScrollToRow(); })), // Update onRowsRendered callback this._invokeOnGridRenderedHelper(); } }, { key: "componentDidUpdate", value: function(prevProps, prevState) { var _props2 = this.props, columnsCount = _props2.columnsCount, columnWidth = _props2.columnWidth, height = _props2.height, rowHeight = _props2.rowHeight, rowsCount = _props2.rowsCount, scrollToColumn = _props2.scrollToColumn, scrollToRow = _props2.scrollToRow, width = _props2.width, _state = this.state, scrollLeft = _state.scrollLeft, scrollTop = _state.scrollTop; // Make sure any changes to :scrollLeft or :scrollTop get applied (scrollLeft >= 0 && scrollLeft !== prevState.scrollLeft || scrollTop >= 0 && scrollTop !== prevState.scrollTop) && (this.refs.scrollingContainer.scrollLeft = scrollLeft, this.refs.scrollingContainer.scrollTop = scrollTop), // Update scrollLeft if appropriate (0, _utils.updateScrollIndexHelper)({ cellMetadata: this._columnMetadata, cellsCount: columnsCount, cellSize: columnWidth, previousCellsCount: prevProps.columnsCount, previousCellSize: prevProps.columnWidth, previousScrollToIndex: prevProps.scrollToColumn, previousSize: prevProps.width, scrollOffset: scrollLeft, scrollToIndex: scrollToColumn, size: width, updateScrollIndexCallback: this._updateScrollLeftForScrollToColumn }), // Update scrollTop if appropriate (0, _utils.updateScrollIndexHelper)({ cellMetadata: this._rowMetadata, cellsCount: rowsCount, cellSize: rowHeight, previousCellsCount: prevProps.rowsCount, previousCellSize: prevProps.rowHeight, previousScrollToIndex: prevProps.scrollToRow, previousSize: prevProps.height, scrollOffset: scrollTop, scrollToIndex: scrollToRow, size: height, updateScrollIndexCallback: this._updateScrollTopForScrollToRow }), // Update onRowsRendered callback if start/stop indices have changed this._invokeOnGridRenderedHelper(); } }, { key: "componentWillMount", value: function() { this._computeGridMetadata(this.props); } }, { key: "componentWillUnmount", value: function() { this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._setImmediateId && clearImmediate(this._setImmediateId), this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId); } }, { key: "componentWillUpdate", value: function(nextProps, nextState) { 0 === nextProps.columnsCount && 0 !== nextState.scrollLeft && this.setState({ scrollLeft: 0 }), 0 === nextProps.rowsCount && 0 !== nextState.scrollTop && this.setState({ scrollTop: 0 }), (0, _utils.computeCellMetadataAndUpdateScrollOffsetHelper)({ cellsCount: this.props.columnsCount, cellSize: this.props.columnWidth, computeMetadataCallback: this._computeGridMetadata, computeMetadataCallbackProps: nextProps, computeMetadataOnNextUpdate: nextState.computeGridMetadataOnNextUpdate, nextCellsCount: nextProps.columnsCount, nextCellSize: nextProps.columnWidth, nextScrollToIndex: nextProps.scrollToColumn, scrollToIndex: this.props.scrollToColumn, updateScrollOffsetForScrollToIndex: this._updateScrollLeftForScrollToColumn }), (0, _utils.computeCellMetadataAndUpdateScrollOffsetHelper)({ cellsCount: this.props.rowsCount, cellSize: this.props.rowHeight, computeMetadataCallback: this._computeGridMetadata, computeMetadataCallbackProps: nextProps, computeMetadataOnNextUpdate: nextState.computeGridMetadataOnNextUpdate, nextCellsCount: nextProps.rowsCount, nextCellSize: nextProps.rowHeight, nextScrollToIndex: nextProps.scrollToRow, scrollToIndex: this.props.scrollToRow, updateScrollOffsetForScrollToIndex: this._updateScrollTopForScrollToRow }), this.setState({ computeGridMetadataOnNextUpdate: !1 }); } }, { key: "render", value: function() { var _props3 = this.props, className = _props3.className, columnsCount = _props3.columnsCount, height = _props3.height, noContentRenderer = _props3.noContentRenderer, renderCell = _props3.renderCell, rowsCount = _props3.rowsCount, width = _props3.width, _state2 = this.state, isScrolling = _state2.isScrolling, scrollLeft = _state2.scrollLeft, scrollTop = _state2.scrollTop, childrenToDisplay = []; // Render only enough columns and rows to cover the visible area of the grid. if (height > 0 && width > 0) { var _getVisibleCellIndices = (0, _utils.getVisibleCellIndices)({ cellCount: columnsCount, cellMetadata: this._columnMetadata, containerSize: width, currentOffset: scrollLeft }), columnStartIndex = _getVisibleCellIndices.start, columnStopIndex = _getVisibleCellIndices.stop, _getVisibleCellIndices2 = (0, _utils.getVisibleCellIndices)({ cellCount: rowsCount, cellMetadata: this._rowMetadata, containerSize: height, currentOffset: scrollTop }), rowStartIndex = _getVisibleCellIndices2.start, rowStopIndex = _getVisibleCellIndices2.stop; // Store for :onSectionRendered callback in componentDidUpdate this._renderedColumnStartIndex = columnStartIndex, this._renderedColumnStopIndex = columnStopIndex, this._renderedRowStartIndex = rowStartIndex, this._renderedRowStopIndex = rowStopIndex; for (var rowIndex = rowStartIndex; rowStopIndex >= rowIndex; rowIndex++) for (var rowDatum = this._rowMetadata[rowIndex], columnIndex = columnStartIndex; columnStopIndex >= columnIndex; columnIndex++) { var columnDatum = this._columnMetadata[columnIndex], child = renderCell({ columnIndex: columnIndex, rowIndex: rowIndex }); child = _react2["default"].createElement("div", { key: "row:" + rowIndex + ", column:" + columnIndex, className: "Grid__cell", style: { left: columnDatum.offset, top: rowDatum.offset, height: this._getRowHeight(rowIndex), width: this._getColumnWidth(columnIndex) } }, child), childrenToDisplay.push(child); } } return _react2["default"].createElement("div", { ref: "scrollingContainer", className: (0, _classnames2["default"])("Grid", className), onKeyDown: this._onKeyPress, onScroll: this._onScroll, onWheel: this._onWheel, tabIndex: 0, style: { height: height, width: width } }, childrenToDisplay.length > 0 && _react2["default"].createElement("div", { className: "Grid__innerScrollContainer", style: { width: this._getTotalColumnsWidth(), height: this._getTotalRowsHeight(), maxWidth: this._getTotalColumnsWidth(), maxHeight: this._getTotalRowsHeight(), pointerEvents: isScrolling ? "none" : "auto" } }, childrenToDisplay), 0 === childrenToDisplay.length && noContentRenderer()); } }, { key: "_computeGridMetadata", value: function(props) { var columnsCount = props.columnsCount, columnWidth = props.columnWidth, rowHeight = props.rowHeight, rowsCount = props.rowsCount; this._columnMetadata = (0, _utils.initCellMetadata)({ cellCount: columnsCount, size: columnWidth }), this._rowMetadata = (0, _utils.initCellMetadata)({ cellCount: rowsCount, size: rowHeight }); } }, { key: "_getColumnWidth", value: function(index) { var columnWidth = this.props.columnWidth; return columnWidth instanceof Function ? columnWidth(index) : columnWidth; } }, { key: "_getRowHeight", value: function(index) { var rowHeight = this.props.rowHeight; return rowHeight instanceof Function ? rowHeight(index) : rowHeight; } }, { key: "_getTotalColumnsWidth", value: function() { if (0 === this._columnMetadata.length) return 0; var datum = this._columnMetadata[this._columnMetadata.length - 1]; return datum.offset + datum.size; } }, { key: "_getTotalRowsHeight", value: function() { if (0 === this._rowMetadata.length) return 0; var datum = this._rowMetadata[this._rowMetadata.length - 1]; return datum.offset + datum.size; } }, { key: "_invokeOnGridRenderedHelper", value: function() { var onSectionRendered = this.props.onSectionRendered; this._onGridRenderedMemoizer({ callback: onSectionRendered, indices: { columnStartIndex: this._renderedColumnStartIndex, columnStopIndex: this._renderedColumnStopIndex, rowStartIndex: this._renderedRowStartIndex, rowStopIndex: this._renderedRowStopIndex } }); } }, { key: "_setNextState", value: function(state) { var _this2 = this; this._setNextStateAnimationFrameId && _raf2["default"].cancel(this._setNextStateAnimationFrameId), this._setNextStateAnimationFrameId = (0, _raf2["default"])(function() { _this2._setNextStateAnimationFrameId = null, _this2.setState(state); }); } }, { key: "_setNextStateForScrollHelper", value: function(_ref3) { var scrollLeft = _ref3.scrollLeft, scrollTop = _ref3.scrollTop; // Certain devices (like Apple touchpad) rapid-fire duplicate events. // Don't force a re-render if this is the case. (this.state.scrollLeft !== scrollLeft || this.state.scrollTop !== scrollTop) && (// Prevent pointer events from interrupting a smooth scroll this._temporarilyDisablePointerEvents(), // The mouse may move faster then the animation frame does. // Use requestAnimationFrame to avoid over-updating. this._setNextState({ isScrolling: !0, scrollLeft: scrollLeft, scrollTop: scrollTop })); } }, { key: "_stopEvent", value: function(event) { event.preventDefault(); } }, { key: "_temporarilyDisablePointerEvents", value: function() { var _this3 = this; this._disablePointerEventsTimeoutId && clearTimeout(this._disablePointerEventsTimeoutId), this._disablePointerEventsTimeoutId = setTimeout(function() { _this3._disablePointerEventsTimeoutId = null, _this3.setState({ isScrolling: !1 }); }, IS_SCROLLING_TIMEOUT); } }, { key: "_updateScrollLeftForScrollToColumn", value: function(scrollToColumnOverride) { var scrollToColumn = null != scrollToColumnOverride ? scrollToColumnOverride : this.props.scrollToColumn, width = this.props.width, scrollLeft = this.state.scrollLeft; if (scrollToColumn >= 0) { var calculatedScrollLeft = (0, _utils.getUpdatedOffsetForIndex)({ cellMetadata: this._columnMetadata, containerSize: width, currentOffset: scrollLeft, targetIndex: scrollToColumn }); scrollLeft !== calculatedScrollLeft && this.setState({ scrollLeft: calculatedScrollLeft }); } } }, { key: "_updateScrollTopForScrollToRow", value: function(scrollToRowOverride) { var scrollToRow = null != scrollToRowOverride ? scrollToRowOverride : this.props.scrollToRow, height = this.props.height, scrollTop = this.state.scrollTop; if (scrollToRow >= 0) { var calculatedScrollTop = (0, _utils.getUpdatedOffsetForIndex)({ cellMetadata: this._rowMetadata, containerSize: height, currentOffset: scrollTop, targetIndex: scrollToRow }); scrollTop !== calculatedScrollTop && this.setState({ scrollTop: calculatedScrollTop }); } } }, { key: "_onKeyPress", value: function(event) { var _props4 = this.props, columnsCount = _props4.columnsCount, height = _props4.height, rowsCount = _props4.rowsCount, width = _props4.width, _state3 = this.state, scrollLeft = _state3.scrollLeft, scrollTop = _state3.scrollTop, start = void 0, datum = void 0, newScrollLeft = void 0, newScrollTop = void 0; if (0 !== columnsCount && 0 !== rowsCount) switch (event.key) { case "ArrowDown": this._stopEvent(event), // Prevent key from also scrolling surrounding window start = (0, _utils.getVisibleCellIndices)({ cellCount: rowsCount, cellMetadata: this._rowMetadata, containerSize: height, currentOffset: scrollTop }).start, datum = this._rowMetadata[start], newScrollTop = Math.min(this._getTotalRowsHeight() - height, scrollTop + datum.size), this.setState({ scrollTop: newScrollTop }); break; case "ArrowLeft": this._stopEvent(event), // Prevent key from also scrolling surrounding window start = (0, _utils.getVisibleCellIndices)({ cellCount: columnsCount, cellMetadata: this._columnMetadata, containerSize: width, currentOffset: scrollLeft }).start, this.scrollToCell({ scrollToColumn: Math.max(0, start - 1), scrollToRow: this.props.scrollToRow }); break; case "ArrowRight": this._stopEvent(event), // Prevent key from also scrolling surrounding window start = (0, _utils.getVisibleCellIndices)({ cellCount: columnsCount, cellMetadata: this._columnMetadata, containerSize: width, currentOffset: scrollLeft }).start, datum = this._columnMetadata[start], newScrollLeft = Math.min(this._getTotalColumnsWidth() - width, scrollLeft + datum.size), this.setState({ scrollLeft: newScrollLeft }); break; case "ArrowUp": this._stopEvent(event), // Prevent key from also scrolling surrounding window start = (0, _utils.getVisibleCellIndices)({ cellCount: rowsCount, cellMetadata: this._rowMetadata, containerSize: height, currentOffset: scrollTop }).start, this.scrollToCell({ scrollToColumn: this.props.scrollToColumn, scrollToRow: Math.max(0, start - 1) }); } } }, { key: "_onScroll", value: function(event) { // In certain edge-cases React dispatches an onScroll event with an invalid target.scrollLeft / target.scrollTop. // This invalid event can be detected by comparing event.target to this component's scrollable DOM element. // See issue #404 for more information. if (event.target === this.refs.scrollingContainer) { // When this component is shrunk drastically, React dispatches a series of back-to-back scroll events, // Gradually converging on a scrollTop that is within the bounds of the new, smaller height. // This causes a series of rapid renders that is slow for long lists. // We can avoid that by doing some simple bounds checking to ensure that scrollTop never exceeds the total height. var _props5 = this.props, height = _props5.height, onScroll = _props5.onScroll, width = _props5.width, totalRowsHeight = this._getTotalRowsHeight(), totalColumnsWidth = this._getTotalColumnsWidth(), scrollLeft = Math.min(totalColumnsWidth - width, event.target.scrollLeft), scrollTop = Math.min(totalRowsHeight - height, event.target.scrollTop); this._setNextStateForScrollHelper({ scrollLeft: scrollLeft, scrollTop: scrollTop }), this._onScrollMemoizer({ callback: onScroll, indices: { scrollLeft: scrollLeft, scrollTop: scrollTop } }); } } }, { key: "_onWheel", value: function(event) { var onScroll = this.props.onScroll, scrollLeft = this.refs.scrollingContainer.scrollLeft, scrollTop = this.refs.scrollingContainer.scrollTop; this._setNextStateForScrollHelper({ scrollLeft: scrollLeft, scrollTop: scrollTop }), this._onScrollMemoizer({ callback: onScroll, indices: { scrollLeft: scrollLeft, scrollTop: scrollTop } }); } } ]), Grid; }(_react.Component); exports["default"] = Grid, module.exports = exports["default"]; }).call(exports, __webpack_require__(13).setImmediate, __webpack_require__(13).clearImmediate); }, /* 21 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _InfiniteLoader2 = __webpack_require__(22), _InfiniteLoader3 = _interopRequireDefault(_InfiniteLoader2); exports["default"] = _InfiniteLoader3["default"]; var _InfiniteLoader4 = _interopRequireDefault(_InfiniteLoader2); exports.InfiniteLoader = _InfiniteLoader4["default"]; }, /* 22 */ /***/ function(module, exports, __webpack_require__) { "use strict"; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) keys.indexOf(i) >= 0 || Object.prototype.hasOwnProperty.call(obj, i) && (target[i] = obj[i]); return target; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) throw new TypeError("Cannot call a class as a function"); } function _inherits(subClass, superClass) { if ("function" != typeof superClass && null !== superClass) 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: !1, writable: !0, configurable: !0 } }), superClass && (Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass); } function isRangeVisible(_ref2) { var lastRenderedStartIndex = _ref2.lastRenderedStartIndex, lastRenderedStopIndex = _ref2.lastRenderedStopIndex, startIndex = _ref2.startIndex, stopIndex = _ref2.stopIndex; return !(startIndex > lastRenderedStopIndex || lastRenderedStartIndex > stopIndex); } /** * Returns all of the ranges within a larger range that contain unloaded rows. */ function scanForUnloadedRanges(_ref3) { for (var isRowLoaded = _ref3.isRowLoaded, startIndex = _ref3.startIndex, stopIndex = _ref3.stopIndex, unloadedRanges = [], rangeStartIndex = null, rangeStopIndex = null, i = startIndex; stopIndex >= i; i++) { var loaded = isRowLoaded(i); loaded ? null !== rangeStopIndex && (unloadedRanges.push({ startIndex: rangeStartIndex, stopIndex: rangeStopIndex }), rangeStartIndex = rangeStopIndex = null) : (rangeStopIndex = i, null === rangeStartIndex && (rangeStartIndex = i)); } return null !== rangeStopIndex && unloadedRanges.push({ startIndex: rangeStartIndex, stopIndex: rangeStopIndex }), unloadedRanges; } Object.defineProperty(exports, "__esModule", { value: !0 }); var _createClass = function() { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || !1, descriptor.configurable = !0, "value" in descriptor && (descriptor.writable = !0), Object.defineProperty(target, descriptor.key, descriptor); } } return function(Constructor, protoProps, staticProps) { return protoProps && defineProperties(Constructor.prototype, protoProps), staticProps && defineProperties(Constructor, staticProps), Constructor; }; }(), _get = function(_x, _x2, _x3) { for (var _again = !0; _again; ) { var object = _x, property = _x2, receiver = _x3; _again = !1, null === object && (object = Function.prototype); var desc = Object.getOwnPropertyDescriptor(object, property); if (void 0 !== desc) { if ("value" in desc) return desc.value; var getter = desc.get; if (void 0 === getter) return; return getter.call(receiver); } var parent = Object.getPrototypeOf(object); if (null === parent) return; _x = parent, _x2 = property, _x3 = receiver, _again = !0, desc = parent = void 0; } }; exports.isRangeVisible = isRangeVisible, exports.scanForUnloadedRanges = scanForUnloadedRanges; var _FlexTable = __webpack_require__(8), _FlexTable2 = _interopRequireDefault(_FlexTable), _react = __webpack_require__(4), _react2 = _interopRequireDefault(_react), _reactPureRenderFunction = __webpack_require__(5), _reactPureRenderFunction2 = _interopRequireDefault(_reactPureRenderFunction), _VirtualScroll = __webpack_require__(11), _VirtualScroll2 = _interopRequireDefault(_VirtualScroll), InfiniteLoader = function(_Component) { function InfiniteLoader(props) { _classCallCheck(this, InfiniteLoader), _get(Object.getPrototypeOf(InfiniteLoader.prototype), "constructor", this).call(this, props), this.shouldComponentUpdate = _reactPureRenderFunction2["default"], this._onRowsRendered = this._onRowsRendered.bind(this); } /** * Determines if the specified start/stop range is visible based on the most recently rendered range. */ return _inherits(InfiniteLoader, _Component), _createClass(InfiniteLoader, null, [ { key: "propTypes", value: { /** Children must be either FlexTable or VirtualScroll */ children: function(props, propName, componentName) { var error = void 0; return _react2["default"].Children.forEach(props.children, function(child) { child.type !== _FlexTable2["default"] && child.type !== _VirtualScroll2["default"] && (error = new Error("InfiniteLoader only accepts children of types FlexTable or VirtualScroll not " + child.type)); }), error; }, /** * Function responsible for tracking the loaded state of each row. * It should implement the following signature: (index: number): boolean */ isRowLoaded: _react.PropTypes.func, /** * Callback to be invoked when more rows must be loaded. * It should implement the following signature: ({ startIndex, stopIndex }): Promise * The returned Promise should be resolved once row data has finished loading. * It will be used to determine when to refresh the list with the newly-loaded data. * This callback may be called multiple times in reaction to a single scroll event. */ loadMoreRows: _react.PropTypes.func.isRequired, /** * Number of rows in list; can be arbitrary high number if actual number is unknown. */ rowsCount: _react.PropTypes.number, /** * Threshold at which to pre-fetch data. * A threshold X means that data will start loading when a user scrolls within X rows. * This value defaults to 15. */ threshold: _react.PropTypes.number }, enumerable: !0 }, { key: "defaultProps", value: { threshold: 15 }, enumerable: !0 } ]), _createClass(InfiniteLoader, [ { key: "componentDidReceiveProps", value: function(previousProps) { var children = this.props.children; if (previousProps.children !== children) { var child = _react2["default"].Children.only(children); this._originalOnRowsRendered = child.props.onRowsRendered; } } }, { key: "componentWillMount", value: function() { var children = this.props.children, child = _react2["default"].Children.only(children); this._originalOnRowsRendered = child.props.onRowsRendered; } }, { key: "render", value: function() { var _props = this.props, children = _props.children, child = (_objectWithoutProperties(_props, [ "children" ]), _react2["default"].Children.only(children)); return child = _react2["default"].cloneElement(child, { onRowsRendered: this._onRowsRendered, ref: "VirtualScroll" }); } }, { key: "_onRowsRendered", value: function(_ref) { var _this = this, startIndex = _ref.startIndex, stopIndex = _ref.stopIndex, _props2 = this.props, isRowLoaded = _props2.isRowLoaded, loadMoreRows = _props2.loadMoreRows, rowsCount = _props2.rowsCount, threshold = _props2.threshold; this._lastRenderedStartIndex = startIndex, this._lastRenderedStopIndex = stopIndex; var unloadedRanges = scanForUnloadedRanges({ isRowLoaded: isRowLoaded, startIndex: Math.max(0, startIndex - threshold), stopIndex: Math.min(rowsCount, stopIndex + threshold) }); unloadedRanges.forEach(function(unloadedRange) { var promise = loadMoreRows(unloadedRange); promise && promise.then(function() { // Refresh the visible rows if any of them have just been loaded isRangeVisible({ lastRenderedStartIndex: _this._lastRenderedStartIndex, lastRenderedStopIndex: _this._lastRenderedStopIndex, startIndex: unloadedRange.startIndex, stopIndex: unloadedRange.stopIndex }) && _this.refs.VirtualScroll && _this.refs.VirtualScroll.forceUpdate(); }); }), this._originalOnRowsRendered && this._originalOnRowsRendered({ startIndex: startIndex, stopIndex: stopIndex }); } } ]), InfiniteLoader; }(_react.Component); exports["default"] = InfiniteLoader; } ]); }); //# sourceMappingURL=react-virtualized.js.map
src/browser/components/Checkbox.js
chad099/react-native-boilerplate
// @flow import type { Color } from '../../common/themes/types'; import React from 'react'; import { Button, Text } from '../../common/components'; // Checkbox with SVG icon. // - flaticon.com // - thenounproject.com // TODO: Make it universal. Add focus style. export type CheckboxProps = { color?: Color, disabled?: boolean, inline?: boolean, label?: string, labelPosition?: 'left' | 'right', onChange?: ({ value: any }) => void, size?: number, svgIconChecked?: React.Element<*>, svgIconUnchecked?: React.Element<*>, value?: any, }; const DefaultSvgIconChecked = ( <svg viewBox="0 0 32 32"> <path d="M2 15 L6 11 L14 19 L28 5 L32 9 L14 27 z" /> </svg> ); const DefaultSvgIconUnchecked = ( <svg viewBox="-16 -16 512 512"> <path d="M405.333,106.667v298.666H106.667V106.667H405.333 M405.333,64H106.667C83.198,64,64,83.198,64,106.667v298.666 C64,428.802,83.198,448,106.667,448h298.666C428.802,448,448,428.802,448,405.333V106.667C448,83.198,428.802,64,405.333,64 L405.333,64z" /> </svg> ); const SvgIcon = ({ color, size, svgIcon, ...props }) => ( <Text as={svgProps => React.cloneElement(svgIcon, svgProps)} style={theme => ({ fill: theme.colors[color], height: theme.typography.fontSize(size), width: theme.typography.fontSize(size), })} {...props} /> ); const marginVertical = labelPosition => ({ [labelPosition === 'right' ? 'marginRight' : 'marginLeft']: 0.5, }); const Checkbox = ( { color = 'black', disabled, inline, label, labelPosition = 'right', onChange, size = 0, svgIconChecked = DefaultSvgIconChecked, svgIconUnchecked = DefaultSvgIconUnchecked, value, }: CheckboxProps, ) => ( <Button alignItems="center" boxStyle={() => ({ outline: 'none' })} disabled={disabled} flexDirection={labelPosition === 'right' ? 'row' : 'row-reverse'} justifyContent={labelPosition === 'right' ? 'flex-start' : 'flex-end'} marginVertical={0} onPress={() => onChange && onChange({ value: !value })} paddingVertical={0} > <SvgIcon color={color} size={size} svgIcon={value ? svgIconChecked : svgIconUnchecked} {...marginVertical(labelPosition)} /> {label && <Text color={color} size={size} {...inline ? marginVertical(labelPosition) : null} > {label} </Text>} </Button> ); export default Checkbox;
packages/material-ui-icons/src/SentimentDissatisfiedSharp.js
callemall/material-ui
import * as React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><circle cx="15.5" cy="9.5" r="1.5" /><circle cx="8.5" cy="9.5" r="1.5" /><path d="M12 14c-2.33 0-4.32 1.45-5.12 3.5h1.67c.69-1.19 1.97-2 3.45-2s2.75.81 3.45 2h1.67c-.8-2.05-2.79-3.5-5.12-3.5zm-.01-12C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z" /></React.Fragment> , 'SentimentDissatisfiedSharp');
ajax/libs/forerunnerdb/1.3.599/fdb-core+views.js
BitsyCode/cdnjs
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('./core'), View = _dereq_('../lib/View'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/View":33,"./core":2}],2:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":7,"../lib/Shim.IE8":32}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; this._keyArr = sharedPathSolver.parse(orderBy, true); }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); sharedPathSolver = new Path(); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof sharedPathSolver.get(obj, sortType.path); if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.value === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.value === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += sharedPathSolver.get(obj, sortType.path); } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Path":28,"./Shared":31}],4:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param data * @param options * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visited === undefined) { resultArr._visited = 0; } resultArr._visited++; result = this.sortAsc(thisDataPathVal, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":28,"./Shared":31}],5:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Crc, Overload, ReactorIO, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name, options) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', keyName, {oldData: oldKey}); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = this.jStringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { if (this.debug()) { console.log(this.logIdentifier() + ' Updated some data'); } op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: updated }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback(false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); self.chainSend('insert', doc, {index: index}); //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = this.jStringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = this.jStringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options), coll; coll = new Collection(); coll.db(this._db); coll.subsetOf(this) .primaryKey(this._primaryKey) .setData(result); return coll; }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.call(this, query, options, callback); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, joinMatchData, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, waterfallCollection, matcher; if (!(options instanceof Array)) { options = this.options(options); } matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Check if the query is an array (multi-operation waterfall query) if (query instanceof Array) { waterfallCollection = this; // Loop the query operations for (i = 0; i < query.length; i++) { // Execute each operation and pass the result into the next // query operation waterfallCollection = waterfallCollection.subset(query[i], options && options[i] ? options[i] : {}); } return waterfallCollection.find(); } // Pre-process any data-changing query operators first if (query.$findSub) { // Check we have all the parts we need if (!query.$findSub.$path) { throw('$findSub missing $path property!'); } return this.findSub( query.$findSub.$query, query.$findSub.$path, query.$findSub.$subQuery, query.$findSub.$subOptions ); } if (query.$findSubOne) { // Check we have all the parts we need if (!query.$findSubOne.$path) { throw('$findSubOne missing $path property!'); } return this.findSubOne( query.$findSubOne.$query, query.$findSubOne.$path, query.$findSubOne.$subQuery, query.$findSubOne.$subOptions ); } // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { joinMatchData = joinMatch[joinMatchIndex]; // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatchData.$query || joinMatchData.$options) { if (joinMatchData.$query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatchData.query; joinSearchQuery = self._resolveDynamicQuery(joinMatchData.$query, resultArr[resultIndex]); } if (joinMatchData.$options) { joinSearchOptions = joinMatchData.$options; } } else { throw('$join $where clause requires "$query" and / or "$options" keys to work!'); } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatchData; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatchData; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatchData; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatchData; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatchData, resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = new Path(query.substr(3, query.length - 3)).value(item); } else { pathResult = new Path(query).value(item); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformIn(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], transformResult, i; for (i = 0; i < data.length; i++) { transformResult = this._transformOut(data[i]); // Support transforms returning multiple items if (transformResult instanceof Array) { finalArr = finalArr.concat(transformResult); } else { finalArr.push(transformResult); } } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ /*Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; };*/ /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this._findSub(this.find(match), path, subDocQuery, subDocOptions); }; Collection.prototype._findSub = function (docArr, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docCount = docArr.length, docIndex, subDocArr, subDocCollection = new Collection('__FDB_temp_' + this.objectId()).db(this._db), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; case '2d': index = new Index2d(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":8,"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],6:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {Name=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { // Handle being passed an instance if (collectionGroupName instanceof CollectionGroup) { return collectionGroupName; } this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":5,"./Shared":31}],7:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":31}],8:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],9:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":15,"./Overload":27,"./Shared":31}],10:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - [email protected] "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders; bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to longitude/latitude. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { latitude: lat, longitude: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; module.exports = GeoHash; },{}],11:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.lookup = function (query, options) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options) { var self = this, geoHash, neighbours, visited, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } // Get the lngLat geohash from the query geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision); // Calculate 9 box geohashes neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'}); // Lookup all matching co-ordinates from the btree results = []; visited = 0; for (i = 0; i < 9; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visited += search._visited; results = results.concat(search); } // Work with original data results = this._collection._primaryIndex.lookup(results); if (results.length) { distance = {}; // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { // Add item inside radius distance finalResults.push(results[i]); } } // Sort by distance from center finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var lat1Rad = this.toRadians(lat1); var lat2Rad = this.toRadians(lat2); var lat2MinusLat1Rad = this.toRadians(lat2-lat1); var lng2MinusLng1Rad = this.toRadians(lng2-lng1); var a = Math.sin(lat2MinusLat1Rad/2) * Math.sin(lat2MinusLat1Rad/2) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.sin(lng2MinusLng1Rad/2) * Math.sin(lng2MinusLng1Rad/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":4,"./GeoHash":10,"./Path":28,"./Shared":31}],12:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options) { return this._btree.lookup(query, options); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":4,"./Path":28,"./Shared":31}],13:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":28,"./Shared":31}],14:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk]) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":31}],15:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":26,"./Shared":31}],16:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],17:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, data, options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],18:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined && data !== "") { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return serialiser.parse(data); //return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return serialiser.stringify(data); //return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":27,"./Serialiser":30}],19:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],20:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":27}],21:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; if (options.$parent && options.$parent.parent && options.$parent.parent.key) { result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { // This is a root $find* query // Test the source against the main findQuery if (this._match(source, findQuery, {}, 'and', options)) { result = this._findSub([source], subPath, subQuery, subOptions); } return result && result.length > 0; } } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; } }; module.exports = Matching; },{}],22:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],24:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":27}],25:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],26:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":28,"./Shared":31}],27:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload: ', def); throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature "' + lookup + '" for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],28:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":31}],29:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":31}],30:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { this._encoder = []; this._decoder = {}; // Handler for Date() objects this.registerEncoder('$date', function (data) { if (data instanceof Date) { return data.toISOString(); } }); this.registerDecoder('$date', function (data) { return new Date(data); }); // Handler for RegExp() objects this.registerEncoder('$regexp', function (data) { if (data instanceof RegExp) { return { source: data.source, params: '' + (data.global ? 'g' : '') + (data.ignoreCase ? 'i' : '') }; } }); this.registerDecoder('$regexp', function (data) { var type = typeof data; if (type === 'object') { return new RegExp(data.source, data.params); } else if (type === 'string') { return new RegExp(data); } }); }; /** * Register an encoder that can handle encoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. * @param {Function} method The encoder method. */ Serialiser.prototype.registerEncoder = function (handles, method) { this._encoder.push(function (data) { var methodVal = method(data), returnObj; if (methodVal !== undefined) { returnObj = {}; returnObj[handles] = methodVal; } return returnObj; }); }; /** * Register a decoder that can handle decoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. When an object * has a field matching this handler name then this decode will be invoked * to provide a decoded version of the data that was previously encoded by * it's counterpart encoder method. * @param {Function} method The decoder method. */ Serialiser.prototype.registerDecoder = function (handles, method) { this._decoder[handles] = method; }; /** * Loops the encoders and asks each one if it wants to handle encoding for * the passed data object. If no value is returned (undefined) then the data * will be passed to the next encoder and so on. If a value is returned the * loop will break and the encoded data will be used. * @param {Object} data The data object to handle. * @returns {*} The encoded data. * @private */ Serialiser.prototype._encode = function (data) { // Loop the encoders and if a return value is given by an encoder // the loop will exit and return that value. var count = this._encoder.length, retVal; while (count-- && !retVal) { retVal = this._encoder[count](data); } return retVal; }; /** * Converts a previously encoded string back into an object. * @param {String} data The string to convert to an object. * @returns {Object} The reconstituted object. */ Serialiser.prototype.parse = function (data) { return this._parse(JSON.parse(data)); }; /** * Handles restoring an object with special data markers back into * it's original format. * @param {Object} data The object to recurse. * @param {Object=} target The target object to restore data to. * @returns {Object} The final restored object. * @private */ Serialiser.prototype._parse = function (data, target) { var i; if (typeof data === 'object' && data !== null) { if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and handle // special object types and restore them for (i in data) { if (data.hasOwnProperty(i)) { if (i.substr(0, 1) === '$' && this._decoder[i]) { // This is a special object type and a handler // exists, restore it return this._decoder[i](data[i]); } // Not a special object or no handler, recurse as normal target[i] = this._parse(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; /** * Converts an object to a encoded string representation. * @param {Object} data The object to encode. */ Serialiser.prototype.stringify = function (data) { return JSON.stringify(this._stringify(data)); }; /** * Recurse down an object and encode special objects so they can be * stringified and later restored. * @param {Object} data The object to parse. * @param {Object=} target The target object to store converted data to. * @returns {Object} The converted object. * @private */ Serialiser.prototype._stringify = function (data, target) { var handledData, i; if (typeof data === 'object' && data !== null) { // Handle special object types so they can be encoded with // a special marker and later restored by a decoder counterpart handledData = this._encode(data); if (handledData) { // An encoder handled this object type so return it now return handledData; } if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and serialise for (i in data) { if (data.hasOwnProperty(i)) { target[i] = this._stringify(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; module.exports = Serialiser; },{}],31:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.599', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, mixin: new Overload({ /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, /** * Adds the properties and methods defined in the mixin to the passed * object. * @memberof Shared * @name mixin * @param {Object} obj The target object to add mixin key/values to. * @param {Object} mixinObj The object containing the keys to mix into * the target object. */ 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],32:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}],33:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket, Overload = _dereq_('./Overload'); Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; View.prototype.init = function (name, query, options) { var self = this; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._privateData = new Collection(this.name() + '_internalPrivate'); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this.publicData().find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this.publicData().findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this.publicData().findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this.publicData().findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.publicData().findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._privateData; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); delete this._from; } // Check if we have an existing reactor io if (this._io) { // Drop the io and remove it this._io.drop(); delete this._io; } if (typeof(source) === 'string') { source = this._db.collection(source); } if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } this._from = source; this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's "from" source and determines how they should be interpreted by // this view. If the view does not have a query then this reactor IO will // simply pass along the chain packet without modifying it. this._io = new ReactorIO(source, this, function (chainPacket) { var data, diff, query, filteredData, doSend, pk, i; // Check that the state of the "self" object is not dropped if (self && !self.isDropped()) { // Check if we have a constraining query if (self._querySettings.query) { if (chainPacket.type === 'insert') { data = chainPacket.data; // Check if the data matches our query if (data instanceof Array) { filteredData = []; for (i = 0; i < data.length; i++) { if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData.push(data[i]); doSend = true; } } } else { if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData = data; doSend = true; } } if (doSend) { this.chainSend('insert', filteredData); } return true; } if (chainPacket.type === 'update') { // Do a DB diff between this view's data and the underlying collection it reads from // to see if something has changed diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options)); if (diff.insert.length || diff.remove.length) { // Now send out new chain packets for each operation if (diff.insert.length) { this.chainSend('insert', diff.insert); } if (diff.update.length) { pk = self._privateData.primaryKey(); for (i = 0; i < diff.update.length; i++) { query = {}; query[pk] = diff.update[i][pk]; this.chainSend('update', { query: query, update: diff.update[i] }); } } if (diff.remove.length) { pk = self._privateData.primaryKey(); var $or = [], removeQuery = { query: { $or: $or } }; for (i = 0; i < diff.remove.length; i++) { $or.push({_id: diff.remove[i][pk]}); } this.chainSend('remove', removeQuery); } // Return true to stop further propagation of the chain packet return true; } else { // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } } } } // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); var collData = source.find(this._querySettings.query, this._querySettings.options); this._privateData.primaryKey(source.primaryKey()); this._privateData.setData(collData, {}, callback); if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._privateData.ensureIndex.apply(this._privateData, arguments); }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data'); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._privateData.setData(collData); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Make sure we are working with an array if (!(chainPacket.data instanceof Array)) { chainPacket.data = [chainPacket.data]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._privateData._insertHandle(chainPacket.data, insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._privateData._data.length; this._privateData._insertHandle(chainPacket.data, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"'); } primaryKey = this._privateData.primaryKey(); // Do the update updates = this._privateData.update( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._privateData._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"'); } this._privateData.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._privateData.on.apply(this._privateData, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._privateData.off.apply(this._privateData, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._privateData.emit.apply(this._privateData, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { var coll = this.publicData(); return coll.distinct.apply(coll, arguments); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this.publicData().primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._privateData) { this._privateData.drop(); } if (this._publicData && this._publicData !== this._privateData) { this._publicData.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._privateData; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this.privateData().db(db); this.publicData().db(db); // Apply the same debug settings this.debug(db.debug()); this.privateData().debug(db.debug()); this.publicData().debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} * @deprecated Use query(<query>, <options>, <refresh>) instead. Query * now supports being presented with multiple different variations of * arguments. */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._privateData.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._privateData.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = new Overload({ '': function () { return this._querySettings.query; }, 'object': function (query) { return this.$main.call(this, query, undefined, true); }, '*, boolean': function (query, refresh) { return this.$main.call(this, query, undefined, refresh); }, 'object, object': function (query, options) { return this.$main.call(this, query, options, true); }, '*, *, boolean': function (query, options, refresh) { return this.$main.call(this, query, options, refresh); }, '$main': function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; if (query.$findSub && !query.$findSub.$from) { query.$findSub.$from = this._privateData.name(); } if (query.$findSubOne && !query.$findSubOne.$from) { query.$findSubOne.$from = this._privateData.name(); } } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; } }); /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { this.rebuildActiveBucket(options.$orderBy); } return this; } return this._querySettings.options; }; View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._privateData._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._privateData.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { if (this._from) { var pubData = this.publicData(), refreshResults; // Re-grab all the data for the view from the collection this._privateData.remove(); //pubData.remove(); refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); this._privateData.insert(refreshResults); this._privateData._data.$cursor = refreshResults.$cursor; pubData._data.$cursor = refreshResults.$cursor; /*if (pubData._linked) { // Update data and observers //var transformedData = this._privateData.find(); // TODO: Shouldn't this data get passed into a transformIn first? // TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data // TODO: Is this even required anymore? After commenting it all seems to work // TODO: Might be worth setting up a test to check transforms and linking then remove this if working? //jQuery.observable(pubData._data).refresh(transformedData); }*/ } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { if (this.publicData()) { return this.publicData().count.apply(this.publicData(), arguments); } return 0; }; // Call underlying View.prototype.subset = function () { return this.publicData().subset.apply(this._privateData, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var self = this; if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } if (this._transformEnabled) { // Check for / create the public data collection if (!this._publicData) { // Create the public data collection this._publicData = new Collection('__FDB__view_publicData_' + this._name); this._publicData.db(this._privateData._db); this._publicData.transform({ enabled: true, dataIn: this._transformIn, dataOut: this._transformOut }); // Create a chain reaction IO node to keep the private and // public data collections in sync this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) { var data = chainPacket.data; switch (chainPacket.type) { case 'primaryKey': self._publicData.primaryKey(data); this.chainSend('primaryKey', data); break; case 'setData': self._publicData.setData(data); this.chainSend('setData', data); break; case 'insert': self._publicData.insert(data); this.chainSend('insert', data); break; case 'update': // Do the update self._publicData.update( data.query, data.update, data.options ); this.chainSend('update', data); break; case 'remove': self._publicData.remove(data.query, chainPacket.options); this.chainSend('remove', data); break; default: break; } }); } // Set initial data and settings this._publicData.primaryKey(this.privateData().primaryKey()); this._publicData.setData(this.privateData().find()); } else { // Remove the public data collection if (this._publicData) { this._publicData.drop(); delete this._publicData; if (this._transformIo) { this._transformIo.drop(); delete this._transformIo; } } } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return (this.publicData()).filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.privateData = function () { return this._privateData; }; /** * Returns a data object representing the public data this view * contains. This can change depending on if transforms are being * applied to the view or not. * * If no transforms are applied then the public data will be the * same as the private data the view holds. If transforms are * applied then the public data will contain the transformed version * of the private data. * * The public data collection is also used by data binding to only * changes to the publicData will show in a data-bound element. */ View.prototype.publicData = function () { if (this._transformEnabled) { return this._publicData; } else { return this._privateData; } }; // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (viewName) { var self = this; // Handle being passed an instance if (viewName instanceof View) { return viewName; } if (this._view[viewName]) { return this._view[viewName]; } else { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + viewName); } } this._view[viewName] = this._view[viewName] || new View(viewName).db(this); self.emit('create', [self._view[viewName], 'view', viewName]); return this._view[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (viewName) { return Boolean(this._view[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./Overload":27,"./ReactorIO":29,"./Shared":31}]},{},[1]);
Examples/UIExplorer/XHRExampleHeaders.js
almost/react-native
/** * The examples provided by Facebook are for non-commercial testing and * evaluation purposes only. * * Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN * AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ 'use strict'; var React = require('react-native'); var { StyleSheet, Text, TouchableHighlight, View, } = React; class XHRExampleHeaders extends React.Component { xhr: XMLHttpRequest; cancelled: boolean; constructor(props) { super(props); this.cancelled = false; this.state = { status: '', headers: '', contentSize: 1, downloaded: 0, }; } download() { this.xhr && this.xhr.abort(); var xhr = this.xhr || new XMLHttpRequest(); xhr.onreadystatechange = () => { if (xhr.readyState === xhr.DONE) { if (this.cancelled) { this.cancelled = false; return; } if (xhr.status === 200) { this.setState({ status: 'Download complete!', headers: xhr.getAllResponseHeaders() }); } else if (xhr.status !== 0) { this.setState({ status: 'Error: Server returned HTTP status of ' + xhr.status + ' ' + xhr.responseText, }); } else { this.setState({ status: 'Error: ' + xhr.responseText, }); } } }; xhr.open('GET', 'https://httpbin.org/response-headers?header1=value&header2=value1&header2=value2'); xhr.send(); this.xhr = xhr; this.setState({status: 'Downloading...'}); } componentWillUnmount() { this.cancelled = true; this.xhr && this.xhr.abort(); } render() { var button = this.state.status === 'Downloading...' ? ( <View style={styles.wrapper}> <View style={styles.button}> <Text>...</Text> </View> </View> ) : ( <TouchableHighlight style={styles.wrapper} onPress={this.download.bind(this)}> <View style={styles.button}> <Text>Get headers</Text> </View> </TouchableHighlight> ); return ( <View> {button} <Text>{this.state.headers}</Text> </View> ); } } var styles = StyleSheet.create({ wrapper: { borderRadius: 5, marginBottom: 5, }, button: { backgroundColor: '#eeeeee', padding: 8, }, }); module.exports = XHRExampleHeaders;
app/javascript/mastodon/features/ui/components/column_header.js
gol-cha/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Icon from 'mastodon/components/icon'; export default class ColumnHeader extends React.PureComponent { static propTypes = { icon: PropTypes.string, type: PropTypes.string, active: PropTypes.bool, onClick: PropTypes.func, columnHeaderId: PropTypes.string, }; handleClick = () => { this.props.onClick(); } render () { const { icon, type, active, columnHeaderId } = this.props; let iconElement = ''; if (icon) { iconElement = <Icon id={icon} fixedWidth className='column-header__icon' />; } return ( <h1 className={classNames('column-header', { active })} id={columnHeaderId || null}> <button onClick={this.handleClick}> {iconElement} {type} </button> </h1> ); } }
src/scenes/home/header/header.js
miaket/operationcode_frontend
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import styles from './header.css'; import NavItem from './navItem/navItem'; import TopNav from './topNav/topNav'; import SideNav from './sideNav/sideNav'; import Logo from './logo/logo'; import Burger from './burger/burger'; class Header extends Component { constructor() { super(); this.state = { isSideNavVisible: false }; this.handleToggleDrawer = this.handleToggleDrawer.bind(this); } handleToggleDrawer(e) { e.preventDefault(); this.setState({ isSideNavVisible: !this.state.isSideNavVisible }); } renderNavContents(signedIn, mentor, onClick) { return ( <span> <NavItem to="/about" text="About" onClick={onClick} /> <NavItem to="/code_schools" text="Code Schools" onClick={onClick} /> <NavItem to="/jobs" text="Job Board" onClick={onClick} /> <NavItem to="https://opencollective.com/operationcode#support" text="Donate" onClick={onClick} isExternal /> {signedIn && <NavItem to="https://op.co.de/mentor-request" text="Request Help" onClick={onClick} isExternal />} {signedIn && <NavItem to="/mentors" text="Mentors" onClick={onClick} />} {mentor && <NavItem to="/requests" text="Requests" onClick={onClick} />} {signedIn && <NavItem to="/squads" text="Squads" onClick={onClick} />} {signedIn ? <NavItem to="/profile" text="Profile" onClick={onClick} /> : <NavItem to="/join" text="Join" onClick={onClick} />} {signedIn ? <NavItem to="/" text="Logout" onClick={this.props.logOut} /> : <NavItem to="/login" text="Login" onClick={onClick} />} </span> ); } render() { const { mentor, signedIn } = this.props; const classes = classNames({ [`${styles.header}`]: true, [`${styles.transparent}`]: this.props.transparent }); return ( <div className={classes} > <Logo /> <Burger onClick={this.handleToggleDrawer} /> <TopNav> {this.renderNavContents(signedIn, mentor)} </TopNav> <SideNav isVisible={this.state.isSideNavVisible} onClose={this.handleToggleDrawer} > {this.renderNavContents(signedIn, mentor, this.handleToggleDrawer)} </SideNav> </div> ); } } Header.propTypes = { transparent: PropTypes.bool, logOut: PropTypes.func, signedIn: PropTypes.bool, mentor: PropTypes.bool }; Header.defaultProps = { transparent: false, logOut: () => {}, signedIn: false, mentor: false }; export default Header;
packages/bonde-admin/src/components/navigation/browsable-list/browsable-list-item.spec.js
ourcities/rebu-client
/* eslint-disable no-unused-expressions */ import React from 'react' import { shallow } from 'enzyme' import { expect } from 'chai' import { BrowsableListItem } from '@/components/navigation/browsable-list' describe('client/components/navigation/browsable-list/browsable-list-item', () => { let wrapper const props = { dispatch: () => {} } beforeAll(() => { wrapper = shallow(<BrowsableListItem {...props} />) }) describe('#render', () => { it('should render without crash', () => { expect(wrapper).to.be.ok }) }) })
examples/flux-utils-todomvc/js/app.js
topogigiovanni/flux
/** * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @flow */ 'use strict'; import React from 'react'; import TodoApp from './components/TodoApp.react'; React.render(<TodoApp />, document.getElementById('todoapp'));
admin/src/route/EditAccount.js
zentrope/webl
// // Copyright (c) 2017 Keith Irwin // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published // by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. import React from 'react'; import { Form, FormControls, FormWidgets, FormWidget, FormLabel, FormTitle } from '../component/Form' import { WorkArea } from '../component/WorkArea' /* /admin/account/edit */ const isBlank = (s) => ((! s) || (s.trim().length === 0)) class EditAccount extends React.PureComponent { constructor(props) { super(props) this.state = {name: "", email: ""} this.handleChange = this.handleChange.bind(this) this.save = this.save.bind(this) this.load = this.load.bind(this) this.disabled = this.disabled.bind(this) } componentDidMount() { this.mounted = true this.load() } componentWillUnmount() { this.mounted = false } handleChange(event) { let name = event.target.name let value = event.target.value this.setState({[name]: value}) } load() { let { client } = this.props client.viewerData(response => { let { email, name } = response.data.viewer this.oldEmail = email this.oldName = name if (this.mounted) { this.setState({email: email, name: name}) } }) } save() { let { name, email } = this.state let { client, onCancel } = this.props client.updateViewer(name, email, (response) => { if (response.errors) { console.error(response.errors) return } onCancel() }) } disabled() { return ( isBlank(this.state.name) || isBlank(this.state.email) || ((this.state.name === this.oldName) && (this.state.email === this.oldEmail)) ) } render() { const { onCancel } = this.props const { name, email } = this.state return ( <WorkArea> <Form> <FormTitle>Edit account</FormTitle> <FormWidgets> <FormWidget> <FormLabel>Name</FormLabel> <input autoFocus={true} name="name" value={name} onChange={this.handleChange}/> </FormWidget> <FormWidget> <FormLabel>Email</FormLabel> <input autoFocus={false} name="email" value={email} onChange={this.handleChange}/> </FormWidget> </FormWidgets> <FormControls> <button disabled={this.disabled()} onClick={this.save}>Save changes</button> <button onClick={onCancel}>Cancel</button> </FormControls> </Form> </WorkArea> ) } } export { EditAccount }
src/svg-icons/communication/call-end.js
IsenrichO/mui-with-arrows
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationCallEnd = (props) => ( <SvgIcon {...props}> <path d="M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08c-.18-.17-.29-.42-.29-.7 0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28-.79-.74-1.69-1.36-2.67-1.85-.33-.16-.56-.5-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"/> </SvgIcon> ); CommunicationCallEnd = pure(CommunicationCallEnd); CommunicationCallEnd.displayName = 'CommunicationCallEnd'; CommunicationCallEnd.muiName = 'SvgIcon'; export default CommunicationCallEnd;
rnNavigator/__tests__/index.android.js
gergob/reactNativeSamples
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
src/svg-icons/device/bluetooth-connected.js
owencm/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBluetoothConnected = (props) => ( <SvgIcon {...props}> <path d="M7 12l-2-2-2 2 2 2 2-2zm10.71-4.29L12 2h-1v7.59L6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 5.83l1.88 1.88L13 9.59V5.83zm1.88 10.46L13 18.17v-3.76l1.88 1.88zM19 10l-2 2 2 2 2-2-2-2z"/> </SvgIcon> ); DeviceBluetoothConnected = pure(DeviceBluetoothConnected); DeviceBluetoothConnected.displayName = 'DeviceBluetoothConnected'; DeviceBluetoothConnected.muiName = 'SvgIcon'; export default DeviceBluetoothConnected;
imports/ui/pages/NotFound.js
zarazi/movies-listie
import React from 'react'; import { Alert } from 'react-bootstrap'; const NotFound = () => ( <div className="NotFound"> <Alert bsStyle="danger"> <p><strong>Error [404]</strong>: { window.location.pathname } does not exist.</p> </Alert> </div> ); export default NotFound;
node_modules/react-router/es6/IndexRoute.js
amybingzhao/savings-planner-web
import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils'; import { component, components, falsy } from './InternalPropTypes'; var func = React.PropTypes.func; /** * An <IndexRoute> is used to specify its parent's <Route indexRoute> in * a JSX route config. */ var IndexRoute = React.createClass({ displayName: 'IndexRoute', statics: { createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) { /* istanbul ignore else: sanity check */ if (parentRoute) { parentRoute.indexRoute = _createRouteFromReactElement(element); } else { process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRoute> does not make sense at the root of your route config') : void 0; } } }, propTypes: { path: falsy, component: component, components: components, getComponent: func, getComponents: func }, /* istanbul ignore next: sanity check */ render: function render() { !false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : invariant(false) : void 0; } }); export default IndexRoute;
src/atoms/Icon/icon.stories.js
sjofartstidningen/bryggan
/* eslint-disable import/no-extraneous-dependencies */ import React from 'react'; import { storiesOf } from '@storybook/react'; import * as Icon from './index'; storiesOf('atoms/Icon', module) .add('all', () => ( <div> {Object.entries(Icon).map( ([key, Comp]) => ( <div key={key} style={{ margin: '1rem', fontFamily: 'Roboto' }}> <Comp /> – {'<'} {key} {' />'} </div> ), [], )} </div> )) .add('without basline alignment', () => ( <div> {Object.entries(Icon).map( ([key, Comp]) => ( <div key={key} style={{ margin: '1rem', fontFamily: 'Roboto' }}> <Comp baseline={false} /> – {'<'} {key} {' baseline={false} />'} </div> ), [], )} </div> ));
src/components/app.js
dom-mages/reactTesting
import React, { Component } from 'react'; import CommentBox from './CommentBox'; import CommentList from './CommentList'; export default class App extends Component { render() { return ( <div> <CommentBox /> <CommentList /> </div> ); } }
test/specs/elements/Container/Container-test.js
shengnian/shengnian-ui-react
import React from 'react' import Container from 'src/elements/Container/Container' import * as common from 'test/specs/commonTests' describe('Container', () => { common.isConformant(Container) common.rendersChildren(Container) common.hasUIClassName(Container) common.propKeyOnlyToClassName(Container, 'text') common.propKeyOnlyToClassName(Container, 'fluid') common.implementsTextAlignProp(Container) it('renders a <div /> element', () => { shallow(<Container />) .should.have.tagName('div') }) })
ee/app/engagement-dashboard/client/components/MessagesTab/MessagesSentSection.js
iiet/iiet-chat
import { ResponsiveBar } from '@nivo/bar'; import { Box, Flex, Select, Skeleton } from '@rocket.chat/fuselage'; import moment from 'moment'; import React, { useMemo, useState } from 'react'; import { useTranslation } from '../../../../../../client/contexts/TranslationContext'; import { useEndpointData } from '../../../../../../client/hooks/useEndpointData'; import CounterSet from '../../../../../../client/components/data/CounterSet'; import { Section } from '../Section'; import { ActionButton } from '../../../../../../client/components/basic/Buttons/ActionButton'; import { saveFile } from '../../../../../../client/lib/saveFile'; const convertDataToCSV = (data) => `// date, newMessages ${ data.map(({ date, newMessages }) => `${ date }, ${ newMessages }`).join('\n') }`; export function MessagesSentSection() { const t = useTranslation(); const periodOptions = useMemo(() => [ ['last 7 days', t('Last_7_days')], ['last 30 days', t('Last_30_days')], ['last 90 days', t('Last_90_days')], ], [t]); const [periodId, setPeriodId] = useState('last 7 days'); const period = useMemo(() => { switch (periodId) { case 'last 7 days': return { start: moment().set({ hour: 0, minute: 0, second: 0, millisecond: 0 }).subtract(7, 'days'), end: moment().set({ hour: 0, minute: 0, second: 0, millisecond: 0 }).subtract(1), }; case 'last 30 days': return { start: moment().set({ hour: 0, minute: 0, second: 0, millisecond: 0 }).subtract(30, 'days'), end: moment().set({ hour: 0, minute: 0, second: 0, millisecond: 0 }).subtract(1), }; case 'last 90 days': return { start: moment().set({ hour: 0, minute: 0, second: 0, millisecond: 0 }).subtract(90, 'days'), end: moment().set({ hour: 0, minute: 0, second: 0, millisecond: 0 }).subtract(1), }; } }, [periodId]); const handlePeriodChange = (periodId) => setPeriodId(periodId); const params = useMemo(() => ({ start: period.start.toISOString(), end: period.end.toISOString(), }), [period]); const data = useEndpointData('engagement-dashboard/messages/messages-sent', params); const [ countFromPeriod, variatonFromPeriod, countFromYesterday, variationFromYesterday, values, ] = useMemo(() => { if (!data) { return []; } const values = Array.from({ length: moment(period.end).diff(period.start, 'days') + 1 }, (_, i) => ({ date: moment(period.start).add(i, 'days').toISOString(), newMessages: 0, })); for (const { day, messages } of data.days) { const i = moment(day).diff(period.start, 'days'); if (i >= 0) { values[i].newMessages += messages; } } return [ data.period.count, data.period.variation, data.yesterday.count, data.yesterday.variation, values, ]; }, [data, period]); const downloadData = () => { saveFile(convertDataToCSV(values), `MessagesSentSection_start_${ params.start }_end_${ params.end }.csv`); }; return <Section title={t('Messages_sent')} filter={<><Select options={periodOptions} value={periodId} onChange={handlePeriodChange} /><ActionButton mis='x16' disabled={!data} onClick={downloadData} aria-label={t('Download_Info')} icon='download'/></>} > <CounterSet counters={[ { count: data ? countFromPeriod : <Skeleton variant='rect' width='3ex' height='1em' />, variation: data ? variatonFromPeriod : 0, description: periodOptions.find(([id]) => id === periodId)[1], }, { count: data ? countFromYesterday : <Skeleton variant='rect' width='3ex' height='1em' />, variation: data ? variationFromYesterday : 0, description: t('Yesterday'), }, ]} /> <Flex.Container> {data ? <Box style={{ height: 240 }}> <Flex.Item align='stretch' grow={1} shrink={0}> <Box style={{ position: 'relative' }}> <Box style={{ position: 'absolute', width: '100%', height: '100%' }}> <ResponsiveBar data={values} indexBy='date' keys={['newMessages']} groupMode='grouped' padding={0.25} margin={{ // TODO: Get it from theme bottom: 20, }} colors={[ // TODO: Get it from theme '#1d74f5', ]} enableLabel={false} enableGridY={false} axisTop={null} axisRight={null} axisBottom={(values.length === 7 && { tickSize: 0, // TODO: Get it from theme tickPadding: 4, tickRotation: 0, format: (date) => moment(date).format('dddd'), }) || null } axisLeft={null} animate={true} motionStiffness={90} motionDamping={15} theme={{ // TODO: Get it from theme axis: { ticks: { text: { fill: '#9EA2A8', fontFamily: 'Inter, -apple-system, system-ui, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Helvetica Neue", "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Meiryo UI", Arial, sans-serif', fontSize: '10px', fontStyle: 'normal', fontWeight: '600', letterSpacing: '0.2px', lineHeight: '12px', }, }, }, tooltip: { container: { backgroundColor: '#1F2329', boxShadow: '0px 0px 12px rgba(47, 52, 61, 0.12), 0px 0px 2px rgba(47, 52, 61, 0.08)', borderRadius: 2, }, }, }} tooltip={({ value }) => <Box fontScale='p2' color='alternative'> {t('Value_messages', { value })} </Box>} /> </Box> </Box> </Flex.Item> </Box> : <Skeleton variant='rect' height={240} />} </Flex.Container> </Section>; }
client/src/Components/ServerList.js
adamveld12/fsb
import React, { Component } from 'react'; import ReactList from 'react-list'; import FontAwesome from 'react-fontawesome'; import ServerListRow from './ServerRow'; import { actions } from '../store.js'; const styles = { container: { background: "#404040", borderColor: "#555555 #111111 #111111 #666666", borderRadius: "4px 4px 4px 4px", borderStyle: "solid", borderWidth: "1px", margin: "10px 0", padding: "5px 10px", fontSize: ".7rem", maxHeight: "1080px", }, header: { color: "white", textAlign: "left", }, list: { marginTop: "15px", marginBottom: "10px", backgroundColor: "#575A5A", overflowY: 'scroll', overflowX: 'hidden', maxHeight: "950px" } }; export default class ServerList extends Component { handleScroll = (evt) => { const s = this.refs.scroller; const { servers, details } = this.props; s.getVisibleRange().forEach((i) => { const { game_id } = servers[i]; if (!(details[game_id] || {}).loading){ this.onLoadDetails(game_id); } }) } onLoadDetails(gameId, index){ actions.details(gameId, index); } renderRows(servers, details){ if (servers.length === 0) return (i, k) => (<div>No servers to show</div>); return (i, k) => { const { game_id } = servers[i]; return (<ServerListRow key={k} index={i} server={servers[i]} details={details[game_id] || {}} onClick={(g, i) => this.onLoadDetails(g, i)} />); } } render() { const { servers, loading, details } = this.props; return ( <section style={styles.container}> <header style={styles.header}> <FontAwesome name="refresh" style={{ display: loading ? "none" : "inline" }} onClick={() => !loading && actions.games()}/> <span style={{ margin: "0 5px" }}>{ loading ? "loading..." : `${servers.length} games active`} </span> { /* 1min auto refresh option shoud go here */ } </header> <div style={styles.list} onScroll={this.handleScroll}> <ReactList ref="scroller" itemRenderer={this.renderRows(servers, details)} useStaticSize={true} type='uniform' pageSize={15} length={servers.length} /> </div> </section> ); } }
webpack/ForemanTasks/Components/Chart/Chart.js
adamruzicka/foreman-tasks
/* Copied from react-c3js: https://github.com/bcbcarl/react-c3js/blob/master/src/index.js Added missing features: * onChartCreate * onChartUpdate TODO: update react-c3js or move to patternfly-react */ /* eslint-disable global-require, import/no-extraneous-dependencies, react/no-find-dom-node, react/no-unused-prop-types, react/require-default-props */ import React from 'react'; import PropTypes from 'prop-types'; import { findDOMNode } from 'react-dom'; let c3; class C3Chart extends React.Component { componentDidMount() { c3 = require('c3'); this.updateChart(this.props); } componentWillReceiveProps(newProps) { this.updateChart(newProps); if (newProps.onPropsChanged) { newProps.onPropsChanged(this.props, newProps, this.chart); } } componentWillUnmount() { this.destroyChart(); } destroyChart() { try { // A workaround for a case, where the chart might be still in transition // phase while unmounting/destroying - destroying right away leads // to issue described in https://github.com/bcbcarl/react-c3js/issues/22. // Delaying the destroy a bit seems to resolve the issue. // The chart API methods are already bind explicitly, therefore we don't need // any special handling when passing the function. setTimeout(this.chart.destroy, 1000); this.chart = null; } catch (err) { throw new Error('Internal C3 error', err); } } generateChart(config) { const newConfig = Object.assign({ bindto: findDOMNode(this) }, config); return c3.generate(newConfig); } loadNewData(data) { this.chart.load(data); } unloadData() { this.chart.unload(); } createChart(config) { const { onChartCreate } = this.props; this.chart = this.generateChart(config); if (onChartCreate) onChartCreate(this.chart, config); } updateChart(config) { const { onChartUpdate } = this.props; if (!this.chart) { this.createChart(config); } if (config.unloadBeforeLoad) { this.unloadData(); } this.loadNewData(config.data); if (onChartUpdate) onChartUpdate(this.chart, config); } render() { const className = this.props.className ? ` ${this.props.className}` : ''; const style = this.props.style ? this.props.style : {}; return <div className={className} style={style} />; } } C3Chart.displayName = 'C3Chart'; C3Chart.propTypes = { data: PropTypes.object.isRequired, title: PropTypes.object, size: PropTypes.object, padding: PropTypes.object, color: PropTypes.object, interaction: PropTypes.object, transition: PropTypes.object, oninit: PropTypes.func, onrendered: PropTypes.func, onmouseover: PropTypes.func, onmouseout: PropTypes.func, onresize: PropTypes.func, onresized: PropTypes.func, axis: PropTypes.object, grid: PropTypes.object, regions: PropTypes.array, legend: PropTypes.object, tooltip: PropTypes.object, subchart: PropTypes.object, zoom: PropTypes.object, point: PropTypes.object, line: PropTypes.object, area: PropTypes.object, bar: PropTypes.object, pie: PropTypes.object, donut: PropTypes.object, gauge: PropTypes.object, className: PropTypes.string, style: PropTypes.object, unloadBeforeLoad: PropTypes.bool, onPropsChanged: PropTypes.func, onChartCreate: PropTypes.func, onChartUpdate: PropTypes.func, }; export default C3Chart;
server/sonar-web/src/main/js/apps/projects/components/ProjectCardLanguages.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import { sortBy } from 'lodash'; import { connect } from 'react-redux'; import Tooltip from '../../../components/controls/Tooltip'; import { getLanguages } from '../../../store/rootReducer'; import { translate } from '../../../helpers/l10n'; class ProjectCardLanguages extends React.Component { getLanguageName(key) { if (key === '<null>') { return translate('unknown'); } const language = this.props.languages[key]; return language != null ? language.name : key; } render() { const { distribution } = this.props; if (distribution == null) { return null; } const parsedLanguages = distribution.split(';').map(item => item.split('=')); const finalLanguages = sortBy(parsedLanguages, l => -1 * Number(l[1])) .slice(0, 2) .map(l => this.getLanguageName(l[0])); const tooltip = ( <span> {finalLanguages.map(language => <span key={language}>{language}<br /></span>)} </span> ); return ( <div className="project-card-languages"> <Tooltip placement="bottom" overlay={tooltip}> <span title={finalLanguages.join('<br/>')} data-toggle="tooltip"> {finalLanguages.join(', ')} </span> </Tooltip> </div> ); } } const mapStateToProps = state => ({ languages: getLanguages(state) }); export default connect(mapStateToProps)(ProjectCardLanguages);
src/routes/user/Modal.js
zhouchao0924/SLCOPY
import React from 'react' import PropTypes from 'prop-types' import { Form, Input, InputNumber, Radio, Modal, Cascader } from 'antd' import city from '../../utils/city' const FormItem = Form.Item const formItemLayout = { labelCol: { span: 6, }, wrapperCol: { span: 14, }, } const modal = ({ item = {}, onOk, form: { getFieldDecorator, validateFields, getFieldsValue, }, ...modalProps }) => { const handleOk = () => { validateFields((errors) => { if (errors) { return } const data = { ...getFieldsValue(), key: item.key, } data.address = data.address.join(' ') onOk(data) }) } const modalOpts = { ...modalProps, onOk: handleOk, } return ( <Modal {...modalOpts}> <Form layout="horizontal"> <FormItem label="Name" hasFeedback {...formItemLayout}> {getFieldDecorator('name', { initialValue: item.name, rules: [ { required: true, }, ], })(<Input />)} </FormItem> <FormItem label="NickName" hasFeedback {...formItemLayout}> {getFieldDecorator('nickName', { initialValue: item.nickName, rules: [ { required: true, }, ], })(<Input />)} </FormItem> <FormItem label="Gender" hasFeedback {...formItemLayout}> {getFieldDecorator('isMale', { initialValue: item.isMale, rules: [ { required: true, type: 'boolean', }, ], })( <Radio.Group> <Radio value>Male</Radio> <Radio value={false}>Female</Radio> </Radio.Group> )} </FormItem> <FormItem label="Age" hasFeedback {...formItemLayout}> {getFieldDecorator('age', { initialValue: item.age, rules: [ { required: true, type: 'number', }, ], })(<InputNumber min={18} max={100} />)} </FormItem> <FormItem label="Phone" hasFeedback {...formItemLayout}> {getFieldDecorator('phone', { initialValue: item.phone, rules: [ { required: true, pattern: /^1[34578]\d{9}$/, message: 'The input is not valid phone!', }, ], })(<Input />)} </FormItem> <FormItem label="E-mail" hasFeedback {...formItemLayout}> {getFieldDecorator('email', { initialValue: item.email, rules: [ { required: true, pattern: /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/, message: 'The input is not valid E-mail!', }, ], })(<Input />)} </FormItem> <FormItem label="Address" hasFeedback {...formItemLayout}> {getFieldDecorator('address', { initialValue: item.address && item.address.split(' '), rules: [ { required: true, }, ], })(<Cascader size="large" style={{ width: '100%' }} options={city} placeholder="Pick an address" />)} </FormItem> </Form> </Modal> ) } modal.propTypes = { form: PropTypes.object.isRequired, type: PropTypes.string, item: PropTypes.object, onOk: PropTypes.func, } export default Form.create()(modal)
tests/routes/Counter/components/Counter.spec.js
Peturman/resume-app
import React from 'react' import { bindActionCreators } from 'redux' import { Counter } from 'routes/Counter/components/Counter' import { shallow } from 'enzyme' describe('(Component) Counter', () => { let _props, _spies, _wrapper beforeEach(() => { _spies = {} _props = { counter : 5, ...bindActionCreators({ doubleAsync : (_spies.doubleAsync = sinon.spy()), increment : (_spies.increment = sinon.spy()) }, _spies.dispatch = sinon.spy()) } _wrapper = shallow(<Counter {..._props} />) }) it('Should render as a <div>.', () => { expect(_wrapper.is('div')).to.equal(true) }) it('Should render with an <h2> that includes Sample Counter text.', () => { expect(_wrapper.find('h2').text()).to.match(/Counter:/) }) it('Should render props.Counter at the end of the sample Counter <h2>.', () => { expect(_wrapper.find('h2').text()).to.match(/5$/) _wrapper.setProps({ counter: 8 }) expect(_wrapper.find('h2').text()).to.match(/8$/) }) it('Should render exactly two buttons.', () => { expect(_wrapper.find('button')).to.have.length(2) }) describe('An increment button...', () => { let _button beforeEach(() => { _button = _wrapper.find('button').filterWhere(a => a.text() === 'Increment') }) it('has bootstrap classes', () => { expect(_button.hasClass('btn btn-default')).to.be.true }) it('Should dispatch a `increment` action when clicked', () => { _spies.dispatch.should.have.not.been.called _button.simulate('click') _spies.dispatch.should.have.been.called _spies.increment.should.have.been.called }) }) describe('A Double (Async) button...', () => { let _button beforeEach(() => { _button = _wrapper.find('button').filterWhere(a => a.text() === 'Double (Async)') }) it('has bootstrap classes', () => { expect(_button.hasClass('btn btn-default')).to.be.true }) it('Should dispatch a `doubleAsync` action when clicked', () => { _spies.dispatch.should.have.not.been.called _button.simulate('click') _spies.dispatch.should.have.been.called _spies.doubleAsync.should.have.been.called }) }) })
imports/ui/containers/feed/postList.js
jiyuu-llc/jiyuu
import React from 'react'; import { composeWithTracker } from 'react-komposer'; import { Feed } from '/lib/collections'; import PostList from '../../components/feed/postList.jsx'; const composer = ( props, onData ) => { if (subsManager.subscribe('mainFeed', Session.get('paginationLimit')).ready() && connectedUserSub.ready()) { var feed = Feed.find({}, {sort: {createdAt: -1}}).fetch() || fakeFeed; onData(null, {feed}); } }; export default composeWithTracker(composer, PostList)(PostList);
src/index.js
angela-cheng/simpleBlog
import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { createStore, applyMiddleware } from 'redux'; import { BrowserRouter, Route, Switch } from 'react-router-dom'; import promise from 'redux-promise'; //import App from './components/app'; we don't need this anymore since there's no "central" component (we're using routes!) //we also deleted components/app.js import PostsShow from './components/posts_show'; import reducers from './reducers'; import PostsIndex from './components/posts_index'; import PostsNew from './components/posts_new'; //Our router is here :-) //Note: We make PostsShow the second one because :id can match new as well ReactDOM.render( <Provider store={createStoreWithMiddleware(reducers)}> <BrowserRouter> <div> <Switch> <Route path="/posts/new" component={PostsNew} /> <Route path="/posts/:id" component={PostsShow} /> <Route path="/" component={PostsIndex} /> </Switch> </div> </BrowserRouter> </Provider> , document.querySelector('.container'));
app/javascript/mastodon/components/radio_button.js
lynlynlynx/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; export default class RadioButton extends React.PureComponent { static propTypes = { value: PropTypes.string.isRequired, checked: PropTypes.bool, name: PropTypes.string.isRequired, onChange: PropTypes.func.isRequired, label: PropTypes.node.isRequired, }; render () { const { name, value, checked, onChange, label } = this.props; return ( <label className='radio-button'> <input name={name} type='radio' value={value} checked={checked} onChange={onChange} /> <span className={classNames('radio-button__input', { checked })} /> <span>{label}</span> </label> ); } }