path
stringlengths
5
304
repo_name
stringlengths
6
79
content
stringlengths
27
1.05M
hello world/1.6 - style/src/components/main.js
wumouren/react-demo
import React from 'react'; export default class Main extends React.Component { render() { return ( <div> </div> ) } }
src/components/app.js
jocelio/meuclima
import React, { Component } from 'react'; import SearchBar from '../containers/search_bar'; import WeatherList from '../containers/weather_list'; export default class App extends Component { render() { return ( <div> <SearchBar /> <WeatherList /> </div> ); } }
scripts/shared/routes/index.js
namroodinc/police-react-mobx
import React from 'react'; import { Router, Route, IndexRoute } from "react-router"; import Home from "../handlers/home"; import Post from "../handlers/post"; import AppController from "../controller/"; export default ( <Router> <Route path="/" component={AppController} > <IndexRoute component={Home} /> <Route path="post" component={Post} /> </Route> <Route path="*" component={Home} /> </Router> );
client/modules/todo/tests/todo-input.spec.js
kifahhk/nerm-boilerplate
import React from 'react'; import sinon from 'sinon'; import { shallow, expect } from '../../../util/test-helper'; import TodoInput from '../components/todo-input'; describe('TodoInput', () => { let component; const spy = sinon.spy(); const props = { onSave: spy, text: '', placeholder: '', editing: false, newTodo: false, }; beforeEach(() => { component = shallow(<TodoInput {...props} />); }); afterEach(() => spy.reset()); it('should render correctly', () => expect(component.find('input')).to.exist ); it('should call onSave on return key press', () => { component.find('input').simulate('keyDown', { which: 13, target: { value: 'text' } }); expect(spy).to.have.been.calledWith('text'); }); it('should render correctly when editing=true', () => { component = shallow(<TodoInput {...props} editing />); expect(component.props().className).equal('edit '); }); it('should render correctly when newTodo=true', () => { component = shallow(<TodoInput {...props} newTodo />); expect(component.props().className).equal('new-todo'); }); it('should update value on change', () => { component.find('input').simulate('change', { target: { value: 'First ToDo' } }); expect(component.find('input').props().value).equal('First ToDo'); }); it('should reset state on return key press if newTodo', () => { component.find('input').simulate('keyDown', { which: 13, target: { value: 'text' } }); expect(component.find('input').props().value).equal(''); }); it('should call onSave on blur', () => { component.find('input').simulate('blur', { target: { value: 'text' } }); expect(spy).to.have.been.calledWith('text'); }); it('should not call onSave on blur if newTodo', () => { component = shallow(<TodoInput {...props} newTodo />); component.find('input').simulate('blur', { target: { value: 'text' } }); expect(spy).to.have.not.been.called; }); });
src/components/ConversationHeader/ConversationHeader.js
jwyung/navigation-rotor
import React, { Component, PropTypes } from 'react'; import Button from '../Shared/Button'; import './conversationHeader.css'; export default class ChannelHeader extends Component { isSpotlightComponent() { return this.props.focus[0] === this.refs['convo-header']; } getChildFocusLevel() { return this.isSpotlightComponent() ? 1 : 0; } getConvoHeaderAttrs() { return { className: `convo-header-component${this.isSpotlightComponent() ? ' is-spotlight-component' : ''}`, tabIndex: this.props.focusLevel || this.isSpotlightComponent() ? '0' : '-1', onKeyDown: this.props.handleFocus }; } getInputAttrs() { return this.getChildFocusLevel() ? {} : { tabIndex: -1 }; } render() { return ( <section data-component-focusable="" ref="convo-header" {...this.getConvoHeaderAttrs()} > <Button className="favorite-convo-btn" focusLevel={this.getChildFocusLevel()} isNaked={true} ariaLabel="Favorite this conversation" text={String.fromCharCode(9829)} /> <h2 className="current-convo">Free food</h2> <div className="utility-group"> <input className="search" type="text" placeholder="Search" {...this.getInputAttrs()} /> <Button focusLevel={this.getChildFocusLevel()} isNaked={true} ariaLabel="Show conversation information" text="Info" /> </div> </section> ); } }
src/@ui/Icon/icons/LikeSolid.js
NewSpring/Apollos
import React from 'react'; import PropTypes from 'prop-types'; import { Svg } from '../../Svg'; import makeIcon from './makeIcon'; const Icon = makeIcon(({ size = 32, fill, ...otherProps } = {}) => ( <Svg width={size} height={size} viewBox="0 0 24 24" {...otherProps}> <Svg.Path d="M10.8 4.03l-.03.03h.1c.4.3.8.64 1.13 1.03.33-.4.72-.75 1.14-1.05h.1c-.02 0-.03-.02-.04-.03.97-.66 2.13-1.03 3.3-1.03C19.6 3 22 5.4 22 8.47c0 3.8-3.4 6.88-8.6 11.46l-1.4 1.4-1.4-1.4C5.4 15.36 2 12.27 2 8.48 2 5.38 4.4 3 7.5 3c1.17 0 2.33.37 3.3 1.03z" fill={fill} /> </Svg> )); Icon.propTypes = { size: PropTypes.number, fill: PropTypes.string, }; export default Icon;
src/main.js
SimoNonnis/react-webpack-lab
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; ReactDOM.render(<App />, document.getElementById('root'));
app/javascript/mastodon/features/favourites/index.js
robotstart/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import ImmutablePropTypes from 'react-immutable-proptypes'; import LoadingIndicator from '../../components/loading_indicator'; import { fetchFavourites } from '../../actions/interactions'; import { ScrollContainer } from 'react-router-scroll'; import AccountContainer from '../../containers/account_container'; import Column from '../ui/components/column'; import ColumnBackButton from '../../components/column_back_button'; import ImmutablePureComponent from 'react-immutable-pure-component'; const mapStateToProps = (state, props) => ({ accountIds: state.getIn(['user_lists', 'favourited_by', Number(props.params.statusId)]) }); class Favourites extends ImmutablePureComponent { componentWillMount () { this.props.dispatch(fetchFavourites(Number(this.props.params.statusId))); } componentWillReceiveProps(nextProps) { if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) { this.props.dispatch(fetchFavourites(Number(nextProps.params.statusId))); } } render () { const { accountIds } = this.props; if (!accountIds) { return ( <Column> <LoadingIndicator /> </Column> ); } return ( <Column> <ColumnBackButton /> <ScrollContainer scrollKey='favourites'> <div className='scrollable'> {accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)} </div> </ScrollContainer> </Column> ); } } Favourites.propTypes = { params: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, accountIds: ImmutablePropTypes.list }; export default connect(mapStateToProps)(Favourites);
src/svg-icons/maps/place.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsPlace = (props) => ( <SvgIcon {...props}> <path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/> </SvgIcon> ); MapsPlace = pure(MapsPlace); MapsPlace.displayName = 'MapsPlace'; MapsPlace.muiName = 'SvgIcon'; export default MapsPlace;
src/app/js/StatsDisplay.js
skratchdot/colorify
import React, { Component } from 'react'; import ColorSpaces from './ColorSpaces'; import Tiles from './Tiles'; import { friendlyName } from './helpers.js'; import throttle from 'lodash.throttle'; const throttleTime = 50; class StatsDisplay extends Component { constructor(props) { super(props); const $this = this; this.state = { throttledUpdate: throttle( function () { $this.forceUpdate(); }, throttleTime, { leading: false } ), }; } shouldComponentUpdate() { setTimeout(this.state.throttledUpdate, 0); // setting timeout of 0 is important! return false; } buildSchemes = () => { const schemes = []; let scheme; for (const schemeName in this.props.stats.schemes) { if ( Object.prototype.hasOwnProperty.call( this.props.stats.schemes, schemeName ) ) { scheme = this.props.stats.schemes[schemeName]; // add to scheme list schemes.push( <h5 key={`name-${schemeName}`}>{friendlyName(schemeName)}</h5> ); schemes.push( <Tiles key={`scheme-${schemeName}`} alpha={this.props.stats.alpha} scheme={scheme} onColorChange={this.props.onColorChange} /> ); } } return schemes; } render() { const schemes = this.buildSchemes(); return ( <div className="stat-display"> <h3 className="page-header">Color Spaces</h3> <ColorSpaces stats={this.props.stats} /> <h3 className="page-header">Websafe / Websmart</h3> <Tiles alpha={this.props.stats.alpha} scheme={[this.props.stats.websafe, this.props.stats.websmart]} onColorChange={this.props.onColorChange} /> <h3 className="page-header">Tints</h3> <Tiles alpha={this.props.stats.alpha} scheme={this.props.stats.tints} onColorChange={this.props.onColorChange} /> <h3 className="page-header">Tones</h3> <Tiles alpha={this.props.stats.alpha} scheme={this.props.stats.tones} onColorChange={this.props.onColorChange} /> <h3 className="page-header">Shades</h3> <Tiles alpha={this.props.stats.alpha} scheme={this.props.stats.shades} onColorChange={this.props.onColorChange} /> <h3 className="page-header">Color Schemes</h3> {schemes} <br /> <br /> </div> ); } } export default StatsDisplay;
src/components/D3YAxis.js
guzmonne/gux-d3-react
import React from 'react' import T from 'prop-types' import {DELAY} from '../variables.js' const d3 = Object.assign({}, require('d3-selection'), require('d3-axis'), require('d3-transition') ) class D3YAxis extends React.Component { componentDidMount(){ this.draw() } componentDidUpdate() { this.draw() } draw = () => { const { yScale, ticks, tickSize, tickPadding, textAnchor, textAngle, textSize, } = this.props this.axis = ( d3.axisLeft(yScale) .ticks(ticks) .tickSize(tickSize) .tickPadding(tickPadding) ) d3.select(this.container) .transition(d3.transition().duration(DELAY)) .call(this.axis) .selectAll('text') .style('text-anchor', textAnchor) .attr('font-size', textSize + 'px') .attr('transform', `rotate(${textAngle})`) } render() { const {className} = this.props return ( <g className={className} ref={c => this.container = c}></g> ) } } D3YAxis.propTypes = { className: T.string, yScale: T.func, ticks: T.number, tickSize: T.number, tickPadding: T.number, textAnchor: T.string, textAngle: T.number, textSize: T.number, } D3YAxis.defaultProps = { className: 'rd3__x-axis', ticks: 5, tickSize: 10, tickPadding: 5, textAnchor: 'end', textAngle: 0, textSize: 10, } export default D3YAxis
ajax/libs/react-native-web/0.17.7/cjs/exports/AppRegistry/renderApplication.js
cdnjs/cdnjs
"use strict"; exports.__esModule = true; exports.default = renderApplication; exports.getApplication = getApplication; var _AppContainer = _interopRequireDefault(require("./AppContainer")); var _invariant = _interopRequireDefault(require("fbjs/lib/invariant")); var _render = _interopRequireWildcard(require("../render")); var _styleResolver = _interopRequireDefault(require("../StyleSheet/styleResolver")); var _react = _interopRequireDefault(require("react")); function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function renderApplication(RootComponent, WrapperComponent, callback, options) { var shouldHydrate = options.hydrate, initialProps = options.initialProps, rootTag = options.rootTag; var renderFn = shouldHydrate ? _render.hydrate : _render.default; (0, _invariant.default)(rootTag, 'Expect to have a valid rootTag, instead got ', rootTag); renderFn( /*#__PURE__*/_react.default.createElement(_AppContainer.default, { WrapperComponent: WrapperComponent, rootTag: rootTag }, /*#__PURE__*/_react.default.createElement(RootComponent, initialProps)), rootTag, callback); } function getApplication(RootComponent, initialProps, WrapperComponent) { var element = /*#__PURE__*/_react.default.createElement(_AppContainer.default, { WrapperComponent: WrapperComponent, rootTag: {} }, /*#__PURE__*/_react.default.createElement(RootComponent, initialProps)); // Don't escape CSS text var getStyleElement = function getStyleElement(props) { var sheet = _styleResolver.default.getStyleSheet(); return /*#__PURE__*/_react.default.createElement("style", _extends({}, props, { dangerouslySetInnerHTML: { __html: sheet.textContent }, id: sheet.id })); }; return { element: element, getStyleElement: getStyleElement }; }
Realization/frontend/czechidm-core/src/content/role/RoleCatalogueRoles.js
bcvsolutions/CzechIdMng
import React from 'react'; import Helmet from 'react-helmet'; // import * as Basic from '../../components/basic'; import SearchParameters from '../../domain/SearchParameters'; import RoleCatalogueRoleTable from './RoleCatalogueRoleTable'; /** * Role catalogues - role assigned to role catalogue. * * @author Radek Tomiška */ export default class RoleCatalogueRoles extends Basic.AbstractContent { getContentKey() { return 'content.role.catalogues'; } getNavigationKey() { return this.getRequestNavigationKey('role-catalogue-roles', this.props.match.params); } render() { const forceSearchParameters = new SearchParameters().setFilter('roleId', this.props.match.params.entityId); // return ( <Basic.Div className="tab-pane-table-body"> { this.renderContentHeader({ style: { marginBottom: 0 }}) } <RoleCatalogueRoleTable uiKey="role-catalogue-role-table" forceSearchParameters={ forceSearchParameters } className="no-margin" match={ this.props.match } columns={[ 'roleCatalogue' ]}/> </Basic.Div> ); } }
ajax/libs/vue/1.0.13-csp/vue.js
BenjaminVanRyseghem/cdnjs
/*! * Vue.js v1.0.13-csp * (c) 2015 Evan You * 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.Vue = factory(); }(this, function () { 'use strict'; var __commonjs_global = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this; function set(obj, key, val) { if (hasOwn(obj, key)) { obj[key] = val; return; } if (obj._isVue) { set(obj._data, key, val); return; } var ob = obj.__ob__; if (!ob) { obj[key] = val; return; } ob.convert(key, val); ob.dep.notify(); if (ob.vms) { var i = ob.vms.length; while (i--) { var vm = ob.vms[i]; vm._proxy(key); vm._digest(); } } return val; } /** * Delete a property and trigger change if necessary. * * @param {Object} obj * @param {String} key */ function del(obj, key) { if (!hasOwn(obj, key)) { return; } delete obj[key]; var ob = obj.__ob__; if (!ob) { return; } ob.dep.notify(); if (ob.vms) { var i = ob.vms.length; while (i--) { var vm = ob.vms[i]; vm._unproxy(key); vm._digest(); } } } var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Check whether the object has the property. * * @param {Object} obj * @param {String} key * @return {Boolean} */ function hasOwn(obj, key) { return hasOwnProperty.call(obj, key); } /** * Check if an expression is a literal value. * * @param {String} exp * @return {Boolean} */ var literalValueRE = /^\s?(true|false|[\d\.]+|'[^']*'|"[^"]*")\s?$/; function isLiteral(exp) { return literalValueRE.test(exp); } /** * Check if a string starts with $ or _ * * @param {String} str * @return {Boolean} */ function isReserved(str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F; } /** * Guard text output, make sure undefined outputs * empty string * * @param {*} value * @return {String} */ function _toString(value) { return value == null ? '' : value.toString(); } /** * Check and convert possible numeric strings to numbers * before setting back to data * * @param {*} value * @return {*|Number} */ function toNumber(value) { if (typeof value !== 'string') { return value; } else { var parsed = Number(value); return isNaN(parsed) ? value : parsed; } } /** * Convert string boolean literals into real booleans. * * @param {*} value * @return {*|Boolean} */ function toBoolean(value) { return value === 'true' ? true : value === 'false' ? false : value; } /** * Strip quotes from a string * * @param {String} str * @return {String | false} */ function stripQuotes(str) { var a = str.charCodeAt(0); var b = str.charCodeAt(str.length - 1); return a === b && (a === 0x22 || a === 0x27) ? str.slice(1, -1) : str; } /** * Camelize a hyphen-delmited string. * * @param {String} str * @return {String} */ var camelizeRE = /-(\w)/g; function camelize(str) { return str.replace(camelizeRE, toUpper); } function toUpper(_, c) { return c ? c.toUpperCase() : ''; } /** * Hyphenate a camelCase string. * * @param {String} str * @return {String} */ var hyphenateRE = /([a-z\d])([A-Z])/g; function hyphenate(str) { return str.replace(hyphenateRE, '$1-$2').toLowerCase(); } /** * Converts hyphen/underscore/slash delimitered names into * camelized classNames. * * e.g. my-component => MyComponent * some_else => SomeElse * some/comp => SomeComp * * @param {String} str * @return {String} */ var classifyRE = /(?:^|[-_\/])(\w)/g; function classify(str) { return str.replace(classifyRE, toUpper); } /** * Simple bind, faster than native * * @param {Function} fn * @param {Object} ctx * @return {Function} */ function bind$1(fn, ctx) { return function (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx); }; } /** * Convert an Array-like object to a real Array. * * @param {Array-like} list * @param {Number} [start] - start index * @return {Array} */ function toArray(list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret; } /** * Mix properties into target object. * * @param {Object} to * @param {Object} from */ function extend(to, from) { var keys = Object.keys(from); var i = keys.length; while (i--) { to[keys[i]] = from[keys[i]]; } return to; } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. * * @param {*} obj * @return {Boolean} */ function isObject(obj) { return obj !== null && typeof obj === 'object'; } /** * Strict object type check. Only returns true * for plain JavaScript objects. * * @param {*} obj * @return {Boolean} */ var toString = Object.prototype.toString; var OBJECT_STRING = '[object Object]'; function isPlainObject(obj) { return toString.call(obj) === OBJECT_STRING; } /** * Array type check. * * @param {*} obj * @return {Boolean} */ var isArray = Array.isArray; /** * Define a non-enumerable property * * @param {Object} obj * @param {String} key * @param {*} val * @param {Boolean} [enumerable] */ function def(obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Debounce a function so it only gets called after the * input stops arriving after the given wait period. * * @param {Function} func * @param {Number} wait * @return {Function} - the debounced function */ function _debounce(func, wait) { var timeout, args, context, timestamp, result; var later = function later() { var last = Date.now() - timestamp; if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; } }; return function () { context = this; args = arguments; timestamp = Date.now(); if (!timeout) { timeout = setTimeout(later, wait); } return result; }; } /** * Manual indexOf because it's slightly faster than * native. * * @param {Array} arr * @param {*} obj */ function indexOf(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) return i; } return -1; } /** * Make a cancellable version of an async callback. * * @param {Function} fn * @return {Function} */ function cancellable(fn) { var cb = function cb() { if (!cb.cancelled) { return fn.apply(this, arguments); } }; cb.cancel = function () { cb.cancelled = true; }; return cb; } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? * * @param {*} a * @param {*} b * @return {Boolean} */ function looseEqual(a, b) { /* eslint-disable eqeqeq */ return a == b || (isObject(a) && isObject(b) ? JSON.stringify(a) === JSON.stringify(b) : false); /* eslint-enable eqeqeq */ } var hasProto = ('__proto__' in {}); // Browser environment sniffing var inBrowser = typeof window !== 'undefined' && Object.prototype.toString.call(window) !== '[object Object]'; var isIE9 = inBrowser && navigator.userAgent.toLowerCase().indexOf('msie 9.0') > 0; var isAndroid = inBrowser && navigator.userAgent.toLowerCase().indexOf('android') > 0; var transitionProp = undefined; var transitionEndEvent = undefined; var animationProp = undefined; var animationEndEvent = undefined; // Transition property/event sniffing if (inBrowser && !isIE9) { var isWebkitTrans = window.ontransitionend === undefined && window.onwebkittransitionend !== undefined; var isWebkitAnim = window.onanimationend === undefined && window.onwebkitanimationend !== undefined; transitionProp = isWebkitTrans ? 'WebkitTransition' : 'transition'; transitionEndEvent = isWebkitTrans ? 'webkitTransitionEnd' : 'transitionend'; animationProp = isWebkitAnim ? 'WebkitAnimation' : 'animation'; animationEndEvent = isWebkitAnim ? 'webkitAnimationEnd' : 'animationend'; } /** * Defer a task to execute it asynchronously. Ideally this * should be executed as a microtask, so we leverage * MutationObserver if it's available, and fallback to * setTimeout(0). * * @param {Function} cb * @param {Object} ctx */ var nextTick = (function () { var callbacks = []; var pending = false; var timerFunc; function nextTickHandler() { pending = false; var copies = callbacks.slice(0); callbacks = []; for (var i = 0; i < copies.length; i++) { copies[i](); } } /* istanbul ignore if */ if (typeof MutationObserver !== 'undefined') { var counter = 1; var observer = new MutationObserver(nextTickHandler); var textNode = document.createTextNode(counter); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = counter; }; } else { timerFunc = setTimeout; } return function (cb, ctx) { var func = ctx ? function () { cb.call(ctx); } : cb; callbacks.push(func); if (pending) return; pending = true; timerFunc(nextTickHandler, 0); }; })(); function Cache(limit) { this.size = 0; this.limit = limit; this.head = this.tail = undefined; this._keymap = Object.create(null); } var p = Cache.prototype; /** * Put <value> into the cache associated with <key>. * Returns the entry which was removed to make room for * the new entry. Otherwise undefined is returned. * (i.e. if there was enough room already). * * @param {String} key * @param {*} value * @return {Entry|undefined} */ p.put = function (key, value) { var entry = { key: key, value: value }; this._keymap[key] = entry; if (this.tail) { this.tail.newer = entry; entry.older = this.tail; } else { this.head = entry; } this.tail = entry; if (this.size === this.limit) { return this.shift(); } else { this.size++; } }; /** * Purge the least recently used (oldest) entry from the * cache. Returns the removed entry or undefined if the * cache was empty. */ p.shift = function () { var entry = this.head; if (entry) { this.head = this.head.newer; this.head.older = undefined; entry.newer = entry.older = undefined; this._keymap[entry.key] = undefined; } return entry; }; /** * Get and register recent use of <key>. Returns the value * associated with <key> or undefined if not in cache. * * @param {String} key * @param {Boolean} returnEntry * @return {Entry|*} */ p.get = function (key, returnEntry) { var entry = this._keymap[key]; if (entry === undefined) return; if (entry === this.tail) { return returnEntry ? entry : entry.value; } // HEAD--------------TAIL // <.older .newer> // <--- add direction -- // A B C <D> E if (entry.newer) { if (entry === this.head) { this.head = entry.newer; } entry.newer.older = entry.older; // C <-- E. } if (entry.older) { entry.older.newer = entry.newer; // C. --> E } entry.newer = undefined; // D --x entry.older = this.tail; // D. --> E if (this.tail) { this.tail.newer = entry; // E. <-- D } this.tail = entry; return returnEntry ? entry : entry.value; }; var cache$1 = new Cache(1000); var filterTokenRE = /[^\s'"]+|'[^']*'|"[^"]*"/g; var reservedArgRE = /^in$|^-?\d+/; /** * Parser state */ var str; var dir; var c; var prev; var i; var l; var lastFilterIndex; var inSingle; var inDouble; var curly; var square; var paren; /** * Push a filter to the current directive object */ function pushFilter() { var exp = str.slice(lastFilterIndex, i).trim(); var filter; if (exp) { filter = {}; var tokens = exp.match(filterTokenRE); filter.name = tokens[0]; if (tokens.length > 1) { filter.args = tokens.slice(1).map(processFilterArg); } } if (filter) { (dir.filters = dir.filters || []).push(filter); } lastFilterIndex = i + 1; } /** * Check if an argument is dynamic and strip quotes. * * @param {String} arg * @return {Object} */ function processFilterArg(arg) { if (reservedArgRE.test(arg)) { return { value: toNumber(arg), dynamic: false }; } else { var stripped = stripQuotes(arg); var dynamic = stripped === arg; return { value: dynamic ? arg : stripped, dynamic: dynamic }; } } /** * Parse a directive value and extract the expression * and its filters into a descriptor. * * Example: * * "a + 1 | uppercase" will yield: * { * expression: 'a + 1', * filters: [ * { name: 'uppercase', args: null } * ] * } * * @param {String} str * @return {Object} */ function parseDirective(s) { var hit = cache$1.get(s); if (hit) { return hit; } // reset parser state str = s; inSingle = inDouble = false; curly = square = paren = 0; lastFilterIndex = 0; dir = {}; for (i = 0, l = str.length; i < l; i++) { prev = c; c = str.charCodeAt(i); if (inSingle) { // check single quote if (c === 0x27 && prev !== 0x5C) inSingle = !inSingle; } else if (inDouble) { // check double quote if (c === 0x22 && prev !== 0x5C) inDouble = !inDouble; } else if (c === 0x7C && // pipe str.charCodeAt(i + 1) !== 0x7C && str.charCodeAt(i - 1) !== 0x7C) { if (dir.expression == null) { // first filter, end of expression lastFilterIndex = i + 1; dir.expression = str.slice(0, i).trim(); } else { // already has filter pushFilter(); } } else { switch (c) { case 0x22: inDouble = true;break; // " case 0x27: inSingle = true;break; // ' case 0x28: paren++;break; // ( case 0x29: paren--;break; // ) case 0x5B: square++;break; // [ case 0x5D: square--;break; // ] case 0x7B: curly++;break; // { case 0x7D: curly--;break; // } } } } if (dir.expression == null) { dir.expression = str.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } cache$1.put(s, dir); return dir; } var directive = Object.freeze({ parseDirective: parseDirective }); var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var cache = undefined; var tagRE = undefined; var htmlRE = undefined; /** * Escape a string so it can be used in a RegExp * constructor. * * @param {String} str */ function escapeRegex(str) { return str.replace(regexEscapeRE, '\\$&'); } function compileRegex() { var open = escapeRegex(config.delimiters[0]); var close = escapeRegex(config.delimiters[1]); var unsafeOpen = escapeRegex(config.unsafeDelimiters[0]); var unsafeClose = escapeRegex(config.unsafeDelimiters[1]); tagRE = new RegExp(unsafeOpen + '(.+?)' + unsafeClose + '|' + open + '(.+?)' + close, 'g'); htmlRE = new RegExp('^' + unsafeOpen + '.*' + unsafeClose + '$'); // reset cache cache = new Cache(1000); } /** * Parse a template text string into an array of tokens. * * @param {String} text * @return {Array<Object> | null} * - {String} type * - {String} value * - {Boolean} [html] * - {Boolean} [oneTime] */ function parseText(text) { if (!cache) { compileRegex(); } var hit = cache.get(text); if (hit) { return hit; } text = text.replace(/\n/g, ''); if (!tagRE.test(text)) { return null; } var tokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index, html, value, first, oneTime; /* eslint-disable no-cond-assign */ while (match = tagRE.exec(text)) { /* eslint-enable no-cond-assign */ index = match.index; // push text token if (index > lastIndex) { tokens.push({ value: text.slice(lastIndex, index) }); } // tag token html = htmlRE.test(match[0]); value = html ? match[1] : match[2]; first = value.charCodeAt(0); oneTime = first === 42; // * value = oneTime ? value.slice(1) : value; tokens.push({ tag: true, value: value.trim(), html: html, oneTime: oneTime }); lastIndex = index + match[0].length; } if (lastIndex < text.length) { tokens.push({ value: text.slice(lastIndex) }); } cache.put(text, tokens); return tokens; } /** * Format a list of tokens into an expression. * e.g. tokens parsed from 'a {{b}} c' can be serialized * into one single expression as '"a " + b + " c"'. * * @param {Array} tokens * @return {String} */ function tokensToExp(tokens) { if (tokens.length > 1) { return tokens.map(function (token) { return formatToken(token); }).join('+'); } else { return formatToken(tokens[0], true); } } /** * Format a single token. * * @param {Object} token * @param {Boolean} single * @return {String} */ function formatToken(token, single) { return token.tag ? inlineFilters(token.value, single) : '"' + token.value + '"'; } /** * For an attribute with multiple interpolation tags, * e.g. attr="some-{{thing | filter}}", in order to combine * the whole thing into a single watchable expression, we * have to inline those filters. This function does exactly * that. This is a bit hacky but it avoids heavy changes * to directive parser and watcher mechanism. * * @param {String} exp * @param {Boolean} single * @return {String} */ var filterRE$1 = /[^|]\|[^|]/; function inlineFilters(exp, single) { if (!filterRE$1.test(exp)) { return single ? exp : '(' + exp + ')'; } else { var dir = parseDirective(exp); if (!dir.filters) { return '(' + exp + ')'; } else { return 'this._applyFilters(' + dir.expression + // value ',null,' + // oldValue (null for read) JSON.stringify(dir.filters) + // filter descriptors ',false)'; // write? } } } var text$1 = Object.freeze({ compileRegex: compileRegex, parseText: parseText, tokensToExp: tokensToExp }); var delimiters = ['{{', '}}']; var unsafeDelimiters = ['{{{', '}}}']; var config = Object.defineProperties({ /** * Whether to print debug messages. * Also enables stack trace for warnings. * * @type {Boolean} */ debug: false, /** * Whether to suppress warnings. * * @type {Boolean} */ silent: false, /** * Whether to use async rendering. */ async: true, /** * Whether to warn against errors caught when evaluating * expressions. */ warnExpressionErrors: true, /** * Whether or not to handle fully object properties which * are already backed by getters and seters. Depending on * use case and environment, this might introduce non-neglible * performance penalties. */ convertAllProperties: false, /** * Internal flag to indicate the delimiters have been * changed. * * @type {Boolean} */ _delimitersChanged: true, /** * List of asset types that a component can own. * * @type {Array} */ _assetTypes: ['component', 'directive', 'elementDirective', 'filter', 'transition', 'partial'], /** * prop binding modes */ _propBindingModes: { ONE_WAY: 0, TWO_WAY: 1, ONE_TIME: 2 }, /** * Max circular updates allowed in a batcher flush cycle. */ _maxUpdateCount: 100 }, { delimiters: { /** * Interpolation delimiters. Changing these would trigger * the text parser to re-compile the regular expressions. * * @type {Array<String>} */ get: function get() { return delimiters; }, set: function set(val) { delimiters = val; compileRegex(); }, configurable: true, enumerable: true }, unsafeDelimiters: { get: function get() { return unsafeDelimiters; }, set: function set(val) { unsafeDelimiters = val; compileRegex(); }, configurable: true, enumerable: true } }); var warn = undefined; if ('development' !== 'production') { (function () { var hasConsole = typeof console !== 'undefined'; warn = function (msg, e) { if (hasConsole && (!config.silent || config.debug)) { console.warn('[Vue warn]: ' + msg); /* istanbul ignore if */ if (config.debug) { if (e) { throw e; } else { console.warn(new Error('Warning Stack Trace').stack); } } } }; })(); } /** * Append with transition. * * @param {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ function appendWithTransition(el, target, vm, cb) { applyTransition(el, 1, function () { target.appendChild(el); }, vm, cb); } /** * InsertBefore with transition. * * @param {Element} el * @param {Element} target * @param {Vue} vm * @param {Function} [cb] */ function beforeWithTransition(el, target, vm, cb) { applyTransition(el, 1, function () { before(el, target); }, vm, cb); } /** * Remove with transition. * * @param {Element} el * @param {Vue} vm * @param {Function} [cb] */ function removeWithTransition(el, vm, cb) { applyTransition(el, -1, function () { remove(el); }, vm, cb); } /** * Apply transitions with an operation callback. * * @param {Element} el * @param {Number} direction * 1: enter * -1: leave * @param {Function} op - the actual DOM operation * @param {Vue} vm * @param {Function} [cb] */ function applyTransition(el, direction, op, vm, cb) { var transition = el.__v_trans; if (!transition || // skip if there are no js hooks and CSS transition is // not supported !transition.hooks && !transitionEndEvent || // skip transitions for initial compile !vm._isCompiled || // if the vm is being manipulated by a parent directive // during the parent's compilation phase, skip the // animation. vm.$parent && !vm.$parent._isCompiled) { op(); if (cb) cb(); return; } var action = direction > 0 ? 'enter' : 'leave'; transition[action](op, cb); } /** * Query an element selector if it's not an element already. * * @param {String|Element} el * @return {Element} */ function query(el) { if (typeof el === 'string') { var selector = el; el = document.querySelector(el); if (!el) { 'development' !== 'production' && warn('Cannot find element: ' + selector); } } return el; } /** * Check if a node is in the document. * Note: document.documentElement.contains should work here * but always returns false for comment nodes in phantomjs, * making unit tests difficult. This is fixed by doing the * contains() check on the node's parentNode instead of * the node itself. * * @param {Node} node * @return {Boolean} */ function inDoc(node) { var doc = document.documentElement; var parent = node && node.parentNode; return doc === node || doc === parent || !!(parent && parent.nodeType === 1 && doc.contains(parent)); } /** * Get and remove an attribute from a node. * * @param {Node} node * @param {String} _attr */ function getAttr(node, _attr) { var val = node.getAttribute(_attr); if (val !== null) { node.removeAttribute(_attr); } return val; } /** * Get an attribute with colon or v-bind: prefix. * * @param {Node} node * @param {String} name * @return {String|null} */ function getBindAttr(node, name) { var val = getAttr(node, ':' + name); if (val === null) { val = getAttr(node, 'v-bind:' + name); } return val; } /** * Check the presence of a bind attribute. * * @param {Node} node * @param {String} name * @return {Boolean} */ function hasBindAttr(node, name) { return node.hasAttribute(name) || node.hasAttribute(':' + name) || node.hasAttribute('v-bind:' + name); } /** * Insert el before target * * @param {Element} el * @param {Element} target */ function before(el, target) { target.parentNode.insertBefore(el, target); } /** * Insert el after target * * @param {Element} el * @param {Element} target */ function after(el, target) { if (target.nextSibling) { before(el, target.nextSibling); } else { target.parentNode.appendChild(el); } } /** * Remove el from DOM * * @param {Element} el */ function remove(el) { el.parentNode.removeChild(el); } /** * Prepend el to target * * @param {Element} el * @param {Element} target */ function prepend(el, target) { if (target.firstChild) { before(el, target.firstChild); } else { target.appendChild(el); } } /** * Replace target with el * * @param {Element} target * @param {Element} el */ function replace(target, el) { var parent = target.parentNode; if (parent) { parent.replaceChild(el, target); } } /** * Add event listener shorthand. * * @param {Element} el * @param {String} event * @param {Function} cb */ function on$1(el, event, cb) { el.addEventListener(event, cb); } /** * Remove event listener shorthand. * * @param {Element} el * @param {String} event * @param {Function} cb */ function off(el, event, cb) { el.removeEventListener(event, cb); } /** * In IE9, setAttribute('class') will result in empty class * if the element also has the :class attribute; However in * PhantomJS, setting `className` does not work on SVG elements... * So we have to do a conditional check here. * * @param {Element} el * @param {String} cls */ function setClass(el, cls) { /* istanbul ignore if */ if (isIE9 && !(el instanceof SVGElement)) { el.className = cls; } else { el.setAttribute('class', cls); } } /** * Add class with compatibility for IE & SVG * * @param {Element} el * @param {String} cls */ function addClass(el, cls) { if (el.classList) { el.classList.add(cls); } else { var cur = ' ' + (el.getAttribute('class') || '') + ' '; if (cur.indexOf(' ' + cls + ' ') < 0) { setClass(el, (cur + cls).trim()); } } } /** * Remove class with compatibility for IE & SVG * * @param {Element} el * @param {String} cls */ function removeClass(el, cls) { if (el.classList) { el.classList.remove(cls); } else { var cur = ' ' + (el.getAttribute('class') || '') + ' '; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } setClass(el, cur.trim()); } if (!el.className) { el.removeAttribute('class'); } } /** * Extract raw content inside an element into a temporary * container div * * @param {Element} el * @param {Boolean} asFragment * @return {Element} */ function extractContent(el, asFragment) { var child; var rawContent; /* istanbul ignore if */ if (isTemplate(el) && el.content instanceof DocumentFragment) { el = el.content; } if (el.hasChildNodes()) { trimNode(el); rawContent = asFragment ? document.createDocumentFragment() : document.createElement('div'); /* eslint-disable no-cond-assign */ while (child = el.firstChild) { /* eslint-enable no-cond-assign */ rawContent.appendChild(child); } } return rawContent; } /** * Trim possible empty head/tail textNodes inside a parent. * * @param {Node} node */ function trimNode(node) { trim(node, node.firstChild); trim(node, node.lastChild); } function trim(parent, node) { if (node && node.nodeType === 3 && !node.data.trim()) { parent.removeChild(node); } } /** * Check if an element is a template tag. * Note if the template appears inside an SVG its tagName * will be in lowercase. * * @param {Element} el */ function isTemplate(el) { return el.tagName && el.tagName.toLowerCase() === 'template'; } /** * Create an "anchor" for performing dom insertion/removals. * This is used in a number of scenarios: * - fragment instance * - v-html * - v-if * - v-for * - component * * @param {String} content * @param {Boolean} persist - IE trashes empty textNodes on * cloneNode(true), so in certain * cases the anchor needs to be * non-empty to be persisted in * templates. * @return {Comment|Text} */ function createAnchor(content, persist) { var anchor = config.debug ? document.createComment(content) : document.createTextNode(persist ? ' ' : ''); anchor.__vue_anchor = true; return anchor; } /** * Find a component ref attribute that starts with $. * * @param {Element} node * @return {String|undefined} */ var refRE = /^v-ref:/; function findRef(node) { if (node.hasAttributes()) { var attrs = node.attributes; for (var i = 0, l = attrs.length; i < l; i++) { var name = attrs[i].name; if (refRE.test(name)) { return camelize(name.replace(refRE, '')); } } } } /** * Map a function to a range of nodes . * * @param {Node} node * @param {Node} end * @param {Function} op */ function mapNodeRange(node, end, op) { var next; while (node !== end) { next = node.nextSibling; op(node); node = next; } op(end); } /** * Remove a range of nodes with transition, store * the nodes in a fragment with correct ordering, * and call callback when done. * * @param {Node} start * @param {Node} end * @param {Vue} vm * @param {DocumentFragment} frag * @param {Function} cb */ function removeNodeRange(start, end, vm, frag, cb) { var done = false; var removed = 0; var nodes = []; mapNodeRange(start, end, function (node) { if (node === end) done = true; nodes.push(node); removeWithTransition(node, vm, onRemoved); }); function onRemoved() { removed++; if (done && removed >= nodes.length) { for (var i = 0; i < nodes.length; i++) { frag.appendChild(nodes[i]); } cb && cb(); } } } var commonTagRE = /^(div|p|span|img|a|b|i|br|ul|ol|li|h1|h2|h3|h4|h5|h6|code|pre|table|th|td|tr|form|label|input|select|option|nav|article|section|header|footer)$/; var reservedTagRE = /^(slot|partial|component)$/; /** * Check if an element is a component, if yes return its * component id. * * @param {Element} el * @param {Object} options * @return {Object|undefined} */ function checkComponentAttr(el, options) { var tag = el.tagName.toLowerCase(); var hasAttrs = el.hasAttributes(); if (!commonTagRE.test(tag) && !reservedTagRE.test(tag)) { if (resolveAsset(options, 'components', tag)) { return { id: tag }; } else { var is = hasAttrs && getIsBinding(el); if (is) { return is; } else if ('development' !== 'production') { if (tag.indexOf('-') > -1 || /HTMLUnknownElement/.test(el.toString()) && // Chrome returns unknown for several HTML5 elements. // https://code.google.com/p/chromium/issues/detail?id=540526 !/^(data|time|rtc|rb)$/.test(tag)) { warn('Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly?'); } } } } else if (hasAttrs) { return getIsBinding(el); } } /** * Get "is" binding from an element. * * @param {Element} el * @return {Object|undefined} */ function getIsBinding(el) { // dynamic syntax var exp = getAttr(el, 'is'); if (exp != null) { return { id: exp }; } else { exp = getBindAttr(el, 'is'); if (exp != null) { return { id: exp, dynamic: true }; } } } /** * Set a prop's initial value on a vm and its data object. * * @param {Vue} vm * @param {Object} prop * @param {*} value */ function initProp(vm, prop, value) { var key = prop.path; value = coerceProp(prop, value); vm[key] = vm._data[key] = assertProp(prop, value) ? value : undefined; } /** * Assert whether a prop is valid. * * @param {Object} prop * @param {*} value */ function assertProp(prop, value) { // if a prop is not provided and is not required, // skip the check. if (prop.raw === null && !prop.required) { return true; } var options = prop.options; var type = options.type; var valid = true; var expectedType; if (type) { if (type === String) { expectedType = 'string'; valid = typeof value === expectedType; } else if (type === Number) { expectedType = 'number'; valid = typeof value === 'number'; } else if (type === Boolean) { expectedType = 'boolean'; valid = typeof value === 'boolean'; } else if (type === Function) { expectedType = 'function'; valid = typeof value === 'function'; } else if (type === Object) { expectedType = 'object'; valid = isPlainObject(value); } else if (type === Array) { expectedType = 'array'; valid = isArray(value); } else { valid = value instanceof type; } } if (!valid) { 'development' !== 'production' && warn('Invalid prop: type check failed for ' + prop.path + '="' + prop.raw + '".' + ' Expected ' + formatType(expectedType) + ', got ' + formatValue(value) + '.'); return false; } var validator = options.validator; if (validator) { if (!validator.call(null, value)) { 'development' !== 'production' && warn('Invalid prop: custom validator check failed for ' + prop.path + '="' + prop.raw + '"'); return false; } } return true; } /** * Force parsing value with coerce option. * * @param {*} value * @param {Object} options * @return {*} */ function coerceProp(prop, value) { var coerce = prop.options.coerce; if (!coerce) { return value; } // coerce is a function return coerce(value); } function formatType(val) { return val ? val.charAt(0).toUpperCase() + val.slice(1) : 'custom type'; } function formatValue(val) { return Object.prototype.toString.call(val).slice(8, -1); } /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. * * All strategy functions follow the same signature: * * @param {*} parentVal * @param {*} childVal * @param {Vue} [vm] */ var strats = config.optionMergeStrategies = Object.create(null); /** * Helper that recursively merges two data objects together. */ function mergeData(to, from) { var key, toVal, fromVal; for (key in from) { toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set(to, key, fromVal); } else if (isObject(toVal) && isObject(fromVal)) { mergeData(toVal, fromVal); } } return to; } /** * Data */ strats.data = function (parentVal, childVal, vm) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal; } if (typeof childVal !== 'function') { 'development' !== 'production' && warn('The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.'); return parentVal; } if (!parentVal) { return childVal; } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn() { return mergeData(childVal.call(this), parentVal.call(this)); }; } else if (parentVal || childVal) { return function mergedInstanceDataFn() { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm) : undefined; if (instanceData) { return mergeData(instanceData, defaultData); } else { return defaultData; } }; } }; /** * El */ strats.el = function (parentVal, childVal, vm) { if (!vm && childVal && typeof childVal !== 'function') { 'development' !== 'production' && warn('The "el" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.'); return; } var ret = childVal || parentVal; // invoke the element factory if this is instance merge return vm && typeof ret === 'function' ? ret.call(vm) : ret; }; /** * Hooks and param attributes are merged as arrays. */ strats.init = strats.created = strats.ready = strats.attached = strats.detached = strats.beforeCompile = strats.compiled = strats.beforeDestroy = strats.destroyed = function (parentVal, childVal) { return childVal ? parentVal ? parentVal.concat(childVal) : isArray(childVal) ? childVal : [childVal] : parentVal; }; /** * 0.11 deprecation warning */ strats.paramAttributes = function () { /* istanbul ignore next */ 'development' !== 'production' && warn('"paramAttributes" option has been deprecated in 0.12. ' + 'Use "props" instead.'); }; /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets(parentVal, childVal) { var res = Object.create(parentVal); return childVal ? extend(res, guardArrayAssets(childVal)) : res; } config._assetTypes.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Events & Watchers. * * Events & watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = strats.events = function (parentVal, childVal) { if (!childVal) return parentVal; if (!parentVal) return childVal; var ret = {}; extend(ret, parentVal); for (var key in childVal) { var parent = ret[key]; var child = childVal[key]; if (parent && !isArray(parent)) { parent = [parent]; } ret[key] = parent ? parent.concat(child) : [child]; } return ret; }; /** * Other object hashes. */ strats.props = strats.methods = strats.computed = function (parentVal, childVal) { if (!childVal) return parentVal; if (!parentVal) return childVal; var ret = Object.create(null); extend(ret, parentVal); extend(ret, childVal); return ret; }; /** * Default strategy. */ var defaultStrat = function defaultStrat(parentVal, childVal) { return childVal === undefined ? parentVal : childVal; }; /** * Make sure component options get converted to actual * constructors. * * @param {Object} options */ function guardComponents(options) { if (options.components) { var components = options.components = guardArrayAssets(options.components); var def; var ids = Object.keys(components); for (var i = 0, l = ids.length; i < l; i++) { var key = ids[i]; if (commonTagRE.test(key) || reservedTagRE.test(key)) { 'development' !== 'production' && warn('Do not use built-in or reserved HTML elements as component ' + 'id: ' + key); continue; } def = components[key]; if (isPlainObject(def)) { components[key] = Vue.extend(def); } } } } /** * Ensure all props option syntax are normalized into the * Object-based format. * * @param {Object} options */ function guardProps(options) { var props = options.props; var i, val; if (isArray(props)) { options.props = {}; i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { options.props[val] = null; } else if (val.name) { options.props[val.name] = val; } } } else if (isPlainObject(props)) { var keys = Object.keys(props); i = keys.length; while (i--) { val = props[keys[i]]; if (typeof val === 'function') { props[keys[i]] = { type: val }; } } } } /** * Guard an Array-format assets option and converted it * into the key-value Object format. * * @param {Object|Array} assets * @return {Object} */ function guardArrayAssets(assets) { if (isArray(assets)) { var res = {}; var i = assets.length; var asset; while (i--) { asset = assets[i]; var id = typeof asset === 'function' ? asset.options && asset.options.name || asset.id : asset.name || asset.id; if (!id) { 'development' !== 'production' && warn('Array-syntax assets must provide a "name" or "id" field.'); } else { res[id] = asset; } } return res; } return assets; } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. * * @param {Object} parent * @param {Object} child * @param {Vue} [vm] - if vm is present, indicates this is * an instantiation merge. */ function mergeOptions(parent, child, vm) { guardComponents(child); guardProps(child); var options = {}; var key; if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { parent = mergeOptions(parent, child.mixins[i], vm); } } for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField(key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options; } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. * * @param {Object} options * @param {String} type * @param {String} id * @return {Object|Function} */ function resolveAsset(options, type, id) { var assets = options[type]; var camelizedId; return assets[id] || // camelCase ID assets[camelizedId = camelize(id)] || // Pascal Case ID assets[camelizedId.charAt(0).toUpperCase() + camelizedId.slice(1)]; } /** * Assert asset exists */ function assertAsset(val, type, id) { if (!val) { 'development' !== 'production' && warn('Failed to resolve ' + type + ': ' + id); } } var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto) /** * Intercept mutating methods and emit events */ ;['push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse'].forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator() { // avoid leaking arguments: // http://jsperf.com/closure-with-arguments var i = arguments.length; var args = new Array(i); while (i--) { args[i] = arguments[i]; } var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': inserted = args; break; case 'unshift': inserted = args; break; case 'splice': inserted = args.slice(2); break; } if (inserted) ob.observeArray(inserted); // notify change ob.dep.notify(); return result; }); }); /** * Swap the element at the given index with a new value * and emits corresponding event. * * @param {Number} index * @param {*} val * @return {*} - replaced element */ def(arrayProto, '$set', function $set(index, val) { if (index >= this.length) { this.length = Number(index) + 1; } return this.splice(index, 1, val)[0]; }); /** * Convenience method to remove the element at given index. * * @param {Number} index * @param {*} val */ def(arrayProto, '$remove', function $remove(item) { /* istanbul ignore if */ if (!this.length) return; var index = indexOf(this, item); if (index > -1) { return this.splice(index, 1); } }); var uid$3 = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. * * @constructor */ function Dep() { this.id = uid$3++; this.subs = []; } // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null; /** * Add a directive subscriber. * * @param {Directive} sub */ Dep.prototype.addSub = function (sub) { this.subs.push(sub); }; /** * Remove a directive subscriber. * * @param {Directive} sub */ Dep.prototype.removeSub = function (sub) { this.subs.$remove(sub); }; /** * Add self as a dependency to the target watcher. */ Dep.prototype.depend = function () { Dep.target.addDep(this); }; /** * Notify all subscribers of a new value. */ Dep.prototype.notify = function () { // stablize the subscriber list first var subs = toArray(this.subs); for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. * * @param {Array|Object} value * @constructor */ function Observer(value) { this.value = value; this.dep = new Dep(); def(value, '__ob__', this); if (isArray(value)) { var augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { this.walk(value); } } // Instance methods /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. * * @param {Object} obj */ Observer.prototype.walk = function (obj) { var keys = Object.keys(obj); for (var i = 0, l = keys.length; i < l; i++) { this.convert(keys[i], obj[keys[i]]); } }; /** * Observe a list of Array items. * * @param {Array} items */ Observer.prototype.observeArray = function (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; /** * Convert a property into getter/setter so we can emit * the events when the property is accessed/changed. * * @param {String} key * @param {*} val */ Observer.prototype.convert = function (key, val) { defineReactive(this.value, key, val); }; /** * Add an owner vm, so that when $set/$delete mutations * happen we can notify owner vms to proxy the keys and * digest the watchers. This is only called when the object * is observed as an instance's root $data. * * @param {Vue} vm */ Observer.prototype.addVm = function (vm) { (this.vms || (this.vms = [])).push(vm); }; /** * Remove an owner vm. This is called when the object is * swapped out as an instance's $data object. * * @param {Vue} vm */ Observer.prototype.removeVm = function (vm) { this.vms.$remove(vm); }; // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ * * @param {Object|Array} target * @param {Object} proto */ function protoAugment(target, src) { target.__proto__ = src; } /** * Augment an target Object or Array by defining * hidden properties. * * @param {Object|Array} target * @param {Object} proto */ function copyAugment(target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. * * @param {*} value * @param {Vue} [vm] * @return {Observer|undefined} * @static */ function observe(value, vm) { if (!value || typeof value !== 'object') { return; } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ((isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue) { ob = new Observer(value); } if (ob && vm) { ob.addVm(vm); } return ob; } /** * Define a reactive property on an Object. * * @param {Object} obj * @param {String} key * @param {*} val */ function defineReactive(obj, key, val) { var dep = new Dep(); // cater for pre-defined getter/setters var getter, setter; if (config.convertAllProperties) { var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return; } getter = property && property.get; setter = property && property.set; } var childOb = observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter() { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); } if (isArray(value)) { for (var e, i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); } } } return value; }, set: function reactiveSetter(newVal) { var value = getter ? getter.call(obj) : val; if (newVal === value) { return; } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = observe(newVal); dep.notify(); } }); } var util = Object.freeze({ defineReactive: defineReactive, set: set, del: del, hasOwn: hasOwn, isLiteral: isLiteral, isReserved: isReserved, _toString: _toString, toNumber: toNumber, toBoolean: toBoolean, stripQuotes: stripQuotes, camelize: camelize, hyphenate: hyphenate, classify: classify, bind: bind$1, toArray: toArray, extend: extend, isObject: isObject, isPlainObject: isPlainObject, def: def, debounce: _debounce, indexOf: indexOf, cancellable: cancellable, looseEqual: looseEqual, isArray: isArray, hasProto: hasProto, inBrowser: inBrowser, isIE9: isIE9, isAndroid: isAndroid, get transitionProp () { return transitionProp; }, get transitionEndEvent () { return transitionEndEvent; }, get animationProp () { return animationProp; }, get animationEndEvent () { return animationEndEvent; }, nextTick: nextTick, query: query, inDoc: inDoc, getAttr: getAttr, getBindAttr: getBindAttr, hasBindAttr: hasBindAttr, before: before, after: after, remove: remove, prepend: prepend, replace: replace, on: on$1, off: off, setClass: setClass, addClass: addClass, removeClass: removeClass, extractContent: extractContent, trimNode: trimNode, isTemplate: isTemplate, createAnchor: createAnchor, findRef: findRef, mapNodeRange: mapNodeRange, removeNodeRange: removeNodeRange, mergeOptions: mergeOptions, resolveAsset: resolveAsset, assertAsset: assertAsset, checkComponentAttr: checkComponentAttr, initProp: initProp, assertProp: assertProp, coerceProp: coerceProp, commonTagRE: commonTagRE, reservedTagRE: reservedTagRE, get warn () { return warn; } }); var uid = 0; function initMixin (Vue) { /** * The main init sequence. This is called for every * instance, including ones that are created from extended * constructors. * * @param {Object} options - this options object should be * the result of merging class * options and the options passed * in to the constructor. */ Vue.prototype._init = function (options) { options = options || {}; this.$el = null; this.$parent = options.parent; this.$root = this.$parent ? this.$parent.$root : this; this.$children = []; this.$refs = {}; // child vm references this.$els = {}; // element references this._watchers = []; // all watchers as an array this._directives = []; // all directives // a uid this._uid = uid++; // a flag to avoid this being observed this._isVue = true; // events bookkeeping this._events = {}; // registered callbacks this._eventsCount = {}; // for $broadcast optimization // fragment instance properties this._isFragment = false; this._fragment = // @type {DocumentFragment} this._fragmentStart = // @type {Text|Comment} this._fragmentEnd = null; // @type {Text|Comment} // lifecycle state this._isCompiled = this._isDestroyed = this._isReady = this._isAttached = this._isBeingDestroyed = false; this._unlinkFn = null; // context: // if this is a transcluded component, context // will be the common parent vm of this instance // and its host. this._context = options._context || this.$parent; // scope: // if this is inside an inline v-for, the scope // will be the intermediate scope created for this // repeat fragment. this is used for linking props // and container directives. this._scope = options._scope; // fragment: // if this instance is compiled inside a Fragment, it // needs to reigster itself as a child of that fragment // for attach/detach to work properly. this._frag = options._frag; if (this._frag) { this._frag.children.push(this); } // push self into parent / transclusion host if (this.$parent) { this.$parent.$children.push(this); } // merge options. options = this.$options = mergeOptions(this.constructor.options, options, this); // set ref this._updateRef(); // initialize data as empty object. // it will be filled up in _initScope(). this._data = {}; // call init hook this._callHook('init'); // initialize data observation and scope inheritance. this._initState(); // setup event system and option events. this._initEvents(); // call created hook this._callHook('created'); // if `el` option is passed, start compilation. if (options.el) { this.$mount(options.el); } }; } var notevil = (function (module, global) { var exports = module.exports; 'use strict'; var __commonjs_global = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this; var primitives = (function (module, global) { var exports = module.exports; var names = ['Object', 'String', 'Boolean', 'Number', 'RegExp', 'Date', 'Array'] var immutable = {string: 'String', boolean: 'Boolean', number: 'Number' } var primitives = names.map(getGlobal) var protos = primitives.map(getProto) var protoReplacements = {} module.exports = Primitives function Primitives(context){ if (this instanceof Primitives){ this.context = context for (var i=0;i<names.length;i++){ if (!this.context[names[i]]){ this.context[names[i]] = wrap(primitives[i]) } } } else { return new Primitives(context) } } Primitives.prototype.replace = function(value){ var primIndex = primitives.indexOf(value) var protoIndex = protos.indexOf(value) if (~primIndex){ var name = names[primIndex] return this.context[name] } else if (~protoIndex) { var name = names[protoIndex] return this.context[name].prototype } else { return value } } Primitives.prototype.getPropertyObject = function(object, property){ if (immutable[typeof object]){ return this.getPrototypeOf(object) } return object } Primitives.prototype.isPrimitive = function(value){ return !!~primitives.indexOf(value) || !!~protos.indexOf(value) } Primitives.prototype.getPrototypeOf = function(value){ if (value == null){ // handle null and undefined return value } var immutableType = immutable[typeof value] if (immutableType){ var proto = this.context[immutableType].prototype } else { var proto = Object.getPrototypeOf(value) } if (!proto || proto === Object.prototype){ return null } else { var replacement = this.replace(proto) if (replacement === value){ replacement = this.replace(Object.prototype) } return replacement } } Primitives.prototype.applyNew = function(func, args){ if (func.wrapped){ var prim = Object.getPrototypeOf(func) var instance = new (Function.prototype.bind.apply(prim, arguments)) setProto(instance, func.prototype) return instance } else { return new (Function.prototype.bind.apply(func, arguments)) } } function getProto(func){ return func.prototype } function getGlobal(str){ return global[str] } function setProto(obj, proto){ obj.__proto__ = proto } function wrap(prim){ var proto = Object.create(prim.prototype) var result = function() { if (this instanceof result){ prim.apply(this, arguments) } else { var instance = prim.apply(null, arguments) setProto(instance, proto) return instance } } setProto(result, prim) result.prototype = proto result.wrapped = true return result } return module.exports; })({exports:{}}, __commonjs_global); var infiniteChecker = (function (module) { var exports = module.exports; module.exports = InfiniteChecker function InfiniteChecker(maxIterations){ if (this instanceof InfiniteChecker){ this.maxIterations = maxIterations this.count = 0 } else { return new InfiniteChecker(maxIterations) } } InfiniteChecker.prototype.check = function(){ this.count += 1 if (this.count > this.maxIterations){ throw new Error('Infinite loop detected - reached max iterations') } } return module.exports; })({exports:{}}); var index$1 = (function (module) { var exports = module.exports; module.exports = hoist function hoist(ast){ var parentStack = [] var variables = [] var functions = [] if (Array.isArray(ast)){ walkAll(ast) prependScope(ast, variables, functions) } else { walk(ast) } return ast // walk through each node of a program of block statement function walkAll(nodes){ var result = null for (var i=0;i<nodes.length;i++){ var childNode = nodes[i] if (childNode.type === 'EmptyStatement') continue var result = walk(childNode) if (result === 'remove'){ nodes.splice(i--, 1) } } } function walk(node){ var parent = parentStack[parentStack.length-1] var remove = false parentStack.push(node) var excludeBody = false if (shouldScope(node, parent)){ hoist(node.body) excludeBody = true } if (node.type === 'VariableDeclarator'){ variables.push(node) } if (node.type === 'FunctionDeclaration'){ functions.push(node) remove = true } for (var key in node){ if (key === 'type' || (excludeBody && key === 'body')) continue if (key in node && node[key] && typeof node[key] == 'object'){ if (node[key].type){ walk(node[key]) } else if (Array.isArray(node[key])){ walkAll(node[key]) } } } parentStack.pop() if (remove){ return 'remove' } } } function shouldScope(node, parent){ if (node.type === 'Program'){ return true } else if (node.type === 'BlockStatement'){ if (parent && (parent.type === 'FunctionExpression' || parent.type === 'FunctionDeclaration')){ return true } } } function prependScope(nodes, variables, functions){ if (variables && variables.length){ var declarations = [] for (var i=0;i<variables.length;i++){ declarations.push({ type: 'VariableDeclarator', id: variables[i].id, init: null }) } nodes.unshift({ type: 'VariableDeclaration', kind: 'var', declarations: declarations }) } if (functions && functions.length){ for (var i=0;i<functions.length;i++){ nodes.unshift(functions[i]) } } } return module.exports; })({exports:{}}); var esprima = (function (module) { var exports = module.exports; /* Copyright (C) 2012 Ariya Hidayat <[email protected]> Copyright (C) 2012 Mathias Bynens <[email protected]> Copyright (C) 2012 Joost-Wim Boekesteijn <[email protected]> Copyright (C) 2012 Kris Kowal <[email protected]> Copyright (C) 2012 Yusuke Suzuki <[email protected]> Copyright (C) 2012 Arpad Borsos <[email protected]> Copyright (C) 2011 Ariya Hidayat <[email protected]> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /*jslint bitwise:true plusplus:true */ /*global esprima:true, define:true, exports:true, window: true, throwError: true, createLiteral: true, generateStatement: true, parseAssignmentExpression: true, parseBlock: true, parseExpression: true, parseFunctionDeclaration: true, parseFunctionExpression: true, parseFunctionSourceElements: true, parseVariableIdentifier: true, parseLeftHandSideExpression: true, parseStatement: true, parseSourceElement: true */ (function (root, factory) { 'use strict'; // Universal Module Definition (UMD) to support AMD, CommonJS/Node.js, // Rhino, and plain browser loading. if (typeof define === 'function' && define.amd) { define(['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.esprima = {})); } }(this, function (exports) { 'use strict'; var Token, TokenName, Syntax, PropertyKind, Messages, Regex, source, strict, index, lineNumber, lineStart, length, buffer, state, extra; Token = { BooleanLiteral: 1, EOF: 2, Identifier: 3, Keyword: 4, NullLiteral: 5, NumericLiteral: 6, Punctuator: 7, StringLiteral: 8 }; TokenName = {}; TokenName[Token.BooleanLiteral] = 'Boolean'; TokenName[Token.EOF] = '<end>'; TokenName[Token.Identifier] = 'Identifier'; TokenName[Token.Keyword] = 'Keyword'; TokenName[Token.NullLiteral] = 'Null'; TokenName[Token.NumericLiteral] = 'Numeric'; TokenName[Token.Punctuator] = 'Punctuator'; TokenName[Token.StringLiteral] = 'String'; Syntax = { AssignmentExpression: 'AssignmentExpression', ArrayExpression: 'ArrayExpression', BlockStatement: 'BlockStatement', BinaryExpression: 'BinaryExpression', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DoWhileStatement: 'DoWhileStatement', DebuggerStatement: 'DebuggerStatement', EmptyStatement: 'EmptyStatement', ExpressionStatement: 'ExpressionStatement', ForStatement: 'ForStatement', ForInStatement: 'ForInStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', Identifier: 'Identifier', IfStatement: 'IfStatement', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', Program: 'Program', Property: 'Property', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SwitchStatement: 'SwitchStatement', SwitchCase: 'SwitchCase', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', UnaryExpression: 'UnaryExpression', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement' }; PropertyKind = { Data: 1, Get: 2, Set: 4 }; // Error messages should be identical to V8. Messages = { UnexpectedToken: 'Unexpected token %0', UnexpectedNumber: 'Unexpected number', UnexpectedString: 'Unexpected string', UnexpectedIdentifier: 'Unexpected identifier', UnexpectedReserved: 'Unexpected reserved word', UnexpectedEOS: 'Unexpected end of input', NewlineAfterThrow: 'Illegal newline after throw', InvalidRegExp: 'Invalid regular expression', UnterminatedRegExp: 'Invalid regular expression: missing /', InvalidLHSInAssignment: 'Invalid left-hand side in assignment', InvalidLHSInForIn: 'Invalid left-hand side in for-in', MultipleDefaultsInSwitch: 'More than one default clause in switch statement', NoCatchOrFinally: 'Missing catch or finally after try', UnknownLabel: 'Undefined label \'%0\'', Redeclaration: '%0 \'%1\' has already been declared', IllegalContinue: 'Illegal continue statement', IllegalBreak: 'Illegal break statement', IllegalReturn: 'Illegal return statement', StrictModeWith: 'Strict mode code may not include a with statement', StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', StrictVarName: 'Variable name may not be eval or arguments in strict mode', StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', StrictParamDupe: 'Strict mode function may not have duplicate parameter names', StrictFunctionName: 'Function name may not be eval or arguments in strict mode', StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', StrictDelete: 'Delete of an unqualified identifier in strict mode.', StrictDuplicateProperty: 'Duplicate data property in object literal not allowed in strict mode', AccessorDataProperty: 'Object literal may not have data and accessor property with the same name', AccessorGetSet: 'Object literal may not have multiple get/set accessors with the same name', StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', StrictReservedWord: 'Use of future reserved word in strict mode' }; // See also tools/generate-unicode-regex.py. Regex = { NonAsciiIdentifierStart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u05d0-\u05ea\u05f0-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u08a0\u08a2-\u08ac\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0977\u0979-\u097f\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d\u0c58\u0c59\u0c60\u0c61\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d60\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1877\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191c\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19c1-\u19c7\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1ce9-\u1cec\u1cee-\u1cf1\u1cf5\u1cf6\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2e2f\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua697\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa80-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]'), NonAsciiIdentifierPart: new RegExp('[\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0300-\u0374\u0376\u0377\u037a-\u037d\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u0483-\u0487\u048a-\u0527\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u05d0-\u05ea\u05f0-\u05f2\u0610-\u061a\u0620-\u0669\u066e-\u06d3\u06d5-\u06dc\u06df-\u06e8\u06ea-\u06fc\u06ff\u0710-\u074a\u074d-\u07b1\u07c0-\u07f5\u07fa\u0800-\u082d\u0840-\u085b\u08a0\u08a2-\u08ac\u08e4-\u08fe\u0900-\u0963\u0966-\u096f\u0971-\u0977\u0979-\u097f\u0981-\u0983\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bc-\u09c4\u09c7\u09c8\u09cb-\u09ce\u09d7\u09dc\u09dd\u09df-\u09e3\u09e6-\u09f1\u0a01-\u0a03\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a59-\u0a5c\u0a5e\u0a66-\u0a75\u0a81-\u0a83\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abc-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ad0\u0ae0-\u0ae3\u0ae6-\u0aef\u0b01-\u0b03\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3c-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b56\u0b57\u0b5c\u0b5d\u0b5f-\u0b63\u0b66-\u0b6f\u0b71\u0b82\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd0\u0bd7\u0be6-\u0bef\u0c01-\u0c03\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c33\u0c35-\u0c39\u0c3d-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c58\u0c59\u0c60-\u0c63\u0c66-\u0c6f\u0c82\u0c83\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbc-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0cde\u0ce0-\u0ce3\u0ce6-\u0cef\u0cf1\u0cf2\u0d02\u0d03\u0d05-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d-\u0d44\u0d46-\u0d48\u0d4a-\u0d4e\u0d57\u0d60-\u0d63\u0d66-\u0d6f\u0d7a-\u0d7f\u0d82\u0d83\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0df2\u0df3\u0e01-\u0e3a\u0e40-\u0e4e\u0e50-\u0e59\u0e81\u0e82\u0e84\u0e87\u0e88\u0e8a\u0e8d\u0e94-\u0e97\u0e99-\u0e9f\u0ea1-\u0ea3\u0ea5\u0ea7\u0eaa\u0eab\u0ead-\u0eb9\u0ebb-\u0ebd\u0ec0-\u0ec4\u0ec6\u0ec8-\u0ecd\u0ed0-\u0ed9\u0edc-\u0edf\u0f00\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e-\u0f47\u0f49-\u0f6c\u0f71-\u0f84\u0f86-\u0f97\u0f99-\u0fbc\u0fc6\u1000-\u1049\u1050-\u109d\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u135d-\u135f\u1380-\u138f\u13a0-\u13f4\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f0\u1700-\u170c\u170e-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176c\u176e-\u1770\u1772\u1773\u1780-\u17d3\u17d7\u17dc\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u1820-\u1877\u1880-\u18aa\u18b0-\u18f5\u1900-\u191c\u1920-\u192b\u1930-\u193b\u1946-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u19d0-\u19d9\u1a00-\u1a1b\u1a20-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1aa7\u1b00-\u1b4b\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1bf3\u1c00-\u1c37\u1c40-\u1c49\u1c4d-\u1c7d\u1cd0-\u1cd2\u1cd4-\u1cf6\u1d00-\u1de6\u1dfc-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u200c\u200d\u203f\u2040\u2054\u2071\u207f\u2090-\u209c\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2102\u2107\u210a-\u2113\u2115\u2119-\u211d\u2124\u2126\u2128\u212a-\u212d\u212f-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d7f-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u2de0-\u2dff\u2e2f\u3005-\u3007\u3021-\u302f\u3031-\u3035\u3038-\u303c\u3041-\u3096\u3099\u309a\u309d-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312d\u3131-\u318e\u31a0-\u31ba\u31f0-\u31ff\u3400-\u4db5\u4e00-\u9fcc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua62b\ua640-\ua66f\ua674-\ua67d\ua67f-\ua697\ua69f-\ua6f1\ua717-\ua71f\ua722-\ua788\ua78b-\ua78e\ua790-\ua793\ua7a0-\ua7aa\ua7f8-\ua827\ua840-\ua873\ua880-\ua8c4\ua8d0-\ua8d9\ua8e0-\ua8f7\ua8fb\ua900-\ua92d\ua930-\ua953\ua960-\ua97c\ua980-\ua9c0\ua9cf-\ua9d9\uaa00-\uaa36\uaa40-\uaa4d\uaa50-\uaa59\uaa60-\uaa76\uaa7a\uaa7b\uaa80-\uaac2\uaadb-\uaadd\uaae0-\uaaef\uaaf2-\uaaf6\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uabc0-\uabea\uabec\uabed\uabf0-\uabf9\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe00-\ufe0f\ufe20-\ufe26\ufe33\ufe34\ufe4d-\ufe4f\ufe70-\ufe74\ufe76-\ufefc\uff10-\uff19\uff21-\uff3a\uff3f\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc]') }; // Ensure the condition is true, otherwise throw an error. // This is only to have a better contract semantic, i.e. another safety net // to catch a logic error. The condition shall be fulfilled in normal case. // Do NOT use this to enforce a certain condition on any user input. function assert(condition, message) { if (!condition) { throw new Error('ASSERT: ' + message); } } function sliceSource(from, to) { return source.slice(from, to); } if (typeof 'esprima'[0] === 'undefined') { sliceSource = function sliceArraySource(from, to) { return source.slice(from, to).join(''); }; } function isDecimalDigit(ch) { return '0123456789'.indexOf(ch) >= 0; } function isHexDigit(ch) { return '0123456789abcdefABCDEF'.indexOf(ch) >= 0; } function isOctalDigit(ch) { return '01234567'.indexOf(ch) >= 0; } // 7.2 White Space function isWhiteSpace(ch) { return (ch === ' ') || (ch === '\u0009') || (ch === '\u000B') || (ch === '\u000C') || (ch === '\u00A0') || (ch.charCodeAt(0) >= 0x1680 && '\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\uFEFF'.indexOf(ch) >= 0); } // 7.3 Line Terminators function isLineTerminator(ch) { return (ch === '\n' || ch === '\r' || ch === '\u2028' || ch === '\u2029'); } // 7.6 Identifier Names and Identifiers function isIdentifierStart(ch) { return (ch === '$') || (ch === '_') || (ch === '\\') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierStart.test(ch)); } function isIdentifierPart(ch) { return (ch === '$') || (ch === '_') || (ch === '\\') || (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') || ((ch >= '0') && (ch <= '9')) || ((ch.charCodeAt(0) >= 0x80) && Regex.NonAsciiIdentifierPart.test(ch)); } // 7.6.1.2 Future Reserved Words function isFutureReservedWord(id) { switch (id) { // Future reserved words. case 'class': case 'enum': case 'export': case 'extends': case 'import': case 'super': return true; } return false; } function isStrictModeReservedWord(id) { switch (id) { // Strict Mode reserved words. case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'yield': case 'let': return true; } return false; } function isRestrictedWord(id) { return id === 'eval' || id === 'arguments'; } // 7.6.1.1 Keywords function isKeyword(id) { var keyword = false; switch (id.length) { case 2: keyword = (id === 'if') || (id === 'in') || (id === 'do'); break; case 3: keyword = (id === 'var') || (id === 'for') || (id === 'new') || (id === 'try'); break; case 4: keyword = (id === 'this') || (id === 'else') || (id === 'case') || (id === 'void') || (id === 'with'); break; case 5: keyword = (id === 'while') || (id === 'break') || (id === 'catch') || (id === 'throw'); break; case 6: keyword = (id === 'return') || (id === 'typeof') || (id === 'delete') || (id === 'switch'); break; case 7: keyword = (id === 'default') || (id === 'finally'); break; case 8: keyword = (id === 'function') || (id === 'continue') || (id === 'debugger'); break; case 10: keyword = (id === 'instanceof'); break; } if (keyword) { return true; } switch (id) { // Future reserved words. // 'const' is specialized as Keyword in V8. case 'const': return true; // For compatiblity to SpiderMonkey and ES.next case 'yield': case 'let': return true; } if (strict && isStrictModeReservedWord(id)) { return true; } return isFutureReservedWord(id); } // 7.4 Comments function skipComment() { var ch, blockComment, lineComment; blockComment = false; lineComment = false; while (index < length) { ch = source[index]; if (lineComment) { ch = source[index++]; if (isLineTerminator(ch)) { lineComment = false; if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; } } else if (blockComment) { if (isLineTerminator(ch)) { if (ch === '\r' && source[index + 1] === '\n') { ++index; } ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { ch = source[index++]; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (ch === '*') { ch = source[index]; if (ch === '/') { ++index; blockComment = false; } } } } else if (ch === '/') { ch = source[index + 1]; if (ch === '/') { index += 2; lineComment = true; } else if (ch === '*') { index += 2; blockComment = true; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { break; } } else if (isWhiteSpace(ch)) { ++index; } else if (isLineTerminator(ch)) { ++index; if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; } else { break; } } } function scanHexEscape(prefix) { var i, len, ch, code = 0; len = (prefix === 'u') ? 4 : 2; for (i = 0; i < len; ++i) { if (index < length && isHexDigit(source[index])) { ch = source[index++]; code = code * 16 + '0123456789abcdef'.indexOf(ch.toLowerCase()); } else { return ''; } } return String.fromCharCode(code); } function scanIdentifier() { var ch, start, id, restore; ch = source[index]; if (!isIdentifierStart(ch)) { return; } start = index; if (ch === '\\') { ++index; if (source[index] !== 'u') { return; } ++index; restore = index; ch = scanHexEscape('u'); if (ch) { if (ch === '\\' || !isIdentifierStart(ch)) { return; } id = ch; } else { index = restore; id = 'u'; } } else { id = source[index++]; } while (index < length) { ch = source[index]; if (!isIdentifierPart(ch)) { break; } if (ch === '\\') { ++index; if (source[index] !== 'u') { return; } ++index; restore = index; ch = scanHexEscape('u'); if (ch) { if (ch === '\\' || !isIdentifierPart(ch)) { return; } id += ch; } else { index = restore; id += 'u'; } } else { id += source[index++]; } } // There is no keyword or literal with only one character. // Thus, it must be an identifier. if (id.length === 1) { return { type: Token.Identifier, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (isKeyword(id)) { return { type: Token.Keyword, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.8.1 Null Literals if (id === 'null') { return { type: Token.NullLiteral, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.8.2 Boolean Literals if (id === 'true' || id === 'false') { return { type: Token.BooleanLiteral, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } return { type: Token.Identifier, value: id, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.7 Punctuators function scanPunctuator() { var start = index, ch1 = source[index], ch2, ch3, ch4; // Check for most common single-character punctuators. if (ch1 === ';' || ch1 === '{' || ch1 === '}') { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === ',' || ch1 === '(' || ch1 === ')') { ++index; return { type: Token.Punctuator, value: ch1, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // Dot (.) can also start a floating-point number, hence the need // to check the next character. ch2 = source[index + 1]; if (ch1 === '.' && !isDecimalDigit(ch2)) { return { type: Token.Punctuator, value: source[index++], lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // Peek more characters. ch3 = source[index + 2]; ch4 = source[index + 3]; // 4-character punctuator: >>>= if (ch1 === '>' && ch2 === '>' && ch3 === '>') { if (ch4 === '=') { index += 4; return { type: Token.Punctuator, value: '>>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } // 3-character punctuators: === !== >>> <<= >>= if (ch1 === '=' && ch2 === '=' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '===', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '!' && ch2 === '=' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '!==', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '>' && ch2 === '>' && ch3 === '>') { index += 3; return { type: Token.Punctuator, value: '>>>', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '<' && ch2 === '<' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '<<=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } if (ch1 === '>' && ch2 === '>' && ch3 === '=') { index += 3; return { type: Token.Punctuator, value: '>>=', lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 2-character punctuators: <= >= == != ++ -- << >> && || // += -= *= %= &= |= ^= /= if (ch2 === '=') { if ('<>=!+-*%&|^/'.indexOf(ch1) >= 0) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } if (ch1 === ch2 && ('+-<>&|'.indexOf(ch1) >= 0)) { if ('+-<>&|'.indexOf(ch2) >= 0) { index += 2; return { type: Token.Punctuator, value: ch1 + ch2, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } // The remaining 1-character punctuators. if ('[]<>+-*%&|^!~?:=/'.indexOf(ch1) >= 0) { return { type: Token.Punctuator, value: source[index++], lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } } // 7.8.3 Numeric Literals function scanNumericLiteral() { var number, start, ch; ch = source[index]; assert(isDecimalDigit(ch) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); start = index; number = ''; if (ch !== '.') { number = source[index++]; ch = source[index]; // Hex number starts with '0x'. // Octal number starts with '0'. if (number === '0') { if (ch === 'x' || ch === 'X') { number += source[index++]; while (index < length) { ch = source[index]; if (!isHexDigit(ch)) { break; } number += source[index++]; } if (number.length <= 2) { // only 0x throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } if (index < length) { ch = source[index]; if (isIdentifierStart(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } return { type: Token.NumericLiteral, value: parseInt(number, 16), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } else if (isOctalDigit(ch)) { number += source[index++]; while (index < length) { ch = source[index]; if (!isOctalDigit(ch)) { break; } number += source[index++]; } if (index < length) { ch = source[index]; if (isIdentifierStart(ch) || isDecimalDigit(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } return { type: Token.NumericLiteral, value: parseInt(number, 8), octal: true, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // decimal number starts with '0' such as '09' is illegal. if (isDecimalDigit(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } while (index < length) { ch = source[index]; if (!isDecimalDigit(ch)) { break; } number += source[index++]; } } if (ch === '.') { number += source[index++]; while (index < length) { ch = source[index]; if (!isDecimalDigit(ch)) { break; } number += source[index++]; } } if (ch === 'e' || ch === 'E') { number += source[index++]; ch = source[index]; if (ch === '+' || ch === '-') { number += source[index++]; } ch = source[index]; if (isDecimalDigit(ch)) { number += source[index++]; while (index < length) { ch = source[index]; if (!isDecimalDigit(ch)) { break; } number += source[index++]; } } else { ch = 'character ' + ch; if (index >= length) { ch = '<end>'; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } if (index < length) { ch = source[index]; if (isIdentifierStart(ch)) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } return { type: Token.NumericLiteral, value: parseFloat(number), lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } // 7.8.4 String Literals function scanStringLiteral() { var str = '', quote, start, ch, code, unescaped, restore, octal = false; quote = source[index]; assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); start = index; ++index; while (index < length) { ch = source[index++]; if (ch === quote) { quote = ''; break; } else if (ch === '\\') { ch = source[index++]; if (!isLineTerminator(ch)) { switch (ch) { case 'n': str += '\n'; break; case 'r': str += '\r'; break; case 't': str += '\t'; break; case 'u': case 'x': restore = index; unescaped = scanHexEscape(ch); if (unescaped) { str += unescaped; } else { index = restore; str += ch; } break; case 'b': str += '\b'; break; case 'f': str += '\f'; break; case 'v': str += '\x0B'; break; default: if (isOctalDigit(ch)) { code = '01234567'.indexOf(ch); // \0 is not octal escape sequence if (code !== 0) { octal = true; } if (index < length && isOctalDigit(source[index])) { octal = true; code = code * 8 + '01234567'.indexOf(source[index++]); // 3 digits are only allowed when string starts // with 0, 1, 2, 3 if ('0123'.indexOf(ch) >= 0 && index < length && isOctalDigit(source[index])) { code = code * 8 + '01234567'.indexOf(source[index++]); } } str += String.fromCharCode(code); } else { str += ch; } break; } } else { ++lineNumber; if (ch === '\r' && source[index] === '\n') { ++index; } } } else if (isLineTerminator(ch)) { break; } else { str += ch; } } if (quote !== '') { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } return { type: Token.StringLiteral, value: str, octal: octal, lineNumber: lineNumber, lineStart: lineStart, range: [start, index] }; } function scanRegExp() { var str, ch, start, pattern, flags, value, classMarker = false, restore, terminated = false; buffer = null; skipComment(); start = index; ch = source[index]; assert(ch === '/', 'Regular expression literal must start with a slash'); str = source[index++]; while (index < length) { ch = source[index++]; str += ch; if (ch === '\\') { ch = source[index++]; // ECMA-262 7.8.5 if (isLineTerminator(ch)) { throwError({}, Messages.UnterminatedRegExp); } str += ch; } else if (classMarker) { if (ch === ']') { classMarker = false; } } else { if (ch === '/') { terminated = true; break; } else if (ch === '[') { classMarker = true; } else if (isLineTerminator(ch)) { throwError({}, Messages.UnterminatedRegExp); } } } if (!terminated) { throwError({}, Messages.UnterminatedRegExp); } // Exclude leading and trailing slash. pattern = str.substr(1, str.length - 2); flags = ''; while (index < length) { ch = source[index]; if (!isIdentifierPart(ch)) { break; } ++index; if (ch === '\\' && index < length) { ch = source[index]; if (ch === 'u') { ++index; restore = index; ch = scanHexEscape('u'); if (ch) { flags += ch; str += '\\u'; for (; restore < index; ++restore) { str += source[restore]; } } else { index = restore; flags += 'u'; str += '\\u'; } } else { str += '\\'; } } else { flags += ch; str += ch; } } try { value = new RegExp(pattern, flags); } catch (e) { throwError({}, Messages.InvalidRegExp); } return { literal: str, value: value, range: [start, index] }; } function isIdentifierName(token) { return token.type === Token.Identifier || token.type === Token.Keyword || token.type === Token.BooleanLiteral || token.type === Token.NullLiteral; } function advance() { var ch, token; skipComment(); if (index >= length) { return { type: Token.EOF, lineNumber: lineNumber, lineStart: lineStart, range: [index, index] }; } token = scanPunctuator(); if (typeof token !== 'undefined') { return token; } ch = source[index]; if (ch === '\'' || ch === '"') { return scanStringLiteral(); } if (ch === '.' || isDecimalDigit(ch)) { return scanNumericLiteral(); } token = scanIdentifier(); if (typeof token !== 'undefined') { return token; } throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } function lex() { var token; if (buffer) { index = buffer.range[1]; lineNumber = buffer.lineNumber; lineStart = buffer.lineStart; token = buffer; buffer = null; return token; } buffer = null; return advance(); } function lookahead() { var pos, line, start; if (buffer !== null) { return buffer; } pos = index; line = lineNumber; start = lineStart; buffer = advance(); index = pos; lineNumber = line; lineStart = start; return buffer; } // Return true if there is a line terminator before the next token. function peekLineTerminator() { var pos, line, start, found; pos = index; line = lineNumber; start = lineStart; skipComment(); found = lineNumber !== line; index = pos; lineNumber = line; lineStart = start; return found; } // Throw an exception function throwError(token, messageFormat) { var error, args = Array.prototype.slice.call(arguments, 2), msg = messageFormat.replace( /%(\d)/g, function (whole, index) { return args[index] || ''; } ); if (typeof token.lineNumber === 'number') { error = new Error('Line ' + token.lineNumber + ': ' + msg); error.index = token.range[0]; error.lineNumber = token.lineNumber; error.column = token.range[0] - lineStart + 1; } else { error = new Error('Line ' + lineNumber + ': ' + msg); error.index = index; error.lineNumber = lineNumber; error.column = index - lineStart + 1; } throw error; } function throwErrorTolerant() { try { throwError.apply(null, arguments); } catch (e) { if (extra.errors) { extra.errors.push(e); } else { throw e; } } } // Throw an exception because of the token. function throwUnexpected(token) { if (token.type === Token.EOF) { throwError(token, Messages.UnexpectedEOS); } if (token.type === Token.NumericLiteral) { throwError(token, Messages.UnexpectedNumber); } if (token.type === Token.StringLiteral) { throwError(token, Messages.UnexpectedString); } if (token.type === Token.Identifier) { throwError(token, Messages.UnexpectedIdentifier); } if (token.type === Token.Keyword) { if (isFutureReservedWord(token.value)) { throwError(token, Messages.UnexpectedReserved); } else if (strict && isStrictModeReservedWord(token.value)) { throwErrorTolerant(token, Messages.StrictReservedWord); return; } throwError(token, Messages.UnexpectedToken, token.value); } // BooleanLiteral, NullLiteral, or Punctuator. throwError(token, Messages.UnexpectedToken, token.value); } // Expect the next token to match the specified punctuator. // If not, an exception will be thrown. function expect(value) { var token = lex(); if (token.type !== Token.Punctuator || token.value !== value) { throwUnexpected(token); } } // Expect the next token to match the specified keyword. // If not, an exception will be thrown. function expectKeyword(keyword) { var token = lex(); if (token.type !== Token.Keyword || token.value !== keyword) { throwUnexpected(token); } } // Return true if the next token matches the specified punctuator. function match(value) { var token = lookahead(); return token.type === Token.Punctuator && token.value === value; } // Return true if the next token matches the specified keyword function matchKeyword(keyword) { var token = lookahead(); return token.type === Token.Keyword && token.value === keyword; } // Return true if the next token is an assignment operator function matchAssign() { var token = lookahead(), op = token.value; if (token.type !== Token.Punctuator) { return false; } return op === '=' || op === '*=' || op === '/=' || op === '%=' || op === '+=' || op === '-=' || op === '<<=' || op === '>>=' || op === '>>>=' || op === '&=' || op === '^=' || op === '|='; } function consumeSemicolon() { var token, line; // Catch the very common case first. if (source[index] === ';') { lex(); return; } line = lineNumber; skipComment(); if (lineNumber !== line) { return; } if (match(';')) { lex(); return; } token = lookahead(); if (token.type !== Token.EOF && !match('}')) { throwUnexpected(token); } } // Return true if provided expression is LeftHandSideExpression function isLeftHandSide(expr) { return expr.type === Syntax.Identifier || expr.type === Syntax.MemberExpression; } // 11.1.4 Array Initialiser function parseArrayInitialiser() { var elements = []; expect('['); while (!match(']')) { if (match(',')) { lex(); elements.push(null); } else { elements.push(parseAssignmentExpression()); if (!match(']')) { expect(','); } } } expect(']'); return { type: Syntax.ArrayExpression, elements: elements }; } // 11.1.5 Object Initialiser function parsePropertyFunction(param, first) { var previousStrict, body; previousStrict = strict; body = parseFunctionSourceElements(); if (first && strict && isRestrictedWord(param[0].name)) { throwErrorTolerant(first, Messages.StrictParamName); } strict = previousStrict; return { type: Syntax.FunctionExpression, id: null, params: param, defaults: [], body: body, rest: null, generator: false, expression: false }; } function parseObjectPropertyKey() { var token = lex(); // Note: This function is called only from parseObjectProperty(), where // EOF and Punctuator tokens are already filtered out. if (token.type === Token.StringLiteral || token.type === Token.NumericLiteral) { if (strict && token.octal) { throwErrorTolerant(token, Messages.StrictOctalLiteral); } return createLiteral(token); } return { type: Syntax.Identifier, name: token.value }; } function parseObjectProperty() { var token, key, id, param; token = lookahead(); if (token.type === Token.Identifier) { id = parseObjectPropertyKey(); // Property Assignment: Getter and Setter. if (token.value === 'get' && !match(':')) { key = parseObjectPropertyKey(); expect('('); expect(')'); return { type: Syntax.Property, key: key, value: parsePropertyFunction([]), kind: 'get' }; } else if (token.value === 'set' && !match(':')) { key = parseObjectPropertyKey(); expect('('); token = lookahead(); if (token.type !== Token.Identifier) { expect(')'); throwErrorTolerant(token, Messages.UnexpectedToken, token.value); return { type: Syntax.Property, key: key, value: parsePropertyFunction([]), kind: 'set' }; } else { param = [ parseVariableIdentifier() ]; expect(')'); return { type: Syntax.Property, key: key, value: parsePropertyFunction(param, token), kind: 'set' }; } } else { expect(':'); return { type: Syntax.Property, key: id, value: parseAssignmentExpression(), kind: 'init' }; } } else if (token.type === Token.EOF || token.type === Token.Punctuator) { throwUnexpected(token); } else { key = parseObjectPropertyKey(); expect(':'); return { type: Syntax.Property, key: key, value: parseAssignmentExpression(), kind: 'init' }; } } function parseObjectInitialiser() { var properties = [], property, name, kind, map = {}, toString = String; expect('{'); while (!match('}')) { property = parseObjectProperty(); if (property.key.type === Syntax.Identifier) { name = property.key.name; } else { name = toString(property.key.value); } kind = (property.kind === 'init') ? PropertyKind.Data : (property.kind === 'get') ? PropertyKind.Get : PropertyKind.Set; if (Object.prototype.hasOwnProperty.call(map, name)) { if (map[name] === PropertyKind.Data) { if (strict && kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.StrictDuplicateProperty); } else if (kind !== PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } } else { if (kind === PropertyKind.Data) { throwErrorTolerant({}, Messages.AccessorDataProperty); } else if (map[name] & kind) { throwErrorTolerant({}, Messages.AccessorGetSet); } } map[name] |= kind; } else { map[name] = kind; } properties.push(property); if (!match('}')) { expect(','); } } expect('}'); return { type: Syntax.ObjectExpression, properties: properties }; } // 11.1.6 The Grouping Operator function parseGroupExpression() { var expr; expect('('); expr = parseExpression(); expect(')'); return expr; } // 11.1 Primary Expressions function parsePrimaryExpression() { var token = lookahead(), type = token.type; if (type === Token.Identifier) { return { type: Syntax.Identifier, name: lex().value }; } if (type === Token.StringLiteral || type === Token.NumericLiteral) { if (strict && token.octal) { throwErrorTolerant(token, Messages.StrictOctalLiteral); } return createLiteral(lex()); } if (type === Token.Keyword) { if (matchKeyword('this')) { lex(); return { type: Syntax.ThisExpression }; } if (matchKeyword('function')) { return parseFunctionExpression(); } } if (type === Token.BooleanLiteral) { lex(); token.value = (token.value === 'true'); return createLiteral(token); } if (type === Token.NullLiteral) { lex(); token.value = null; return createLiteral(token); } if (match('[')) { return parseArrayInitialiser(); } if (match('{')) { return parseObjectInitialiser(); } if (match('(')) { return parseGroupExpression(); } if (match('/') || match('/=')) { return createLiteral(scanRegExp()); } return throwUnexpected(lex()); } // 11.2 Left-Hand-Side Expressions function parseArguments() { var args = []; expect('('); if (!match(')')) { while (index < length) { args.push(parseAssignmentExpression()); if (match(')')) { break; } expect(','); } } expect(')'); return args; } function parseNonComputedProperty() { var token = lex(); if (!isIdentifierName(token)) { throwUnexpected(token); } return { type: Syntax.Identifier, name: token.value }; } function parseNonComputedMember() { expect('.'); return parseNonComputedProperty(); } function parseComputedMember() { var expr; expect('['); expr = parseExpression(); expect(']'); return expr; } function parseNewExpression() { var expr; expectKeyword('new'); expr = { type: Syntax.NewExpression, callee: parseLeftHandSideExpression(), 'arguments': [] }; if (match('(')) { expr['arguments'] = parseArguments(); } return expr; } function parseLeftHandSideExpressionAllowCall() { var expr; expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || match('(')) { if (match('(')) { expr = { type: Syntax.CallExpression, callee: expr, 'arguments': parseArguments() }; } else if (match('[')) { expr = { type: Syntax.MemberExpression, computed: true, object: expr, property: parseComputedMember() }; } else { expr = { type: Syntax.MemberExpression, computed: false, object: expr, property: parseNonComputedMember() }; } } return expr; } function parseLeftHandSideExpression() { var expr; expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[')) { if (match('[')) { expr = { type: Syntax.MemberExpression, computed: true, object: expr, property: parseComputedMember() }; } else { expr = { type: Syntax.MemberExpression, computed: false, object: expr, property: parseNonComputedMember() }; } } return expr; } // 11.3 Postfix Expressions function parsePostfixExpression() { var expr = parseLeftHandSideExpressionAllowCall(), token; token = lookahead(); if (token.type !== Token.Punctuator) { return expr; } if ((match('++') || match('--')) && !peekLineTerminator()) { // 11.3.1, 11.3.2 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPostfix); } if (!isLeftHandSide(expr)) { throwErrorTolerant({}, Messages.InvalidLHSInAssignment); } expr = { type: Syntax.UpdateExpression, operator: lex().value, argument: expr, prefix: false }; } return expr; } // 11.4 Unary Operators function parseUnaryExpression() { var token, expr; token = lookahead(); if (token.type !== Token.Punctuator && token.type !== Token.Keyword) { return parsePostfixExpression(); } if (match('++') || match('--')) { token = lex(); expr = parseUnaryExpression(); // 11.4.4, 11.4.5 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant({}, Messages.StrictLHSPrefix); } if (!isLeftHandSide(expr)) { throwErrorTolerant({}, Messages.InvalidLHSInAssignment); } expr = { type: Syntax.UpdateExpression, operator: token.value, argument: expr, prefix: true }; return expr; } if (match('+') || match('-') || match('~') || match('!')) { expr = { type: Syntax.UnaryExpression, operator: lex().value, argument: parseUnaryExpression(), prefix: true }; return expr; } if (matchKeyword('delete') || matchKeyword('void') || matchKeyword('typeof')) { expr = { type: Syntax.UnaryExpression, operator: lex().value, argument: parseUnaryExpression(), prefix: true }; if (strict && expr.operator === 'delete' && expr.argument.type === Syntax.Identifier) { throwErrorTolerant({}, Messages.StrictDelete); } return expr; } return parsePostfixExpression(); } // 11.5 Multiplicative Operators function parseMultiplicativeExpression() { var expr = parseUnaryExpression(); while (match('*') || match('/') || match('%')) { expr = { type: Syntax.BinaryExpression, operator: lex().value, left: expr, right: parseUnaryExpression() }; } return expr; } // 11.6 Additive Operators function parseAdditiveExpression() { var expr = parseMultiplicativeExpression(); while (match('+') || match('-')) { expr = { type: Syntax.BinaryExpression, operator: lex().value, left: expr, right: parseMultiplicativeExpression() }; } return expr; } // 11.7 Bitwise Shift Operators function parseShiftExpression() { var expr = parseAdditiveExpression(); while (match('<<') || match('>>') || match('>>>')) { expr = { type: Syntax.BinaryExpression, operator: lex().value, left: expr, right: parseAdditiveExpression() }; } return expr; } // 11.8 Relational Operators function parseRelationalExpression() { var expr, previousAllowIn; previousAllowIn = state.allowIn; state.allowIn = true; expr = parseShiftExpression(); while (match('<') || match('>') || match('<=') || match('>=') || (previousAllowIn && matchKeyword('in')) || matchKeyword('instanceof')) { expr = { type: Syntax.BinaryExpression, operator: lex().value, left: expr, right: parseShiftExpression() }; } state.allowIn = previousAllowIn; return expr; } // 11.9 Equality Operators function parseEqualityExpression() { var expr = parseRelationalExpression(); while (match('==') || match('!=') || match('===') || match('!==')) { expr = { type: Syntax.BinaryExpression, operator: lex().value, left: expr, right: parseRelationalExpression() }; } return expr; } // 11.10 Binary Bitwise Operators function parseBitwiseANDExpression() { var expr = parseEqualityExpression(); while (match('&')) { lex(); expr = { type: Syntax.BinaryExpression, operator: '&', left: expr, right: parseEqualityExpression() }; } return expr; } function parseBitwiseXORExpression() { var expr = parseBitwiseANDExpression(); while (match('^')) { lex(); expr = { type: Syntax.BinaryExpression, operator: '^', left: expr, right: parseBitwiseANDExpression() }; } return expr; } function parseBitwiseORExpression() { var expr = parseBitwiseXORExpression(); while (match('|')) { lex(); expr = { type: Syntax.BinaryExpression, operator: '|', left: expr, right: parseBitwiseXORExpression() }; } return expr; } // 11.11 Binary Logical Operators function parseLogicalANDExpression() { var expr = parseBitwiseORExpression(); while (match('&&')) { lex(); expr = { type: Syntax.LogicalExpression, operator: '&&', left: expr, right: parseBitwiseORExpression() }; } return expr; } function parseLogicalORExpression() { var expr = parseLogicalANDExpression(); while (match('||')) { lex(); expr = { type: Syntax.LogicalExpression, operator: '||', left: expr, right: parseLogicalANDExpression() }; } return expr; } // 11.12 Conditional Operator function parseConditionalExpression() { var expr, previousAllowIn, consequent; expr = parseLogicalORExpression(); if (match('?')) { lex(); previousAllowIn = state.allowIn; state.allowIn = true; consequent = parseAssignmentExpression(); state.allowIn = previousAllowIn; expect(':'); expr = { type: Syntax.ConditionalExpression, test: expr, consequent: consequent, alternate: parseAssignmentExpression() }; } return expr; } // 11.13 Assignment Operators function parseAssignmentExpression() { var token, expr; token = lookahead(); expr = parseConditionalExpression(); if (matchAssign()) { // LeftHandSideExpression if (!isLeftHandSide(expr)) { throwErrorTolerant({}, Messages.InvalidLHSInAssignment); } // 11.13.1 if (strict && expr.type === Syntax.Identifier && isRestrictedWord(expr.name)) { throwErrorTolerant(token, Messages.StrictLHSAssignment); } expr = { type: Syntax.AssignmentExpression, operator: lex().value, left: expr, right: parseAssignmentExpression() }; } return expr; } // 11.14 Comma Operator function parseExpression() { var expr = parseAssignmentExpression(); if (match(',')) { expr = { type: Syntax.SequenceExpression, expressions: [ expr ] }; while (index < length) { if (!match(',')) { break; } lex(); expr.expressions.push(parseAssignmentExpression()); } } return expr; } // 12.1 Block function parseStatementList() { var list = [], statement; while (index < length) { if (match('}')) { break; } statement = parseSourceElement(); if (typeof statement === 'undefined') { break; } list.push(statement); } return list; } function parseBlock() { var block; expect('{'); block = parseStatementList(); expect('}'); return { type: Syntax.BlockStatement, body: block }; } // 12.2 Variable Statement function parseVariableIdentifier() { var token = lex(); if (token.type !== Token.Identifier) { throwUnexpected(token); } return { type: Syntax.Identifier, name: token.value }; } function parseVariableDeclaration(kind) { var id = parseVariableIdentifier(), init = null; // 12.2.1 if (strict && isRestrictedWord(id.name)) { throwErrorTolerant({}, Messages.StrictVarName); } if (kind === 'const') { expect('='); init = parseAssignmentExpression(); } else if (match('=')) { lex(); init = parseAssignmentExpression(); } return { type: Syntax.VariableDeclarator, id: id, init: init }; } function parseVariableDeclarationList(kind) { var list = []; do { list.push(parseVariableDeclaration(kind)); if (!match(',')) { break; } lex(); } while (index < length); return list; } function parseVariableStatement() { var declarations; expectKeyword('var'); declarations = parseVariableDeclarationList(); consumeSemicolon(); return { type: Syntax.VariableDeclaration, declarations: declarations, kind: 'var' }; } // kind may be `const` or `let` // Both are experimental and not in the specification yet. // see http://wiki.ecmascript.org/doku.php?id=harmony:const // and http://wiki.ecmascript.org/doku.php?id=harmony:let function parseConstLetDeclaration(kind) { var declarations; expectKeyword(kind); declarations = parseVariableDeclarationList(kind); consumeSemicolon(); return { type: Syntax.VariableDeclaration, declarations: declarations, kind: kind }; } // 12.3 Empty Statement function parseEmptyStatement() { expect(';'); return { type: Syntax.EmptyStatement }; } // 12.4 Expression Statement function parseExpressionStatement() { var expr = parseExpression(); consumeSemicolon(); return { type: Syntax.ExpressionStatement, expression: expr }; } // 12.5 If statement function parseIfStatement() { var test, consequent, alternate; expectKeyword('if'); expect('('); test = parseExpression(); expect(')'); consequent = parseStatement(); if (matchKeyword('else')) { lex(); alternate = parseStatement(); } else { alternate = null; } return { type: Syntax.IfStatement, test: test, consequent: consequent, alternate: alternate }; } // 12.6 Iteration Statements function parseDoWhileStatement() { var body, test, oldInIteration; expectKeyword('do'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); if (match(';')) { lex(); } return { type: Syntax.DoWhileStatement, body: body, test: test }; } function parseWhileStatement() { var test, body, oldInIteration; expectKeyword('while'); expect('('); test = parseExpression(); expect(')'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; return { type: Syntax.WhileStatement, test: test, body: body }; } function parseForVariableDeclaration() { var token = lex(); return { type: Syntax.VariableDeclaration, declarations: parseVariableDeclarationList(), kind: token.value }; } function parseForStatement() { var init, test, update, left, right, body, oldInIteration; init = test = update = null; expectKeyword('for'); expect('('); if (match(';')) { lex(); } else { if (matchKeyword('var') || matchKeyword('let')) { state.allowIn = false; init = parseForVariableDeclaration(); state.allowIn = true; if (init.declarations.length === 1 && matchKeyword('in')) { lex(); left = init; right = parseExpression(); init = null; } } else { state.allowIn = false; init = parseExpression(); state.allowIn = true; if (matchKeyword('in')) { // LeftHandSideExpression if (!isLeftHandSide(init)) { throwErrorTolerant({}, Messages.InvalidLHSInForIn); } lex(); left = init; right = parseExpression(); init = null; } } if (typeof left === 'undefined') { expect(';'); } } if (typeof left === 'undefined') { if (!match(';')) { test = parseExpression(); } expect(';'); if (!match(')')) { update = parseExpression(); } } expect(')'); oldInIteration = state.inIteration; state.inIteration = true; body = parseStatement(); state.inIteration = oldInIteration; if (typeof left === 'undefined') { return { type: Syntax.ForStatement, init: init, test: test, update: update, body: body }; } return { type: Syntax.ForInStatement, left: left, right: right, body: body, each: false }; } // 12.7 The continue statement function parseContinueStatement() { var token, label = null; expectKeyword('continue'); // Optimize the most common form: 'continue;'. if (source[index] === ';') { lex(); if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return { type: Syntax.ContinueStatement, label: null }; } if (peekLineTerminator()) { if (!state.inIteration) { throwError({}, Messages.IllegalContinue); } return { type: Syntax.ContinueStatement, label: null }; } token = lookahead(); if (token.type === Token.Identifier) { label = parseVariableIdentifier(); if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !state.inIteration) { throwError({}, Messages.IllegalContinue); } return { type: Syntax.ContinueStatement, label: label }; } // 12.8 The break statement function parseBreakStatement() { var token, label = null; expectKeyword('break'); // Optimize the most common form: 'break;'. if (source[index] === ';') { lex(); if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return { type: Syntax.BreakStatement, label: null }; } if (peekLineTerminator()) { if (!(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return { type: Syntax.BreakStatement, label: null }; } token = lookahead(); if (token.type === Token.Identifier) { label = parseVariableIdentifier(); if (!Object.prototype.hasOwnProperty.call(state.labelSet, label.name)) { throwError({}, Messages.UnknownLabel, label.name); } } consumeSemicolon(); if (label === null && !(state.inIteration || state.inSwitch)) { throwError({}, Messages.IllegalBreak); } return { type: Syntax.BreakStatement, label: label }; } // 12.9 The return statement function parseReturnStatement() { var token, argument = null; expectKeyword('return'); if (!state.inFunctionBody) { throwErrorTolerant({}, Messages.IllegalReturn); } // 'return' followed by a space and an identifier is very common. if (source[index] === ' ') { if (isIdentifierStart(source[index + 1])) { argument = parseExpression(); consumeSemicolon(); return { type: Syntax.ReturnStatement, argument: argument }; } } if (peekLineTerminator()) { return { type: Syntax.ReturnStatement, argument: null }; } if (!match(';')) { token = lookahead(); if (!match('}') && token.type !== Token.EOF) { argument = parseExpression(); } } consumeSemicolon(); return { type: Syntax.ReturnStatement, argument: argument }; } // 12.10 The with statement function parseWithStatement() { var object, body; if (strict) { throwErrorTolerant({}, Messages.StrictModeWith); } expectKeyword('with'); expect('('); object = parseExpression(); expect(')'); body = parseStatement(); return { type: Syntax.WithStatement, object: object, body: body }; } // 12.10 The swith statement function parseSwitchCase() { var test, consequent = [], statement; if (matchKeyword('default')) { lex(); test = null; } else { expectKeyword('case'); test = parseExpression(); } expect(':'); while (index < length) { if (match('}') || matchKeyword('default') || matchKeyword('case')) { break; } statement = parseStatement(); if (typeof statement === 'undefined') { break; } consequent.push(statement); } return { type: Syntax.SwitchCase, test: test, consequent: consequent }; } function parseSwitchStatement() { var discriminant, cases, clause, oldInSwitch, defaultFound; expectKeyword('switch'); expect('('); discriminant = parseExpression(); expect(')'); expect('{'); cases = []; if (match('}')) { lex(); return { type: Syntax.SwitchStatement, discriminant: discriminant, cases: cases }; } oldInSwitch = state.inSwitch; state.inSwitch = true; defaultFound = false; while (index < length) { if (match('}')) { break; } clause = parseSwitchCase(); if (clause.test === null) { if (defaultFound) { throwError({}, Messages.MultipleDefaultsInSwitch); } defaultFound = true; } cases.push(clause); } state.inSwitch = oldInSwitch; expect('}'); return { type: Syntax.SwitchStatement, discriminant: discriminant, cases: cases }; } // 12.13 The throw statement function parseThrowStatement() { var argument; expectKeyword('throw'); if (peekLineTerminator()) { throwError({}, Messages.NewlineAfterThrow); } argument = parseExpression(); consumeSemicolon(); return { type: Syntax.ThrowStatement, argument: argument }; } // 12.14 The try statement function parseCatchClause() { var param; expectKeyword('catch'); expect('('); if (match(')')) { throwUnexpected(lookahead()); } param = parseVariableIdentifier(); // 12.14.1 if (strict && isRestrictedWord(param.name)) { throwErrorTolerant({}, Messages.StrictCatchVariable); } expect(')'); return { type: Syntax.CatchClause, param: param, body: parseBlock() }; } function parseTryStatement() { var block, handlers = [], finalizer = null; expectKeyword('try'); block = parseBlock(); if (matchKeyword('catch')) { handlers.push(parseCatchClause()); } if (matchKeyword('finally')) { lex(); finalizer = parseBlock(); } if (handlers.length === 0 && !finalizer) { throwError({}, Messages.NoCatchOrFinally); } return { type: Syntax.TryStatement, block: block, guardedHandlers: [], handlers: handlers, finalizer: finalizer }; } // 12.15 The debugger statement function parseDebuggerStatement() { expectKeyword('debugger'); consumeSemicolon(); return { type: Syntax.DebuggerStatement }; } // 12 Statements function parseStatement() { var token = lookahead(), expr, labeledBody; if (token.type === Token.EOF) { throwUnexpected(token); } if (token.type === Token.Punctuator) { switch (token.value) { case ';': return parseEmptyStatement(); case '{': return parseBlock(); case '(': return parseExpressionStatement(); default: break; } } if (token.type === Token.Keyword) { switch (token.value) { case 'break': return parseBreakStatement(); case 'continue': return parseContinueStatement(); case 'debugger': return parseDebuggerStatement(); case 'do': return parseDoWhileStatement(); case 'for': return parseForStatement(); case 'function': return parseFunctionDeclaration(); case 'if': return parseIfStatement(); case 'return': return parseReturnStatement(); case 'switch': return parseSwitchStatement(); case 'throw': return parseThrowStatement(); case 'try': return parseTryStatement(); case 'var': return parseVariableStatement(); case 'while': return parseWhileStatement(); case 'with': return parseWithStatement(); default: break; } } expr = parseExpression(); // 12.12 Labelled Statements if ((expr.type === Syntax.Identifier) && match(':')) { lex(); if (Object.prototype.hasOwnProperty.call(state.labelSet, expr.name)) { throwError({}, Messages.Redeclaration, 'Label', expr.name); } state.labelSet[expr.name] = true; labeledBody = parseStatement(); delete state.labelSet[expr.name]; return { type: Syntax.LabeledStatement, label: expr, body: labeledBody }; } consumeSemicolon(); return { type: Syntax.ExpressionStatement, expression: expr }; } // 13 Function Definition function parseFunctionSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted, oldLabelSet, oldInIteration, oldInSwitch, oldInFunctionBody; expect('{'); while (index < length) { token = lookahead(); if (token.type !== Token.StringLiteral) { break; } sourceElement = parseSourceElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = sliceSource(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } oldLabelSet = state.labelSet; oldInIteration = state.inIteration; oldInSwitch = state.inSwitch; oldInFunctionBody = state.inFunctionBody; state.labelSet = {}; state.inIteration = false; state.inSwitch = false; state.inFunctionBody = true; while (index < length) { if (match('}')) { break; } sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } expect('}'); state.labelSet = oldLabelSet; state.inIteration = oldInIteration; state.inSwitch = oldInSwitch; state.inFunctionBody = oldInFunctionBody; return { type: Syntax.BlockStatement, body: sourceElements }; } function parseFunctionDeclaration() { var id, param, params = [], body, token, stricted, firstRestricted, message, previousStrict, paramSet; expectKeyword('function'); token = lookahead(); id = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } expect('('); if (!match(')')) { paramSet = {}; while (index < length) { token = lookahead(); param = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { stricted = token; message = Messages.StrictParamName; } if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { stricted = token; message = Messages.StrictParamDupe; } } else if (!firstRestricted) { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictParamName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { firstRestricted = token; message = Messages.StrictParamDupe; } } params.push(param); paramSet[param.name] = true; if (match(')')) { break; } expect(','); } } expect(')'); previousStrict = strict; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && stricted) { throwErrorTolerant(stricted, message); } strict = previousStrict; return { type: Syntax.FunctionDeclaration, id: id, params: params, defaults: [], body: body, rest: null, generator: false, expression: false }; } function parseFunctionExpression() { var token, id = null, stricted, firstRestricted, message, param, params = [], body, previousStrict, paramSet; expectKeyword('function'); if (!match('(')) { token = lookahead(); id = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { throwErrorTolerant(token, Messages.StrictFunctionName); } } else { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictFunctionName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } } } expect('('); if (!match(')')) { paramSet = {}; while (index < length) { token = lookahead(); param = parseVariableIdentifier(); if (strict) { if (isRestrictedWord(token.value)) { stricted = token; message = Messages.StrictParamName; } if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { stricted = token; message = Messages.StrictParamDupe; } } else if (!firstRestricted) { if (isRestrictedWord(token.value)) { firstRestricted = token; message = Messages.StrictParamName; } else if (isStrictModeReservedWord(token.value)) { firstRestricted = token; message = Messages.StrictReservedWord; } else if (Object.prototype.hasOwnProperty.call(paramSet, token.value)) { firstRestricted = token; message = Messages.StrictParamDupe; } } params.push(param); paramSet[param.name] = true; if (match(')')) { break; } expect(','); } } expect(')'); previousStrict = strict; body = parseFunctionSourceElements(); if (strict && firstRestricted) { throwError(firstRestricted, message); } if (strict && stricted) { throwErrorTolerant(stricted, message); } strict = previousStrict; return { type: Syntax.FunctionExpression, id: id, params: params, defaults: [], body: body, rest: null, generator: false, expression: false }; } // 14 Program function parseSourceElement() { var token = lookahead(); if (token.type === Token.Keyword) { switch (token.value) { case 'const': case 'let': return parseConstLetDeclaration(token.value); case 'function': return parseFunctionDeclaration(); default: return parseStatement(); } } if (token.type !== Token.EOF) { return parseStatement(); } } function parseSourceElements() { var sourceElement, sourceElements = [], token, directive, firstRestricted; while (index < length) { token = lookahead(); if (token.type !== Token.StringLiteral) { break; } sourceElement = parseSourceElement(); sourceElements.push(sourceElement); if (sourceElement.expression.type !== Syntax.Literal) { // this is not directive break; } directive = sliceSource(token.range[0] + 1, token.range[1] - 1); if (directive === 'use strict') { strict = true; if (firstRestricted) { throwErrorTolerant(firstRestricted, Messages.StrictOctalLiteral); } } else { if (!firstRestricted && token.octal) { firstRestricted = token; } } } while (index < length) { sourceElement = parseSourceElement(); if (typeof sourceElement === 'undefined') { break; } sourceElements.push(sourceElement); } return sourceElements; } function parseProgram() { var program; strict = false; program = { type: Syntax.Program, body: parseSourceElements() }; return program; } // The following functions are needed only when the option to preserve // the comments is active. function addComment(type, value, start, end, loc) { assert(typeof start === 'number', 'Comment must have valid position'); // Because the way the actual token is scanned, often the comments // (if any) are skipped twice during the lexical analysis. // Thus, we need to skip adding a comment if the comment array already // handled it. if (extra.comments.length > 0) { if (extra.comments[extra.comments.length - 1].range[1] > start) { return; } } extra.comments.push({ type: type, value: value, range: [start, end], loc: loc }); } function scanComment() { var comment, ch, loc, start, blockComment, lineComment; comment = ''; blockComment = false; lineComment = false; while (index < length) { ch = source[index]; if (lineComment) { ch = source[index++]; if (isLineTerminator(ch)) { loc.end = { line: lineNumber, column: index - lineStart - 1 }; lineComment = false; addComment('Line', comment, start, index - 1, loc); if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; comment = ''; } else if (index >= length) { lineComment = false; comment += ch; loc.end = { line: lineNumber, column: length - lineStart }; addComment('Line', comment, start, length, loc); } else { comment += ch; } } else if (blockComment) { if (isLineTerminator(ch)) { if (ch === '\r' && source[index + 1] === '\n') { ++index; comment += '\r\n'; } else { comment += ch; } ++lineNumber; ++index; lineStart = index; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { ch = source[index++]; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } comment += ch; if (ch === '*') { ch = source[index]; if (ch === '/') { comment = comment.substr(0, comment.length - 1); blockComment = false; ++index; loc.end = { line: lineNumber, column: index - lineStart }; addComment('Block', comment, start, index, loc); comment = ''; } } } } else if (ch === '/') { ch = source[index + 1]; if (ch === '/') { loc = { start: { line: lineNumber, column: index - lineStart } }; start = index; index += 2; lineComment = true; if (index >= length) { loc.end = { line: lineNumber, column: index - lineStart }; lineComment = false; addComment('Line', comment, start, index, loc); } } else if (ch === '*') { start = index; index += 2; blockComment = true; loc = { start: { line: lineNumber, column: index - lineStart - 2 } }; if (index >= length) { throwError({}, Messages.UnexpectedToken, 'ILLEGAL'); } } else { break; } } else if (isWhiteSpace(ch)) { ++index; } else if (isLineTerminator(ch)) { ++index; if (ch === '\r' && source[index] === '\n') { ++index; } ++lineNumber; lineStart = index; } else { break; } } } function filterCommentLocation() { var i, entry, comment, comments = []; for (i = 0; i < extra.comments.length; ++i) { entry = extra.comments[i]; comment = { type: entry.type, value: entry.value }; if (extra.range) { comment.range = entry.range; } if (extra.loc) { comment.loc = entry.loc; } comments.push(comment); } extra.comments = comments; } function collectToken() { var start, loc, token, range, value; skipComment(); start = index; loc = { start: { line: lineNumber, column: index - lineStart } }; token = extra.advance(); loc.end = { line: lineNumber, column: index - lineStart }; if (token.type !== Token.EOF) { range = [token.range[0], token.range[1]]; value = sliceSource(token.range[0], token.range[1]); extra.tokens.push({ type: TokenName[token.type], value: value, range: range, loc: loc }); } return token; } function collectRegex() { var pos, loc, regex, token; skipComment(); pos = index; loc = { start: { line: lineNumber, column: index - lineStart } }; regex = extra.scanRegExp(); loc.end = { line: lineNumber, column: index - lineStart }; // Pop the previous token, which is likely '/' or '/=' if (extra.tokens.length > 0) { token = extra.tokens[extra.tokens.length - 1]; if (token.range[0] === pos && token.type === 'Punctuator') { if (token.value === '/' || token.value === '/=') { extra.tokens.pop(); } } } extra.tokens.push({ type: 'RegularExpression', value: regex.literal, range: [pos, index], loc: loc }); return regex; } function filterTokenLocation() { var i, entry, token, tokens = []; for (i = 0; i < extra.tokens.length; ++i) { entry = extra.tokens[i]; token = { type: entry.type, value: entry.value }; if (extra.range) { token.range = entry.range; } if (extra.loc) { token.loc = entry.loc; } tokens.push(token); } extra.tokens = tokens; } function createLiteral(token) { return { type: Syntax.Literal, value: token.value }; } function createRawLiteral(token) { return { type: Syntax.Literal, value: token.value, raw: sliceSource(token.range[0], token.range[1]) }; } function createLocationMarker() { var marker = {}; marker.range = [index, index]; marker.loc = { start: { line: lineNumber, column: index - lineStart }, end: { line: lineNumber, column: index - lineStart } }; marker.end = function () { this.range[1] = index; this.loc.end.line = lineNumber; this.loc.end.column = index - lineStart; }; marker.applyGroup = function (node) { if (extra.range) { node.groupRange = [this.range[0], this.range[1]]; } if (extra.loc) { node.groupLoc = { start: { line: this.loc.start.line, column: this.loc.start.column }, end: { line: this.loc.end.line, column: this.loc.end.column } }; } }; marker.apply = function (node) { if (extra.range) { node.range = [this.range[0], this.range[1]]; } if (extra.loc) { node.loc = { start: { line: this.loc.start.line, column: this.loc.start.column }, end: { line: this.loc.end.line, column: this.loc.end.column } }; } }; return marker; } function trackGroupExpression() { var marker, expr; skipComment(); marker = createLocationMarker(); expect('('); expr = parseExpression(); expect(')'); marker.end(); marker.applyGroup(expr); return expr; } function trackLeftHandSideExpression() { var marker, expr; skipComment(); marker = createLocationMarker(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[')) { if (match('[')) { expr = { type: Syntax.MemberExpression, computed: true, object: expr, property: parseComputedMember() }; marker.end(); marker.apply(expr); } else { expr = { type: Syntax.MemberExpression, computed: false, object: expr, property: parseNonComputedMember() }; marker.end(); marker.apply(expr); } } return expr; } function trackLeftHandSideExpressionAllowCall() { var marker, expr; skipComment(); marker = createLocationMarker(); expr = matchKeyword('new') ? parseNewExpression() : parsePrimaryExpression(); while (match('.') || match('[') || match('(')) { if (match('(')) { expr = { type: Syntax.CallExpression, callee: expr, 'arguments': parseArguments() }; marker.end(); marker.apply(expr); } else if (match('[')) { expr = { type: Syntax.MemberExpression, computed: true, object: expr, property: parseComputedMember() }; marker.end(); marker.apply(expr); } else { expr = { type: Syntax.MemberExpression, computed: false, object: expr, property: parseNonComputedMember() }; marker.end(); marker.apply(expr); } } return expr; } function filterGroup(node) { var n, i, entry; n = (Object.prototype.toString.apply(node) === '[object Array]') ? [] : {}; for (i in node) { if (node.hasOwnProperty(i) && i !== 'groupRange' && i !== 'groupLoc') { entry = node[i]; if (entry === null || typeof entry !== 'object' || entry instanceof RegExp) { n[i] = entry; } else { n[i] = filterGroup(entry); } } } return n; } function wrapTrackingFunction(range, loc) { return function (parseFunction) { function isBinary(node) { return node.type === Syntax.LogicalExpression || node.type === Syntax.BinaryExpression; } function visit(node) { var start, end; if (isBinary(node.left)) { visit(node.left); } if (isBinary(node.right)) { visit(node.right); } if (range) { if (node.left.groupRange || node.right.groupRange) { start = node.left.groupRange ? node.left.groupRange[0] : node.left.range[0]; end = node.right.groupRange ? node.right.groupRange[1] : node.right.range[1]; node.range = [start, end]; } else if (typeof node.range === 'undefined') { start = node.left.range[0]; end = node.right.range[1]; node.range = [start, end]; } } if (loc) { if (node.left.groupLoc || node.right.groupLoc) { start = node.left.groupLoc ? node.left.groupLoc.start : node.left.loc.start; end = node.right.groupLoc ? node.right.groupLoc.end : node.right.loc.end; node.loc = { start: start, end: end }; } else if (typeof node.loc === 'undefined') { node.loc = { start: node.left.loc.start, end: node.right.loc.end }; } } } return function () { var marker, node; skipComment(); marker = createLocationMarker(); node = parseFunction.apply(null, arguments); marker.end(); if (range && typeof node.range === 'undefined') { marker.apply(node); } if (loc && typeof node.loc === 'undefined') { marker.apply(node); } if (isBinary(node)) { visit(node); } return node; }; }; } function patch() { var wrapTracking; if (extra.comments) { extra.skipComment = skipComment; skipComment = scanComment; } if (extra.raw) { extra.createLiteral = createLiteral; createLiteral = createRawLiteral; } if (extra.range || extra.loc) { extra.parseGroupExpression = parseGroupExpression; extra.parseLeftHandSideExpression = parseLeftHandSideExpression; extra.parseLeftHandSideExpressionAllowCall = parseLeftHandSideExpressionAllowCall; parseGroupExpression = trackGroupExpression; parseLeftHandSideExpression = trackLeftHandSideExpression; parseLeftHandSideExpressionAllowCall = trackLeftHandSideExpressionAllowCall; wrapTracking = wrapTrackingFunction(extra.range, extra.loc); extra.parseAdditiveExpression = parseAdditiveExpression; extra.parseAssignmentExpression = parseAssignmentExpression; extra.parseBitwiseANDExpression = parseBitwiseANDExpression; extra.parseBitwiseORExpression = parseBitwiseORExpression; extra.parseBitwiseXORExpression = parseBitwiseXORExpression; extra.parseBlock = parseBlock; extra.parseFunctionSourceElements = parseFunctionSourceElements; extra.parseCatchClause = parseCatchClause; extra.parseComputedMember = parseComputedMember; extra.parseConditionalExpression = parseConditionalExpression; extra.parseConstLetDeclaration = parseConstLetDeclaration; extra.parseEqualityExpression = parseEqualityExpression; extra.parseExpression = parseExpression; extra.parseForVariableDeclaration = parseForVariableDeclaration; extra.parseFunctionDeclaration = parseFunctionDeclaration; extra.parseFunctionExpression = parseFunctionExpression; extra.parseLogicalANDExpression = parseLogicalANDExpression; extra.parseLogicalORExpression = parseLogicalORExpression; extra.parseMultiplicativeExpression = parseMultiplicativeExpression; extra.parseNewExpression = parseNewExpression; extra.parseNonComputedProperty = parseNonComputedProperty; extra.parseObjectProperty = parseObjectProperty; extra.parseObjectPropertyKey = parseObjectPropertyKey; extra.parsePostfixExpression = parsePostfixExpression; extra.parsePrimaryExpression = parsePrimaryExpression; extra.parseProgram = parseProgram; extra.parsePropertyFunction = parsePropertyFunction; extra.parseRelationalExpression = parseRelationalExpression; extra.parseStatement = parseStatement; extra.parseShiftExpression = parseShiftExpression; extra.parseSwitchCase = parseSwitchCase; extra.parseUnaryExpression = parseUnaryExpression; extra.parseVariableDeclaration = parseVariableDeclaration; extra.parseVariableIdentifier = parseVariableIdentifier; parseAdditiveExpression = wrapTracking(extra.parseAdditiveExpression); parseAssignmentExpression = wrapTracking(extra.parseAssignmentExpression); parseBitwiseANDExpression = wrapTracking(extra.parseBitwiseANDExpression); parseBitwiseORExpression = wrapTracking(extra.parseBitwiseORExpression); parseBitwiseXORExpression = wrapTracking(extra.parseBitwiseXORExpression); parseBlock = wrapTracking(extra.parseBlock); parseFunctionSourceElements = wrapTracking(extra.parseFunctionSourceElements); parseCatchClause = wrapTracking(extra.parseCatchClause); parseComputedMember = wrapTracking(extra.parseComputedMember); parseConditionalExpression = wrapTracking(extra.parseConditionalExpression); parseConstLetDeclaration = wrapTracking(extra.parseConstLetDeclaration); parseEqualityExpression = wrapTracking(extra.parseEqualityExpression); parseExpression = wrapTracking(extra.parseExpression); parseForVariableDeclaration = wrapTracking(extra.parseForVariableDeclaration); parseFunctionDeclaration = wrapTracking(extra.parseFunctionDeclaration); parseFunctionExpression = wrapTracking(extra.parseFunctionExpression); parseLeftHandSideExpression = wrapTracking(parseLeftHandSideExpression); parseLogicalANDExpression = wrapTracking(extra.parseLogicalANDExpression); parseLogicalORExpression = wrapTracking(extra.parseLogicalORExpression); parseMultiplicativeExpression = wrapTracking(extra.parseMultiplicativeExpression); parseNewExpression = wrapTracking(extra.parseNewExpression); parseNonComputedProperty = wrapTracking(extra.parseNonComputedProperty); parseObjectProperty = wrapTracking(extra.parseObjectProperty); parseObjectPropertyKey = wrapTracking(extra.parseObjectPropertyKey); parsePostfixExpression = wrapTracking(extra.parsePostfixExpression); parsePrimaryExpression = wrapTracking(extra.parsePrimaryExpression); parseProgram = wrapTracking(extra.parseProgram); parsePropertyFunction = wrapTracking(extra.parsePropertyFunction); parseRelationalExpression = wrapTracking(extra.parseRelationalExpression); parseStatement = wrapTracking(extra.parseStatement); parseShiftExpression = wrapTracking(extra.parseShiftExpression); parseSwitchCase = wrapTracking(extra.parseSwitchCase); parseUnaryExpression = wrapTracking(extra.parseUnaryExpression); parseVariableDeclaration = wrapTracking(extra.parseVariableDeclaration); parseVariableIdentifier = wrapTracking(extra.parseVariableIdentifier); } if (typeof extra.tokens !== 'undefined') { extra.advance = advance; extra.scanRegExp = scanRegExp; advance = collectToken; scanRegExp = collectRegex; } } function unpatch() { if (typeof extra.skipComment === 'function') { skipComment = extra.skipComment; } if (extra.raw) { createLiteral = extra.createLiteral; } if (extra.range || extra.loc) { parseAdditiveExpression = extra.parseAdditiveExpression; parseAssignmentExpression = extra.parseAssignmentExpression; parseBitwiseANDExpression = extra.parseBitwiseANDExpression; parseBitwiseORExpression = extra.parseBitwiseORExpression; parseBitwiseXORExpression = extra.parseBitwiseXORExpression; parseBlock = extra.parseBlock; parseFunctionSourceElements = extra.parseFunctionSourceElements; parseCatchClause = extra.parseCatchClause; parseComputedMember = extra.parseComputedMember; parseConditionalExpression = extra.parseConditionalExpression; parseConstLetDeclaration = extra.parseConstLetDeclaration; parseEqualityExpression = extra.parseEqualityExpression; parseExpression = extra.parseExpression; parseForVariableDeclaration = extra.parseForVariableDeclaration; parseFunctionDeclaration = extra.parseFunctionDeclaration; parseFunctionExpression = extra.parseFunctionExpression; parseGroupExpression = extra.parseGroupExpression; parseLeftHandSideExpression = extra.parseLeftHandSideExpression; parseLeftHandSideExpressionAllowCall = extra.parseLeftHandSideExpressionAllowCall; parseLogicalANDExpression = extra.parseLogicalANDExpression; parseLogicalORExpression = extra.parseLogicalORExpression; parseMultiplicativeExpression = extra.parseMultiplicativeExpression; parseNewExpression = extra.parseNewExpression; parseNonComputedProperty = extra.parseNonComputedProperty; parseObjectProperty = extra.parseObjectProperty; parseObjectPropertyKey = extra.parseObjectPropertyKey; parsePrimaryExpression = extra.parsePrimaryExpression; parsePostfixExpression = extra.parsePostfixExpression; parseProgram = extra.parseProgram; parsePropertyFunction = extra.parsePropertyFunction; parseRelationalExpression = extra.parseRelationalExpression; parseStatement = extra.parseStatement; parseShiftExpression = extra.parseShiftExpression; parseSwitchCase = extra.parseSwitchCase; parseUnaryExpression = extra.parseUnaryExpression; parseVariableDeclaration = extra.parseVariableDeclaration; parseVariableIdentifier = extra.parseVariableIdentifier; } if (typeof extra.scanRegExp === 'function') { advance = extra.advance; scanRegExp = extra.scanRegExp; } } function stringToArray(str) { var length = str.length, result = [], i; for (i = 0; i < length; ++i) { result[i] = str.charAt(i); } return result; } function parse(code, options) { var program, toString; toString = String; if (typeof code !== 'string' && !(code instanceof String)) { code = toString(code); } source = code; index = 0; lineNumber = (source.length > 0) ? 1 : 0; lineStart = 0; length = source.length; buffer = null; state = { allowIn: true, labelSet: {}, inFunctionBody: false, inIteration: false, inSwitch: false }; extra = {}; if (typeof options !== 'undefined') { extra.range = (typeof options.range === 'boolean') && options.range; extra.loc = (typeof options.loc === 'boolean') && options.loc; extra.raw = (typeof options.raw === 'boolean') && options.raw; if (typeof options.tokens === 'boolean' && options.tokens) { extra.tokens = []; } if (typeof options.comment === 'boolean' && options.comment) { extra.comments = []; } if (typeof options.tolerant === 'boolean' && options.tolerant) { extra.errors = []; } } if (length > 0) { if (typeof source[0] === 'undefined') { // Try first to convert to a string. This is good as fast path // for old IE which understands string indexing for string // literals only and not for string object. if (code instanceof String) { source = code.valueOf(); } // Force accessing the characters via an array. if (typeof source[0] === 'undefined') { source = stringToArray(code); } } } patch(); try { program = parseProgram(); if (typeof extra.comments !== 'undefined') { filterCommentLocation(); program.comments = extra.comments; } if (typeof extra.tokens !== 'undefined') { filterTokenLocation(); program.tokens = extra.tokens; } if (typeof extra.errors !== 'undefined') { program.errors = extra.errors; } if (extra.range || extra.loc) { program.body = filterGroup(program.body); } } catch (e) { throw e; } finally { unpatch(); extra = {}; } return program; } // Sync with package.json. exports.version = '1.0.4'; exports.parse = parse; // Deep copy. exports.Syntax = (function () { var name, types = {}; if (typeof Object.create === 'function') { types = Object.create(null); } for (name in Syntax) { if (Syntax.hasOwnProperty(name)) { types[name] = Syntax[name]; } } if (typeof Object.freeze === 'function') { Object.freeze(types); } return types; }()); })); /* vim: set sw=4 ts=4 et tw=80 : */ return module.exports; })({exports:{}}); var index = (function (module, global) { var exports = module.exports; var parse = esprima.parse var hoist = index$1 var InfiniteChecker = infiniteChecker var Primitives = primitives module.exports = safeEval module.exports.FunctionFactory = FunctionFactory module.exports.Function = FunctionFactory() var maxIterations = 1000000 // 'eval' with a controlled environment function safeEval(src, parentContext){ var tree = prepareAst(src) var context = Object.create(parentContext || {}) return finalValue(evaluateAst(tree, context)) } // create a 'Function' constructor for a controlled environment function FunctionFactory(parentContext){ var context = Object.create(parentContext || {}) return function Function() { // normalize arguments array var args = Array.prototype.slice.call(arguments) var src = args.slice(-1)[0] args = args.slice(0,-1) if (typeof src === 'string'){ //HACK: esprima doesn't like returns outside functions src = parse('function a(){' + src + '}').body[0].body } var tree = prepareAst(src) return getFunction(tree, args, context) } } // takes an AST or js source and returns an AST function prepareAst(src){ var tree = (typeof src === 'string') ? parse(src) : src return hoist(tree) } // evaluate an AST in the given context function evaluateAst(tree, context){ var safeFunction = FunctionFactory(context) var primitives = Primitives(context) // block scoped context for catch (ex) and 'let' var blockContext = context return walk(tree) // recursively walk every node in an array function walkAll(nodes){ var result = undefined for (var i=0;i<nodes.length;i++){ var childNode = nodes[i] if (childNode.type === 'EmptyStatement') continue result = walk(childNode) if (result instanceof ReturnValue){ return result } } return result } // recursively evalutate the node of an AST function walk(node){ if (!node) return switch (node.type) { case 'Program': return walkAll(node.body) case 'BlockStatement': enterBlock() var result = walkAll(node.body) leaveBlock() return result case 'FunctionDeclaration': var params = node.params.map(getName) var value = getFunction(node.body, params, blockContext) return context[node.id.name] = value case 'FunctionExpression': var params = node.params.map(getName) return getFunction(node.body, params, blockContext) case 'ReturnStatement': var value = walk(node.argument) return new ReturnValue('return', value) case 'BreakStatement': return new ReturnValue('break') case 'ContinueStatement': return new ReturnValue('continue') case 'ExpressionStatement': return walk(node.expression) case 'AssignmentExpression': return setValue(blockContext, node.left, node.right, node.operator) case 'UpdateExpression': return setValue(blockContext, node.argument, null, node.operator) case 'VariableDeclaration': node.declarations.forEach(function(declaration){ var target = node.kind === 'let' ? blockContext : context if (declaration.init){ target[declaration.id.name] = walk(declaration.init) } else { target[declaration.id.name] = undefined } }) break case 'SwitchStatement': var defaultHandler = null var matched = false var value = walk(node.discriminant) var result = undefined enterBlock() var i = 0 while (result == null){ if (i<node.cases.length){ if (node.cases[i].test){ // check or fall through matched = matched || (walk(node.cases[i].test) === value) } else if (defaultHandler == null) { defaultHandler = i } if (matched){ var r = walkAll(node.cases[i].consequent) if (r instanceof ReturnValue){ // break out if (r.type == 'break') break result = r } } i += 1 // continue } else if (!matched && defaultHandler != null){ // go back and do the default handler i = defaultHandler matched = true } else { // nothing we can do break } } leaveBlock() return result case 'IfStatement': if (walk(node.test)){ return walk(node.consequent) } else if (node.alternate) { return walk(node.alternate) } case 'ForStatement': var infinite = InfiniteChecker(maxIterations) var result = undefined enterBlock() // allow lets on delarations for (walk(node.init); walk(node.test); walk(node.update)){ var r = walk(node.body) // handle early return, continue and break if (r instanceof ReturnValue){ if (r.type == 'continue') continue if (r.type == 'break') break result = r break } infinite.check() } leaveBlock() return result case 'ForInStatement': var infinite = InfiniteChecker(maxIterations) var result = undefined var value = walk(node.right) var property = node.left var target = context enterBlock() if (property.type == 'VariableDeclaration'){ walk(property) property = property.declarations[0].id if (property.kind === 'let'){ target = blockContext } } for (var key in value){ setValue(target, property, {type: 'Literal', value: key}) var r = walk(node.body) // handle early return, continue and break if (r instanceof ReturnValue){ if (r.type == 'continue') continue if (r.type == 'break') break result = r break } infinite.check() } leaveBlock() return result case 'WhileStatement': var infinite = InfiniteChecker(maxIterations) while (walk(node.test)){ walk(node.body) infinite.check() } break case 'TryStatement': try { walk(node.block) } catch (error) { enterBlock() var catchClause = node.handlers[0] if (catchClause) { blockContext[catchClause.param.name] = error walk(catchClause.body) } leaveBlock() } finally { if (node.finalizer) { walk(node.finalizer) } } break case 'Literal': return node.value case 'UnaryExpression': var val = walk(node.argument) switch(node.operator) { case '+': return +val case '-': return -val case '~': return ~val case '!': return !val case 'typeof': return typeof val default: return unsupportedExpression(node) } case 'ArrayExpression': var obj = blockContext['Array']() for (var i=0;i<node.elements.length;i++){ obj.push(walk(node.elements[i])) } return obj case 'ObjectExpression': var obj = blockContext['Object']() for (var i = 0; i < node.properties.length; i++) { var prop = node.properties[i] var value = (prop.value === null) ? prop.value : walk(prop.value) obj[prop.key.value || prop.key.name] = value } return obj case 'NewExpression': var args = node.arguments.map(function(arg){ return walk(arg) }) var target = walk(node.callee) return primitives.applyNew(target, args) case 'BinaryExpression': var l = walk(node.left) var r = walk(node.right) switch(node.operator) { case '==': return l === r case '===': return l === r case '!=': return l != r case '!==': return l !== r case '+': return l + r case '-': return l - r case '*': return l * r case '/': return l / r case '%': return l % r case '<': return l < r case '<=': return l <= r case '>': return l > r case '>=': return l >= r case '|': return l | r case '&': return l & r case '^': return l ^ r case 'instanceof': return l instanceof r default: return unsupportedExpression(node) } case 'LogicalExpression': switch(node.operator) { case '&&': return walk(node.left) && walk(node.right) case '||': return walk(node.left) || walk(node.right) default: return unsupportedExpression(node) } case 'ThisExpression': return blockContext['this'] case 'Identifier': if (node.name === 'undefined'){ return undefined } else if (hasProperty(blockContext, node.name, primitives)){ return finalValue(blockContext[node.name]) } else { throw new ReferenceError(node.name + ' is not defined') } case 'CallExpression': var args = node.arguments.map(function(arg){ return walk(arg) }) var object = null var target = walk(node.callee) if (node.callee.type === 'MemberExpression'){ object = walk(node.callee.object) } return target.apply(object, args) case 'MemberExpression': var obj = walk(node.object) if (node.computed){ var prop = walk(node.property) } else { var prop = node.property.name } obj = primitives.getPropertyObject(obj, prop) return checkValue(obj[prop]); case 'ConditionalExpression': var val = walk(node.test) return val ? walk(node.consequent) : walk(node.alternate) case 'EmptyStatement': return default: return unsupportedExpression(node) } } // safely retrieve a value function checkValue(value){ if (value === Function$1){ value = safeFunction } return finalValue(value) } // block scope context control function enterBlock(){ blockContext = Object.create(blockContext) } function leaveBlock(){ blockContext = Object.getPrototypeOf(blockContext) } // set a value in the specified context if allowed function setValue(object, left, right, operator){ var name = null if (left.type === 'Identifier'){ name = left.name // handle parent context shadowing object = objectForKey(object, name, primitives) } else if (left.type === 'MemberExpression'){ if (left.computed){ name = walk(left.property) } else { name = left.property.name } object = walk(left.object) } // stop built in properties from being able to be changed if (canSetProperty(object, name, primitives)){ switch(operator) { case undefined: return object[name] = walk(right) case '=': return object[name] = walk(right) case '+=': return object[name] += walk(right) case '-=': return object[name] -= walk(right) case '++': return object[name]++ case '--': return object[name]-- } } } } // when an unsupported expression is encountered, throw an error function unsupportedExpression(node){ console.error(node) var err = new Error('Unsupported expression: ' + node.type) err.node = node throw err } // walk a provided object's prototypal hierarchy to retrieve an inherited object function objectForKey(object, key, primitives){ var proto = primitives.getPrototypeOf(object) if (!proto || hasOwnProperty(object, key)){ return object } else { return objectForKey(proto, key, primitives) } } function hasProperty(object, key, primitives){ var proto = primitives.getPrototypeOf(object) var hasOwn = hasOwnProperty(object, key) if (object[key] !== undefined){ return true } else if (!proto || hasOwn){ return hasOwn } else { return hasProperty(proto, key, primitives) } } function hasOwnProperty(object, key){ return Object.prototype.hasOwnProperty.call(object, key) } function propertyIsEnumerable(object, key){ return Object.prototype.propertyIsEnumerable.call(object, key) } // determine if we have write access to a property function canSetProperty(object, property, primitives){ if (property === '__proto__' || primitives.isPrimitive(object)){ return false } else if (object != null){ if (hasOwnProperty(object, property)){ if (propertyIsEnumerable(object, property)){ return true } else { return false } } else { return canSetProperty(primitives.getPrototypeOf(object), property, primitives) } } else { return true } } // generate a function with specified context function getFunction(body, params, parentContext){ return function(){ var context = Object.create(parentContext) if (this == global){ context['this'] = null } else { context['this'] = this } // normalize arguments array var args = Array.prototype.slice.call(arguments) context['arguments'] = arguments args.forEach(function(arg,idx){ var param = params[idx] if (param){ context[param] = arg } }) var result = evaluateAst(body, context) if (result instanceof ReturnValue){ return result.value } } } function finalValue(value){ if (value instanceof ReturnValue){ return value.value } return value } // get the name of an identifier function getName(identifier){ return identifier.name } // a ReturnValue struct for differentiating between expression result and return statement function ReturnValue(type, value){ this.type = type this.value = value } return module.exports; })({exports:{}}, __commonjs_global); var Function$1 = index.Function; module.exports = index; return module.exports; })({exports:{}}, __commonjs_global); var pathCache = new Cache(1000); // actions var APPEND = 0; var PUSH = 1; var INC_SUB_PATH_DEPTH = 2; var PUSH_SUB_PATH = 3; // states var BEFORE_PATH = 0; var IN_PATH = 1; var BEFORE_IDENT = 2; var IN_IDENT = 3; var IN_SUB_PATH = 4; var IN_SINGLE_QUOTE = 5; var IN_DOUBLE_QUOTE = 6; var AFTER_PATH = 7; var ERROR = 8; var pathStateMachine = []; pathStateMachine[BEFORE_PATH] = { 'ws': [BEFORE_PATH], 'ident': [IN_IDENT, APPEND], '[': [IN_SUB_PATH], 'eof': [AFTER_PATH] }; pathStateMachine[IN_PATH] = { 'ws': [IN_PATH], '.': [BEFORE_IDENT], '[': [IN_SUB_PATH], 'eof': [AFTER_PATH] }; pathStateMachine[BEFORE_IDENT] = { 'ws': [BEFORE_IDENT], 'ident': [IN_IDENT, APPEND] }; pathStateMachine[IN_IDENT] = { 'ident': [IN_IDENT, APPEND], '0': [IN_IDENT, APPEND], 'number': [IN_IDENT, APPEND], 'ws': [IN_PATH, PUSH], '.': [BEFORE_IDENT, PUSH], '[': [IN_SUB_PATH, PUSH], 'eof': [AFTER_PATH, PUSH] }; pathStateMachine[IN_SUB_PATH] = { "'": [IN_SINGLE_QUOTE, APPEND], '"': [IN_DOUBLE_QUOTE, APPEND], '[': [IN_SUB_PATH, INC_SUB_PATH_DEPTH], ']': [IN_PATH, PUSH_SUB_PATH], 'eof': ERROR, 'else': [IN_SUB_PATH, APPEND] }; pathStateMachine[IN_SINGLE_QUOTE] = { "'": [IN_SUB_PATH, APPEND], 'eof': ERROR, 'else': [IN_SINGLE_QUOTE, APPEND] }; pathStateMachine[IN_DOUBLE_QUOTE] = { '"': [IN_SUB_PATH, APPEND], 'eof': ERROR, 'else': [IN_DOUBLE_QUOTE, APPEND] }; /** * Determine the type of a character in a keypath. * * @param {Char} ch * @return {String} type */ function getPathCharType(ch) { if (ch === undefined) { return 'eof'; } var code = ch.charCodeAt(0); switch (code) { case 0x5B: // [ case 0x5D: // ] case 0x2E: // . case 0x22: // " case 0x27: // ' case 0x30: // 0 return ch; case 0x5F: // _ case 0x24: // $ return 'ident'; case 0x20: // Space case 0x09: // Tab case 0x0A: // Newline case 0x0D: // Return case 0xA0: // No-break space case 0xFEFF: // Byte Order Mark case 0x2028: // Line Separator case 0x2029: // Paragraph Separator return 'ws'; } // a-z, A-Z if (code >= 0x61 && code <= 0x7A || code >= 0x41 && code <= 0x5A) { return 'ident'; } // 1-9 if (code >= 0x31 && code <= 0x39) { return 'number'; } return 'else'; } /** * Format a subPath, return its plain form if it is * a literal string or number. Otherwise prepend the * dynamic indicator (*). * * @param {String} path * @return {String} */ function formatSubPath(path) { var trimmed = path.trim(); // invalid leading 0 if (path.charAt(0) === '0' && isNaN(path)) { return false; } return isLiteral(trimmed) ? stripQuotes(trimmed) : '*' + trimmed; } /** * Parse a string path into an array of segments * * @param {String} path * @return {Array|undefined} */ function parse(path) { var keys = []; var index = -1; var mode = BEFORE_PATH; var subPathDepth = 0; var c, newChar, key, type, transition, action, typeMap; var actions = []; actions[PUSH] = function () { if (key !== undefined) { keys.push(key); key = undefined; } }; actions[APPEND] = function () { if (key === undefined) { key = newChar; } else { key += newChar; } }; actions[INC_SUB_PATH_DEPTH] = function () { actions[APPEND](); subPathDepth++; }; actions[PUSH_SUB_PATH] = function () { if (subPathDepth > 0) { subPathDepth--; mode = IN_SUB_PATH; actions[APPEND](); } else { subPathDepth = 0; key = formatSubPath(key); if (key === false) { return false; } else { actions[PUSH](); } } }; function maybeUnescapeQuote() { var nextChar = path[index + 1]; if (mode === IN_SINGLE_QUOTE && nextChar === "'" || mode === IN_DOUBLE_QUOTE && nextChar === '"') { index++; newChar = '\\' + nextChar; actions[APPEND](); return true; } } while (mode != null) { index++; c = path[index]; if (c === '\\' && maybeUnescapeQuote()) { continue; } type = getPathCharType(c); typeMap = pathStateMachine[mode]; transition = typeMap[type] || typeMap['else'] || ERROR; if (transition === ERROR) { return; // parse error } mode = transition[0]; action = actions[transition[1]]; if (action) { newChar = transition[2]; newChar = newChar === undefined ? c : newChar; if (action() === false) { return; } } if (mode === AFTER_PATH) { keys.raw = path; return keys; } } } /** * External parse that check for a cache hit first * * @param {String} path * @return {Array|undefined} */ function parsePath(path) { var hit = pathCache.get(path); if (!hit) { hit = parse(path); if (hit) { pathCache.put(path, hit); } } return hit; } /** * Get from an object from a path string * * @param {Object} obj * @param {String} path */ function getPath(obj, path) { return parseExpression(path).get(obj); } /** * Warn against setting non-existent root path on a vm. */ var warnNonExistent; if ('development' !== 'production') { warnNonExistent = function (path) { warn('You are setting a non-existent path "' + path.raw + '" ' + 'on a vm instance. Consider pre-initializing the property ' + 'with the "data" option for more reliable reactivity ' + 'and better performance.'); }; } /** * Set on an object from a path * * @param {Object} obj * @param {String | Array} path * @param {*} val */ function setPath(obj, path, val) { var original = obj; if (typeof path === 'string') { path = parse(path); } if (!path || !isObject(obj)) { return false; } var last, key; for (var i = 0, l = path.length; i < l; i++) { last = obj; key = path[i]; if (key.charAt(0) === '*') { key = parseExpression(key.slice(1)).get.call(original, original); } if (i < l - 1) { obj = obj[key]; if (!isObject(obj)) { obj = {}; if ('development' !== 'production' && last._isVue) { warnNonExistent(path); } set(last, key, obj); } } else { if (isArray(obj)) { obj.$set(key, val); } else if (key in obj) { obj[key] = val; } else { if ('development' !== 'production' && obj._isVue) { warnNonExistent(path); } set(obj, key, val); } } } return true; } var path = Object.freeze({ parsePath: parsePath, getPath: getPath, setPath: setPath }); var expressionCache = new Cache(1000); var allowedKeywords = 'Math,Date,this,true,false,null,undefined,Infinity,NaN,' + 'isNaN,isFinite,decodeURI,decodeURIComponent,encodeURI,' + 'encodeURIComponent,parseInt,parseFloat'; var allowedKeywordsRE = new RegExp('^(' + allowedKeywords.replace(/,/g, '\\b|') + '\\b)'); // keywords that don't make sense inside expressions var improperKeywords = 'break,case,class,catch,const,continue,debugger,default,' + 'delete,do,else,export,extends,finally,for,function,if,' + 'import,in,instanceof,let,return,super,switch,throw,try,' + 'var,while,with,yield,enum,await,implements,package,' + 'proctected,static,interface,private,public'; var improperKeywordsRE = new RegExp('^(' + improperKeywords.replace(/,/g, '\\b|') + '\\b)'); var wsRE = /\s/g; var newlineRE = /\n/g; var saveRE = /[\{,]\s*[\w\$_]+\s*:|('(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*")|new |typeof |void /g; var restoreRE = /"(\d+)"/g; var pathTestRE = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?'\]|\[".*?"\]|\[\d+\]|\[[A-Za-z_$][\w$]*\])*$/; var identRE = /[^\w$\.](?:[A-Za-z_$][\w$]*)/g; var booleanLiteralRE = /^(?:true|false)$/; /** * Save / Rewrite / Restore * * When rewriting paths found in an expression, it is * possible for the same letter sequences to be found in * strings and Object literal property keys. Therefore we * remove and store these parts in a temporary array, and * restore them after the path rewrite. */ var saved = []; /** * Save replacer * * The save regex can match two possible cases: * 1. An opening object literal * 2. A string * If matched as a plain string, we need to escape its * newlines, since the string needs to be preserved when * generating the function body. * * @param {String} str * @param {String} isString - str if matched as a string * @return {String} - placeholder with index */ function save(str, isString) { var i = saved.length; saved[i] = isString ? str.replace(newlineRE, '\\n') : str; return '"' + i + '"'; } /** * Path rewrite replacer * * @param {String} raw * @return {String} */ function rewrite(raw) { var c = raw.charAt(0); var path = raw.slice(1); if (allowedKeywordsRE.test(path)) { return raw; } else { path = path.indexOf('"') > -1 ? path.replace(restoreRE, restore) : path; return c + 'scope.' + path; } } /** * Restore replacer * * @param {String} str * @param {String} i - matched save index * @return {String} */ function restore(str, i) { return saved[i]; } /** * Rewrite an expression, prefixing all path accessors with * `scope.` and generate getter/setter functions. * * @param {String} exp * @return {Function} */ function compileGetter(exp) { if (improperKeywordsRE.test(exp)) { 'development' !== 'production' && warn('Avoid using reserved keywords in expression: ' + exp); } // reset state saved.length = 0; // save strings and object literal keys var body = exp.replace(saveRE, save).replace(wsRE, ''); // rewrite all paths // pad 1 space here becaue the regex matches 1 extra char body = (' ' + body).replace(identRE, rewrite).replace(restoreRE, restore); return makeGetterFn(body); } /** * Build a getter function. Requires eval. * * We isolate the try/catch so it doesn't affect the * optimization of the parse function when it is not called. * * @param {String} body * @return {Function|undefined} */ function makeGetterFn(body) { try { var fn = notevil.Function('scope', 'Math', 'return ' + body); return function (scope) { return fn.call(this, scope, Math); }; } catch (e) { 'development' !== 'production' && warn('Invalid expression. ' + 'Generated function body: ' + body); } } /** * Compile a setter function for the expression. * * @param {String} exp * @return {Function|undefined} */ function compileSetter(exp) { var path = parsePath(exp); if (path) { return function (scope, val) { setPath(scope, path, val); }; } else { 'development' !== 'production' && warn('Invalid setter expression: ' + exp); } } /** * Parse an expression into re-written getter/setters. * * @param {String} exp * @param {Boolean} needSet * @return {Function} */ function parseExpression(exp, needSet) { exp = exp.trim(); // try cache var hit = expressionCache.get(exp); if (hit) { if (needSet && !hit.set) { hit.set = compileSetter(hit.exp); } return hit; } var res = { exp: exp }; res.get = isSimplePath(exp) && exp.indexOf('[') < 0 // optimized super simple getter ? makeGetterFn('scope.' + exp) // dynamic getter : compileGetter(exp); if (needSet) { res.set = compileSetter(exp); } expressionCache.put(exp, res); return res; } /** * Check if an expression is a simple path. * * @param {String} exp * @return {Boolean} */ function isSimplePath(exp) { return pathTestRE.test(exp) && // don't treat true/false as paths !booleanLiteralRE.test(exp) && // Math constants e.g. Math.PI, Math.E etc. exp.slice(0, 5) !== 'Math.'; } var expression = Object.freeze({ parseExpression: parseExpression, isSimplePath: isSimplePath }); // we have two separate queues: one for directive updates // and one for user watcher registered via $watch(). // we want to guarantee directive updates to be called // before user watchers so that when user watchers are // triggered, the DOM would have already been in updated // state. var queue = []; var userQueue = []; var has = {}; var circular = {}; var waiting = false; var internalQueueDepleted = false; /** * Reset the batcher's state. */ function resetBatcherState() { queue = []; userQueue = []; has = {}; circular = {}; waiting = internalQueueDepleted = false; } /** * Flush both queues and run the watchers. */ function flushBatcherQueue() { runBatcherQueue(queue); internalQueueDepleted = true; runBatcherQueue(userQueue); // dev tool hook /* istanbul ignore if */ if ('development' !== 'production') { if (inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__) { window.__VUE_DEVTOOLS_GLOBAL_HOOK__.emit('flush'); } } resetBatcherState(); } /** * Run the watchers in a single queue. * * @param {Array} queue */ function runBatcherQueue(queue) { // do not cache length because more watchers might be pushed // as we run existing watchers for (var i = 0; i < queue.length; i++) { var watcher = queue[i]; var id = watcher.id; has[id] = null; watcher.run(); // in dev build, check and stop circular updates. if ('development' !== 'production' && has[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > config._maxUpdateCount) { queue.splice(has[id], 1); warn('You may have an infinite update loop for watcher ' + 'with expression: ' + watcher.expression); } } } } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. * * @param {Watcher} watcher * properties: * - {Number} id * - {Function} run */ function pushWatcher(watcher) { var id = watcher.id; if (has[id] == null) { // if an internal watcher is pushed, but the internal // queue is already depleted, we run it immediately. if (internalQueueDepleted && !watcher.user) { watcher.run(); return; } // push watcher into appropriate queue var q = watcher.user ? userQueue : queue; has[id] = q.length; q.push(watcher); // queue the flush if (!waiting) { waiting = true; nextTick(flushBatcherQueue); } } } var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. * * @param {Vue} vm * @param {String} expression * @param {Function} cb * @param {Object} options * - {Array} filters * - {Boolean} twoWay * - {Boolean} deep * - {Boolean} user * - {Boolean} sync * - {Boolean} lazy * - {Function} [preProcess] * - {Function} [postProcess] * @constructor */ function Watcher(vm, expOrFn, cb, options) { // mix in options if (options) { extend(this, options); } var isFn = typeof expOrFn === 'function'; this.vm = vm; vm._watchers.push(this); this.expression = isFn ? expOrFn.toString() : expOrFn; this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = Object.create(null); this.newDeps = null; this.prevError = null; // for async error stacks // parse expression for getter/setter if (isFn) { this.getter = expOrFn; this.setter = undefined; } else { var res = parseExpression(expOrFn, this.twoWay); this.getter = res.get; this.setter = res.set; } this.value = this.lazy ? undefined : this.get(); // state for avoiding false triggers for deep and Array // watchers during vm._digest() this.queued = this.shallow = false; } /** * Add a dependency to this directive. * * @param {Dep} dep */ Watcher.prototype.addDep = function (dep) { var id = dep.id; if (!this.newDeps[id]) { this.newDeps[id] = dep; if (!this.deps[id]) { this.deps[id] = dep; dep.addSub(this); } } }; /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function () { this.beforeGet(); var scope = this.scope || this.vm; var value; try { value = this.getter.call(scope, scope); } catch (e) { if ('development' !== 'production' && config.warnExpressionErrors) { warn('Error when evaluating expression "' + this.expression + '". ' + (config.debug ? '' : 'Turn on debug mode to see stack trace.'), e); } } // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } if (this.preProcess) { value = this.preProcess(value); } if (this.filters) { value = scope._applyFilters(value, null, this.filters, false); } if (this.postProcess) { value = this.postProcess(value); } this.afterGet(); return value; }; /** * Set the corresponding value with the setter. * * @param {*} value */ Watcher.prototype.set = function (value) { var scope = this.scope || this.vm; if (this.filters) { value = scope._applyFilters(value, this.value, this.filters, true); } try { this.setter.call(scope, scope, value); } catch (e) { if ('development' !== 'production' && config.warnExpressionErrors) { warn('Error when evaluating setter "' + this.expression + '"', e); } } // two-way sync for v-for alias var forContext = scope.$forContext; if (forContext && forContext.alias === this.expression) { if (forContext.filters) { 'development' !== 'production' && warn('It seems you are using two-way binding on ' + 'a v-for alias (' + this.expression + '), and the ' + 'v-for has filters. This will not work properly. ' + 'Either remove the filters or use an array of ' + 'objects and bind to object properties instead.'); return; } forContext._withLock(function () { if (scope.$key) { // original is an object forContext.rawValue[scope.$key] = value; } else { forContext.rawValue.$set(scope.$index, value); } }); } }; /** * Prepare for dependency collection. */ Watcher.prototype.beforeGet = function () { Dep.target = this; this.newDeps = Object.create(null); }; /** * Clean up for dependency collection. */ Watcher.prototype.afterGet = function () { Dep.target = null; var ids = Object.keys(this.deps); var i = ids.length; while (i--) { var id = ids[i]; if (!this.newDeps[id]) { this.deps[id].removeSub(this); } } this.deps = this.newDeps; }; /** * Subscriber interface. * Will be called when a dependency changes. * * @param {Boolean} shallow */ Watcher.prototype.update = function (shallow) { if (this.lazy) { this.dirty = true; } else if (this.sync || !config.async) { this.run(); } else { // if queued, only overwrite shallow with non-shallow, // but not the other way around. this.shallow = this.queued ? shallow ? this.shallow : false : !!shallow; this.queued = true; // record before-push error stack in debug mode /* istanbul ignore if */ if ('development' !== 'production' && config.debug) { this.prevError = new Error('[vue] async stack trace'); } pushWatcher(this); } }; /** * Batcher job interface. * Will be called by the batcher. */ Watcher.prototype.run = function () { if (this.active) { var value = this.get(); if (value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated; but only do so if this is a // non-shallow update (caused by a vm digest). (isObject(value) || this.deep) && !this.shallow) { // set new value var oldValue = this.value; this.value = value; // in debug + async mode, when a watcher callbacks // throws, we also throw the saved before-push error // so the full cross-tick stack trace is available. var prevError = this.prevError; /* istanbul ignore if */ if ('development' !== 'production' && config.debug && prevError) { this.prevError = null; try { this.cb.call(this.vm, value, oldValue); } catch (e) { nextTick(function () { throw prevError; }, 0); throw e; } } else { this.cb.call(this.vm, value, oldValue); } } this.queued = this.shallow = false; } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function () { // avoid overwriting another watcher that is being // collected. var current = Dep.target; this.value = this.get(); this.dirty = false; Dep.target = current; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function () { var depIds = Object.keys(this.deps); var i = depIds.length; while (i--) { this.deps[depIds[i]].depend(); } }; /** * Remove self from all dependencies' subcriber list. */ Watcher.prototype.teardown = function () { if (this.active) { // remove self from vm's watcher list // we can skip this if the vm if being destroyed // which can improve teardown performance. if (!this.vm._isBeingDestroyed) { this.vm._watchers.$remove(this); } var depIds = Object.keys(this.deps); var i = depIds.length; while (i--) { this.deps[depIds[i]].removeSub(this); } this.active = false; this.vm = this.cb = this.value = null; } }; /** * Recrusively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. * * @param {*} val */ function traverse(val) { var i, keys; if (isArray(val)) { i = val.length; while (i--) traverse(val[i]); } else if (isObject(val)) { keys = Object.keys(val); i = keys.length; while (i--) traverse(val[keys[i]]); } } var cloak = { bind: function bind() { var el = this.el; this.vm.$once('pre-hook:compiled', function () { el.removeAttribute('v-cloak'); }); } }; var ref = { bind: function bind() { 'development' !== 'production' && warn('v-ref:' + this.arg + ' must be used on a child ' + 'component. Found on <' + this.el.tagName.toLowerCase() + '>.'); } }; var ON = 700; var MODEL = 800; var BIND = 850; var TRANSITION = 1100; var EL = 1500; var COMPONENT = 1500; var PARTIAL = 1750; var SLOT = 1750; var FOR = 2000; var IF = 2000; var el = { priority: EL, bind: function bind() { /* istanbul ignore if */ if (!this.arg) { return; } var id = this.id = camelize(this.arg); var refs = (this._scope || this.vm).$els; if (hasOwn(refs, id)) { refs[id] = this.el; } else { defineReactive(refs, id, this.el); } }, unbind: function unbind() { var refs = (this._scope || this.vm).$els; if (refs[this.id] === this.el) { refs[this.id] = null; } } }; var prefixes = ['-webkit-', '-moz-', '-ms-']; var camelPrefixes = ['Webkit', 'Moz', 'ms']; var importantRE = /!important;?$/; var propCache = Object.create(null); var testEl = null; var style = { deep: true, update: function update(value) { if (typeof value === 'string') { this.el.style.cssText = value; } else if (isArray(value)) { this.handleObject(value.reduce(extend, {})); } else { this.handleObject(value || {}); } }, handleObject: function handleObject(value) { // cache object styles so that only changed props // are actually updated. var cache = this.cache || (this.cache = {}); var name, val; for (name in cache) { if (!(name in value)) { this.handleSingle(name, null); delete cache[name]; } } for (name in value) { val = value[name]; if (val !== cache[name]) { cache[name] = val; this.handleSingle(name, val); } } }, handleSingle: function handleSingle(prop, value) { prop = normalize(prop); if (!prop) return; // unsupported prop // cast possible numbers/booleans into strings if (value != null) value += ''; if (value) { var isImportant = importantRE.test(value) ? 'important' : ''; if (isImportant) { value = value.replace(importantRE, '').trim(); } this.el.style.setProperty(prop, value, isImportant); } else { this.el.style.removeProperty(prop); } } }; /** * Normalize a CSS property name. * - cache result * - auto prefix * - camelCase -> dash-case * * @param {String} prop * @return {String} */ function normalize(prop) { if (propCache[prop]) { return propCache[prop]; } var res = prefix(prop); propCache[prop] = propCache[res] = res; return res; } /** * Auto detect the appropriate prefix for a CSS property. * https://gist.github.com/paulirish/523692 * * @param {String} prop * @return {String} */ function prefix(prop) { prop = hyphenate(prop); var camel = camelize(prop); var upper = camel.charAt(0).toUpperCase() + camel.slice(1); if (!testEl) { testEl = document.createElement('div'); } if (camel in testEl.style) { return prop; } var i = prefixes.length; var prefixed; while (i--) { prefixed = camelPrefixes[i] + upper; if (prefixed in testEl.style) { return prefixes[i] + prop; } } } // xlink var xlinkNS = 'http://www.w3.org/1999/xlink'; var xlinkRE = /^xlink:/; // check for attributes that prohibit interpolations var disallowedInterpAttrRE = /^v-|^:|^@|^(is|transition|transition-mode|debounce|track-by|stagger|enter-stagger|leave-stagger)$/; // these attributes should also set their corresponding properties // because they only affect the initial state of the element var attrWithPropsRE = /^(value|checked|selected|muted)$/; // these attributes should set a hidden property for // binding v-model to object values var modelProps = { value: '_value', 'true-value': '_trueValue', 'false-value': '_falseValue' }; var bind = { priority: BIND, bind: function bind() { var attr = this.arg; var tag = this.el.tagName; // should be deep watch on object mode if (!attr) { this.deep = true; } // handle interpolation bindings if (this.descriptor.interp) { // only allow binding on native attributes if (disallowedInterpAttrRE.test(attr) || attr === 'name' && (tag === 'PARTIAL' || tag === 'SLOT')) { 'development' !== 'production' && warn(attr + '="' + this.descriptor.raw + '": ' + 'attribute interpolation is not allowed in Vue.js ' + 'directives and special attributes.'); this.el.removeAttribute(attr); this.invalid = true; } /* istanbul ignore if */ if ('development' !== 'production') { var raw = attr + '="' + this.descriptor.raw + '": '; // warn src if (attr === 'src') { warn(raw + 'interpolation in "src" attribute will cause ' + 'a 404 request. Use v-bind:src instead.'); } // warn style if (attr === 'style') { warn(raw + 'interpolation in "style" attribute will cause ' + 'the attribute to be discarded in Internet Explorer. ' + 'Use v-bind:style instead.'); } } } }, update: function update(value) { if (this.invalid) { return; } var attr = this.arg; if (this.arg) { this.handleSingle(attr, value); } else { this.handleObject(value || {}); } }, // share object handler with v-bind:class handleObject: style.handleObject, handleSingle: function handleSingle(attr, value) { var el = this.el; var interp = this.descriptor.interp; if (!interp && attrWithPropsRE.test(attr) && attr in el) { el[attr] = attr === 'value' ? value == null // IE9 will set input.value to "null" for null... ? '' : value : value; } // set model props var modelProp = modelProps[attr]; if (!interp && modelProp) { el[modelProp] = value; // update v-model if present var model = el.__v_model; if (model) { model.listener(); } } // do not set value attribute for textarea if (attr === 'value' && el.tagName === 'TEXTAREA') { el.removeAttribute(attr); return; } // update attribute if (value != null && value !== false) { if (attr === 'class') { // handle edge case #1960: // class interpolation should not overwrite Vue transition class if (el.__v_trans) { value += ' ' + el.__v_trans.id + '-transition'; } setClass(el, value); } else if (xlinkRE.test(attr)) { el.setAttributeNS(xlinkNS, attr, value); } else { el.setAttribute(attr, value); } } else { el.removeAttribute(attr); } } }; // keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, 'delete': 46, up: 38, left: 37, right: 39, down: 40 }; function keyFilter(handler, keys) { var codes = keys.map(function (key) { var charCode = key.charCodeAt(0); if (charCode > 47 && charCode < 58) { return parseInt(key, 10); } if (key.length === 1) { charCode = key.toUpperCase().charCodeAt(0); if (charCode > 64 && charCode < 91) { return charCode; } } return keyCodes[key]; }); return function keyHandler(e) { if (codes.indexOf(e.keyCode) > -1) { return handler.call(this, e); } }; } function stopFilter(handler) { return function stopHandler(e) { e.stopPropagation(); return handler.call(this, e); }; } function preventFilter(handler) { return function preventHandler(e) { e.preventDefault(); return handler.call(this, e); }; } var on = { acceptStatement: true, priority: ON, bind: function bind() { // deal with iframes if (this.el.tagName === 'IFRAME' && this.arg !== 'load') { var self = this; this.iframeBind = function () { on$1(self.el.contentWindow, self.arg, self.handler); }; this.on('load', this.iframeBind); } }, update: function update(handler) { // stub a noop for v-on with no value, // e.g. @mousedown.prevent if (!this.descriptor.raw) { handler = function () {}; } if (typeof handler !== 'function') { 'development' !== 'production' && warn('v-on:' + this.arg + '="' + this.expression + '" expects a function value, ' + 'got ' + handler); return; } // apply modifiers if (this.modifiers.stop) { handler = stopFilter(handler); } if (this.modifiers.prevent) { handler = preventFilter(handler); } // key filter var keys = Object.keys(this.modifiers).filter(function (key) { return key !== 'stop' && key !== 'prevent'; }); if (keys.length) { handler = keyFilter(handler, keys); } this.reset(); this.handler = handler; if (this.iframeBind) { this.iframeBind(); } else { on$1(this.el, this.arg, this.handler); } }, reset: function reset() { var el = this.iframeBind ? this.el.contentWindow : this.el; if (this.handler) { off(el, this.arg, this.handler); } }, unbind: function unbind() { this.reset(); } }; var checkbox = { bind: function bind() { var self = this; var el = this.el; this.getValue = function () { return el.hasOwnProperty('_value') ? el._value : self.params.number ? toNumber(el.value) : el.value; }; function getBooleanValue() { var val = el.checked; if (val && el.hasOwnProperty('_trueValue')) { return el._trueValue; } if (!val && el.hasOwnProperty('_falseValue')) { return el._falseValue; } return val; } this.listener = function () { var model = self._watcher.value; if (isArray(model)) { var val = self.getValue(); if (el.checked) { if (indexOf(model, val) < 0) { model.push(val); } } else { model.$remove(val); } } else { self.set(getBooleanValue()); } }; this.on('change', this.listener); if (el.hasAttribute('checked')) { this.afterBind = this.listener; } }, update: function update(value) { var el = this.el; if (isArray(value)) { el.checked = indexOf(value, this.getValue()) > -1; } else { if (el.hasOwnProperty('_trueValue')) { el.checked = looseEqual(value, el._trueValue); } else { el.checked = !!value; } } } }; var select = { bind: function bind() { var self = this; var el = this.el; // method to force update DOM using latest value. this.forceUpdate = function () { if (self._watcher) { self.update(self._watcher.get()); } }; // check if this is a multiple select var multiple = this.multiple = el.hasAttribute('multiple'); // attach listener this.listener = function () { var value = getValue(el, multiple); value = self.params.number ? isArray(value) ? value.map(toNumber) : toNumber(value) : value; self.set(value); }; this.on('change', this.listener); // if has initial value, set afterBind var initValue = getValue(el, multiple, true); if (multiple && initValue.length || !multiple && initValue !== null) { this.afterBind = this.listener; } // All major browsers except Firefox resets // selectedIndex with value -1 to 0 when the element // is appended to a new parent, therefore we have to // force a DOM update whenever that happens... this.vm.$on('hook:attached', this.forceUpdate); }, update: function update(value) { var el = this.el; el.selectedIndex = -1; var multi = this.multiple && isArray(value); var options = el.options; var i = options.length; var op, val; while (i--) { op = options[i]; val = op.hasOwnProperty('_value') ? op._value : op.value; /* eslint-disable eqeqeq */ op.selected = multi ? indexOf$1(value, val) > -1 : looseEqual(value, val); /* eslint-enable eqeqeq */ } }, unbind: function unbind() { /* istanbul ignore next */ this.vm.$off('hook:attached', this.forceUpdate); } }; /** * Get select value * * @param {SelectElement} el * @param {Boolean} multi * @param {Boolean} init * @return {Array|*} */ function getValue(el, multi, init) { var res = multi ? [] : null; var op, val, selected; for (var i = 0, l = el.options.length; i < l; i++) { op = el.options[i]; selected = init ? op.hasAttribute('selected') : op.selected; if (selected) { val = op.hasOwnProperty('_value') ? op._value : op.value; if (multi) { res.push(val); } else { return val; } } } return res; } /** * Native Array.indexOf uses strict equal, but in this * case we need to match string/numbers with custom equal. * * @param {Array} arr * @param {*} val */ function indexOf$1(arr, val) { var i = arr.length; while (i--) { if (looseEqual(arr[i], val)) { return i; } } return -1; } var radio = { bind: function bind() { var self = this; var el = this.el; this.getValue = function () { // value overwrite via v-bind:value if (el.hasOwnProperty('_value')) { return el._value; } var val = el.value; if (self.params.number) { val = toNumber(val); } return val; }; this.listener = function () { self.set(self.getValue()); }; this.on('change', this.listener); if (el.hasAttribute('checked')) { this.afterBind = this.listener; } }, update: function update(value) { this.el.checked = looseEqual(value, this.getValue()); } }; var text$2 = { bind: function bind() { var self = this; var el = this.el; var isRange = el.type === 'range'; var lazy = this.params.lazy; var number = this.params.number; var debounce = this.params.debounce; // handle composition events. // http://blog.evanyou.me/2014/01/03/composition-event/ // skip this for Android because it handles composition // events quite differently. Android doesn't trigger // composition events for language input methods e.g. // Chinese, but instead triggers them for spelling // suggestions... (see Discussion/#162) var composing = false; if (!isAndroid && !isRange) { this.on('compositionstart', function () { composing = true; }); this.on('compositionend', function () { composing = false; // in IE11 the "compositionend" event fires AFTER // the "input" event, so the input handler is blocked // at the end... have to call it here. // // #1327: in lazy mode this is unecessary. if (!lazy) { self.listener(); } }); } // prevent messing with the input when user is typing, // and force update on blur. this.focused = false; if (!isRange) { this.on('focus', function () { self.focused = true; }); this.on('blur', function () { self.focused = false; // do not sync value after fragment removal (#2017) if (!self._frag || self._frag.inserted) { self.rawListener(); } }); } // Now attach the main listener this.listener = this.rawListener = function () { if (composing || !self._bound) { return; } var val = number || isRange ? toNumber(el.value) : el.value; self.set(val); // force update on next tick to avoid lock & same value // also only update when user is not typing nextTick(function () { if (self._bound && !self.focused) { self.update(self._watcher.value); } }); }; // apply debounce if (debounce) { this.listener = _debounce(this.listener, debounce); } // Support jQuery events, since jQuery.trigger() doesn't // trigger native events in some cases and some plugins // rely on $.trigger() // // We want to make sure if a listener is attached using // jQuery, it is also removed with jQuery, that's why // we do the check for each directive instance and // store that check result on itself. This also allows // easier test coverage control by unsetting the global // jQuery variable in tests. this.hasjQuery = typeof jQuery === 'function'; if (this.hasjQuery) { jQuery(el).on('change', this.listener); if (!lazy) { jQuery(el).on('input', this.listener); } } else { this.on('change', this.listener); if (!lazy) { this.on('input', this.listener); } } // IE9 doesn't fire input event on backspace/del/cut if (!lazy && isIE9) { this.on('cut', function () { nextTick(self.listener); }); this.on('keyup', function (e) { if (e.keyCode === 46 || e.keyCode === 8) { self.listener(); } }); } // set initial value if present if (el.hasAttribute('value') || el.tagName === 'TEXTAREA' && el.value.trim()) { this.afterBind = this.listener; } }, update: function update(value) { this.el.value = _toString(value); }, unbind: function unbind() { var el = this.el; if (this.hasjQuery) { jQuery(el).off('change', this.listener); jQuery(el).off('input', this.listener); } } }; var handlers = { text: text$2, radio: radio, select: select, checkbox: checkbox }; var model = { priority: MODEL, twoWay: true, handlers: handlers, params: ['lazy', 'number', 'debounce'], /** * Possible elements: * <select> * <textarea> * <input type="*"> * - text * - checkbox * - radio * - number */ bind: function bind() { // friendly warning... this.checkFilters(); if (this.hasRead && !this.hasWrite) { 'development' !== 'production' && warn('It seems you are using a read-only filter with ' + 'v-model. You might want to use a two-way filter ' + 'to ensure correct behavior.'); } var el = this.el; var tag = el.tagName; var handler; if (tag === 'INPUT') { handler = handlers[el.type] || handlers.text; } else if (tag === 'SELECT') { handler = handlers.select; } else if (tag === 'TEXTAREA') { handler = handlers.text; } else { 'development' !== 'production' && warn('v-model does not support element type: ' + tag); return; } el.__v_model = this; handler.bind.call(this); this.update = handler.update; this._unbind = handler.unbind; }, /** * Check read/write filter stats. */ checkFilters: function checkFilters() { var filters = this.filters; if (!filters) return; var i = filters.length; while (i--) { var filter = resolveAsset(this.vm.$options, 'filters', filters[i].name); if (typeof filter === 'function' || filter.read) { this.hasRead = true; } if (filter.write) { this.hasWrite = true; } } }, unbind: function unbind() { this.el.__v_model = null; this._unbind && this._unbind(); } }; var show = { bind: function bind() { // check else block var next = this.el.nextElementSibling; if (next && getAttr(next, 'v-else') !== null) { this.elseEl = next; } }, update: function update(value) { this.apply(this.el, value); if (this.elseEl) { this.apply(this.elseEl, !value); } }, apply: function apply(el, value) { if (inDoc(el)) { applyTransition(el, value ? 1 : -1, toggle, this.vm); } else { toggle(); } function toggle() { el.style.display = value ? '' : 'none'; } } }; var templateCache = new Cache(1000); var idSelectorCache = new Cache(1000); var map = { efault: [0, '', ''], legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'] }; 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.g = map.defs = map.symbol = map.use = map.image = 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" ' + 'xmlns:xlink="http://www.w3.org/1999/xlink" ' + 'xmlns:ev="http://www.w3.org/2001/xml-events"' + 'version="1.1">', '</svg>']; /** * Check if a node is a supported template node with a * DocumentFragment content. * * @param {Node} node * @return {Boolean} */ function isRealTemplate(node) { return isTemplate(node) && node.content instanceof DocumentFragment; } var tagRE$1 = /<([\w:]+)/; var entityRE = /&#?\w+?;/; /** * Convert a string template to a DocumentFragment. * Determines correct wrapping by tag types. Wrapping * strategy found in jQuery & component/domify. * * @param {String} templateString * @param {Boolean} raw * @return {DocumentFragment} */ function stringToFragment(templateString, raw) { // try a cache hit first var hit = templateCache.get(templateString); if (hit) { return hit; } var frag = document.createDocumentFragment(); var tagMatch = templateString.match(tagRE$1); var entityMatch = entityRE.test(templateString); if (!tagMatch && !entityMatch) { // text only, return a single text node. frag.appendChild(document.createTextNode(templateString)); } else { var tag = tagMatch && tagMatch[1]; var wrap = map[tag] || map.efault; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var node = document.createElement('div'); if (!raw) { templateString = templateString.trim(); } node.innerHTML = prefix + templateString + suffix; while (depth--) { node = node.lastChild; } var child; /* eslint-disable no-cond-assign */ while (child = node.firstChild) { /* eslint-enable no-cond-assign */ frag.appendChild(child); } } templateCache.put(templateString, frag); return frag; } /** * Convert a template node to a DocumentFragment. * * @param {Node} node * @return {DocumentFragment} */ function nodeToFragment(node) { // if its a template tag and the browser supports it, // its content is already a document fragment. if (isRealTemplate(node)) { trimNode(node.content); return node.content; } // script template if (node.tagName === 'SCRIPT') { return stringToFragment(node.textContent); } // normal node, clone it to avoid mutating the original var clonedNode = cloneNode(node); var frag = document.createDocumentFragment(); var child; /* eslint-disable no-cond-assign */ while (child = clonedNode.firstChild) { /* eslint-enable no-cond-assign */ frag.appendChild(child); } trimNode(frag); return frag; } // Test for the presence of the Safari template cloning bug // https://bugs.webkit.org/showug.cgi?id=137755 var hasBrokenTemplate = (function () { /* istanbul ignore else */ if (inBrowser) { var a = document.createElement('div'); a.innerHTML = '<template>1</template>'; return !a.cloneNode(true).firstChild.innerHTML; } else { return false; } })(); // Test for IE10/11 textarea placeholder clone bug var hasTextareaCloneBug = (function () { /* istanbul ignore else */ if (inBrowser) { var t = document.createElement('textarea'); t.placeholder = 't'; return t.cloneNode(true).value === 't'; } else { return false; } })(); /** * 1. Deal with Safari cloning nested <template> bug by * manually cloning all template instances. * 2. Deal with IE10/11 textarea placeholder bug by setting * the correct value after cloning. * * @param {Element|DocumentFragment} node * @return {Element|DocumentFragment} */ function cloneNode(node) { if (!node.querySelectorAll) { return node.cloneNode(); } var res = node.cloneNode(true); var i, original, cloned; /* istanbul ignore if */ if (hasBrokenTemplate) { var tempClone = res; if (isRealTemplate(node)) { node = node.content; tempClone = res.content; } original = node.querySelectorAll('template'); if (original.length) { cloned = tempClone.querySelectorAll('template'); i = cloned.length; while (i--) { cloned[i].parentNode.replaceChild(cloneNode(original[i]), cloned[i]); } } } /* istanbul ignore if */ if (hasTextareaCloneBug) { if (node.tagName === 'TEXTAREA') { res.value = node.value; } else { original = node.querySelectorAll('textarea'); if (original.length) { cloned = res.querySelectorAll('textarea'); i = cloned.length; while (i--) { cloned[i].value = original[i].value; } } } } return res; } /** * Process the template option and normalizes it into a * a DocumentFragment that can be used as a partial or a * instance template. * * @param {*} template * Possible values include: * - DocumentFragment object * - Node object of type Template * - id selector: '#some-template-id' * - template string: '<div><span>{{msg}}</span></div>' * @param {Boolean} shouldClone * @param {Boolean} raw * inline HTML interpolation. Do not check for id * selector and keep whitespace in the string. * @return {DocumentFragment|undefined} */ function parseTemplate(template, shouldClone, raw) { var node, frag; // if the template is already a document fragment, // do nothing if (template instanceof DocumentFragment) { trimNode(template); return shouldClone ? cloneNode(template) : template; } if (typeof template === 'string') { // id selector if (!raw && template.charAt(0) === '#') { // id selector can be cached too frag = idSelectorCache.get(template); if (!frag) { node = document.getElementById(template.slice(1)); if (node) { frag = nodeToFragment(node); // save selector to cache idSelectorCache.put(template, frag); } } } else { // normal string template frag = stringToFragment(template, raw); } } else if (template.nodeType) { // a direct node frag = nodeToFragment(template); } return frag && shouldClone ? cloneNode(frag) : frag; } var template = Object.freeze({ cloneNode: cloneNode, parseTemplate: parseTemplate }); /** * Abstraction for a partially-compiled fragment. * Can optionally compile content with a child scope. * * @param {Function} linker * @param {Vue} vm * @param {DocumentFragment} frag * @param {Vue} [host] * @param {Object} [scope] */ function Fragment(linker, vm, frag, host, scope, parentFrag) { this.children = []; this.childFrags = []; this.vm = vm; this.scope = scope; this.inserted = false; this.parentFrag = parentFrag; if (parentFrag) { parentFrag.childFrags.push(this); } this.unlink = linker(vm, frag, host, scope, this); var single = this.single = frag.childNodes.length === 1 && // do not go single mode if the only node is an anchor !frag.childNodes[0].__vue_anchor; if (single) { this.node = frag.childNodes[0]; this.before = singleBefore; this.remove = singleRemove; } else { this.node = createAnchor('fragment-start'); this.end = createAnchor('fragment-end'); this.frag = frag; prepend(this.node, frag); frag.appendChild(this.end); this.before = multiBefore; this.remove = multiRemove; } this.node.__vfrag__ = this; } /** * Call attach/detach for all components contained within * this fragment. Also do so recursively for all child * fragments. * * @param {Function} hook */ Fragment.prototype.callHook = function (hook) { var i, l; for (i = 0, l = this.children.length; i < l; i++) { hook(this.children[i]); } for (i = 0, l = this.childFrags.length; i < l; i++) { this.childFrags[i].callHook(hook); } }; /** * Destroy the fragment. */ Fragment.prototype.destroy = function () { if (this.parentFrag) { this.parentFrag.childFrags.$remove(this); } this.unlink(); }; /** * Insert fragment before target, single node version * * @param {Node} target * @param {Boolean} withTransition */ function singleBefore(target, withTransition) { this.inserted = true; var method = withTransition !== false ? beforeWithTransition : before; method(this.node, target, this.vm); if (inDoc(this.node)) { this.callHook(attach); } } /** * Remove fragment, single node version */ function singleRemove() { this.inserted = false; var shouldCallRemove = inDoc(this.node); var self = this; self.callHook(destroyChild); removeWithTransition(this.node, this.vm, function () { if (shouldCallRemove) { self.callHook(detach); } self.destroy(); }); } /** * Insert fragment before target, multi-nodes version * * @param {Node} target * @param {Boolean} withTransition */ function multiBefore(target, withTransition) { this.inserted = true; var vm = this.vm; var method = withTransition !== false ? beforeWithTransition : before; mapNodeRange(this.node, this.end, function (node) { method(node, target, vm); }); if (inDoc(this.node)) { this.callHook(attach); } } /** * Remove fragment, multi-nodes version */ function multiRemove() { this.inserted = false; var self = this; var shouldCallRemove = inDoc(this.node); self.callHook(destroyChild); removeNodeRange(this.node, this.end, this.vm, this.frag, function () { if (shouldCallRemove) { self.callHook(detach); } self.destroy(); }); } /** * Call attach hook for a Vue instance. * * @param {Vue} child */ function attach(child) { if (!child._isAttached) { child._callHook('attached'); } } /** * Call destroy for all contained instances, * with remove:false and defer:true. * Defer is necessary because we need to * keep the children to call detach hooks * on them. * * @param {Vue} child */ function destroyChild(child) { child.$destroy(false, true); } /** * Call detach hook for a Vue instance. * * @param {Vue} child */ function detach(child) { if (child._isAttached) { child._callHook('detached'); } } var linkerCache = new Cache(5000); /** * A factory that can be used to create instances of a * fragment. Caches the compiled linker if possible. * * @param {Vue} vm * @param {Element|String} el */ function FragmentFactory(vm, el) { this.vm = vm; var template; var isString = typeof el === 'string'; if (isString || isTemplate(el)) { template = parseTemplate(el, true); } else { template = document.createDocumentFragment(); template.appendChild(el); } this.template = template; // linker can be cached, but only for components var linker; var cid = vm.constructor.cid; if (cid > 0) { var cacheId = cid + (isString ? el : el.outerHTML); linker = linkerCache.get(cacheId); if (!linker) { linker = compile(template, vm.$options, true); linkerCache.put(cacheId, linker); } } else { linker = compile(template, vm.$options, true); } this.linker = linker; } /** * Create a fragment instance with given host and scope. * * @param {Vue} host * @param {Object} scope * @param {Fragment} parentFrag */ FragmentFactory.prototype.create = function (host, scope, parentFrag) { var frag = cloneNode(this.template); return new Fragment(this.linker, this.vm, frag, host, scope, parentFrag); }; var vIf = { priority: IF, bind: function bind() { var el = this.el; if (!el.__vue__) { // check else block var next = el.nextElementSibling; if (next && getAttr(next, 'v-else') !== null) { remove(next); this.elseFactory = new FragmentFactory(this.vm, next); } // check main block this.anchor = createAnchor('v-if'); replace(el, this.anchor); this.factory = new FragmentFactory(this.vm, el); } else { 'development' !== 'production' && warn('v-if="' + this.expression + '" cannot be ' + 'used on an instance root element.'); this.invalid = true; } }, update: function update(value) { if (this.invalid) return; if (value) { if (!this.frag) { this.insert(); } } else { this.remove(); } }, insert: function insert() { if (this.elseFrag) { this.elseFrag.remove(); this.elseFrag = null; } this.frag = this.factory.create(this._host, this._scope, this._frag); this.frag.before(this.anchor); }, remove: function remove() { if (this.frag) { this.frag.remove(); this.frag = null; } if (this.elseFactory && !this.elseFrag) { this.elseFrag = this.elseFactory.create(this._host, this._scope, this._frag); this.elseFrag.before(this.anchor); } }, unbind: function unbind() { if (this.frag) { this.frag.destroy(); } } }; var uid$1 = 0; var vFor = { priority: FOR, params: ['track-by', 'stagger', 'enter-stagger', 'leave-stagger'], bind: function bind() { // support "item in items" syntax var inMatch = this.expression.match(/(.*) in (.*)/); if (inMatch) { var itMatch = inMatch[1].match(/\((.*),(.*)\)/); if (itMatch) { this.iterator = itMatch[1].trim(); this.alias = itMatch[2].trim(); } else { this.alias = inMatch[1].trim(); } this.expression = inMatch[2]; } if (!this.alias) { 'development' !== 'production' && warn('Alias is required in v-for.'); return; } // uid as a cache identifier this.id = '__v-for__' + ++uid$1; // check if this is an option list, // so that we know if we need to update the <select>'s // v-model when the option list has changed. // because v-model has a lower priority than v-for, // the v-model is not bound here yet, so we have to // retrive it in the actual updateModel() function. var tag = this.el.tagName; this.isOption = (tag === 'OPTION' || tag === 'OPTGROUP') && this.el.parentNode.tagName === 'SELECT'; // setup anchor nodes this.start = createAnchor('v-for-start'); this.end = createAnchor('v-for-end'); replace(this.el, this.end); before(this.start, this.end); // cache this.cache = Object.create(null); // fragment factory this.factory = new FragmentFactory(this.vm, this.el); }, update: function update(data) { this.diff(data); this.updateRef(); this.updateModel(); }, /** * Diff, based on new data and old data, determine the * minimum amount of DOM manipulations needed to make the * DOM reflect the new data Array. * * The algorithm diffs the new data Array by storing a * hidden reference to an owner vm instance on previously * seen data. This allows us to achieve O(n) which is * better than a levenshtein distance based algorithm, * which is O(m * n). * * @param {Array} data */ diff: function diff(data) { // check if the Array was converted from an Object var item = data[0]; var convertedFromObject = this.fromObject = isObject(item) && hasOwn(item, '$key') && hasOwn(item, '$value'); var trackByKey = this.params.trackBy; var oldFrags = this.frags; var frags = this.frags = new Array(data.length); var alias = this.alias; var iterator = this.iterator; var start = this.start; var end = this.end; var inDocument = inDoc(start); var init = !oldFrags; var i, l, frag, key, value, primitive; // First pass, go through the new Array and fill up // the new frags array. If a piece of data has a cached // instance for it, we reuse it. Otherwise build a new // instance. for (i = 0, l = data.length; i < l; i++) { item = data[i]; key = convertedFromObject ? item.$key : null; value = convertedFromObject ? item.$value : item; primitive = !isObject(value); frag = !init && this.getCachedFrag(value, i, key); if (frag) { // reusable fragment frag.reused = true; // update $index frag.scope.$index = i; // update $key if (key) { frag.scope.$key = key; } // update iterator if (iterator) { frag.scope[iterator] = key !== null ? key : i; } // update data for track-by, object repeat & // primitive values. if (trackByKey || convertedFromObject || primitive) { frag.scope[alias] = value; } } else { // new isntance frag = this.create(value, alias, i, key); frag.fresh = !init; } frags[i] = frag; if (init) { frag.before(end); } } // we're done for the initial render. if (init) { return; } // Second pass, go through the old fragments and // destroy those who are not reused (and remove them // from cache) var removalIndex = 0; var totalRemoved = oldFrags.length - frags.length; for (i = 0, l = oldFrags.length; i < l; i++) { frag = oldFrags[i]; if (!frag.reused) { this.deleteCachedFrag(frag); this.remove(frag, removalIndex++, totalRemoved, inDocument); } } // Final pass, move/insert new fragments into the // right place. var targetPrev, prevEl, currentPrev; var insertionIndex = 0; for (i = 0, l = frags.length; i < l; i++) { frag = frags[i]; // this is the frag that we should be after targetPrev = frags[i - 1]; prevEl = targetPrev ? targetPrev.staggerCb ? targetPrev.staggerAnchor : targetPrev.end || targetPrev.node : start; if (frag.reused && !frag.staggerCb) { currentPrev = findPrevFrag(frag, start, this.id); if (currentPrev !== targetPrev && (!currentPrev || // optimization for moving a single item. // thanks to suggestions by @livoras in #1807 findPrevFrag(currentPrev, start, this.id) !== targetPrev)) { this.move(frag, prevEl); } } else { // new instance, or still in stagger. // insert with updated stagger index. this.insert(frag, insertionIndex++, prevEl, inDocument); } frag.reused = frag.fresh = false; } }, /** * Create a new fragment instance. * * @param {*} value * @param {String} alias * @param {Number} index * @param {String} [key] * @return {Fragment} */ create: function create(value, alias, index, key) { var host = this._host; // create iteration scope var parentScope = this._scope || this.vm; var scope = Object.create(parentScope); // ref holder for the scope scope.$refs = Object.create(parentScope.$refs); scope.$els = Object.create(parentScope.$els); // make sure point $parent to parent scope scope.$parent = parentScope; // for two-way binding on alias scope.$forContext = this; // define scope properties defineReactive(scope, alias, value); defineReactive(scope, '$index', index); if (key) { defineReactive(scope, '$key', key); } else if (scope.$key) { // avoid accidental fallback def(scope, '$key', null); } if (this.iterator) { defineReactive(scope, this.iterator, key !== null ? key : index); } var frag = this.factory.create(host, scope, this._frag); frag.forId = this.id; this.cacheFrag(value, frag, index, key); return frag; }, /** * Update the v-ref on owner vm. */ updateRef: function updateRef() { var ref = this.descriptor.ref; if (!ref) return; var hash = (this._scope || this.vm).$refs; var refs; if (!this.fromObject) { refs = this.frags.map(findVmFromFrag); } else { refs = {}; this.frags.forEach(function (frag) { refs[frag.scope.$key] = findVmFromFrag(frag); }); } hash[ref] = refs; }, /** * For option lists, update the containing v-model on * parent <select>. */ updateModel: function updateModel() { if (this.isOption) { var parent = this.start.parentNode; var model = parent && parent.__v_model; if (model) { model.forceUpdate(); } } }, /** * Insert a fragment. Handles staggering. * * @param {Fragment} frag * @param {Number} index * @param {Node} prevEl * @param {Boolean} inDocument */ insert: function insert(frag, index, prevEl, inDocument) { if (frag.staggerCb) { frag.staggerCb.cancel(); frag.staggerCb = null; } var staggerAmount = this.getStagger(frag, index, null, 'enter'); if (inDocument && staggerAmount) { // create an anchor and insert it synchronously, // so that we can resolve the correct order without // worrying about some elements not inserted yet var anchor = frag.staggerAnchor; if (!anchor) { anchor = frag.staggerAnchor = createAnchor('stagger-anchor'); anchor.__vfrag__ = frag; } after(anchor, prevEl); var op = frag.staggerCb = cancellable(function () { frag.staggerCb = null; frag.before(anchor); remove(anchor); }); setTimeout(op, staggerAmount); } else { frag.before(prevEl.nextSibling); } }, /** * Remove a fragment. Handles staggering. * * @param {Fragment} frag * @param {Number} index * @param {Number} total * @param {Boolean} inDocument */ remove: function remove(frag, index, total, inDocument) { if (frag.staggerCb) { frag.staggerCb.cancel(); frag.staggerCb = null; // it's not possible for the same frag to be removed // twice, so if we have a pending stagger callback, // it means this frag is queued for enter but removed // before its transition started. Since it is already // destroyed, we can just leave it in detached state. return; } var staggerAmount = this.getStagger(frag, index, total, 'leave'); if (inDocument && staggerAmount) { var op = frag.staggerCb = cancellable(function () { frag.staggerCb = null; frag.remove(); }); setTimeout(op, staggerAmount); } else { frag.remove(); } }, /** * Move a fragment to a new position. * Force no transition. * * @param {Fragment} frag * @param {Node} prevEl */ move: function move(frag, prevEl) { frag.before(prevEl.nextSibling, false); }, /** * Cache a fragment using track-by or the object key. * * @param {*} value * @param {Fragment} frag * @param {Number} index * @param {String} [key] */ cacheFrag: function cacheFrag(value, frag, index, key) { var trackByKey = this.params.trackBy; var cache = this.cache; var primitive = !isObject(value); var id; if (key || trackByKey || primitive) { id = trackByKey ? trackByKey === '$index' ? index : value[trackByKey] : key || value; if (!cache[id]) { cache[id] = frag; } else if (trackByKey !== '$index') { 'development' !== 'production' && this.warnDuplicate(value); } } else { id = this.id; if (hasOwn(value, id)) { if (value[id] === null) { value[id] = frag; } else { 'development' !== 'production' && this.warnDuplicate(value); } } else { def(value, id, frag); } } frag.raw = value; }, /** * Get a cached fragment from the value/index/key * * @param {*} value * @param {Number} index * @param {String} key * @return {Fragment} */ getCachedFrag: function getCachedFrag(value, index, key) { var trackByKey = this.params.trackBy; var primitive = !isObject(value); var frag; if (key || trackByKey || primitive) { var id = trackByKey ? trackByKey === '$index' ? index : value[trackByKey] : key || value; frag = this.cache[id]; } else { frag = value[this.id]; } if (frag && (frag.reused || frag.fresh)) { 'development' !== 'production' && this.warnDuplicate(value); } return frag; }, /** * Delete a fragment from cache. * * @param {Fragment} frag */ deleteCachedFrag: function deleteCachedFrag(frag) { var value = frag.raw; var trackByKey = this.params.trackBy; var scope = frag.scope; var index = scope.$index; // fix #948: avoid accidentally fall through to // a parent repeater which happens to have $key. var key = hasOwn(scope, '$key') && scope.$key; var primitive = !isObject(value); if (trackByKey || key || primitive) { var id = trackByKey ? trackByKey === '$index' ? index : value[trackByKey] : key || value; this.cache[id] = null; } else { value[this.id] = null; frag.raw = null; } }, /** * Get the stagger amount for an insertion/removal. * * @param {Fragment} frag * @param {Number} index * @param {Number} total * @param {String} type */ getStagger: function getStagger(frag, index, total, type) { type = type + 'Stagger'; var trans = frag.node.__v_trans; var hooks = trans && trans.hooks; var hook = hooks && (hooks[type] || hooks.stagger); return hook ? hook.call(frag, index, total) : index * parseInt(this.params[type] || this.params.stagger, 10); }, /** * Pre-process the value before piping it through the * filters. This is passed to and called by the watcher. */ _preProcess: function _preProcess(value) { // regardless of type, store the un-filtered raw value. this.rawValue = value; return value; }, /** * Post-process the value after it has been piped through * the filters. This is passed to and called by the watcher. * * It is necessary for this to be called during the * wathcer's dependency collection phase because we want * the v-for to update when the source Object is mutated. */ _postProcess: function _postProcess(value) { if (isArray(value)) { return value; } else if (isPlainObject(value)) { // convert plain object to array. var keys = Object.keys(value); var i = keys.length; var res = new Array(i); var key; while (i--) { key = keys[i]; res[i] = { $key: key, $value: value[key] }; } return res; } else { if (typeof value === 'number') { value = range(value); } return value || []; } }, unbind: function unbind() { if (this.descriptor.ref) { (this._scope || this.vm).$refs[this.descriptor.ref] = null; } if (this.frags) { var i = this.frags.length; var frag; while (i--) { frag = this.frags[i]; this.deleteCachedFrag(frag); frag.destroy(); } } } }; /** * Helper to find the previous element that is a fragment * anchor. This is necessary because a destroyed frag's * element could still be lingering in the DOM before its * leaving transition finishes, but its inserted flag * should have been set to false so we can skip them. * * If this is a block repeat, we want to make sure we only * return frag that is bound to this v-for. (see #929) * * @param {Fragment} frag * @param {Comment|Text} anchor * @param {String} id * @return {Fragment} */ function findPrevFrag(frag, anchor, id) { var el = frag.node.previousSibling; /* istanbul ignore if */ if (!el) return; frag = el.__vfrag__; while ((!frag || frag.forId !== id || !frag.inserted) && el !== anchor) { el = el.previousSibling; /* istanbul ignore if */ if (!el) return; frag = el.__vfrag__; } return frag; } /** * Find a vm from a fragment. * * @param {Fragment} frag * @return {Vue|undefined} */ function findVmFromFrag(frag) { var node = frag.node; // handle multi-node frag if (frag.end) { while (!node.__vue__ && node !== frag.end && node.nextSibling) { node = node.nextSibling; } } return node.__vue__; } /** * Create a range array from given number. * * @param {Number} n * @return {Array} */ function range(n) { var i = -1; var ret = new Array(n); while (++i < n) { ret[i] = i; } return ret; } if ('development' !== 'production') { vFor.warnDuplicate = function (value) { warn('Duplicate value found in v-for="' + this.descriptor.raw + '": ' + JSON.stringify(value) + '. Use track-by="$index" if ' + 'you are expecting duplicate values.'); }; } var html = { bind: function bind() { // a comment node means this is a binding for // {{{ inline unescaped html }}} if (this.el.nodeType === 8) { // hold nodes this.nodes = []; // replace the placeholder with proper anchor this.anchor = createAnchor('v-html'); replace(this.el, this.anchor); } }, update: function update(value) { value = _toString(value); if (this.nodes) { this.swap(value); } else { this.el.innerHTML = value; } }, swap: function swap(value) { // remove old nodes var i = this.nodes.length; while (i--) { remove(this.nodes[i]); } // convert new value to a fragment // do not attempt to retrieve from id selector var frag = parseTemplate(value, true, true); // save a reference to these nodes so we can remove later this.nodes = toArray(frag.childNodes); before(frag, this.anchor); } }; var text = { bind: function bind() { this.attr = this.el.nodeType === 3 ? 'data' : 'textContent'; }, update: function update(value) { this.el[this.attr] = _toString(value); } }; // must export plain object var publicDirectives = { text: text, html: html, 'for': vFor, 'if': vIf, show: show, model: model, on: on, bind: bind, el: el, ref: ref, cloak: cloak }; var queue$1 = []; var queued = false; /** * Push a job into the queue. * * @param {Function} job */ function pushJob(job) { queue$1.push(job); if (!queued) { queued = true; nextTick(flush); } } /** * Flush the queue, and do one forced reflow before * triggering transitions. */ function flush() { // Force layout var f = document.documentElement.offsetHeight; for (var i = 0; i < queue$1.length; i++) { queue$1[i](); } queue$1 = []; queued = false; // dummy return, so js linters don't complain about // unused variable f return f; } var TYPE_TRANSITION = 1; var TYPE_ANIMATION = 2; var transDurationProp = transitionProp + 'Duration'; var animDurationProp = animationProp + 'Duration'; /** * A Transition object that encapsulates the state and logic * of the transition. * * @param {Element} el * @param {String} id * @param {Object} hooks * @param {Vue} vm */ function Transition(el, id, hooks, vm) { this.id = id; this.el = el; this.enterClass = id + '-enter'; this.leaveClass = id + '-leave'; this.hooks = hooks; this.vm = vm; // async state this.pendingCssEvent = this.pendingCssCb = this.cancel = this.pendingJsCb = this.op = this.cb = null; this.justEntered = false; this.entered = this.left = false; this.typeCache = {}; // bind var self = this;['enterNextTick', 'enterDone', 'leaveNextTick', 'leaveDone'].forEach(function (m) { self[m] = bind$1(self[m], self); }); } var p$1 = Transition.prototype; /** * Start an entering transition. * * 1. enter transition triggered * 2. call beforeEnter hook * 3. add enter class * 4. insert/show element * 5. call enter hook (with possible explicit js callback) * 6. reflow * 7. based on transition type: * - transition: * remove class now, wait for transitionend, * then done if there's no explicit js callback. * - animation: * wait for animationend, remove class, * then done if there's no explicit js callback. * - no css transition: * done now if there's no explicit js callback. * 8. wait for either done or js callback, then call * afterEnter hook. * * @param {Function} op - insert/show the element * @param {Function} [cb] */ p$1.enter = function (op, cb) { this.cancelPending(); this.callHook('beforeEnter'); this.cb = cb; addClass(this.el, this.enterClass); op(); this.entered = false; this.callHookWithCb('enter'); if (this.entered) { return; // user called done synchronously. } this.cancel = this.hooks && this.hooks.enterCancelled; pushJob(this.enterNextTick); }; /** * The "nextTick" phase of an entering transition, which is * to be pushed into a queue and executed after a reflow so * that removing the class can trigger a CSS transition. */ p$1.enterNextTick = function () { // Important hack: // in Chrome, if a just-entered element is applied the // leave class while its interpolated property still has // a very small value (within one frame), Chrome will // skip the leave transition entirely and not firing the // transtionend event. Therefore we need to protected // against such cases using a one-frame timeout. this.justEntered = true; var self = this; setTimeout(function () { self.justEntered = false; }, 17); var enterDone = this.enterDone; var type = this.getCssTransitionType(this.enterClass); if (!this.pendingJsCb) { if (type === TYPE_TRANSITION) { // trigger transition by removing enter class now removeClass(this.el, this.enterClass); this.setupCssCb(transitionEndEvent, enterDone); } else if (type === TYPE_ANIMATION) { this.setupCssCb(animationEndEvent, enterDone); } else { enterDone(); } } else if (type === TYPE_TRANSITION) { removeClass(this.el, this.enterClass); } }; /** * The "cleanup" phase of an entering transition. */ p$1.enterDone = function () { this.entered = true; this.cancel = this.pendingJsCb = null; removeClass(this.el, this.enterClass); this.callHook('afterEnter'); if (this.cb) this.cb(); }; /** * Start a leaving transition. * * 1. leave transition triggered. * 2. call beforeLeave hook * 3. add leave class (trigger css transition) * 4. call leave hook (with possible explicit js callback) * 5. reflow if no explicit js callback is provided * 6. based on transition type: * - transition or animation: * wait for end event, remove class, then done if * there's no explicit js callback. * - no css transition: * done if there's no explicit js callback. * 7. wait for either done or js callback, then call * afterLeave hook. * * @param {Function} op - remove/hide the element * @param {Function} [cb] */ p$1.leave = function (op, cb) { this.cancelPending(); this.callHook('beforeLeave'); this.op = op; this.cb = cb; addClass(this.el, this.leaveClass); this.left = false; this.callHookWithCb('leave'); if (this.left) { return; // user called done synchronously. } this.cancel = this.hooks && this.hooks.leaveCancelled; // only need to handle leaveDone if // 1. the transition is already done (synchronously called // by the user, which causes this.op set to null) // 2. there's no explicit js callback if (this.op && !this.pendingJsCb) { // if a CSS transition leaves immediately after enter, // the transitionend event never fires. therefore we // detect such cases and end the leave immediately. if (this.justEntered) { this.leaveDone(); } else { pushJob(this.leaveNextTick); } } }; /** * The "nextTick" phase of a leaving transition. */ p$1.leaveNextTick = function () { var type = this.getCssTransitionType(this.leaveClass); if (type) { var event = type === TYPE_TRANSITION ? transitionEndEvent : animationEndEvent; this.setupCssCb(event, this.leaveDone); } else { this.leaveDone(); } }; /** * The "cleanup" phase of a leaving transition. */ p$1.leaveDone = function () { this.left = true; this.cancel = this.pendingJsCb = null; this.op(); removeClass(this.el, this.leaveClass); this.callHook('afterLeave'); if (this.cb) this.cb(); this.op = null; }; /** * Cancel any pending callbacks from a previously running * but not finished transition. */ p$1.cancelPending = function () { this.op = this.cb = null; var hasPending = false; if (this.pendingCssCb) { hasPending = true; off(this.el, this.pendingCssEvent, this.pendingCssCb); this.pendingCssEvent = this.pendingCssCb = null; } if (this.pendingJsCb) { hasPending = true; this.pendingJsCb.cancel(); this.pendingJsCb = null; } if (hasPending) { removeClass(this.el, this.enterClass); removeClass(this.el, this.leaveClass); } if (this.cancel) { this.cancel.call(this.vm, this.el); this.cancel = null; } }; /** * Call a user-provided synchronous hook function. * * @param {String} type */ p$1.callHook = function (type) { if (this.hooks && this.hooks[type]) { this.hooks[type].call(this.vm, this.el); } }; /** * Call a user-provided, potentially-async hook function. * We check for the length of arguments to see if the hook * expects a `done` callback. If true, the transition's end * will be determined by when the user calls that callback; * otherwise, the end is determined by the CSS transition or * animation. * * @param {String} type */ p$1.callHookWithCb = function (type) { var hook = this.hooks && this.hooks[type]; if (hook) { if (hook.length > 1) { this.pendingJsCb = cancellable(this[type + 'Done']); } hook.call(this.vm, this.el, this.pendingJsCb); } }; /** * Get an element's transition type based on the * calculated styles. * * @param {String} className * @return {Number} */ p$1.getCssTransitionType = function (className) { /* istanbul ignore if */ if (!transitionEndEvent || // skip CSS transitions if page is not visible - // this solves the issue of transitionend events not // firing until the page is visible again. // pageVisibility API is supported in IE10+, same as // CSS transitions. document.hidden || // explicit js-only transition this.hooks && this.hooks.css === false || // element is hidden isHidden(this.el)) { return; } var type = this.typeCache[className]; if (type) return type; var inlineStyles = this.el.style; var computedStyles = window.getComputedStyle(this.el); var transDuration = inlineStyles[transDurationProp] || computedStyles[transDurationProp]; if (transDuration && transDuration !== '0s') { type = TYPE_TRANSITION; } else { var animDuration = inlineStyles[animDurationProp] || computedStyles[animDurationProp]; if (animDuration && animDuration !== '0s') { type = TYPE_ANIMATION; } } if (type) { this.typeCache[className] = type; } return type; }; /** * Setup a CSS transitionend/animationend callback. * * @param {String} event * @param {Function} cb */ p$1.setupCssCb = function (event, cb) { this.pendingCssEvent = event; var self = this; var el = this.el; var onEnd = this.pendingCssCb = function (e) { if (e.target === el) { off(el, event, onEnd); self.pendingCssEvent = self.pendingCssCb = null; if (!self.pendingJsCb && cb) { cb(); } } }; on$1(el, event, onEnd); }; /** * Check if an element is hidden - in that case we can just * skip the transition alltogether. * * @param {Element} el * @return {Boolean} */ function isHidden(el) { return !(el.offsetWidth || el.offsetHeight || el.getClientRects().length); } var transition = { priority: TRANSITION, update: function update(id, oldId) { var el = this.el; // resolve on owner vm var hooks = resolveAsset(this.vm.$options, 'transitions', id); id = id || 'v'; // apply on closest vm el.__v_trans = new Transition(el, id, hooks, this.el.__vue__ || this.vm); if (oldId) { removeClass(el, oldId + '-transition'); } addClass(el, id + '-transition'); } }; var bindingModes = config._propBindingModes; var propDef = { bind: function bind() { var child = this.vm; var parent = child._context; // passed in from compiler directly var prop = this.descriptor.prop; var childKey = prop.path; var parentKey = prop.parentPath; var twoWay = prop.mode === bindingModes.TWO_WAY; var parentWatcher = this.parentWatcher = new Watcher(parent, parentKey, function (val) { val = coerceProp(prop, val); if (assertProp(prop, val)) { child[childKey] = val; } }, { twoWay: twoWay, filters: prop.filters, // important: props need to be observed on the // v-for scope if present scope: this._scope }); // set the child initial value. initProp(child, prop, parentWatcher.value); // setup two-way binding if (twoWay) { // important: defer the child watcher creation until // the created hook (after data observation) var self = this; child.$once('pre-hook:created', function () { self.childWatcher = new Watcher(child, childKey, function (val) { parentWatcher.set(val); }, { // ensure sync upward before parent sync down. // this is necessary in cases e.g. the child // mutates a prop array, then replaces it. (#1683) sync: true }); }); } }, unbind: function unbind() { this.parentWatcher.teardown(); if (this.childWatcher) { this.childWatcher.teardown(); } } }; var component = { priority: COMPONENT, params: ['keep-alive', 'transition-mode', 'inline-template'], /** * Setup. Two possible usages: * * - static: * <comp> or <div v-component="comp"> * * - dynamic: * <component :is="view"> */ bind: function bind() { if (!this.el.__vue__) { // keep-alive cache this.keepAlive = this.params.keepAlive; if (this.keepAlive) { this.cache = {}; } // check inline-template if (this.params.inlineTemplate) { // extract inline template as a DocumentFragment this.inlineTemplate = extractContent(this.el, true); } // component resolution related state this.pendingComponentCb = this.Component = null; // transition related state this.pendingRemovals = 0; this.pendingRemovalCb = null; // create a ref anchor this.anchor = createAnchor('v-component'); replace(this.el, this.anchor); // remove is attribute. // this is removed during compilation, but because compilation is // cached, when the component is used elsewhere this attribute // will remain at link time. this.el.removeAttribute('is'); // remove ref, same as above if (this.descriptor.ref) { this.el.removeAttribute('v-ref:' + hyphenate(this.descriptor.ref)); } // if static, build right now. if (this.literal) { this.setComponent(this.expression); } } else { 'development' !== 'production' && warn('cannot mount component "' + this.expression + '" ' + 'on already mounted element: ' + this.el); } }, /** * Public update, called by the watcher in the dynamic * literal scenario, e.g. <component :is="view"> */ update: function update(value) { if (!this.literal) { this.setComponent(value); } }, /** * Switch dynamic components. May resolve the component * asynchronously, and perform transition based on * specified transition mode. Accepts a few additional * arguments specifically for vue-router. * * The callback is called when the full transition is * finished. * * @param {String} value * @param {Function} [cb] */ setComponent: function setComponent(value, cb) { this.invalidatePending(); if (!value) { // just remove current this.unbuild(true); this.remove(this.childVM, cb); this.childVM = null; } else { var self = this; this.resolveComponent(value, function () { self.mountComponent(cb); }); } }, /** * Resolve the component constructor to use when creating * the child vm. */ resolveComponent: function resolveComponent(id, cb) { var self = this; this.pendingComponentCb = cancellable(function (Component) { self.ComponentName = Component.options.name || id; self.Component = Component; cb(); }); this.vm._resolveComponent(id, this.pendingComponentCb); }, /** * Create a new instance using the current constructor and * replace the existing instance. This method doesn't care * whether the new component and the old one are actually * the same. * * @param {Function} [cb] */ mountComponent: function mountComponent(cb) { // actual mount this.unbuild(true); var self = this; var activateHook = this.Component.options.activate; var cached = this.getCached(); var newComponent = this.build(); if (activateHook && !cached) { this.waitingFor = newComponent; activateHook.call(newComponent, function () { if (self.waitingFor !== newComponent) { return; } self.waitingFor = null; self.transition(newComponent, cb); }); } else { // update ref for kept-alive component if (cached) { newComponent._updateRef(); } this.transition(newComponent, cb); } }, /** * When the component changes or unbinds before an async * constructor is resolved, we need to invalidate its * pending callback. */ invalidatePending: function invalidatePending() { if (this.pendingComponentCb) { this.pendingComponentCb.cancel(); this.pendingComponentCb = null; } }, /** * Instantiate/insert a new child vm. * If keep alive and has cached instance, insert that * instance; otherwise build a new one and cache it. * * @param {Object} [extraOptions] * @return {Vue} - the created instance */ build: function build(extraOptions) { var cached = this.getCached(); if (cached) { return cached; } if (this.Component) { // default options var options = { name: this.ComponentName, el: cloneNode(this.el), template: this.inlineTemplate, // make sure to add the child with correct parent // if this is a transcluded component, its parent // should be the transclusion host. parent: this._host || this.vm, // if no inline-template, then the compiled // linker can be cached for better performance. _linkerCachable: !this.inlineTemplate, _ref: this.descriptor.ref, _asComponent: true, _isRouterView: this._isRouterView, // if this is a transcluded component, context // will be the common parent vm of this instance // and its host. _context: this.vm, // if this is inside an inline v-for, the scope // will be the intermediate scope created for this // repeat fragment. this is used for linking props // and container directives. _scope: this._scope, // pass in the owner fragment of this component. // this is necessary so that the fragment can keep // track of its contained components in order to // call attach/detach hooks for them. _frag: this._frag }; // extra options // in 1.0.0 this is used by vue-router only /* istanbul ignore if */ if (extraOptions) { extend(options, extraOptions); } var child = new this.Component(options); if (this.keepAlive) { this.cache[this.Component.cid] = child; } /* istanbul ignore if */ if ('development' !== 'production' && this.el.hasAttribute('transition') && child._isFragment) { warn('Transitions will not work on a fragment instance. ' + 'Template: ' + child.$options.template); } return child; } }, /** * Try to get a cached instance of the current component. * * @return {Vue|undefined} */ getCached: function getCached() { return this.keepAlive && this.cache[this.Component.cid]; }, /** * Teardown the current child, but defers cleanup so * that we can separate the destroy and removal steps. * * @param {Boolean} defer */ unbuild: function unbuild(defer) { if (this.waitingFor) { this.waitingFor.$destroy(); this.waitingFor = null; } var child = this.childVM; if (!child || this.keepAlive) { if (child) { // remove ref child._updateRef(true); } return; } // the sole purpose of `deferCleanup` is so that we can // "deactivate" the vm right now and perform DOM removal // later. child.$destroy(false, defer); }, /** * Remove current destroyed child and manually do * the cleanup after removal. * * @param {Function} cb */ remove: function remove(child, cb) { var keepAlive = this.keepAlive; if (child) { // we may have a component switch when a previous // component is still being transitioned out. // we want to trigger only one lastest insertion cb // when the existing transition finishes. (#1119) this.pendingRemovals++; this.pendingRemovalCb = cb; var self = this; child.$remove(function () { self.pendingRemovals--; if (!keepAlive) child._cleanup(); if (!self.pendingRemovals && self.pendingRemovalCb) { self.pendingRemovalCb(); self.pendingRemovalCb = null; } }); } else if (cb) { cb(); } }, /** * Actually swap the components, depending on the * transition mode. Defaults to simultaneous. * * @param {Vue} target * @param {Function} [cb] */ transition: function transition(target, cb) { var self = this; var current = this.childVM; // for devtool inspection if ('development' !== 'production') { if (current) current._inactive = true; target._inactive = false; } this.childVM = target; switch (self.params.transitionMode) { case 'in-out': target.$before(self.anchor, function () { self.remove(current, cb); }); break; case 'out-in': self.remove(current, function () { target.$before(self.anchor, cb); }); break; default: self.remove(current); target.$before(self.anchor, cb); } }, /** * Unbind. */ unbind: function unbind() { this.invalidatePending(); // Do not defer cleanup when unbinding this.unbuild(); // destroy all keep-alive cached instances if (this.cache) { for (var key in this.cache) { this.cache[key].$destroy(); } this.cache = null; } } }; var vClass = { deep: true, update: function update(value) { if (value && typeof value === 'string') { this.handleObject(stringToObject(value)); } else if (isPlainObject(value)) { this.handleObject(value); } else if (isArray(value)) { this.handleArray(value); } else { this.cleanup(); } }, handleObject: function handleObject(value) { this.cleanup(value); var keys = this.prevKeys = Object.keys(value); for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; if (value[key]) { addClass(this.el, key); } else { removeClass(this.el, key); } } }, handleArray: function handleArray(value) { this.cleanup(value); for (var i = 0, l = value.length; i < l; i++) { if (value[i]) { addClass(this.el, value[i]); } } this.prevKeys = value.slice(); }, cleanup: function cleanup(value) { if (this.prevKeys) { var i = this.prevKeys.length; while (i--) { var key = this.prevKeys[i]; if (key && (!value || !contains$1(value, key))) { removeClass(this.el, key); } } } } }; function stringToObject(value) { var res = {}; var keys = value.trim().split(/\s+/); var i = keys.length; while (i--) { res[keys[i]] = true; } return res; } function contains$1(value, key) { return isArray(value) ? value.indexOf(key) > -1 : hasOwn(value, key); } var internalDirectives = { style: style, 'class': vClass, component: component, prop: propDef, transition: transition }; var propBindingModes = config._propBindingModes; var empty = {}; // regexes var identRE$1 = /^[$_a-zA-Z]+[\w$]*$/; var settablePathRE = /^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*|\[[^\[\]]+\])*$/; /** * Compile props on a root element and return * a props link function. * * @param {Element|DocumentFragment} el * @param {Array} propOptions * @return {Function} propsLinkFn */ function compileProps(el, propOptions) { var props = []; var names = Object.keys(propOptions); var i = names.length; var options, name, attr, value, path, parsed, prop; while (i--) { name = names[i]; options = propOptions[name] || empty; if ('development' !== 'production' && name === '$data') { warn('Do not use $data as prop.'); continue; } // props could contain dashes, which will be // interpreted as minus calculations by the parser // so we need to camelize the path here path = camelize(name); if (!identRE$1.test(path)) { 'development' !== 'production' && warn('Invalid prop key: "' + name + '". Prop keys ' + 'must be valid identifiers.'); continue; } prop = { name: name, path: path, options: options, mode: propBindingModes.ONE_WAY, raw: null }; attr = hyphenate(name); // first check dynamic version if ((value = getBindAttr(el, attr)) === null) { if ((value = getBindAttr(el, attr + '.sync')) !== null) { prop.mode = propBindingModes.TWO_WAY; } else if ((value = getBindAttr(el, attr + '.once')) !== null) { prop.mode = propBindingModes.ONE_TIME; } } if (value !== null) { // has dynamic binding! prop.raw = value; parsed = parseDirective(value); value = parsed.expression; prop.filters = parsed.filters; // check binding type if (isLiteral(value)) { // for expressions containing literal numbers and // booleans, there's no need to setup a prop binding, // so we can optimize them as a one-time set. prop.optimizedLiteral = true; } else { prop.dynamic = true; // check non-settable path for two-way bindings if ('development' !== 'production' && prop.mode === propBindingModes.TWO_WAY && !settablePathRE.test(value)) { prop.mode = propBindingModes.ONE_WAY; warn('Cannot bind two-way prop with non-settable ' + 'parent path: ' + value); } } prop.parentPath = value; // warn required two-way if ('development' !== 'production' && options.twoWay && prop.mode !== propBindingModes.TWO_WAY) { warn('Prop "' + name + '" expects a two-way binding type.'); } } else if ((value = getAttr(el, attr)) !== null) { // has literal binding! prop.raw = value; } else if (options.required) { // warn missing required 'development' !== 'production' && warn('Missing required prop: ' + name); } // push prop props.push(prop); } return makePropsLinkFn(props); } /** * Build a function that applies props to a vm. * * @param {Array} props * @return {Function} propsLinkFn */ function makePropsLinkFn(props) { return function propsLinkFn(vm, scope) { // store resolved props info vm._props = {}; var i = props.length; var prop, path, options, value, raw; while (i--) { prop = props[i]; raw = prop.raw; path = prop.path; options = prop.options; vm._props[path] = prop; if (raw === null) { // initialize absent prop initProp(vm, prop, getDefault(vm, options)); } else if (prop.dynamic) { // dynamic prop if (vm._context) { if (prop.mode === propBindingModes.ONE_TIME) { // one time binding value = (scope || vm._context).$get(prop.parentPath); initProp(vm, prop, value); } else { // dynamic binding vm._bindDir({ name: 'prop', def: propDef, prop: prop }, null, null, scope); // el, host, scope } } else { 'development' !== 'production' && warn('Cannot bind dynamic prop on a root instance' + ' with no parent: ' + prop.name + '="' + raw + '"'); } } else if (prop.optimizedLiteral) { // optimized literal, cast it and just set once var stripped = stripQuotes(raw); value = stripped === raw ? toBoolean(toNumber(raw)) : stripped; initProp(vm, prop, value); } else { // string literal, but we need to cater for // Boolean props with no value value = options.type === Boolean && raw === '' ? true : raw; initProp(vm, prop, value); } } }; } /** * Get the default value of a prop. * * @param {Vue} vm * @param {Object} options * @return {*} */ function getDefault(vm, options) { // no default, return undefined if (!hasOwn(options, 'default')) { // absent boolean value defaults to false return options.type === Boolean ? false : undefined; } var def = options['default']; // warn against non-factory defaults for Object & Array if (isObject(def)) { 'development' !== 'production' && warn('Object/Array as default prop values will be shared ' + 'across multiple instances. Use a factory function ' + 'to return the default value instead.'); } // call factory function for non-Function types return typeof def === 'function' && options.type !== Function ? def.call(vm) : def; } // special binding prefixes var bindRE = /^v-bind:|^:/; var onRE = /^v-on:|^@/; var argRE = /:(.*)$/; var modifierRE = /\.[^\.]+/g; var transitionRE = /^(v-bind:|:)?transition$/; // terminal directives var terminalDirectives = ['for', 'if']; // default directive priority var DEFAULT_PRIORITY = 1000; /** * Compile a template and return a reusable composite link * function, which recursively contains more link functions * inside. This top level compile function would normally * be called on instance root nodes, but can also be used * for partial compilation if the partial argument is true. * * The returned composite link function, when called, will * return an unlink function that tearsdown all directives * created during the linking phase. * * @param {Element|DocumentFragment} el * @param {Object} options * @param {Boolean} partial * @return {Function} */ function compile(el, options, partial) { // link function for the node itself. var nodeLinkFn = partial || !options._asComponent ? compileNode(el, options) : null; // link function for the childNodes var childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && el.tagName !== 'SCRIPT' && el.hasChildNodes() ? compileNodeList(el.childNodes, options) : null; /** * A composite linker function to be called on a already * compiled piece of DOM, which instantiates all directive * instances. * * @param {Vue} vm * @param {Element|DocumentFragment} el * @param {Vue} [host] - host vm of transcluded content * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - link context fragment * @return {Function|undefined} */ return function compositeLinkFn(vm, el, host, scope, frag) { // cache childNodes before linking parent, fix #657 var childNodes = toArray(el.childNodes); // link var dirs = linkAndCapture(function compositeLinkCapturer() { if (nodeLinkFn) nodeLinkFn(vm, el, host, scope, frag); if (childLinkFn) childLinkFn(vm, childNodes, host, scope, frag); }, vm); return makeUnlinkFn(vm, dirs); }; } /** * Apply a linker to a vm/element pair and capture the * directives created during the process. * * @param {Function} linker * @param {Vue} vm */ function linkAndCapture(linker, vm) { var originalDirCount = vm._directives.length; linker(); var dirs = vm._directives.slice(originalDirCount); dirs.sort(directiveComparator); for (var i = 0, l = dirs.length; i < l; i++) { dirs[i]._bind(); } return dirs; } /** * Directive priority sort comparator * * @param {Object} a * @param {Object} b */ function directiveComparator(a, b) { a = a.descriptor.def.priority || DEFAULT_PRIORITY; b = b.descriptor.def.priority || DEFAULT_PRIORITY; return a > b ? -1 : a === b ? 0 : 1; } /** * Linker functions return an unlink function that * tearsdown all directives instances generated during * the process. * * We create unlink functions with only the necessary * information to avoid retaining additional closures. * * @param {Vue} vm * @param {Array} dirs * @param {Vue} [context] * @param {Array} [contextDirs] * @return {Function} */ function makeUnlinkFn(vm, dirs, context, contextDirs) { return function unlink(destroying) { teardownDirs(vm, dirs, destroying); if (context && contextDirs) { teardownDirs(context, contextDirs); } }; } /** * Teardown partial linked directives. * * @param {Vue} vm * @param {Array} dirs * @param {Boolean} destroying */ function teardownDirs(vm, dirs, destroying) { var i = dirs.length; while (i--) { dirs[i]._teardown(); if (!destroying) { vm._directives.$remove(dirs[i]); } } } /** * Compile link props on an instance. * * @param {Vue} vm * @param {Element} el * @param {Object} props * @param {Object} [scope] * @return {Function} */ function compileAndLinkProps(vm, el, props, scope) { var propsLinkFn = compileProps(el, props); var propDirs = linkAndCapture(function () { propsLinkFn(vm, scope); }, vm); return makeUnlinkFn(vm, propDirs); } /** * Compile the root element of an instance. * * 1. attrs on context container (context scope) * 2. attrs on the component template root node, if * replace:true (child scope) * * If this is a fragment instance, we only need to compile 1. * * @param {Vue} vm * @param {Element} el * @param {Object} options * @param {Object} contextOptions * @return {Function} */ function compileRoot(el, options, contextOptions) { var containerAttrs = options._containerAttrs; var replacerAttrs = options._replacerAttrs; var contextLinkFn, replacerLinkFn; // only need to compile other attributes for // non-fragment instances if (el.nodeType !== 11) { // for components, container and replacer need to be // compiled separately and linked in different scopes. if (options._asComponent) { // 2. container attributes if (containerAttrs && contextOptions) { contextLinkFn = compileDirectives(containerAttrs, contextOptions); } if (replacerAttrs) { // 3. replacer attributes replacerLinkFn = compileDirectives(replacerAttrs, options); } } else { // non-component, just compile as a normal element. replacerLinkFn = compileDirectives(el.attributes, options); } } else if ('development' !== 'production' && containerAttrs) { // warn container directives for fragment instances var names = containerAttrs.filter(function (attr) { // allow vue-loader/vueify scoped css attributes return attr.name.indexOf('_v-') < 0 && // allow event listeners !onRE.test(attr.name) && // allow slots attr.name !== 'slot'; }).map(function (attr) { return '"' + attr.name + '"'; }); if (names.length) { var plural = names.length > 1; warn('Attribute' + (plural ? 's ' : ' ') + names.join(', ') + (plural ? ' are' : ' is') + ' ignored on component ' + '<' + options.el.tagName.toLowerCase() + '> because ' + 'the component is a fragment instance: ' + 'http://vuejs.org/guide/components.html#Fragment_Instance'); } } return function rootLinkFn(vm, el, scope) { // link context scope dirs var context = vm._context; var contextDirs; if (context && contextLinkFn) { contextDirs = linkAndCapture(function () { contextLinkFn(context, el, null, scope); }, context); } // link self var selfDirs = linkAndCapture(function () { if (replacerLinkFn) replacerLinkFn(vm, el); }, vm); // return the unlink function that tearsdown context // container directives. return makeUnlinkFn(vm, selfDirs, context, contextDirs); }; } /** * Compile a node and return a nodeLinkFn based on the * node type. * * @param {Node} node * @param {Object} options * @return {Function|null} */ function compileNode(node, options) { var type = node.nodeType; if (type === 1 && node.tagName !== 'SCRIPT') { return compileElement(node, options); } else if (type === 3 && node.data.trim()) { return compileTextNode(node, options); } else { return null; } } /** * Compile an element and return a nodeLinkFn. * * @param {Element} el * @param {Object} options * @return {Function|null} */ function compileElement(el, options) { // preprocess textareas. // textarea treats its text content as the initial value. // just bind it as an attr directive for value. if (el.tagName === 'TEXTAREA') { var tokens = parseText(el.value); if (tokens) { el.setAttribute(':value', tokensToExp(tokens)); el.value = ''; } } var linkFn; var hasAttrs = el.hasAttributes(); // check terminal directives (for & if) if (hasAttrs) { linkFn = checkTerminalDirectives(el, options); } // check element directives if (!linkFn) { linkFn = checkElementDirectives(el, options); } // check component if (!linkFn) { linkFn = checkComponent(el, options); } // normal directives if (!linkFn && hasAttrs) { linkFn = compileDirectives(el.attributes, options); } return linkFn; } /** * Compile a textNode and return a nodeLinkFn. * * @param {TextNode} node * @param {Object} options * @return {Function|null} textNodeLinkFn */ function compileTextNode(node, options) { // skip marked text nodes if (node._skip) { return removeText; } var tokens = parseText(node.wholeText); if (!tokens) { return null; } // mark adjacent text nodes as skipped, // because we are using node.wholeText to compile // all adjacent text nodes together. This fixes // issues in IE where sometimes it splits up a single // text node into multiple ones. var next = node.nextSibling; while (next && next.nodeType === 3) { next._skip = true; next = next.nextSibling; } var frag = document.createDocumentFragment(); var el, token; for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i]; el = token.tag ? processTextToken(token, options) : document.createTextNode(token.value); frag.appendChild(el); } return makeTextNodeLinkFn(tokens, frag, options); } /** * Linker for an skipped text node. * * @param {Vue} vm * @param {Text} node */ function removeText(vm, node) { remove(node); } /** * Process a single text token. * * @param {Object} token * @param {Object} options * @return {Node} */ function processTextToken(token, options) { var el; if (token.oneTime) { el = document.createTextNode(token.value); } else { if (token.html) { el = document.createComment('v-html'); setTokenType('html'); } else { // IE will clean up empty textNodes during // frag.cloneNode(true), so we have to give it // something here... el = document.createTextNode(' '); setTokenType('text'); } } function setTokenType(type) { if (token.descriptor) return; var parsed = parseDirective(token.value); token.descriptor = { name: type, def: publicDirectives[type], expression: parsed.expression, filters: parsed.filters }; } return el; } /** * Build a function that processes a textNode. * * @param {Array<Object>} tokens * @param {DocumentFragment} frag */ function makeTextNodeLinkFn(tokens, frag) { return function textNodeLinkFn(vm, el, host, scope) { var fragClone = frag.cloneNode(true); var childNodes = toArray(fragClone.childNodes); var token, value, node; for (var i = 0, l = tokens.length; i < l; i++) { token = tokens[i]; value = token.value; if (token.tag) { node = childNodes[i]; if (token.oneTime) { value = (scope || vm).$eval(value); if (token.html) { replace(node, parseTemplate(value, true)); } else { node.data = value; } } else { vm._bindDir(token.descriptor, node, host, scope); } } } replace(el, fragClone); }; } /** * Compile a node list and return a childLinkFn. * * @param {NodeList} nodeList * @param {Object} options * @return {Function|undefined} */ function compileNodeList(nodeList, options) { var linkFns = []; var nodeLinkFn, childLinkFn, node; for (var i = 0, l = nodeList.length; i < l; i++) { node = nodeList[i]; nodeLinkFn = compileNode(node, options); childLinkFn = !(nodeLinkFn && nodeLinkFn.terminal) && node.tagName !== 'SCRIPT' && node.hasChildNodes() ? compileNodeList(node.childNodes, options) : null; linkFns.push(nodeLinkFn, childLinkFn); } return linkFns.length ? makeChildLinkFn(linkFns) : null; } /** * Make a child link function for a node's childNodes. * * @param {Array<Function>} linkFns * @return {Function} childLinkFn */ function makeChildLinkFn(linkFns) { return function childLinkFn(vm, nodes, host, scope, frag) { var node, nodeLinkFn, childrenLinkFn; for (var i = 0, n = 0, l = linkFns.length; i < l; n++) { node = nodes[n]; nodeLinkFn = linkFns[i++]; childrenLinkFn = linkFns[i++]; // cache childNodes before linking parent, fix #657 var childNodes = toArray(node.childNodes); if (nodeLinkFn) { nodeLinkFn(vm, node, host, scope, frag); } if (childrenLinkFn) { childrenLinkFn(vm, childNodes, host, scope, frag); } } }; } /** * Check for element directives (custom elements that should * be resovled as terminal directives). * * @param {Element} el * @param {Object} options */ function checkElementDirectives(el, options) { var tag = el.tagName.toLowerCase(); if (commonTagRE.test(tag)) return; // special case: give named slot a higher priority // than unnamed slots if (tag === 'slot' && hasBindAttr(el, 'name')) { tag = '_namedSlot'; } var def = resolveAsset(options, 'elementDirectives', tag); if (def) { return makeTerminalNodeLinkFn(el, tag, '', options, def); } } /** * Check if an element is a component. If yes, return * a component link function. * * @param {Element} el * @param {Object} options * @return {Function|undefined} */ function checkComponent(el, options) { var component = checkComponentAttr(el, options); if (component) { var ref = findRef(el); var descriptor = { name: 'component', ref: ref, expression: component.id, def: internalDirectives.component, modifiers: { literal: !component.dynamic } }; var componentLinkFn = function componentLinkFn(vm, el, host, scope, frag) { if (ref) { defineReactive((scope || vm).$refs, ref, null); } vm._bindDir(descriptor, el, host, scope, frag); }; componentLinkFn.terminal = true; return componentLinkFn; } } /** * Check an element for terminal directives in fixed order. * If it finds one, return a terminal link function. * * @param {Element} el * @param {Object} options * @return {Function} terminalLinkFn */ function checkTerminalDirectives(el, options) { // skip v-pre if (getAttr(el, 'v-pre') !== null) { return skip; } // skip v-else block, but only if following v-if if (el.hasAttribute('v-else')) { var prev = el.previousElementSibling; if (prev && prev.hasAttribute('v-if')) { return skip; } } var value, dirName; for (var i = 0, l = terminalDirectives.length; i < l; i++) { dirName = terminalDirectives[i]; /* eslint-disable no-cond-assign */ if (value = el.getAttribute('v-' + dirName)) { return makeTerminalNodeLinkFn(el, dirName, value, options); } /* eslint-enable no-cond-assign */ } } function skip() {} skip.terminal = true; /** * Build a node link function for a terminal directive. * A terminal link function terminates the current * compilation recursion and handles compilation of the * subtree in the directive. * * @param {Element} el * @param {String} dirName * @param {String} value * @param {Object} options * @param {Object} [def] * @return {Function} terminalLinkFn */ function makeTerminalNodeLinkFn(el, dirName, value, options, def) { var parsed = parseDirective(value); var descriptor = { name: dirName, expression: parsed.expression, filters: parsed.filters, raw: value, // either an element directive, or if/for def: def || publicDirectives[dirName] }; // check ref for v-for and router-view if (dirName === 'for' || dirName === 'router-view') { descriptor.ref = findRef(el); } var fn = function terminalNodeLinkFn(vm, el, host, scope, frag) { if (descriptor.ref) { defineReactive((scope || vm).$refs, descriptor.ref, null); } vm._bindDir(descriptor, el, host, scope, frag); }; fn.terminal = true; return fn; } /** * Compile the directives on an element and return a linker. * * @param {Array|NamedNodeMap} attrs * @param {Object} options * @return {Function} */ function compileDirectives(attrs, options) { var i = attrs.length; var dirs = []; var attr, name, value, rawName, rawValue, dirName, arg, modifiers, dirDef, tokens; while (i--) { attr = attrs[i]; name = rawName = attr.name; value = rawValue = attr.value; tokens = parseText(value); // reset arg arg = null; // check modifiers modifiers = parseModifiers(name); name = name.replace(modifierRE, ''); // attribute interpolations if (tokens) { value = tokensToExp(tokens); arg = name; pushDir('bind', publicDirectives.bind, true); // warn against mixing mustaches with v-bind if ('development' !== 'production') { if (name === 'class' && Array.prototype.some.call(attrs, function (attr) { return attr.name === ':class' || attr.name === 'v-bind:class'; })) { warn('class="' + rawValue + '": Do not mix mustache interpolation ' + 'and v-bind for "class" on the same element. Use one or the other.'); } } } else // special attribute: transition if (transitionRE.test(name)) { modifiers.literal = !bindRE.test(name); pushDir('transition', internalDirectives.transition); } else // event handlers if (onRE.test(name)) { arg = name.replace(onRE, ''); pushDir('on', publicDirectives.on); } else // attribute bindings if (bindRE.test(name)) { dirName = name.replace(bindRE, ''); if (dirName === 'style' || dirName === 'class') { pushDir(dirName, internalDirectives[dirName]); } else { arg = dirName; pushDir('bind', publicDirectives.bind); } } else // normal directives if (name.indexOf('v-') === 0) { // check arg arg = (arg = name.match(argRE)) && arg[1]; if (arg) { name = name.replace(argRE, ''); } // extract directive name dirName = name.slice(2); // skip v-else (when used with v-show) if (dirName === 'else') { continue; } dirDef = resolveAsset(options, 'directives', dirName); if ('development' !== 'production') { assertAsset(dirDef, 'directive', dirName); } if (dirDef) { pushDir(dirName, dirDef); } } } /** * Push a directive. * * @param {String} dirName * @param {Object|Function} def * @param {Boolean} [interp] */ function pushDir(dirName, def, interp) { var parsed = parseDirective(value); dirs.push({ name: dirName, attr: rawName, raw: rawValue, def: def, arg: arg, modifiers: modifiers, expression: parsed.expression, filters: parsed.filters, interp: interp }); } if (dirs.length) { return makeNodeLinkFn(dirs); } } /** * Parse modifiers from directive attribute name. * * @param {String} name * @return {Object} */ function parseModifiers(name) { var res = Object.create(null); var match = name.match(modifierRE); if (match) { var i = match.length; while (i--) { res[match[i].slice(1)] = true; } } return res; } /** * Build a link function for all directives on a single node. * * @param {Array} directives * @return {Function} directivesLinkFn */ function makeNodeLinkFn(directives) { return function nodeLinkFn(vm, el, host, scope, frag) { // reverse apply because it's sorted low to high var i = directives.length; while (i--) { vm._bindDir(directives[i], el, host, scope, frag); } }; } var specialCharRE = /[^\w\-:\.]/; /** * Process an element or a DocumentFragment based on a * instance option object. This allows us to transclude * a template node/fragment before the instance is created, * so the processed fragment can then be cloned and reused * in v-for. * * @param {Element} el * @param {Object} options * @return {Element|DocumentFragment} */ function transclude(el, options) { // extract container attributes to pass them down // to compiler, because they need to be compiled in // parent scope. we are mutating the options object here // assuming the same object will be used for compile // right after this. if (options) { options._containerAttrs = extractAttrs(el); } // for template tags, what we want is its content as // a documentFragment (for fragment instances) if (isTemplate(el)) { el = parseTemplate(el); } if (options) { if (options._asComponent && !options.template) { options.template = '<slot></slot>'; } if (options.template) { options._content = extractContent(el); el = transcludeTemplate(el, options); } } if (el instanceof DocumentFragment) { // anchors for fragment instance // passing in `persist: true` to avoid them being // discarded by IE during template cloning prepend(createAnchor('v-start', true), el); el.appendChild(createAnchor('v-end', true)); } return el; } /** * Process the template option. * If the replace option is true this will swap the $el. * * @param {Element} el * @param {Object} options * @return {Element|DocumentFragment} */ function transcludeTemplate(el, options) { var template = options.template; var frag = parseTemplate(template, true); if (frag) { var replacer = frag.firstChild; var tag = replacer.tagName && replacer.tagName.toLowerCase(); if (options.replace) { /* istanbul ignore if */ if (el === document.body) { 'development' !== 'production' && warn('You are mounting an instance with a template to ' + '<body>. This will replace <body> entirely. You ' + 'should probably use `replace: false` here.'); } // there are many cases where the instance must // become a fragment instance: basically anything that // can create more than 1 root nodes. if ( // multi-children template frag.childNodes.length > 1 || // non-element template replacer.nodeType !== 1 || // single nested component tag === 'component' || resolveAsset(options, 'components', tag) || hasBindAttr(replacer, 'is') || // element directive resolveAsset(options, 'elementDirectives', tag) || // for block replacer.hasAttribute('v-for') || // if block replacer.hasAttribute('v-if')) { return frag; } else { options._replacerAttrs = extractAttrs(replacer); mergeAttrs(el, replacer); return replacer; } } else { el.appendChild(frag); return el; } } else { 'development' !== 'production' && warn('Invalid template option: ' + template); } } /** * Helper to extract a component container's attributes * into a plain object array. * * @param {Element} el * @return {Array} */ function extractAttrs(el) { if (el.nodeType === 1 && el.hasAttributes()) { return toArray(el.attributes); } } /** * Merge the attributes of two elements, and make sure * the class names are merged properly. * * @param {Element} from * @param {Element} to */ function mergeAttrs(from, to) { var attrs = from.attributes; var i = attrs.length; var name, value; while (i--) { name = attrs[i].name; value = attrs[i].value; if (!to.hasAttribute(name) && !specialCharRE.test(name)) { to.setAttribute(name, value); } else if (name === 'class') { value.split(/\s+/).forEach(function (cls) { addClass(to, cls); }); } } } var compiler = Object.freeze({ compile: compile, compileAndLinkProps: compileAndLinkProps, compileRoot: compileRoot, transclude: transclude }); function stateMixin (Vue) { /** * Accessor for `$data` property, since setting $data * requires observing the new object and updating * proxied properties. */ Object.defineProperty(Vue.prototype, '$data', { get: function get() { return this._data; }, set: function set(newData) { if (newData !== this._data) { this._setData(newData); } } }); /** * Setup the scope of an instance, which contains: * - observed data * - computed properties * - user methods * - meta properties */ Vue.prototype._initState = function () { this._initProps(); this._initMeta(); this._initMethods(); this._initData(); this._initComputed(); }; /** * Initialize props. */ Vue.prototype._initProps = function () { var options = this.$options; var el = options.el; var props = options.props; if (props && !el) { 'development' !== 'production' && warn('Props will not be compiled if no `el` option is ' + 'provided at instantiation.'); } // make sure to convert string selectors into element now el = options.el = query(el); this._propsUnlinkFn = el && el.nodeType === 1 && props // props must be linked in proper scope if inside v-for ? compileAndLinkProps(this, el, props, this._scope) : null; }; /** * Initialize the data. */ Vue.prototype._initData = function () { var propsData = this._data; var optionsDataFn = this.$options.data; var optionsData = optionsDataFn && optionsDataFn(); if (optionsData) { this._data = optionsData; for (var prop in propsData) { if ('development' !== 'production' && hasOwn(optionsData, prop)) { warn('Data field "' + prop + '" is already defined ' + 'as a prop. Use prop default value instead.'); } if (this._props[prop].raw !== null || !hasOwn(optionsData, prop)) { set(optionsData, prop, propsData[prop]); } } } var data = this._data; // proxy data on instance var keys = Object.keys(data); var i, key; i = keys.length; while (i--) { key = keys[i]; this._proxy(key); } // observe data observe(data, this); }; /** * Swap the instance's $data. Called in $data's setter. * * @param {Object} newData */ Vue.prototype._setData = function (newData) { newData = newData || {}; var oldData = this._data; this._data = newData; var keys, key, i; // unproxy keys not present in new data keys = Object.keys(oldData); i = keys.length; while (i--) { key = keys[i]; if (!(key in newData)) { this._unproxy(key); } } // proxy keys not already proxied, // and trigger change for changed values keys = Object.keys(newData); i = keys.length; while (i--) { key = keys[i]; if (!hasOwn(this, key)) { // new property this._proxy(key); } } oldData.__ob__.removeVm(this); observe(newData, this); this._digest(); }; /** * Proxy a property, so that * vm.prop === vm._data.prop * * @param {String} key */ Vue.prototype._proxy = function (key) { if (!isReserved(key)) { // need to store ref to self here // because these getter/setters might // be called by child scopes via // prototype inheritance. var self = this; Object.defineProperty(self, key, { configurable: true, enumerable: true, get: function proxyGetter() { return self._data[key]; }, set: function proxySetter(val) { self._data[key] = val; } }); } }; /** * Unproxy a property. * * @param {String} key */ Vue.prototype._unproxy = function (key) { if (!isReserved(key)) { delete this[key]; } }; /** * Force update on every watcher in scope. */ Vue.prototype._digest = function () { for (var i = 0, l = this._watchers.length; i < l; i++) { this._watchers[i].update(true); // shallow updates } }; /** * Setup computed properties. They are essentially * special getter/setters */ function noop() {} Vue.prototype._initComputed = function () { var computed = this.$options.computed; if (computed) { for (var key in computed) { var userDef = computed[key]; var def = { enumerable: true, configurable: true }; if (typeof userDef === 'function') { def.get = makeComputedGetter(userDef, this); def.set = noop; } else { def.get = userDef.get ? userDef.cache !== false ? makeComputedGetter(userDef.get, this) : bind$1(userDef.get, this) : noop; def.set = userDef.set ? bind$1(userDef.set, this) : noop; } Object.defineProperty(this, key, def); } } }; function makeComputedGetter(getter, owner) { var watcher = new Watcher(owner, getter, null, { lazy: true }); return function computedGetter() { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value; }; } /** * Setup instance methods. Methods must be bound to the * instance since they might be passed down as a prop to * child components. */ Vue.prototype._initMethods = function () { var methods = this.$options.methods; if (methods) { for (var key in methods) { this[key] = bind$1(methods[key], this); } } }; /** * Initialize meta information like $index, $key & $value. */ Vue.prototype._initMeta = function () { var metas = this.$options._meta; if (metas) { for (var key in metas) { defineReactive(this, key, metas[key]); } } }; } var eventRE = /^v-on:|^@/; function eventsMixin (Vue) { /** * Setup the instance's option events & watchers. * If the value is a string, we pull it from the * instance's methods by name. */ Vue.prototype._initEvents = function () { var options = this.$options; if (options._asComponent) { registerComponentEvents(this, options.el); } registerCallbacks(this, '$on', options.events); registerCallbacks(this, '$watch', options.watch); }; /** * Register v-on events on a child component * * @param {Vue} vm * @param {Element} el */ function registerComponentEvents(vm, el) { var attrs = el.attributes; var name, handler; for (var i = 0, l = attrs.length; i < l; i++) { name = attrs[i].name; if (eventRE.test(name)) { name = name.replace(eventRE, ''); handler = (vm._scope || vm._context).$eval(attrs[i].value, true); vm.$on(name.replace(eventRE), handler); } } } /** * Register callbacks for option events and watchers. * * @param {Vue} vm * @param {String} action * @param {Object} hash */ function registerCallbacks(vm, action, hash) { if (!hash) return; var handlers, key, i, j; for (key in hash) { handlers = hash[key]; if (isArray(handlers)) { for (i = 0, j = handlers.length; i < j; i++) { register(vm, action, key, handlers[i]); } } else { register(vm, action, key, handlers); } } } /** * Helper to register an event/watch callback. * * @param {Vue} vm * @param {String} action * @param {String} key * @param {Function|String|Object} handler * @param {Object} [options] */ function register(vm, action, key, handler, options) { var type = typeof handler; if (type === 'function') { vm[action](key, handler, options); } else if (type === 'string') { var methods = vm.$options.methods; var method = methods && methods[handler]; if (method) { vm[action](key, method, options); } else { 'development' !== 'production' && warn('Unknown method: "' + handler + '" when ' + 'registering callback for ' + action + ': "' + key + '".'); } } else if (handler && type === 'object') { register(vm, action, key, handler.handler, handler); } } /** * Setup recursive attached/detached calls */ Vue.prototype._initDOMHooks = function () { this.$on('hook:attached', onAttached); this.$on('hook:detached', onDetached); }; /** * Callback to recursively call attached hook on children */ function onAttached() { if (!this._isAttached) { this._isAttached = true; this.$children.forEach(callAttach); } } /** * Iterator to call attached hook * * @param {Vue} child */ function callAttach(child) { if (!child._isAttached && inDoc(child.$el)) { child._callHook('attached'); } } /** * Callback to recursively call detached hook on children */ function onDetached() { if (this._isAttached) { this._isAttached = false; this.$children.forEach(callDetach); } } /** * Iterator to call detached hook * * @param {Vue} child */ function callDetach(child) { if (child._isAttached && !inDoc(child.$el)) { child._callHook('detached'); } } /** * Trigger all handlers for a hook * * @param {String} hook */ Vue.prototype._callHook = function (hook) { this.$emit('pre-hook:' + hook); var handlers = this.$options[hook]; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { handlers[i].call(this); } } this.$emit('hook:' + hook); }; } function noop() {} /** * A directive links a DOM element with a piece of data, * which is the result of evaluating an expression. * It registers a watcher with the expression and calls * the DOM update function when a change is triggered. * * @param {String} name * @param {Node} el * @param {Vue} vm * @param {Object} descriptor * - {String} name * - {Object} def * - {String} expression * - {Array<Object>} [filters] * - {Boolean} literal * - {String} attr * - {String} raw * @param {Object} def - directive definition object * @param {Vue} [host] - transclusion host component * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - owner fragment * @constructor */ function Directive(descriptor, vm, el, host, scope, frag) { this.vm = vm; this.el = el; // copy descriptor properties this.descriptor = descriptor; this.name = descriptor.name; this.expression = descriptor.expression; this.arg = descriptor.arg; this.modifiers = descriptor.modifiers; this.filters = descriptor.filters; this.literal = this.modifiers && this.modifiers.literal; // private this._locked = false; this._bound = false; this._listeners = null; // link context this._host = host; this._scope = scope; this._frag = frag; // store directives on node in dev mode if ('development' !== 'production' && this.el) { this.el._vue_directives = this.el._vue_directives || []; this.el._vue_directives.push(this); } } /** * Initialize the directive, mixin definition properties, * setup the watcher, call definition bind() and update() * if present. * * @param {Object} def */ Directive.prototype._bind = function () { var name = this.name; var descriptor = this.descriptor; // remove attribute if ((name !== 'cloak' || this.vm._isCompiled) && this.el && this.el.removeAttribute) { var attr = descriptor.attr || 'v-' + name; this.el.removeAttribute(attr); } // copy def properties var def = descriptor.def; if (typeof def === 'function') { this.update = def; } else { extend(this, def); } // setup directive params this._setupParams(); // initial bind if (this.bind) { this.bind(); } this._bound = true; if (this.literal) { this.update && this.update(descriptor.raw); } else if ((this.expression || this.modifiers) && (this.update || this.twoWay) && !this._checkStatement()) { // wrapped updater for context var dir = this; if (this.update) { this._update = function (val, oldVal) { if (!dir._locked) { dir.update(val, oldVal); } }; } else { this._update = noop; } var preProcess = this._preProcess ? bind$1(this._preProcess, this) : null; var postProcess = this._postProcess ? bind$1(this._postProcess, this) : null; var watcher = this._watcher = new Watcher(this.vm, this.expression, this._update, // callback { filters: this.filters, twoWay: this.twoWay, deep: this.deep, preProcess: preProcess, postProcess: postProcess, scope: this._scope }); // v-model with inital inline value need to sync back to // model instead of update to DOM on init. They would // set the afterBind hook to indicate that. if (this.afterBind) { this.afterBind(); } else if (this.update) { this.update(watcher.value); } } }; /** * Setup all param attributes, e.g. track-by, * transition-mode, etc... */ Directive.prototype._setupParams = function () { if (!this.params) { return; } var params = this.params; // swap the params array with a fresh object. this.params = Object.create(null); var i = params.length; var key, val, mappedKey; while (i--) { key = params[i]; mappedKey = camelize(key); val = getBindAttr(this.el, key); if (val != null) { // dynamic this._setupParamWatcher(mappedKey, val); } else { // static val = getAttr(this.el, key); if (val != null) { this.params[mappedKey] = val === '' ? true : val; } } } }; /** * Setup a watcher for a dynamic param. * * @param {String} key * @param {String} expression */ Directive.prototype._setupParamWatcher = function (key, expression) { var self = this; var called = false; var unwatch = (this._scope || this.vm).$watch(expression, function (val, oldVal) { self.params[key] = val; // since we are in immediate mode, // only call the param change callbacks if this is not the first update. if (called) { var cb = self.paramWatchers && self.paramWatchers[key]; if (cb) { cb.call(self, val, oldVal); } } else { called = true; } }, { immediate: true, user: false });(this._paramUnwatchFns || (this._paramUnwatchFns = [])).push(unwatch); }; /** * Check if the directive is a function caller * and if the expression is a callable one. If both true, * we wrap up the expression and use it as the event * handler. * * e.g. on-click="a++" * * @return {Boolean} */ Directive.prototype._checkStatement = function () { var expression = this.expression; if (expression && this.acceptStatement && !isSimplePath(expression)) { var fn = parseExpression(expression).get; var scope = this._scope || this.vm; var handler = function handler(e) { scope.$event = e; fn.call(scope, scope); scope.$event = null; }; if (this.filters) { handler = scope._applyFilters(handler, null, this.filters); } this.update(handler); return true; } }; /** * Set the corresponding value with the setter. * This should only be used in two-way directives * e.g. v-model. * * @param {*} value * @public */ Directive.prototype.set = function (value) { /* istanbul ignore else */ if (this.twoWay) { this._withLock(function () { this._watcher.set(value); }); } else if ('development' !== 'production') { warn('Directive.set() can only be used inside twoWay' + 'directives.'); } }; /** * Execute a function while preventing that function from * triggering updates on this directive instance. * * @param {Function} fn */ Directive.prototype._withLock = function (fn) { var self = this; self._locked = true; fn.call(self); nextTick(function () { self._locked = false; }); }; /** * Convenience method that attaches a DOM event listener * to the directive element and autometically tears it down * during unbind. * * @param {String} event * @param {Function} handler */ Directive.prototype.on = function (event, handler) { on$1(this.el, event, handler);(this._listeners || (this._listeners = [])).push([event, handler]); }; /** * Teardown the watcher and call unbind. */ Directive.prototype._teardown = function () { if (this._bound) { this._bound = false; if (this.unbind) { this.unbind(); } if (this._watcher) { this._watcher.teardown(); } var listeners = this._listeners; var i; if (listeners) { i = listeners.length; while (i--) { off(this.el, listeners[i][0], listeners[i][1]); } } var unwatchFns = this._paramUnwatchFns; if (unwatchFns) { i = unwatchFns.length; while (i--) { unwatchFns[i](); } } if ('development' !== 'production' && this.el) { this.el._vue_directives.$remove(this); } this.vm = this.el = this._watcher = this._listeners = null; } }; function lifecycleMixin (Vue) { /** * Update v-ref for component. * * @param {Boolean} remove */ Vue.prototype._updateRef = function (remove) { var ref = this.$options._ref; if (ref) { var refs = (this._scope || this._context).$refs; if (remove) { if (refs[ref] === this) { refs[ref] = null; } } else { refs[ref] = this; } } }; /** * Transclude, compile and link element. * * If a pre-compiled linker is available, that means the * passed in element will be pre-transcluded and compiled * as well - all we need to do is to call the linker. * * Otherwise we need to call transclude/compile/link here. * * @param {Element} el * @return {Element} */ Vue.prototype._compile = function (el) { var options = this.$options; // transclude and init element // transclude can potentially replace original // so we need to keep reference; this step also injects // the template and caches the original attributes // on the container node and replacer node. var original = el; el = transclude(el, options); this._initElement(el); // handle v-pre on root node (#2026) if (el.nodeType === 1 && getAttr(el, 'v-pre') !== null) { return; } // root is always compiled per-instance, because // container attrs and props can be different every time. var contextOptions = this._context && this._context.$options; var rootLinker = compileRoot(el, options, contextOptions); // compile and link the rest var contentLinkFn; var ctor = this.constructor; // component compilation can be cached // as long as it's not using inline-template if (options._linkerCachable) { contentLinkFn = ctor.linker; if (!contentLinkFn) { contentLinkFn = ctor.linker = compile(el, options); } } // link phase // make sure to link root with prop scope! var rootUnlinkFn = rootLinker(this, el, this._scope); var contentUnlinkFn = contentLinkFn ? contentLinkFn(this, el) : compile(el, options)(this, el); // register composite unlink function // to be called during instance destruction this._unlinkFn = function () { rootUnlinkFn(); // passing destroying: true to avoid searching and // splicing the directives contentUnlinkFn(true); }; // finally replace original if (options.replace) { replace(original, el); } this._isCompiled = true; this._callHook('compiled'); return el; }; /** * Initialize instance element. Called in the public * $mount() method. * * @param {Element} el */ Vue.prototype._initElement = function (el) { if (el instanceof DocumentFragment) { this._isFragment = true; this.$el = this._fragmentStart = el.firstChild; this._fragmentEnd = el.lastChild; // set persisted text anchors to empty if (this._fragmentStart.nodeType === 3) { this._fragmentStart.data = this._fragmentEnd.data = ''; } this._fragment = el; } else { this.$el = el; } this.$el.__vue__ = this; this._callHook('beforeCompile'); }; /** * Create and bind a directive to an element. * * @param {String} name - directive name * @param {Node} node - target node * @param {Object} desc - parsed directive descriptor * @param {Object} def - directive definition object * @param {Vue} [host] - transclusion host component * @param {Object} [scope] - v-for scope * @param {Fragment} [frag] - owner fragment */ Vue.prototype._bindDir = function (descriptor, node, host, scope, frag) { this._directives.push(new Directive(descriptor, this, node, host, scope, frag)); }; /** * Teardown an instance, unobserves the data, unbind all the * directives, turn off all the event listeners, etc. * * @param {Boolean} remove - whether to remove the DOM node. * @param {Boolean} deferCleanup - if true, defer cleanup to * be called later */ Vue.prototype._destroy = function (remove, deferCleanup) { if (this._isBeingDestroyed) { if (!deferCleanup) { this._cleanup(); } return; } var destroyReady; var pendingRemoval; var self = this; // Cleanup should be called either synchronously or asynchronoysly as // callback of this.$remove(), or if remove and deferCleanup are false. // In any case it should be called after all other removing, unbinding and // turning of is done var cleanupIfPossible = function cleanupIfPossible() { if (destroyReady && !pendingRemoval && !deferCleanup) { self._cleanup(); } }; // remove DOM element if (remove && this.$el) { pendingRemoval = true; this.$remove(function () { pendingRemoval = false; cleanupIfPossible(); }); } this._callHook('beforeDestroy'); this._isBeingDestroyed = true; var i; // remove self from parent. only necessary // if parent is not being destroyed as well. var parent = this.$parent; if (parent && !parent._isBeingDestroyed) { parent.$children.$remove(this); // unregister ref (remove: true) this._updateRef(true); } // destroy all children. i = this.$children.length; while (i--) { this.$children[i].$destroy(); } // teardown props if (this._propsUnlinkFn) { this._propsUnlinkFn(); } // teardown all directives. this also tearsdown all // directive-owned watchers. if (this._unlinkFn) { this._unlinkFn(); } i = this._watchers.length; while (i--) { this._watchers[i].teardown(); } // remove reference to self on $el if (this.$el) { this.$el.__vue__ = null; } destroyReady = true; cleanupIfPossible(); }; /** * Clean up to ensure garbage collection. * This is called after the leave transition if there * is any. */ Vue.prototype._cleanup = function () { if (this._isDestroyed) { return; } // remove self from owner fragment // do it in cleanup so that we can call $destroy with // defer right when a fragment is about to be removed. if (this._frag) { this._frag.children.$remove(this); } // remove reference from data ob // frozen object may not have observer. if (this._data.__ob__) { this._data.__ob__.removeVm(this); } // Clean up references to private properties and other // instances. preserve reference to _data so that proxy // accessors still work. The only potential side effect // here is that mutating the instance after it's destroyed // may affect the state of other components that are still // observing the same object, but that seems to be a // reasonable responsibility for the user rather than // always throwing an error on them. this.$el = this.$parent = this.$root = this.$children = this._watchers = this._context = this._scope = this._directives = null; // call the last hook... this._isDestroyed = true; this._callHook('destroyed'); // turn off all instance listeners. this.$off(); }; } function miscMixin (Vue) { /** * Apply a list of filter (descriptors) to a value. * Using plain for loops here because this will be called in * the getter of any watcher with filters so it is very * performance sensitive. * * @param {*} value * @param {*} [oldValue] * @param {Array} filters * @param {Boolean} write * @return {*} */ Vue.prototype._applyFilters = function (value, oldValue, filters, write) { var filter, fn, args, arg, offset, i, l, j, k; for (i = 0, l = filters.length; i < l; i++) { filter = filters[i]; fn = resolveAsset(this.$options, 'filters', filter.name); if ('development' !== 'production') { assertAsset(fn, 'filter', filter.name); } if (!fn) continue; fn = write ? fn.write : fn.read || fn; if (typeof fn !== 'function') continue; args = write ? [value, oldValue] : [value]; offset = write ? 2 : 1; if (filter.args) { for (j = 0, k = filter.args.length; j < k; j++) { arg = filter.args[j]; args[j + offset] = arg.dynamic ? this.$get(arg.value) : arg.value; } } value = fn.apply(this, args); } return value; }; /** * Resolve a component, depending on whether the component * is defined normally or using an async factory function. * Resolves synchronously if already resolved, otherwise * resolves asynchronously and caches the resolved * constructor on the factory. * * @param {String} id * @param {Function} cb */ Vue.prototype._resolveComponent = function (id, cb) { var factory = resolveAsset(this.$options, 'components', id); if ('development' !== 'production') { assertAsset(factory, 'component', id); } if (!factory) { return; } // async component factory if (!factory.options) { if (factory.resolved) { // cached cb(factory.resolved); } else if (factory.requested) { // pool callbacks factory.pendingCallbacks.push(cb); } else { factory.requested = true; var cbs = factory.pendingCallbacks = [cb]; factory(function resolve(res) { if (isPlainObject(res)) { res = Vue.extend(res); } // cache resolved factory.resolved = res; // invoke callbacks for (var i = 0, l = cbs.length; i < l; i++) { cbs[i](res); } }, function reject(reason) { 'development' !== 'production' && warn('Failed to resolve async component: ' + id + '. ' + (reason ? '\nReason: ' + reason : '')); }); } } else { // normal component cb(factory); } }; } function globalAPI (Vue) { /** * Expose useful internals */ Vue.util = util; Vue.config = config; Vue.set = set; Vue['delete'] = del; Vue.nextTick = nextTick; /** * The following are exposed for advanced usage / plugins */ Vue.compiler = compiler; Vue.FragmentFactory = FragmentFactory; Vue.internalDirectives = internalDirectives; Vue.parsers = { path: path, text: text$1, template: template, directive: directive, expression: expression }; /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance * * @param {Object} extendOptions */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var isFirstExtend = Super.cid === 0; if (isFirstExtend && extendOptions._Ctor) { return extendOptions._Ctor; } var name = extendOptions.name || Super.options.name; if ('development' !== 'production') { if (!/^[a-zA-Z][\w-]+$/.test(name)) { warn('Invalid component name: ' + name); name = null; } } var Sub = function VueComponent(options) { Vue.call(this, options); }; Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions(Super.options, extendOptions); Sub['super'] = Super; // allow further extension Sub.extend = Super.extend; // create asset registers, so extended classes // can have their private assets too. config._assetTypes.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // cache constructor if (isFirstExtend) { extendOptions._Ctor = Sub; } return Sub; }; /** * Plugin system * * @param {Object} plugin */ Vue.use = function (plugin) { /* istanbul ignore if */ if (plugin.installed) { return; } // additional parameters var args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else { plugin.apply(null, args); } plugin.installed = true; return this; }; /** * Apply a global mixin by merging it into the default * options. */ Vue.mixin = function (mixin) { Vue.options = mergeOptions(Vue.options, mixin); }; /** * Create asset registration methods with the following * signature: * * @param {String} id * @param {*} definition */ config._assetTypes.forEach(function (type) { Vue[type] = function (id, definition) { if (!definition) { return this.options[type + 's'][id]; } else { /* istanbul ignore if */ if ('development' !== 'production') { if (type === 'component' && (commonTagRE.test(id) || reservedTagRE.test(id))) { warn('Do not use built-in or reserved HTML elements as component ' + 'id: ' + id); } } if (type === 'component' && isPlainObject(definition)) { definition.name = id; definition = Vue.extend(definition); } this.options[type + 's'][id] = definition; return definition; } }; }); } var filterRE = /[^|]\|[^|]/; function dataAPI (Vue) { /** * Get the value from an expression on this vm. * * @param {String} exp * @param {Boolean} [asStatement] * @return {*} */ Vue.prototype.$get = function (exp, asStatement) { var res = parseExpression(exp); if (res) { if (asStatement && !isSimplePath(exp)) { var self = this; return function statementHandler() { self.$arguments = toArray(arguments); res.get.call(self, self); self.$arguments = null; }; } else { try { return res.get.call(this, this); } catch (e) {} } } }; /** * Set the value from an expression on this vm. * The expression must be a valid left-hand * expression in an assignment. * * @param {String} exp * @param {*} val */ Vue.prototype.$set = function (exp, val) { var res = parseExpression(exp, true); if (res && res.set) { res.set.call(this, this, val); } }; /** * Delete a property on the VM * * @param {String} key */ Vue.prototype.$delete = function (key) { del(this._data, key); }; /** * Watch an expression, trigger callback when its * value changes. * * @param {String|Function} expOrFn * @param {Function} cb * @param {Object} [options] * - {Boolean} deep * - {Boolean} immediate * @return {Function} - unwatchFn */ Vue.prototype.$watch = function (expOrFn, cb, options) { var vm = this; var parsed; if (typeof expOrFn === 'string') { parsed = parseDirective(expOrFn); expOrFn = parsed.expression; } var watcher = new Watcher(vm, expOrFn, cb, { deep: options && options.deep, sync: options && options.sync, filters: parsed && parsed.filters, user: !options || options.user !== false }); if (options && options.immediate) { cb.call(vm, watcher.value); } return function unwatchFn() { watcher.teardown(); }; }; /** * Evaluate a text directive, including filters. * * @param {String} text * @param {Boolean} [asStatement] * @return {String} */ Vue.prototype.$eval = function (text, asStatement) { // check for filters. if (filterRE.test(text)) { var dir = parseDirective(text); // the filter regex check might give false positive // for pipes inside strings, so it's possible that // we don't get any filters here var val = this.$get(dir.expression, asStatement); return dir.filters ? this._applyFilters(val, null, dir.filters) : val; } else { // no filter return this.$get(text, asStatement); } }; /** * Interpolate a piece of template text. * * @param {String} text * @return {String} */ Vue.prototype.$interpolate = function (text) { var tokens = parseText(text); var vm = this; if (tokens) { if (tokens.length === 1) { return vm.$eval(tokens[0].value) + ''; } else { return tokens.map(function (token) { return token.tag ? vm.$eval(token.value) : token.value; }).join(''); } } else { return text; } }; /** * Log instance data as a plain JS object * so that it is easier to inspect in console. * This method assumes console is available. * * @param {String} [path] */ Vue.prototype.$log = function (path) { var data = path ? getPath(this._data, path) : this._data; if (data) { data = clean(data); } // include computed fields if (!path) { for (var key in this.$options.computed) { data[key] = clean(this[key]); } } console.log(data); }; /** * "clean" a getter/setter converted object into a plain * object copy. * * @param {Object} - obj * @return {Object} */ function clean(obj) { return JSON.parse(JSON.stringify(obj)); } } function domAPI (Vue) { /** * Convenience on-instance nextTick. The callback is * auto-bound to the instance, and this avoids component * modules having to rely on the global Vue. * * @param {Function} fn */ Vue.prototype.$nextTick = function (fn) { nextTick(fn, this); }; /** * Append instance to target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$appendTo = function (target, cb, withTransition) { return insert(this, target, cb, withTransition, append, appendWithTransition); }; /** * Prepend instance to target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$prependTo = function (target, cb, withTransition) { target = query(target); if (target.hasChildNodes()) { this.$before(target.firstChild, cb, withTransition); } else { this.$appendTo(target, cb, withTransition); } return this; }; /** * Insert instance before target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$before = function (target, cb, withTransition) { return insert(this, target, cb, withTransition, beforeWithCb, beforeWithTransition); }; /** * Insert instance after target * * @param {Node} target * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$after = function (target, cb, withTransition) { target = query(target); if (target.nextSibling) { this.$before(target.nextSibling, cb, withTransition); } else { this.$appendTo(target.parentNode, cb, withTransition); } return this; }; /** * Remove instance from DOM * * @param {Function} [cb] * @param {Boolean} [withTransition] - defaults to true */ Vue.prototype.$remove = function (cb, withTransition) { if (!this.$el.parentNode) { return cb && cb(); } var inDocument = this._isAttached && inDoc(this.$el); // if we are not in document, no need to check // for transitions if (!inDocument) withTransition = false; var self = this; var realCb = function realCb() { if (inDocument) self._callHook('detached'); if (cb) cb(); }; if (this._isFragment) { removeNodeRange(this._fragmentStart, this._fragmentEnd, this, this._fragment, realCb); } else { var op = withTransition === false ? removeWithCb : removeWithTransition; op(this.$el, this, realCb); } return this; }; /** * Shared DOM insertion function. * * @param {Vue} vm * @param {Element} target * @param {Function} [cb] * @param {Boolean} [withTransition] * @param {Function} op1 - op for non-transition insert * @param {Function} op2 - op for transition insert * @return vm */ function insert(vm, target, cb, withTransition, op1, op2) { target = query(target); var targetIsDetached = !inDoc(target); var op = withTransition === false || targetIsDetached ? op1 : op2; var shouldCallHook = !targetIsDetached && !vm._isAttached && !inDoc(vm.$el); if (vm._isFragment) { mapNodeRange(vm._fragmentStart, vm._fragmentEnd, function (node) { op(node, target, vm); }); cb && cb(); } else { op(vm.$el, target, vm, cb); } if (shouldCallHook) { vm._callHook('attached'); } return vm; } /** * Check for selectors * * @param {String|Element} el */ function query(el) { return typeof el === 'string' ? document.querySelector(el) : el; } /** * Append operation that takes a callback. * * @param {Node} el * @param {Node} target * @param {Vue} vm - unused * @param {Function} [cb] */ function append(el, target, vm, cb) { target.appendChild(el); if (cb) cb(); } /** * InsertBefore operation that takes a callback. * * @param {Node} el * @param {Node} target * @param {Vue} vm - unused * @param {Function} [cb] */ function beforeWithCb(el, target, vm, cb) { before(el, target); if (cb) cb(); } /** * Remove operation that takes a callback. * * @param {Node} el * @param {Vue} vm - unused * @param {Function} [cb] */ function removeWithCb(el, vm, cb) { remove(el); if (cb) cb(); } } function eventsAPI (Vue) { /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn */ Vue.prototype.$on = function (event, fn) { (this._events[event] || (this._events[event] = [])).push(fn); modifyListenerCount(this, event, 1); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn */ Vue.prototype.$once = function (event, fn) { var self = this; function on() { self.$off(event, on); fn.apply(this, arguments); } on.fn = fn; this.$on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn */ Vue.prototype.$off = function (event, fn) { var cbs; // all if (!arguments.length) { if (this.$parent) { for (event in this._events) { cbs = this._events[event]; if (cbs) { modifyListenerCount(this, event, -cbs.length); } } } this._events = {}; return this; } // specific event cbs = this._events[event]; if (!cbs) { return this; } if (arguments.length === 1) { modifyListenerCount(this, event, -cbs.length); this._events[event] = null; return this; } // specific handler var cb; var i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { modifyListenerCount(this, event, -1); cbs.splice(i, 1); break; } } return this; }; /** * Trigger an event on self. * * @param {String} event * @return {Boolean} shouldPropagate */ Vue.prototype.$emit = function (event) { var cbs = this._events[event]; var shouldPropagate = !cbs; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; var args = toArray(arguments, 1); for (var i = 0, l = cbs.length; i < l; i++) { var res = cbs[i].apply(this, args); if (res === true) { shouldPropagate = true; } } } return shouldPropagate; }; /** * Recursively broadcast an event to all children instances. * * @param {String} event * @param {...*} additional arguments */ Vue.prototype.$broadcast = function (event) { // if no child has registered for this event, // then there's no need to broadcast. if (!this._eventsCount[event]) return; var children = this.$children; for (var i = 0, l = children.length; i < l; i++) { var child = children[i]; var shouldPropagate = child.$emit.apply(child, arguments); if (shouldPropagate) { child.$broadcast.apply(child, arguments); } } return this; }; /** * Recursively propagate an event up the parent chain. * * @param {String} event * @param {...*} additional arguments */ Vue.prototype.$dispatch = function () { this.$emit.apply(this, arguments); var parent = this.$parent; while (parent) { var shouldPropagate = parent.$emit.apply(parent, arguments); parent = shouldPropagate ? parent.$parent : null; } return this; }; /** * Modify the listener counts on all parents. * This bookkeeping allows $broadcast to return early when * no child has listened to a certain event. * * @param {Vue} vm * @param {String} event * @param {Number} count */ var hookRE = /^hook:/; function modifyListenerCount(vm, event, count) { var parent = vm.$parent; // hooks do not get broadcasted so no need // to do bookkeeping for them if (!parent || !count || hookRE.test(event)) return; while (parent) { parent._eventsCount[event] = (parent._eventsCount[event] || 0) + count; parent = parent.$parent; } } } function lifecycleAPI (Vue) { /** * Set instance target element and kick off the compilation * process. The passed in `el` can be a selector string, an * existing Element, or a DocumentFragment (for block * instances). * * @param {Element|DocumentFragment|string} el * @public */ Vue.prototype.$mount = function (el) { if (this._isCompiled) { 'development' !== 'production' && warn('$mount() should be called only once.'); return; } el = query(el); if (!el) { el = document.createElement('div'); } this._compile(el); this._initDOMHooks(); if (inDoc(this.$el)) { this._callHook('attached'); ready.call(this); } else { this.$once('hook:attached', ready); } return this; }; /** * Mark an instance as ready. */ function ready() { this._isAttached = true; this._isReady = true; this._callHook('ready'); } /** * Teardown the instance, simply delegate to the internal * _destroy. */ Vue.prototype.$destroy = function (remove, deferCleanup) { this._destroy(remove, deferCleanup); }; /** * Partially compile a piece of DOM and return a * decompile function. * * @param {Element|DocumentFragment} el * @param {Vue} [host] * @return {Function} */ Vue.prototype.$compile = function (el, host, scope, frag) { return compile(el, this.$options, true)(this, el, host, scope, frag); }; } /** * The exposed Vue constructor. * * API conventions: * - public API methods/properties are prefixed with `$` * - internal methods/properties are prefixed with `_` * - non-prefixed properties are assumed to be proxied user * data. * * @constructor * @param {Object} [options] * @public */ function Vue(options) { this._init(options); } // install internals initMixin(Vue); stateMixin(Vue); eventsMixin(Vue); lifecycleMixin(Vue); miscMixin(Vue); // install APIs globalAPI(Vue); dataAPI(Vue); domAPI(Vue); eventsAPI(Vue); lifecycleAPI(Vue); var convertArray = vFor._postProcess; /** * Limit filter for arrays * * @param {Number} n * @param {Number} offset (Decimal expected) */ function limitBy(arr, n, offset) { offset = offset ? parseInt(offset, 10) : 0; return typeof n === 'number' ? arr.slice(offset, offset + n) : arr; } /** * Filter filter for arrays * * @param {String} search * @param {String} [delimiter] * @param {String} ...dataKeys */ function filterBy(arr, search, delimiter) { arr = convertArray(arr); if (search == null) { return arr; } if (typeof search === 'function') { return arr.filter(search); } // cast to lowercase string search = ('' + search).toLowerCase(); // allow optional `in` delimiter // because why not var n = delimiter === 'in' ? 3 : 2; // extract and flatten keys var keys = toArray(arguments, n).reduce(function (prev, cur) { return prev.concat(cur); }, []); var res = []; var item, key, val, j; for (var i = 0, l = arr.length; i < l; i++) { item = arr[i]; val = item && item.$value || item; j = keys.length; if (j) { while (j--) { key = keys[j]; if (key === '$key' && contains(item.$key, search) || contains(getPath(val, key), search)) { res.push(item); break; } } } else if (contains(item, search)) { res.push(item); } } return res; } /** * Filter filter for arrays * * @param {String} sortKey * @param {String} reverse */ function orderBy(arr, sortKey, reverse) { arr = convertArray(arr); if (!sortKey) { return arr; } var order = reverse && reverse < 0 ? -1 : 1; // sort on a copy to avoid mutating original array return arr.slice().sort(function (a, b) { if (sortKey !== '$key') { if (isObject(a) && '$value' in a) a = a.$value; if (isObject(b) && '$value' in b) b = b.$value; } a = isObject(a) ? getPath(a, sortKey) : a; b = isObject(b) ? getPath(b, sortKey) : b; return a === b ? 0 : a > b ? order : -order; }); } /** * String contain helper * * @param {*} val * @param {String} search */ function contains(val, search) { var i; if (isPlainObject(val)) { var keys = Object.keys(val); i = keys.length; while (i--) { if (contains(val[keys[i]], search)) { return true; } } } else if (isArray(val)) { i = val.length; while (i--) { if (contains(val[i], search)) { return true; } } } else if (val != null) { return val.toString().toLowerCase().indexOf(search) > -1; } } var digitsRE = /(\d{3})(?=\d)/g; // asset collections must be a plain object. var filters = { orderBy: orderBy, filterBy: filterBy, limitBy: limitBy, /** * Stringify value. * * @param {Number} indent */ json: { read: function read(value, indent) { return typeof value === 'string' ? value : JSON.stringify(value, null, Number(indent) || 2); }, write: function write(value) { try { return JSON.parse(value); } catch (e) { return value; } } }, /** * 'abc' => 'Abc' */ capitalize: function capitalize(value) { if (!value && value !== 0) return ''; value = value.toString(); return value.charAt(0).toUpperCase() + value.slice(1); }, /** * 'abc' => 'ABC' */ uppercase: function uppercase(value) { return value || value === 0 ? value.toString().toUpperCase() : ''; }, /** * 'AbC' => 'abc' */ lowercase: function lowercase(value) { return value || value === 0 ? value.toString().toLowerCase() : ''; }, /** * 12345 => $12,345.00 * * @param {String} sign */ currency: function currency(value, _currency) { value = parseFloat(value); if (!isFinite(value) || !value && value !== 0) return ''; _currency = _currency != null ? _currency : '$'; var stringified = Math.abs(value).toFixed(2); var _int = stringified.slice(0, -3); var i = _int.length % 3; var head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? ',' : '') : ''; var _float = stringified.slice(-3); var sign = value < 0 ? '-' : ''; return _currency + sign + head + _int.slice(i).replace(digitsRE, '$1,') + _float; }, /** * 'item' => 'items' * * @params * an array of strings corresponding to * the single, double, triple ... forms of the word to * be pluralized. When the number to be pluralized * exceeds the length of the args, it will use the last * entry in the array. * * e.g. ['single', 'double', 'triple', 'multiple'] */ pluralize: function pluralize(value) { var args = toArray(arguments, 1); return args.length > 1 ? args[value % 10 - 1] || args[args.length - 1] : args[0] + (value === 1 ? '' : 's'); }, /** * Debounce a handler function. * * @param {Function} handler * @param {Number} delay = 300 * @return {Function} */ debounce: function debounce(handler, delay) { if (!handler) return; if (!delay) { delay = 300; } return _debounce(handler, delay); } }; var partial = { priority: PARTIAL, params: ['name'], // watch changes to name for dynamic partials paramWatchers: { name: function name(value) { vIf.remove.call(this); if (value) { this.insert(value); } } }, bind: function bind() { this.anchor = createAnchor('v-partial'); replace(this.el, this.anchor); this.insert(this.params.name); }, insert: function insert(id) { var partial = resolveAsset(this.vm.$options, 'partials', id); if ('development' !== 'production') { assertAsset(partial, 'partial', id); } if (partial) { this.factory = new FragmentFactory(this.vm, partial); vIf.insert.call(this); } }, unbind: function unbind() { if (this.frag) { this.frag.destroy(); } } }; // This is the elementDirective that handles <content> // transclusions. It relies on the raw content of an // instance being stored as `$options._content` during // the transclude phase. // We are exporting two versions, one for named and one // for unnamed, because the unnamed slots must be compiled // AFTER all named slots have selected their content. So // we need to give them different priorities in the compilation // process. (See #1965) var slot = { priority: SLOT, bind: function bind() { var host = this.vm; var raw = host.$options._content; if (!raw) { this.fallback(); return; } var context = host._context; var slotName = this.params && this.params.name; if (!slotName) { // Default slot this.tryCompile(extractFragment(raw.childNodes, raw, true), context, host); } else { // Named slot var selector = '[slot="' + slotName + '"]'; var nodes = raw.querySelectorAll(selector); if (nodes.length) { this.tryCompile(extractFragment(nodes, raw), context, host); } else { this.fallback(); } } }, tryCompile: function tryCompile(content, context, host) { if (content.hasChildNodes()) { this.compile(content, context, host); } else { this.fallback(); } }, compile: function compile(content, context, host) { if (content && context) { var scope = host ? host._scope : this._scope; this.unlink = context.$compile(content, host, scope, this._frag); } if (content) { replace(this.el, content); } else { remove(this.el); } }, fallback: function fallback() { this.compile(extractContent(this.el, true), this.vm); }, unbind: function unbind() { if (this.unlink) { this.unlink(); } } }; var namedSlot = extend(extend({}, slot), { priority: slot.priority + 1, params: ['name'] }); /** * Extract qualified content nodes from a node list. * * @param {NodeList} nodes * @param {Element} parent * @param {Boolean} main * @return {DocumentFragment} */ function extractFragment(nodes, parent, main) { var frag = document.createDocumentFragment(); for (var i = 0, l = nodes.length; i < l; i++) { var node = nodes[i]; // if this is the main outlet, we want to skip all // previously selected nodes; // otherwise, we want to mark the node as selected. // clone the node so the original raw content remains // intact. this ensures proper re-compilation in cases // where the outlet is inside a conditional block if (main && !node.__v_selected) { append(node); } else if (!main && node.parentNode === parent) { node.__v_selected = true; append(node); } } return frag; function append(node) { if (isTemplate(node) && !node.hasAttribute('v-if') && !node.hasAttribute('v-for')) { node = parseTemplate(node); } node = cloneNode(node); frag.appendChild(node); } } var elementDirectives = { slot: slot, _namedSlot: namedSlot, // same as slot but with higher priority partial: partial }; Vue.version = '1.0.13-csp'; /** * Vue and every constructor that extends Vue has an * associated options object, which can be accessed during * compilation steps as `this.constructor.options`. * * These can be seen as the default options of every * Vue instance. */ Vue.options = { directives: publicDirectives, elementDirectives: elementDirectives, filters: filters, transitions: {}, components: {}, partials: {}, replace: true }; // devtools global hook /* istanbul ignore if */ if ('development' !== 'production' && inBrowser) { if (window.__VUE_DEVTOOLS_GLOBAL_HOOK__) { window.__VUE_DEVTOOLS_GLOBAL_HOOK__.emit('init', Vue); } else if (/Chrome\/\d+/.test(navigator.userAgent)) { console.log('Download the Vue Devtools for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools'); } } return Vue; }));
node_modules/react-dom/lib/ReactComponentEnvironment.js
LaurentEtienne/Kfe
/** * 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. * * */ 'use strict'; var _prodInvariant = require('./reactProdInvariant'); var invariant = require('fbjs/lib/invariant'); var injected = false; var ReactComponentEnvironment = { /** * 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.') : _prodInvariant('104') : void 0; ReactComponentEnvironment.replaceNodeWithMarkup = environment.replaceNodeWithMarkup; ReactComponentEnvironment.processChildrenUpdates = environment.processChildrenUpdates; injected = true; } } }; module.exports = ReactComponentEnvironment;
node_modules/react-icons/io/ios-fastforward.js
bengimbel/Solstice-React-Contacts-Project
import React from 'react' import Icon from 'react-icon-base' const IoIosFastforward = props => ( <Icon viewBox="0 0 40 40" {...props}> <g><path d="m17.5 10l17.5 10-17.5 10v-9.6l-17.5 9.6v-20l17.5 9.6v-9.6z"/></g> </Icon> ) export default IoIosFastforward
src/sites/constellations.js
cosmowiki/cosmowiki
import React from 'react'; import ConstellationsComponent from '../components/constellations'; export default class Constellations { static componentWithData(constellations) { return <ConstellationsComponent constellations={constellations} />; } static fromRawData(rawData) { return rawData.map(raw => Constellation.fromRawData(raw)) } } class Constellation { static fromRawData(raw) { const item = new Constellation(); item.name = raw.itemname; item.latinName = raw.itemname2; item.shortName = raw.itemname4; item.wikipediaUrl = raw.itemurl; item.imageSmallUrl = raw.itemimgsmallurl; item.imageLargeUrl = raw.itemimgurl; item.imageSrc = raw.itemimgsrc; item.imageLicence = raw.itemimglicence; item.imageLicenceUrl = raw.itemimglicenceurl; item.namedYear = raw.itemdateyear; item.astronomer = raw.itemparent; item.astronomerUrl = raw.itemparenturl; item.rightAscension = raw.itemrightascension; item.declination = raw.itemdeclination; item.author = Author.fromRawData(raw); item.brightestStar = Star.fromRawData(raw); item.year = raw.itemdateyear; item.visibility = raw.itemvisibility; item.visibleFrom = raw.itemvisiblefrom; item.visibleTo = raw.itemvisibleto; item.squareDegrees = raw.itemsquaredegrees; item.starsOver3Mag = raw['itemstarsover3mag']; item.highestBrightness = raw.itemhighestbrightness; item.brightestStar = raw.itembrighteststar; item.brightestStarUrl = raw.itembrighteststarurl; return item; } } class Author { static fromRawData(raw) { const author = new Author(); author.name = raw.itemparent; author.wikipediaUrl = raw.itemparenturl; return author; } } class Star { static fromRawData(raw) { const star = new Star(); star.name = raw.itemproperty7; star.wikipediaUrl = raw.itemproperty8; return star; } } /* { "itemname": "Achterdeck des Schiffs", "itemname2": "Puppis", "itemname3": "Puppis", "itemname4": "Pup", "itemurl": "https://de.wikipedia.org/wiki/Puppis_%28Sternbild%29", "itemurl2": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e2/Puppis_IAU.svg/191px-Puppis_IAU.svg.png", "itemimgurl": "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e2/Puppis_IAU.svg/610px-Puppis_IAU.svg.png", "itemimgsrc": "IAU and Sky & Telescope magazine (Roger Sinnott & Rick Fienberg)", "itemimglicence": "CC by-sa 3.0", "itemimglicenceurl": "https://creativecommons.org/licenses/by-sa/3.0/deed.en", "itemdateyear": 1763, "itemparent": "Lacaille", "itemparenturl": "https://de.wikipedia.org/wiki/Nicolas_Louis_de_Lacaille", "itemrightascension": "07h 15m 28,8s", "itemdeclination": "−31° 10' 38,4\"", "itemproperty": "S", "itemproperty2": "39° N", "itemproperty3": "90° S", "itemproperty4": 673.434, "itemproperty5": 4, "itemproperty6": 2.06, "itemproperty7": "Naos", "itemproperty8": "https://de.wikipedia.org/wiki/Naos_%28Stern%29" }, */
fields/explorer/components/FieldType.js
dryna/keystone-twoje-urodziny
import React from 'react'; import Markdown from 'react-markdown'; import Col from './Col'; import Row from './Row'; import FieldSpec from './FieldSpec'; const ExplorerFieldType = React.createClass({ getInitialState () { return { readmeIsVisible: !!this.props.readme, filter: this.props.FilterComponent.getDefaultValue(), value: this.props.value, }; }, componentWillReceiveProps (newProps) { if (this.props.params.type === newProps.params.type) return; this.setState({ filter: newProps.FilterComponent.getDefaultValue(), readmeIsVisible: newProps.readme ? this.state.readmeIsVisible : false, value: newProps.value, }); }, onFieldChange (e) { var logValue = typeof e.value === 'string' ? `"${e.value}"` : e.value; console.log(`${this.props.params.type} field value changed:`, logValue); this.setState({ value: e.value, }); }, onFilterChange (value) { console.log(`${this.props.params.type} filter value changed:`, value); this.setState({ filter: value, }); }, toggleReadme () { this.setState({ readmeIsVisible: !this.state.readmeIsVisible }); }, render () { const { FieldComponent, FilterComponent, readme, toggleSidebar } = this.props; const { readmeIsVisible } = this.state; const specs = Array.isArray(this.props.spec) ? this.props.spec : [this.props.spec]; return ( <div className="fx-page"> <div className="fx-page__header"> <div className="fx-page__header__title"> <button className="fx-page__header__button fx-page__header__button--sidebar mega-octicon octicon-three-bars" onClick={toggleSidebar} type="button" /> {FieldComponent.type} </div> {!!readme && ( <button className="fx-page__header__button fx-page__header__button--readme mega-octicon octicon-file-text" onClick={this.toggleReadme} title={readmeIsVisible ? 'Hide Readme' : 'Show Readme'} type="button" /> )} </div> <div className="fx-page__content"> <Row> <Col> <div className="fx-page__content__inner"> {specs.map((spec, i) => ( <FieldSpec key={spec.path} i={i} FieldComponent={FieldComponent} FilterComponent={FilterComponent} spec={spec} readmeIsVisible={readmeIsVisible} /> ))} </div> </Col> {!!readmeIsVisible && ( <Col width={380}> <Markdown className="Markdown" source={readme} /> </Col> )} </Row> </div> </div> ); }, }); module.exports = ExplorerFieldType;
ajax/libs/react-native-web/0.17.4/exports/RefreshControl/index.js
cdnjs/cdnjs
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } /** * Copyright (c) Nicolas Gallagher. * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * */ import View from '../View'; import React from 'react'; function RefreshControl(props) { var colors = props.colors, enabled = props.enabled, onRefresh = props.onRefresh, progressBackgroundColor = props.progressBackgroundColor, progressViewOffset = props.progressViewOffset, refreshing = props.refreshing, size = props.size, tintColor = props.tintColor, title = props.title, titleColor = props.titleColor, rest = _objectWithoutPropertiesLoose(props, ["colors", "enabled", "onRefresh", "progressBackgroundColor", "progressViewOffset", "refreshing", "size", "tintColor", "title", "titleColor"]); return /*#__PURE__*/React.createElement(View, rest); } export default RefreshControl;
fields/types/datetime/DatetimeField.js
trentmillar/keystone
import DateInput from '../../components/DateInput'; import Field from '../Field'; import moment from 'moment'; import React from 'react'; import { Button, FormField, FormInput, FormNote, InlineGroup as Group, InlineGroupSection as Section, } from '../../../admin/client/App/elemental'; module.exports = Field.create({ displayName: 'DatetimeField', statics: { type: 'Datetime', }, focusTargetRef: 'dateInput', // default input formats dateInputFormat: 'YYYY-MM-DD', timeInputFormat: 'h:mm:ss a', tzOffsetInputFormat: 'Z', // parse formats (duplicated from lib/fieldTypes/datetime.js) parseFormats: ['YYYY-MM-DD', 'YYYY-MM-DD h:m:s a', 'YYYY-MM-DD h:m a', 'YYYY-MM-DD H:m:s', 'YYYY-MM-DD H:m'], getInitialState () { return { dateValue: this.props.value && this.moment(this.props.value).format(this.dateInputFormat), timeValue: this.props.value && this.moment(this.props.value).format(this.timeInputFormat), tzOffsetValue: this.props.value ? this.moment(this.props.value).format(this.tzOffsetInputFormat) : this.moment().format(this.tzOffsetInputFormat), }; }, getDefaultProps () { return { formatString: 'Do MMM YYYY, h:mm:ss a', }; }, moment () { if (this.props.isUTC) return moment.utc.apply(moment, arguments); else return moment.apply(undefined, arguments); }, // TODO: Move isValid() so we can share with server-side code isValid (value) { return this.moment(value, this.parseFormats).isValid(); }, // TODO: Move format() so we can share with server-side code format (value, format) { format = format || this.dateInputFormat + ' ' + this.timeInputFormat; return value ? this.moment(value).format(format) : ''; }, handleChange (dateValue, timeValue, tzOffsetValue) { var value = dateValue + ' ' + timeValue; var datetimeFormat = this.dateInputFormat + ' ' + this.timeInputFormat; // if the change included a timezone offset, include that in the calculation (so NOW works correctly during DST changes) if (typeof tzOffsetValue !== 'undefined') { value += ' ' + tzOffsetValue; datetimeFormat += ' ' + this.tzOffsetInputFormat; } // if not, calculate the timezone offset based on the date (respect different DST values) else { this.setState({ tzOffsetValue: this.moment(value, datetimeFormat).format(this.tzOffsetInputFormat) }); } this.props.onChange({ path: this.props.path, value: this.isValid(value) ? this.moment(value, datetimeFormat).toISOString() : null, }); }, dateChanged ({ value }) { this.setState({ dateValue: value }); this.handleChange(value, this.state.timeValue); }, timeChanged (evt) { this.setState({ timeValue: evt.target.value }); this.handleChange(this.state.dateValue, evt.target.value); }, setNow () { var dateValue = this.moment().format(this.dateInputFormat); var timeValue = this.moment().format(this.timeInputFormat); var tzOffsetValue = this.moment().format(this.tzOffsetInputFormat); this.setState({ dateValue: dateValue, timeValue: timeValue, tzOffsetValue: tzOffsetValue, }); this.handleChange(dateValue, timeValue, tzOffsetValue); }, renderNote () { if (!this.props.note) return null; return <FormNote note={this.props.note} />; }, renderUI () { var input; if (this.shouldRenderField()) { input = ( <div> <Group> <Section grow> <DateInput format={this.dateInputFormat} name={this.getInputName(this.props.paths.date)} onChange={this.dateChanged} ref="dateInput" value={this.state.dateValue} /> </Section> <Section grow> <FormInput autoComplete="off" name={this.getInputName(this.props.paths.time)} onChange={this.timeChanged} placeholder="HH:MM:SS am/pm" value={this.state.timeValue} /> </Section> <Section> <Button onClick={this.setNow}>Now</Button> </Section> </Group> <input name={this.getInputName(this.props.paths.tzOffset)} type="hidden" value={this.state.tzOffsetValue} /> </div> ); } else { input = ( <FormInput noedit> {this.format(this.props.value, this.props.formatString)} </FormInput> ); } return ( <FormField label={this.props.label} className="field-type-datetime" htmlFor={this.getInputName(this.props.path)}> {input} {this.renderNote()} </FormField> ); }, });
src/renderers/__tests__/ReactCompositeComponentNestedState-test.js
rlugojr/react
/** * 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. * * @emails react-core */ 'use strict'; var React; var ReactDOM; var ReactTestUtils; describe('ReactCompositeComponentNestedState-state', () => { beforeEach(() => { React = require('React'); ReactDOM = require('ReactDOM'); ReactTestUtils = require('ReactTestUtils'); }); it('should provide up to date values for props', () => { class ParentComponent extends React.Component { state = {color: 'blue'}; handleColor = (color) => { this.props.logger('parent-handleColor', this.state.color); this.setState({color: color}, function() { this.props.logger('parent-after-setState', this.state.color); }); }; render() { this.props.logger('parent-render', this.state.color); return ( <ChildComponent logger={this.props.logger} color={this.state.color} onSelectColor={this.handleColor} /> ); } } class ChildComponent extends React.Component { constructor(props) { super(props); props.logger('getInitialState', props.color); this.state = {hue: 'dark ' + props.color}; } handleHue = (shade, color) => { this.props.logger('handleHue', this.state.hue, this.props.color); this.props.onSelectColor(color); this.setState(function(state, props) { this.props.logger('setState-this', this.state.hue, this.props.color); this.props.logger('setState-args', state.hue, props.color); return {hue: shade + ' ' + props.color}; }, function() { this.props.logger('after-setState', this.state.hue, this.props.color); }); }; render() { this.props.logger('render', this.state.hue, this.props.color); return ( <div> <button onClick={this.handleHue.bind(this, 'dark', 'blue')}> Dark Blue </button> <button onClick={this.handleHue.bind(this, 'light', 'blue')}> Light Blue </button> <button onClick={this.handleHue.bind(this, 'dark', 'green')}> Dark Green </button> <button onClick={this.handleHue.bind(this, 'light', 'green')}> Light Green </button> </div> ); } } var container = document.createElement('div'); document.body.appendChild(container); var logger = jest.fn(); void ReactDOM.render( <ParentComponent logger={logger} />, container ); // click "light green" ReactTestUtils.Simulate.click( container.childNodes[0].childNodes[3] ); expect(logger.mock.calls).toEqual([ ['parent-render', 'blue'], ['getInitialState', 'blue'], ['render', 'dark blue', 'blue'], ['handleHue', 'dark blue', 'blue'], ['parent-handleColor', 'blue'], ['parent-render', 'green'], ['setState-this', 'dark blue', 'blue'], ['setState-args', 'dark blue', 'green'], ['render', 'light green', 'green'], ['after-setState', 'light green', 'green'], ['parent-after-setState', 'green'], ]); }); });
fields/types/email/EmailField.js
tony2cssc/keystone
import Field from '../Field'; import React from 'react'; import { FormInput } from 'elemental'; /* TODO: - gravatar - validate email address */ module.exports = Field.create({ displayName: 'EmailField', renderField () { return ( <FormInput name={this.props.path} ref="focusTarget" value={this.props.value} onChange={this.valueChanged} autoComplete="off" type="email" /> ); }, renderValue () { return this.props.value ? ( <FormInput noedit href={'mailto:' + this.props.value}>{this.props.value}</FormInput> ) : ( <FormInput noedit>(not set)</FormInput> ); }, });
src/containers/WorkBench/BarGraph.js
UncleYee/crm-ui
import React from 'react'; import Highcharts from 'highcharts'; import {WhitePanel} from 'components'; import {primaryColor} from 'utils/colors'; import {connect} from 'react-redux'; import {getHealthInfo} from 'redux/modules/clientSuccessWorkbench'; const styles = { root: { position: 'relative', overflow: 'hidden', paddingLeft: -50, width: 430, height: 456 }, graph: { marginTop: 40, width: 400, height: 315 } }; const getConfig = (data) =>{ return { credits: { enabled: false }, colors: [ primaryColor ], chart: { type: 'column', style: { }, marginRight: 40 }, title: { text: null }, legend: { // 图例 enabled: false }, yAxis: { min: 0, title: { text: '企业数', }, }, xAxis: { title: { text: '健康度分值' }, labels: { // y: 20, style: { fontFamily: 'Times New Roman', fontSize: 11, fontWeight: 'bold' } }, tickLength: 0, categories: data.data.tagList }, tooltip: { headerFormat: '<span style="font-size:10px">健康度分值:{point.key}</span><table>', pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' + '<td style="padding:0"><b>{point.y:.0f}</b></td></tr>', footerFormat: '</table>', shared: true, useHTML: true }, plotOptions: { series: { cursor: 'pointer', point: { events: { click: function jump() { const start = this.category.split('~')[0]; const end = this.category.split('~')[1]; const url = 'queryCustomerSuccessInit.action?queryMap.minHealthScore=' + start + '&queryMap.maxHealthScore=' + end + '&queryMap.tenantType=1'; window.top._hack_tab(url, '客户成功', '客户成功'); } } } } }, series: [{ name: '企业数', data: data.data.dataList }] }; }; @connect(state => ({ healthInfo: state.clientSuccessWorkbench.healthInfo || {} }), { getHealthInfo }) export default class BarGraph extends React.Component { static propTypes = { style: React.PropTypes.object, healthInfo: React.PropTypes.object, getHealthInfo: React.PropTypes.func, title: React.PropTypes.string, }; constructor(props) { super(props); } componentDidMount() { this.props.getHealthInfo().then((data) => { Highcharts.chart('barGraph', getConfig(data)); }); } render() { const { style, title } = this.props; const rootStyle = Object.assign(styles.root, style); return ( <WhitePanel style={rootStyle} title={title}> <div style={styles.graph} id="barGraph" /> </WhitePanel> ); } }
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/react-router-dom/4.1.1/es/HashRouter.js
Akkuma/npm-cache-benchmark
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } import React from 'react'; import PropTypes from 'prop-types'; import createHistory from 'history/createHashHistory'; import { Router } from 'react-router'; /** * The public API for a <Router> that uses window.location.hash. */ var HashRouter = function (_React$Component) { _inherits(HashRouter, _React$Component); function HashRouter() { var _temp, _this, _ret; _classCallCheck(this, HashRouter); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.history = createHistory(_this.props), _temp), _possibleConstructorReturn(_this, _ret); } HashRouter.prototype.render = function render() { return React.createElement(Router, { history: this.history, children: this.props.children }); }; return HashRouter; }(React.Component); HashRouter.propTypes = { basename: PropTypes.string, getUserConfirmation: PropTypes.func, hashType: PropTypes.oneOf(['hashbang', 'noslash', 'slash']), children: PropTypes.node }; export default HashRouter;
docs/src/app/components/pages/components/Table/Page.js
pradel/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import tableReadmeText from './README'; import TableExampleSimple from './ExampleSimple'; import tableExampleSimpleCode from '!raw!./ExampleSimple'; import TableExampleComplex from './ExampleComplex'; import tableExampleComplexCode from '!raw!./ExampleComplex'; import tableCode from '!raw!material-ui/lib/Table/Table'; import tableRowCode from '!raw!material-ui/lib/Table/TableRow'; import tableRowColumnCode from '!raw!material-ui/lib/Table/TableRowColumn'; import tableHeaderCode from '!raw!material-ui/lib/Table/TableHeader'; import tableHeaderColumnCode from '!raw!material-ui/lib/Table/TableHeaderColumn'; import tableBodyCode from '!raw!material-ui/lib/Table/TableBody'; import tableFooterCode from '!raw!material-ui/lib/Table/TableFooter'; const descriptions = { simple: 'A simple table demonstrating the hierarchy of the `Table` component and its sub-components.', complex: 'A more complex example, allowing the table height to be set, and key boolean properties to be toggled.', }; const TablePage = () => ( <div> <Title render={(previousTitle) => `Table - ${previousTitle}`} /> <MarkdownElement text={tableReadmeText} /> <CodeExample title="Simple example" description={descriptions.simple} code={tableExampleSimpleCode} > <TableExampleSimple /> </CodeExample> <CodeExample title="Complex example" description={descriptions.complex} code={tableExampleComplexCode} > <TableExampleComplex /> </CodeExample> <PropTypeDescription code={tableCode} header="### Table Properties" /> <PropTypeDescription code={tableRowCode} header="### TableRow Properties" /> <PropTypeDescription code={tableRowColumnCode} header="### TableRowColumn Properties" /> <PropTypeDescription code={tableHeaderCode} header="### TableHeader Properties" /> <PropTypeDescription code={tableHeaderColumnCode} header="### TableHeaderColumn Properties" /> <PropTypeDescription code={tableBodyCode} header="### TableBody Properties" /> <PropTypeDescription code={tableFooterCode} header="### TableFooter Properties" /> </div> ); export default TablePage;
lib/pmux-gw/static/js/jquery-ui-1.9.2.custom.js
AsherBond/pmux-gw
/*! jQuery UI - v1.9.2 - 2012-11-23 * http://jqueryui.com * Includes: jquery.ui.core.js, jquery.ui.widget.js, jquery.ui.mouse.js, jquery.ui.position.js, jquery.ui.accordion.js, jquery.ui.autocomplete.js, jquery.ui.button.js, jquery.ui.datepicker.js, jquery.ui.dialog.js, jquery.ui.draggable.js, jquery.ui.droppable.js, jquery.ui.effect.js, jquery.ui.effect-blind.js, jquery.ui.effect-bounce.js, jquery.ui.effect-clip.js, jquery.ui.effect-drop.js, jquery.ui.effect-explode.js, jquery.ui.effect-fade.js, jquery.ui.effect-fold.js, jquery.ui.effect-highlight.js, jquery.ui.effect-pulsate.js, jquery.ui.effect-scale.js, jquery.ui.effect-shake.js, jquery.ui.effect-slide.js, jquery.ui.effect-transfer.js, jquery.ui.menu.js, jquery.ui.progressbar.js, jquery.ui.resizable.js, jquery.ui.selectable.js, jquery.ui.slider.js, jquery.ui.sortable.js, jquery.ui.spinner.js, jquery.ui.tabs.js, jquery.ui.tooltip.js * Copyright (c) 2012 jQuery Foundation and other contributors Licensed MIT */ (function( $, undefined ) { var uuid = 0, runiqueId = /^ui-id-\d+$/; // prevent duplicate loading // this is only a problem because we proxy existing functions // and we don't want to double proxy them $.ui = $.ui || {}; if ( $.ui.version ) { return; } $.extend( $.ui, { version: "1.9.2", keyCode: { BACKSPACE: 8, COMMA: 188, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, LEFT: 37, 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, SPACE: 32, TAB: 9, UP: 38 } }); // plugins $.fn.extend({ _focus: $.fn.focus, focus: function( delay, fn ) { return typeof delay === "number" ? this.each(function() { var elem = this; setTimeout(function() { $( elem ).focus(); if ( fn ) { fn.call( elem ); } }, delay ); }) : this._focus.apply( this, arguments ); }, scrollParent: function() { var scrollParent; if (($.ui.ie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.css(this,'position')) && (/(auto|scroll)/).test($.css(this,'overflow')+$.css(this,'overflow-y')+$.css(this,'overflow-x')); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.css(this,'overflow')+$.css(this,'overflow-y')+$.css(this,'overflow-x')); }).eq(0); } return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent; }, zIndex: function( zIndex ) { if ( zIndex !== undefined ) { return this.css( "zIndex", zIndex ); } if ( this.length ) { var elem = $( this[ 0 ] ), position, value; while ( elem.length && elem[ 0 ] !== document ) { // Ignore z-index if position is set to a value where z-index is ignored by the browser // This makes behavior of this function consistent across browsers // WebKit always returns auto if the element is positioned position = elem.css( "position" ); if ( position === "absolute" || position === "relative" || position === "fixed" ) { // IE returns 0 when zIndex is not specified // other browsers return a string // we ignore the case of nested elements with an explicit value of 0 // <div style="z-index: -10;"><div style="z-index: 0;"></div></div> value = parseInt( elem.css( "zIndex" ), 10 ); if ( !isNaN( value ) && value !== 0 ) { return value; } } elem = elem.parent(); } } return 0; }, uniqueId: function() { return this.each(function() { if ( !this.id ) { this.id = "ui-id-" + (++uuid); } }); }, removeUniqueId: function() { return this.each(function() { if ( runiqueId.test( this.id ) ) { $( this ).removeAttr( "id" ); } }); } }); // selectors function focusable( element, isTabIndexNotNaN ) { var map, mapName, img, nodeName = element.nodeName.toLowerCase(); if ( "area" === nodeName ) { map = element.parentNode; mapName = map.name; if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) { return false; } img = $( "img[usemap=#" + mapName + "]" )[0]; return !!img && visible( img ); } return ( /input|select|textarea|button|object/.test( nodeName ) ? !element.disabled : "a" === nodeName ? element.href || isTabIndexNotNaN : isTabIndexNotNaN) && // the element and all of its ancestors must be visible visible( element ); } function visible( element ) { return $.expr.filters.visible( element ) && !$( element ).parents().andSelf().filter(function() { return $.css( this, "visibility" ) === "hidden"; }).length; } $.extend( $.expr[ ":" ], { data: $.expr.createPseudo ? $.expr.createPseudo(function( dataName ) { return function( elem ) { return !!$.data( elem, dataName ); }; }) : // support: jQuery <1.8 function( elem, i, match ) { return !!$.data( elem, match[ 3 ] ); }, focusable: function( element ) { return focusable( element, !isNaN( $.attr( element, "tabindex" ) ) ); }, tabbable: function( element ) { var tabIndex = $.attr( element, "tabindex" ), isTabIndexNaN = isNaN( tabIndex ); return ( isTabIndexNaN || tabIndex >= 0 ) && focusable( element, !isTabIndexNaN ); } }); // support $(function() { var body = document.body, div = body.appendChild( div = document.createElement( "div" ) ); // access offsetHeight before setting the style to prevent a layout bug // in IE 9 which causes the element to continue to take up space even // after it is removed from the DOM (#8026) div.offsetHeight; $.extend( div.style, { minHeight: "100px", height: "auto", padding: 0, borderWidth: 0 }); $.support.minHeight = div.offsetHeight === 100; $.support.selectstart = "onselectstart" in div; // set display to none to avoid a layout bug in IE // http://dev.jquery.com/ticket/4014 body.removeChild( div ).style.display = "none"; }); // support: jQuery <1.8 if ( !$( "<a>" ).outerWidth( 1 ).jquery ) { $.each( [ "Width", "Height" ], function( i, name ) { var side = name === "Width" ? [ "Left", "Right" ] : [ "Top", "Bottom" ], type = name.toLowerCase(), orig = { innerWidth: $.fn.innerWidth, innerHeight: $.fn.innerHeight, outerWidth: $.fn.outerWidth, outerHeight: $.fn.outerHeight }; function reduce( elem, size, border, margin ) { $.each( side, function() { size -= parseFloat( $.css( elem, "padding" + this ) ) || 0; if ( border ) { size -= parseFloat( $.css( elem, "border" + this + "Width" ) ) || 0; } if ( margin ) { size -= parseFloat( $.css( elem, "margin" + this ) ) || 0; } }); return size; } $.fn[ "inner" + name ] = function( size ) { if ( size === undefined ) { return orig[ "inner" + name ].call( this ); } return this.each(function() { $( this ).css( type, reduce( this, size ) + "px" ); }); }; $.fn[ "outer" + name] = function( size, margin ) { if ( typeof size !== "number" ) { return orig[ "outer" + name ].call( this, size ); } return this.each(function() { $( this).css( type, reduce( this, size, true, margin ) + "px" ); }); }; }); } // support: jQuery 1.6.1, 1.6.2 (http://bugs.jquery.com/ticket/9413) if ( $( "<a>" ).data( "a-b", "a" ).removeData( "a-b" ).data( "a-b" ) ) { $.fn.removeData = (function( removeData ) { return function( key ) { if ( arguments.length ) { return removeData.call( this, $.camelCase( key ) ); } else { return removeData.call( this ); } }; })( $.fn.removeData ); } // deprecated (function() { var uaMatch = /msie ([\w.]+)/.exec( navigator.userAgent.toLowerCase() ) || []; $.ui.ie = uaMatch.length ? true : false; $.ui.ie6 = parseFloat( uaMatch[ 1 ], 10 ) === 6; })(); $.fn.extend({ disableSelection: function() { return this.bind( ( $.support.selectstart ? "selectstart" : "mousedown" ) + ".ui-disableSelection", function( event ) { event.preventDefault(); }); }, enableSelection: function() { return this.unbind( ".ui-disableSelection" ); } }); $.extend( $.ui, { // $.ui.plugin is deprecated. Use the proxy pattern instead. plugin: { add: function( module, option, set ) { var i, proto = $.ui[ module ].prototype; for ( i in set ) { proto.plugins[ i ] = proto.plugins[ i ] || []; proto.plugins[ i ].push( [ option, set[ i ] ] ); } }, call: function( instance, name, args ) { var i, set = instance.plugins[ name ]; if ( !set || !instance.element[ 0 ].parentNode || instance.element[ 0 ].parentNode.nodeType === 11 ) { return; } for ( i = 0; i < set.length; i++ ) { if ( instance.options[ set[ i ][ 0 ] ] ) { set[ i ][ 1 ].apply( instance.element, args ); } } } }, contains: $.contains, // only used by resizable hasScroll: function( el, a ) { //If overflow is hidden, the element might have extra content, but the user wants to hide it if ( $( el ).css( "overflow" ) === "hidden") { return false; } var scroll = ( a && a === "left" ) ? "scrollLeft" : "scrollTop", has = false; if ( el[ scroll ] > 0 ) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[ scroll ] = 1; has = ( el[ scroll ] > 0 ); el[ scroll ] = 0; return has; }, // these are odd functions, fix the API or move into individual plugins isOverAxis: function( x, reference, size ) { //Determines when x coordinate is over "b" element axis return ( x > reference ) && ( x < ( reference + size ) ); }, isOver: function( y, x, top, left, height, width ) { //Determines when x, y coordinates is over "b" element return $.ui.isOverAxis( y, top, height ) && $.ui.isOverAxis( x, left, width ); } }); })( jQuery ); (function( $, undefined ) { var uuid = 0, slice = Array.prototype.slice, _cleanData = $.cleanData; $.cleanData = function( elems ) { for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) { try { $( elem ).triggerHandler( "remove" ); // http://bugs.jquery.com/ticket/8235 } catch( e ) {} } _cleanData( elems ); }; $.widget = function( name, base, prototype ) { var fullName, existingConstructor, constructor, basePrototype, namespace = name.split( "." )[ 0 ]; name = name.split( "." )[ 1 ]; fullName = namespace + "-" + name; if ( !prototype ) { prototype = base; base = $.Widget; } // create selector for plugin $.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) { return !!$.data( elem, fullName ); }; $[ namespace ] = $[ namespace ] || {}; existingConstructor = $[ namespace ][ name ]; constructor = $[ namespace ][ name ] = function( options, element ) { // allow instantiation without "new" keyword if ( !this._createWidget ) { return new constructor( options, element ); } // allow instantiation without initializing for simple inheritance // must use "new" keyword (the code above always passes args) if ( arguments.length ) { this._createWidget( options, element ); } }; // extend with the existing constructor to carry over any static properties $.extend( constructor, existingConstructor, { version: prototype.version, // copy the object used to create the prototype in case we need to // redefine the widget later _proto: $.extend( {}, prototype ), // track widgets that inherit from this widget in case this widget is // redefined after a widget inherits from it _childConstructors: [] }); basePrototype = new base(); // we need to make the options hash a property directly on the new instance // otherwise we'll modify the options hash on the prototype that we're // inheriting from basePrototype.options = $.widget.extend( {}, basePrototype.options ); $.each( prototype, function( prop, value ) { if ( $.isFunction( value ) ) { prototype[ prop ] = (function() { var _super = function() { return base.prototype[ prop ].apply( this, arguments ); }, _superApply = function( args ) { return base.prototype[ prop ].apply( this, args ); }; return function() { var __super = this._super, __superApply = this._superApply, returnValue; this._super = _super; this._superApply = _superApply; returnValue = value.apply( this, arguments ); this._super = __super; this._superApply = __superApply; return returnValue; }; })(); } }); constructor.prototype = $.widget.extend( basePrototype, { // TODO: remove support for widgetEventPrefix // always use the name + a colon as the prefix, e.g., draggable:start // don't prefix for widgets that aren't DOM-based widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name }, prototype, { constructor: constructor, namespace: namespace, widgetName: name, // TODO remove widgetBaseClass, see #8155 widgetBaseClass: fullName, widgetFullName: fullName }); // If this widget is being redefined then we need to find all widgets that // are inheriting from it and redefine all of them so that they inherit from // the new version of this widget. We're essentially trying to replace one // level in the prototype chain. if ( existingConstructor ) { $.each( existingConstructor._childConstructors, function( i, child ) { var childPrototype = child.prototype; // redefine the child widget using the same prototype that was // originally used, but inherit from the new version of the base $.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto ); }); // remove the list of existing child constructors from the old constructor // so the old child constructors can be garbage collected delete existingConstructor._childConstructors; } else { base._childConstructors.push( constructor ); } $.widget.bridge( name, constructor ); }; $.widget.extend = function( target ) { var input = slice.call( arguments, 1 ), inputIndex = 0, inputLength = input.length, key, value; for ( ; inputIndex < inputLength; inputIndex++ ) { for ( key in input[ inputIndex ] ) { value = input[ inputIndex ][ key ]; if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) { // Clone objects if ( $.isPlainObject( value ) ) { target[ key ] = $.isPlainObject( target[ key ] ) ? $.widget.extend( {}, target[ key ], value ) : // Don't extend strings, arrays, etc. with objects $.widget.extend( {}, value ); // Copy everything else by reference } else { target[ key ] = value; } } } } return target; }; $.widget.bridge = function( name, object ) { var fullName = object.prototype.widgetFullName || name; $.fn[ name ] = function( options ) { var isMethodCall = typeof options === "string", args = slice.call( arguments, 1 ), returnValue = this; // allow multiple hashes to be passed on init options = !isMethodCall && args.length ? $.widget.extend.apply( null, [ options ].concat(args) ) : options; if ( isMethodCall ) { this.each(function() { var methodValue, instance = $.data( this, fullName ); if ( !instance ) { return $.error( "cannot call methods on " + name + " prior to initialization; " + "attempted to call method '" + options + "'" ); } if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) { return $.error( "no such method '" + options + "' for " + name + " widget instance" ); } methodValue = instance[ options ].apply( instance, args ); if ( methodValue !== instance && methodValue !== undefined ) { returnValue = methodValue && methodValue.jquery ? returnValue.pushStack( methodValue.get() ) : methodValue; return false; } }); } else { this.each(function() { var instance = $.data( this, fullName ); if ( instance ) { instance.option( options || {} )._init(); } else { $.data( this, fullName, new object( options, this ) ); } }); } return returnValue; }; }; $.Widget = function( /* options, element */ ) {}; $.Widget._childConstructors = []; $.Widget.prototype = { widgetName: "widget", widgetEventPrefix: "", defaultElement: "<div>", options: { disabled: false, // callbacks create: null }, _createWidget: function( options, element ) { element = $( element || this.defaultElement || this )[ 0 ]; this.element = $( element ); this.uuid = uuid++; this.eventNamespace = "." + this.widgetName + this.uuid; this.options = $.widget.extend( {}, this.options, this._getCreateOptions(), options ); this.bindings = $(); this.hoverable = $(); this.focusable = $(); if ( element !== this ) { // 1.9 BC for #7810 // TODO remove dual storage $.data( element, this.widgetName, this ); $.data( element, this.widgetFullName, this ); this._on( true, this.element, { remove: function( event ) { if ( event.target === element ) { this.destroy(); } } }); this.document = $( element.style ? // element within the document element.ownerDocument : // element is window or document element.document || element ); this.window = $( this.document[0].defaultView || this.document[0].parentWindow ); } this._create(); this._trigger( "create", null, this._getCreateEventData() ); this._init(); }, _getCreateOptions: $.noop, _getCreateEventData: $.noop, _create: $.noop, _init: $.noop, destroy: function() { this._destroy(); // we can probably remove the unbind calls in 2.0 // all event bindings should go through this._on() this.element .unbind( this.eventNamespace ) // 1.9 BC for #7810 // TODO remove dual storage .removeData( this.widgetName ) .removeData( this.widgetFullName ) // support: jquery <1.6.3 // http://bugs.jquery.com/ticket/9413 .removeData( $.camelCase( this.widgetFullName ) ); this.widget() .unbind( this.eventNamespace ) .removeAttr( "aria-disabled" ) .removeClass( this.widgetFullName + "-disabled " + "ui-state-disabled" ); // clean up events and states this.bindings.unbind( this.eventNamespace ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); }, _destroy: $.noop, widget: function() { return this.element; }, option: function( key, value ) { var options = key, parts, curOption, i; if ( arguments.length === 0 ) { // don't return a reference to the internal hash return $.widget.extend( {}, this.options ); } if ( typeof key === "string" ) { // handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } } options = {}; parts = key.split( "." ); key = parts.shift(); if ( parts.length ) { curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] ); for ( i = 0; i < parts.length - 1; i++ ) { curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {}; curOption = curOption[ parts[ i ] ]; } key = parts.pop(); if ( value === undefined ) { return curOption[ key ] === undefined ? null : curOption[ key ]; } curOption[ key ] = value; } else { if ( value === undefined ) { return this.options[ key ] === undefined ? null : this.options[ key ]; } options[ key ] = value; } } this._setOptions( options ); return this; }, _setOptions: function( options ) { var key; for ( key in options ) { this._setOption( key, options[ key ] ); } return this; }, _setOption: function( key, value ) { this.options[ key ] = value; if ( key === "disabled" ) { this.widget() .toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value ) .attr( "aria-disabled", value ); this.hoverable.removeClass( "ui-state-hover" ); this.focusable.removeClass( "ui-state-focus" ); } return this; }, enable: function() { return this._setOption( "disabled", false ); }, disable: function() { return this._setOption( "disabled", true ); }, _on: function( suppressDisabledCheck, element, handlers ) { var delegateElement, instance = this; // no suppressDisabledCheck flag, shuffle arguments if ( typeof suppressDisabledCheck !== "boolean" ) { handlers = element; element = suppressDisabledCheck; suppressDisabledCheck = false; } // no element argument, shuffle and use this.element if ( !handlers ) { handlers = element; element = this.element; delegateElement = this.widget(); } else { // accept selectors, DOM elements element = delegateElement = $( element ); this.bindings = this.bindings.add( element ); } $.each( handlers, function( event, handler ) { function handlerProxy() { // allow widgets to customize the disabled handling // - disabled as an array instead of boolean // - disabled class as method for disabling individual parts if ( !suppressDisabledCheck && ( instance.options.disabled === true || $( this ).hasClass( "ui-state-disabled" ) ) ) { return; } return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } // copy the guid so direct unbinding works if ( typeof handler !== "string" ) { handlerProxy.guid = handler.guid = handler.guid || handlerProxy.guid || $.guid++; } var match = event.match( /^(\w+)\s*(.*)$/ ), eventName = match[1] + instance.eventNamespace, selector = match[2]; if ( selector ) { delegateElement.delegate( selector, eventName, handlerProxy ); } else { element.bind( eventName, handlerProxy ); } }); }, _off: function( element, eventName ) { eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace; element.unbind( eventName ).undelegate( eventName ); }, _delay: function( handler, delay ) { function handlerProxy() { return ( typeof handler === "string" ? instance[ handler ] : handler ) .apply( instance, arguments ); } var instance = this; return setTimeout( handlerProxy, delay || 0 ); }, _hoverable: function( element ) { this.hoverable = this.hoverable.add( element ); this._on( element, { mouseenter: function( event ) { $( event.currentTarget ).addClass( "ui-state-hover" ); }, mouseleave: function( event ) { $( event.currentTarget ).removeClass( "ui-state-hover" ); } }); }, _focusable: function( element ) { this.focusable = this.focusable.add( element ); this._on( element, { focusin: function( event ) { $( event.currentTarget ).addClass( "ui-state-focus" ); }, focusout: function( event ) { $( event.currentTarget ).removeClass( "ui-state-focus" ); } }); }, _trigger: function( type, event, data ) { var prop, orig, callback = this.options[ type ]; data = data || {}; event = $.Event( event ); event.type = ( type === this.widgetEventPrefix ? type : this.widgetEventPrefix + type ).toLowerCase(); // the original event may come from any element // so we need to reset the target on the new event event.target = this.element[ 0 ]; // copy original event properties over to the new event orig = event.originalEvent; if ( orig ) { for ( prop in orig ) { if ( !( prop in event ) ) { event[ prop ] = orig[ prop ]; } } } this.element.trigger( event, data ); return !( $.isFunction( callback ) && callback.apply( this.element[0], [ event ].concat( data ) ) === false || event.isDefaultPrevented() ); } }; $.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) { $.Widget.prototype[ "_" + method ] = function( element, options, callback ) { if ( typeof options === "string" ) { options = { effect: options }; } var hasOptions, effectName = !options ? method : options === true || typeof options === "number" ? defaultEffect : options.effect || defaultEffect; options = options || {}; if ( typeof options === "number" ) { options = { duration: options }; } hasOptions = !$.isEmptyObject( options ); options.complete = callback; if ( options.delay ) { element.delay( options.delay ); } if ( hasOptions && $.effects && ( $.effects.effect[ effectName ] || $.uiBackCompat !== false && $.effects[ effectName ] ) ) { element[ method ]( options ); } else if ( effectName !== method && element[ effectName ] ) { element[ effectName ]( options.duration, options.easing, callback ); } else { element.queue(function( next ) { $( this )[ method ](); if ( callback ) { callback.call( element[ 0 ] ); } next(); }); } }; }); // DEPRECATED if ( $.uiBackCompat !== false ) { $.Widget.prototype._getCreateOptions = function() { return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ]; }; } })( jQuery ); (function( $, undefined ) { var mouseHandled = false; $( document ).mouseup( function( e ) { mouseHandled = false; }); $.widget("ui.mouse", { version: "1.9.2", options: { cancel: 'input,textarea,button,select,option', distance: 1, delay: 0 }, _mouseInit: function() { var that = this; this.element .bind('mousedown.'+this.widgetName, function(event) { return that._mouseDown(event); }) .bind('click.'+this.widgetName, function(event) { if (true === $.data(event.target, that.widgetName + '.preventClickEvent')) { $.removeData(event.target, that.widgetName + '.preventClickEvent'); event.stopImmediatePropagation(); return false; } }); this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind('.'+this.widgetName); if ( this._mouseMoveDelegate ) { $(document) .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); } }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart if( mouseHandled ) { return; } // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var that = this, btnIsLeft = (event.which === 1), // event.target.nodeName works around a bug in IE 8 with // disabled inputs (#7620) elIsCancel = (typeof this.options.cancel === "string" && event.target.nodeName ? $(event.target).closest(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { that.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // Click event may never have fired (Gecko & Opera) if (true === $.data(event.target, this.widgetName + '.preventClickEvent')) { $.removeData(event.target, this.widgetName + '.preventClickEvent'); } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return that._mouseMove(event); }; this._mouseUpDelegate = function(event) { return that._mouseUp(event); }; $(document) .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .bind('mouseup.'+this.widgetName, this._mouseUpDelegate); event.preventDefault(); mouseHandled = true; return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.ui.ie && !(document.documentMode >= 9) && !event.button) { return this._mouseUp(event); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { $(document) .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); if (this._mouseStarted) { this._mouseStarted = false; if (event.target === this._mouseDownEvent.target) { $.data(event.target, this.widgetName + '.preventClickEvent', true); } this._mouseStop(event); } return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(event) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(event) {}, _mouseDrag: function(event) {}, _mouseStop: function(event) {}, _mouseCapture: function(event) { return true; } }); })(jQuery); (function( $, undefined ) { $.ui = $.ui || {}; var cachedScrollbarWidth, max = Math.max, abs = Math.abs, round = Math.round, rhorizontal = /left|center|right/, rvertical = /top|center|bottom/, roffset = /[\+\-]\d+%?/, rposition = /^\w+/, rpercent = /%$/, _position = $.fn.position; function getOffsets( offsets, width, height ) { return [ parseInt( offsets[ 0 ], 10 ) * ( rpercent.test( offsets[ 0 ] ) ? width / 100 : 1 ), parseInt( offsets[ 1 ], 10 ) * ( rpercent.test( offsets[ 1 ] ) ? height / 100 : 1 ) ]; } function parseCss( element, property ) { return parseInt( $.css( element, property ), 10 ) || 0; } $.position = { scrollbarWidth: function() { if ( cachedScrollbarWidth !== undefined ) { return cachedScrollbarWidth; } var w1, w2, div = $( "<div style='display:block;width:50px;height:50px;overflow:hidden;'><div style='height:100px;width:auto;'></div></div>" ), innerDiv = div.children()[0]; $( "body" ).append( div ); w1 = innerDiv.offsetWidth; div.css( "overflow", "scroll" ); w2 = innerDiv.offsetWidth; if ( w1 === w2 ) { w2 = div[0].clientWidth; } div.remove(); return (cachedScrollbarWidth = w1 - w2); }, getScrollInfo: function( within ) { var overflowX = within.isWindow ? "" : within.element.css( "overflow-x" ), overflowY = within.isWindow ? "" : within.element.css( "overflow-y" ), hasOverflowX = overflowX === "scroll" || ( overflowX === "auto" && within.width < within.element[0].scrollWidth ), hasOverflowY = overflowY === "scroll" || ( overflowY === "auto" && within.height < within.element[0].scrollHeight ); return { width: hasOverflowX ? $.position.scrollbarWidth() : 0, height: hasOverflowY ? $.position.scrollbarWidth() : 0 }; }, getWithinInfo: function( element ) { var withinElement = $( element || window ), isWindow = $.isWindow( withinElement[0] ); return { element: withinElement, isWindow: isWindow, offset: withinElement.offset() || { left: 0, top: 0 }, scrollLeft: withinElement.scrollLeft(), scrollTop: withinElement.scrollTop(), width: isWindow ? withinElement.width() : withinElement.outerWidth(), height: isWindow ? withinElement.height() : withinElement.outerHeight() }; } }; $.fn.position = function( options ) { if ( !options || !options.of ) { return _position.apply( this, arguments ); } // make a copy, we don't want to modify arguments options = $.extend( {}, options ); var atOffset, targetWidth, targetHeight, targetOffset, basePosition, target = $( options.of ), within = $.position.getWithinInfo( options.within ), scrollInfo = $.position.getScrollInfo( within ), targetElem = target[0], collision = ( options.collision || "flip" ).split( " " ), offsets = {}; if ( targetElem.nodeType === 9 ) { targetWidth = target.width(); targetHeight = target.height(); targetOffset = { top: 0, left: 0 }; } else if ( $.isWindow( targetElem ) ) { targetWidth = target.width(); targetHeight = target.height(); targetOffset = { top: target.scrollTop(), left: target.scrollLeft() }; } else if ( targetElem.preventDefault ) { // force left top to allow flipping options.at = "left top"; targetWidth = targetHeight = 0; targetOffset = { top: targetElem.pageY, left: targetElem.pageX }; } else { targetWidth = target.outerWidth(); targetHeight = target.outerHeight(); targetOffset = target.offset(); } // clone to reuse original targetOffset later basePosition = $.extend( {}, targetOffset ); // force my and at to have valid horizontal and vertical positions // if a value is missing or invalid, it will be converted to center $.each( [ "my", "at" ], function() { var pos = ( options[ this ] || "" ).split( " " ), horizontalOffset, verticalOffset; if ( pos.length === 1) { pos = rhorizontal.test( pos[ 0 ] ) ? pos.concat( [ "center" ] ) : rvertical.test( pos[ 0 ] ) ? [ "center" ].concat( pos ) : [ "center", "center" ]; } pos[ 0 ] = rhorizontal.test( pos[ 0 ] ) ? pos[ 0 ] : "center"; pos[ 1 ] = rvertical.test( pos[ 1 ] ) ? pos[ 1 ] : "center"; // calculate offsets horizontalOffset = roffset.exec( pos[ 0 ] ); verticalOffset = roffset.exec( pos[ 1 ] ); offsets[ this ] = [ horizontalOffset ? horizontalOffset[ 0 ] : 0, verticalOffset ? verticalOffset[ 0 ] : 0 ]; // reduce to just the positions without the offsets options[ this ] = [ rposition.exec( pos[ 0 ] )[ 0 ], rposition.exec( pos[ 1 ] )[ 0 ] ]; }); // normalize collision option if ( collision.length === 1 ) { collision[ 1 ] = collision[ 0 ]; } if ( options.at[ 0 ] === "right" ) { basePosition.left += targetWidth; } else if ( options.at[ 0 ] === "center" ) { basePosition.left += targetWidth / 2; } if ( options.at[ 1 ] === "bottom" ) { basePosition.top += targetHeight; } else if ( options.at[ 1 ] === "center" ) { basePosition.top += targetHeight / 2; } atOffset = getOffsets( offsets.at, targetWidth, targetHeight ); basePosition.left += atOffset[ 0 ]; basePosition.top += atOffset[ 1 ]; return this.each(function() { var collisionPosition, using, elem = $( this ), elemWidth = elem.outerWidth(), elemHeight = elem.outerHeight(), marginLeft = parseCss( this, "marginLeft" ), marginTop = parseCss( this, "marginTop" ), collisionWidth = elemWidth + marginLeft + parseCss( this, "marginRight" ) + scrollInfo.width, collisionHeight = elemHeight + marginTop + parseCss( this, "marginBottom" ) + scrollInfo.height, position = $.extend( {}, basePosition ), myOffset = getOffsets( offsets.my, elem.outerWidth(), elem.outerHeight() ); if ( options.my[ 0 ] === "right" ) { position.left -= elemWidth; } else if ( options.my[ 0 ] === "center" ) { position.left -= elemWidth / 2; } if ( options.my[ 1 ] === "bottom" ) { position.top -= elemHeight; } else if ( options.my[ 1 ] === "center" ) { position.top -= elemHeight / 2; } position.left += myOffset[ 0 ]; position.top += myOffset[ 1 ]; // if the browser doesn't support fractions, then round for consistent results if ( !$.support.offsetFractions ) { position.left = round( position.left ); position.top = round( position.top ); } collisionPosition = { marginLeft: marginLeft, marginTop: marginTop }; $.each( [ "left", "top" ], function( i, dir ) { if ( $.ui.position[ collision[ i ] ] ) { $.ui.position[ collision[ i ] ][ dir ]( position, { targetWidth: targetWidth, targetHeight: targetHeight, elemWidth: elemWidth, elemHeight: elemHeight, collisionPosition: collisionPosition, collisionWidth: collisionWidth, collisionHeight: collisionHeight, offset: [ atOffset[ 0 ] + myOffset[ 0 ], atOffset [ 1 ] + myOffset[ 1 ] ], my: options.my, at: options.at, within: within, elem : elem }); } }); if ( $.fn.bgiframe ) { elem.bgiframe(); } if ( options.using ) { // adds feedback as second argument to using callback, if present using = function( props ) { var left = targetOffset.left - position.left, right = left + targetWidth - elemWidth, top = targetOffset.top - position.top, bottom = top + targetHeight - elemHeight, feedback = { target: { element: target, left: targetOffset.left, top: targetOffset.top, width: targetWidth, height: targetHeight }, element: { element: elem, left: position.left, top: position.top, width: elemWidth, height: elemHeight }, horizontal: right < 0 ? "left" : left > 0 ? "right" : "center", vertical: bottom < 0 ? "top" : top > 0 ? "bottom" : "middle" }; if ( targetWidth < elemWidth && abs( left + right ) < targetWidth ) { feedback.horizontal = "center"; } if ( targetHeight < elemHeight && abs( top + bottom ) < targetHeight ) { feedback.vertical = "middle"; } if ( max( abs( left ), abs( right ) ) > max( abs( top ), abs( bottom ) ) ) { feedback.important = "horizontal"; } else { feedback.important = "vertical"; } options.using.call( this, props, feedback ); }; } elem.offset( $.extend( position, { using: using } ) ); }); }; $.ui.position = { fit: { left: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollLeft : within.offset.left, outerWidth = within.width, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = withinOffset - collisionPosLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - withinOffset, newOverRight; // element is wider than within if ( data.collisionWidth > outerWidth ) { // element is initially over the left side of within if ( overLeft > 0 && overRight <= 0 ) { newOverRight = position.left + overLeft + data.collisionWidth - outerWidth - withinOffset; position.left += overLeft - newOverRight; // element is initially over right side of within } else if ( overRight > 0 && overLeft <= 0 ) { position.left = withinOffset; // element is initially over both left and right sides of within } else { if ( overLeft > overRight ) { position.left = withinOffset + outerWidth - data.collisionWidth; } else { position.left = withinOffset; } } // too far left -> align with left edge } else if ( overLeft > 0 ) { position.left += overLeft; // too far right -> align with right edge } else if ( overRight > 0 ) { position.left -= overRight; // adjust based on position and margin } else { position.left = max( position.left - collisionPosLeft, position.left ); } }, top: function( position, data ) { var within = data.within, withinOffset = within.isWindow ? within.scrollTop : within.offset.top, outerHeight = data.within.height, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = withinOffset - collisionPosTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - withinOffset, newOverBottom; // element is taller than within if ( data.collisionHeight > outerHeight ) { // element is initially over the top of within if ( overTop > 0 && overBottom <= 0 ) { newOverBottom = position.top + overTop + data.collisionHeight - outerHeight - withinOffset; position.top += overTop - newOverBottom; // element is initially over bottom of within } else if ( overBottom > 0 && overTop <= 0 ) { position.top = withinOffset; // element is initially over both top and bottom of within } else { if ( overTop > overBottom ) { position.top = withinOffset + outerHeight - data.collisionHeight; } else { position.top = withinOffset; } } // too far up -> align with top } else if ( overTop > 0 ) { position.top += overTop; // too far down -> align with bottom edge } else if ( overBottom > 0 ) { position.top -= overBottom; // adjust based on position and margin } else { position.top = max( position.top - collisionPosTop, position.top ); } } }, flip: { left: function( position, data ) { var within = data.within, withinOffset = within.offset.left + within.scrollLeft, outerWidth = within.width, offsetLeft = within.isWindow ? within.scrollLeft : within.offset.left, collisionPosLeft = position.left - data.collisionPosition.marginLeft, overLeft = collisionPosLeft - offsetLeft, overRight = collisionPosLeft + data.collisionWidth - outerWidth - offsetLeft, myOffset = data.my[ 0 ] === "left" ? -data.elemWidth : data.my[ 0 ] === "right" ? data.elemWidth : 0, atOffset = data.at[ 0 ] === "left" ? data.targetWidth : data.at[ 0 ] === "right" ? -data.targetWidth : 0, offset = -2 * data.offset[ 0 ], newOverRight, newOverLeft; if ( overLeft < 0 ) { newOverRight = position.left + myOffset + atOffset + offset + data.collisionWidth - outerWidth - withinOffset; if ( newOverRight < 0 || newOverRight < abs( overLeft ) ) { position.left += myOffset + atOffset + offset; } } else if ( overRight > 0 ) { newOverLeft = position.left - data.collisionPosition.marginLeft + myOffset + atOffset + offset - offsetLeft; if ( newOverLeft > 0 || abs( newOverLeft ) < overRight ) { position.left += myOffset + atOffset + offset; } } }, top: function( position, data ) { var within = data.within, withinOffset = within.offset.top + within.scrollTop, outerHeight = within.height, offsetTop = within.isWindow ? within.scrollTop : within.offset.top, collisionPosTop = position.top - data.collisionPosition.marginTop, overTop = collisionPosTop - offsetTop, overBottom = collisionPosTop + data.collisionHeight - outerHeight - offsetTop, top = data.my[ 1 ] === "top", myOffset = top ? -data.elemHeight : data.my[ 1 ] === "bottom" ? data.elemHeight : 0, atOffset = data.at[ 1 ] === "top" ? data.targetHeight : data.at[ 1 ] === "bottom" ? -data.targetHeight : 0, offset = -2 * data.offset[ 1 ], newOverTop, newOverBottom; if ( overTop < 0 ) { newOverBottom = position.top + myOffset + atOffset + offset + data.collisionHeight - outerHeight - withinOffset; if ( ( position.top + myOffset + atOffset + offset) > overTop && ( newOverBottom < 0 || newOverBottom < abs( overTop ) ) ) { position.top += myOffset + atOffset + offset; } } else if ( overBottom > 0 ) { newOverTop = position.top - data.collisionPosition.marginTop + myOffset + atOffset + offset - offsetTop; if ( ( position.top + myOffset + atOffset + offset) > overBottom && ( newOverTop > 0 || abs( newOverTop ) < overBottom ) ) { position.top += myOffset + atOffset + offset; } } } }, flipfit: { left: function() { $.ui.position.flip.left.apply( this, arguments ); $.ui.position.fit.left.apply( this, arguments ); }, top: function() { $.ui.position.flip.top.apply( this, arguments ); $.ui.position.fit.top.apply( this, arguments ); } } }; // fraction support test (function () { var testElement, testElementParent, testElementStyle, offsetLeft, i, body = document.getElementsByTagName( "body" )[ 0 ], div = document.createElement( "div" ); //Create a "fake body" for testing based on method used in jQuery.support testElement = document.createElement( body ? "div" : "body" ); testElementStyle = { visibility: "hidden", width: 0, height: 0, border: 0, margin: 0, background: "none" }; if ( body ) { $.extend( testElementStyle, { position: "absolute", left: "-1000px", top: "-1000px" }); } for ( i in testElementStyle ) { testElement.style[ i ] = testElementStyle[ i ]; } testElement.appendChild( div ); testElementParent = body || document.documentElement; testElementParent.insertBefore( testElement, testElementParent.firstChild ); div.style.cssText = "position: absolute; left: 10.7432222px;"; offsetLeft = $( div ).offset().left; $.support.offsetFractions = offsetLeft > 10 && offsetLeft < 11; testElement.innerHTML = ""; testElementParent.removeChild( testElement ); })(); // DEPRECATED if ( $.uiBackCompat !== false ) { // offset option (function( $ ) { var _position = $.fn.position; $.fn.position = function( options ) { if ( !options || !options.offset ) { return _position.call( this, options ); } var offset = options.offset.split( " " ), at = options.at.split( " " ); if ( offset.length === 1 ) { offset[ 1 ] = offset[ 0 ]; } if ( /^\d/.test( offset[ 0 ] ) ) { offset[ 0 ] = "+" + offset[ 0 ]; } if ( /^\d/.test( offset[ 1 ] ) ) { offset[ 1 ] = "+" + offset[ 1 ]; } if ( at.length === 1 ) { if ( /left|center|right/.test( at[ 0 ] ) ) { at[ 1 ] = "center"; } else { at[ 1 ] = at[ 0 ]; at[ 0 ] = "center"; } } return _position.call( this, $.extend( options, { at: at[ 0 ] + offset[ 0 ] + " " + at[ 1 ] + offset[ 1 ], offset: undefined } ) ); }; }( jQuery ) ); } }( jQuery ) ); (function( $, undefined ) { var uid = 0, hideProps = {}, showProps = {}; hideProps.height = hideProps.paddingTop = hideProps.paddingBottom = hideProps.borderTopWidth = hideProps.borderBottomWidth = "hide"; showProps.height = showProps.paddingTop = showProps.paddingBottom = showProps.borderTopWidth = showProps.borderBottomWidth = "show"; $.widget( "ui.accordion", { version: "1.9.2", options: { active: 0, animate: {}, collapsible: false, event: "click", header: "> li > :first-child,> :not(li):even", heightStyle: "auto", icons: { activeHeader: "ui-icon-triangle-1-s", header: "ui-icon-triangle-1-e" }, // callbacks activate: null, beforeActivate: null }, _create: function() { var accordionId = this.accordionId = "ui-accordion-" + (this.element.attr( "id" ) || ++uid), options = this.options; this.prevShow = this.prevHide = $(); this.element.addClass( "ui-accordion ui-widget ui-helper-reset" ); this.headers = this.element.find( options.header ) .addClass( "ui-accordion-header ui-helper-reset ui-state-default ui-corner-all" ); this._hoverable( this.headers ); this._focusable( this.headers ); this.headers.next() .addClass( "ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom" ) .hide(); // don't allow collapsible: false and active: false / null if ( !options.collapsible && (options.active === false || options.active == null) ) { options.active = 0; } // handle negative values if ( options.active < 0 ) { options.active += this.headers.length; } this.active = this._findActive( options.active ) .addClass( "ui-accordion-header-active ui-state-active" ) .toggleClass( "ui-corner-all ui-corner-top" ); this.active.next() .addClass( "ui-accordion-content-active" ) .show(); this._createIcons(); this.refresh(); // ARIA this.element.attr( "role", "tablist" ); this.headers .attr( "role", "tab" ) .each(function( i ) { var header = $( this ), headerId = header.attr( "id" ), panel = header.next(), panelId = panel.attr( "id" ); if ( !headerId ) { headerId = accordionId + "-header-" + i; header.attr( "id", headerId ); } if ( !panelId ) { panelId = accordionId + "-panel-" + i; panel.attr( "id", panelId ); } header.attr( "aria-controls", panelId ); panel.attr( "aria-labelledby", headerId ); }) .next() .attr( "role", "tabpanel" ); this.headers .not( this.active ) .attr({ "aria-selected": "false", tabIndex: -1 }) .next() .attr({ "aria-expanded": "false", "aria-hidden": "true" }) .hide(); // make sure at least one header is in the tab order if ( !this.active.length ) { this.headers.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active.attr({ "aria-selected": "true", tabIndex: 0 }) .next() .attr({ "aria-expanded": "true", "aria-hidden": "false" }); } this._on( this.headers, { keydown: "_keydown" }); this._on( this.headers.next(), { keydown: "_panelKeyDown" }); this._setupEvents( options.event ); }, _getCreateEventData: function() { return { header: this.active, content: !this.active.length ? $() : this.active.next() }; }, _createIcons: function() { var icons = this.options.icons; if ( icons ) { $( "<span>" ) .addClass( "ui-accordion-header-icon ui-icon " + icons.header ) .prependTo( this.headers ); this.active.children( ".ui-accordion-header-icon" ) .removeClass( icons.header ) .addClass( icons.activeHeader ); this.headers.addClass( "ui-accordion-icons" ); } }, _destroyIcons: function() { this.headers .removeClass( "ui-accordion-icons" ) .children( ".ui-accordion-header-icon" ) .remove(); }, _destroy: function() { var contents; // clean up main element this.element .removeClass( "ui-accordion ui-widget ui-helper-reset" ) .removeAttr( "role" ); // clean up headers this.headers .removeClass( "ui-accordion-header ui-accordion-header-active ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-state-disabled ui-corner-top" ) .removeAttr( "role" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-controls" ) .removeAttr( "tabIndex" ) .each(function() { if ( /^ui-accordion/.test( this.id ) ) { this.removeAttribute( "id" ); } }); this._destroyIcons(); // clean up content panels contents = this.headers.next() .css( "display", "" ) .removeAttr( "role" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-labelledby" ) .removeClass( "ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active ui-state-disabled" ) .each(function() { if ( /^ui-accordion/.test( this.id ) ) { this.removeAttribute( "id" ); } }); if ( this.options.heightStyle !== "content" ) { contents.css( "height", "" ); } }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "event" ) { if ( this.options.event ) { this._off( this.headers, this.options.event ); } this._setupEvents( value ); } this._super( key, value ); // setting collapsible: false while collapsed; open first panel if ( key === "collapsible" && !value && this.options.active === false ) { this._activate( 0 ); } if ( key === "icons" ) { this._destroyIcons(); if ( value ) { this._createIcons(); } } // #5332 - opacity doesn't cascade to positioned elements in IE // so we need to add the disabled class to the headers and panels if ( key === "disabled" ) { this.headers.add( this.headers.next() ) .toggleClass( "ui-state-disabled", !!value ); } }, _keydown: function( event ) { if ( event.altKey || event.ctrlKey ) { return; } var keyCode = $.ui.keyCode, length = this.headers.length, currentIndex = this.headers.index( event.target ), toFocus = false; switch ( event.keyCode ) { case keyCode.RIGHT: case keyCode.DOWN: toFocus = this.headers[ ( currentIndex + 1 ) % length ]; break; case keyCode.LEFT: case keyCode.UP: toFocus = this.headers[ ( currentIndex - 1 + length ) % length ]; break; case keyCode.SPACE: case keyCode.ENTER: this._eventHandler( event ); break; case keyCode.HOME: toFocus = this.headers[ 0 ]; break; case keyCode.END: toFocus = this.headers[ length - 1 ]; break; } if ( toFocus ) { $( event.target ).attr( "tabIndex", -1 ); $( toFocus ).attr( "tabIndex", 0 ); toFocus.focus(); event.preventDefault(); } }, _panelKeyDown : function( event ) { if ( event.keyCode === $.ui.keyCode.UP && event.ctrlKey ) { $( event.currentTarget ).prev().focus(); } }, refresh: function() { var maxHeight, overflow, heightStyle = this.options.heightStyle, parent = this.element.parent(); if ( heightStyle === "fill" ) { // IE 6 treats height like minHeight, so we need to turn off overflow // in order to get a reliable height // we use the minHeight support test because we assume that only // browsers that don't support minHeight will treat height as minHeight if ( !$.support.minHeight ) { overflow = parent.css( "overflow" ); parent.css( "overflow", "hidden"); } maxHeight = parent.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); if ( overflow ) { parent.css( "overflow", overflow ); } this.headers.each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.headers.next() .each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.headers.next() .each(function() { maxHeight = Math.max( maxHeight, $( this ).css( "height", "" ).height() ); }) .height( maxHeight ); } }, _activate: function( index ) { var active = this._findActive( index )[ 0 ]; // trying to activate the already active panel if ( active === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the currently active header active = active || this.active[ 0 ]; this._eventHandler({ target: active, currentTarget: active, preventDefault: $.noop }); }, _findActive: function( selector ) { return typeof selector === "number" ? this.headers.eq( selector ) : $(); }, _setupEvents: function( event ) { var events = {}; if ( !event ) { return; } $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); this._on( this.headers, events ); }, _eventHandler: function( event ) { var options = this.options, active = this.active, clicked = $( event.currentTarget ), clickedIsActive = clicked[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : clicked.next(), toHide = active.next(), eventData = { oldHeader: active, oldPanel: toHide, newHeader: collapsing ? $() : clicked, newPanel: toShow }; event.preventDefault(); if ( // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.headers.index( clicked ); // when the call to ._toggle() comes after the class changes // it causes a very odd bug in IE 8 (see #6720) this.active = clickedIsActive ? $() : clicked; this._toggle( eventData ); // switch classes // corner classes on the previously active header stay after the animation active.removeClass( "ui-accordion-header-active ui-state-active" ); if ( options.icons ) { active.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.activeHeader ) .addClass( options.icons.header ); } if ( !clickedIsActive ) { clicked .removeClass( "ui-corner-all" ) .addClass( "ui-accordion-header-active ui-state-active ui-corner-top" ); if ( options.icons ) { clicked.children( ".ui-accordion-header-icon" ) .removeClass( options.icons.header ) .addClass( options.icons.activeHeader ); } clicked .next() .addClass( "ui-accordion-content-active" ); } }, _toggle: function( data ) { var toShow = data.newPanel, toHide = this.prevShow.length ? this.prevShow : data.oldPanel; // handle activating a panel during the animation for another activation this.prevShow.add( this.prevHide ).stop( true, true ); this.prevShow = toShow; this.prevHide = toHide; if ( this.options.animate ) { this._animate( toShow, toHide, data ); } else { toHide.hide(); toShow.show(); this._toggleComplete( data ); } toHide.attr({ "aria-expanded": "false", "aria-hidden": "true" }); toHide.prev().attr( "aria-selected", "false" ); // if we're switching panels, remove the old header from the tab order // if we're opening from collapsed state, remove the previous header from the tab order // if we're collapsing, then keep the collapsing header in the tab order if ( toShow.length && toHide.length ) { toHide.prev().attr( "tabIndex", -1 ); } else if ( toShow.length ) { this.headers.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow .attr({ "aria-expanded": "true", "aria-hidden": "false" }) .prev() .attr({ "aria-selected": "true", tabIndex: 0 }); }, _animate: function( toShow, toHide, data ) { var total, easing, duration, that = this, adjust = 0, down = toShow.length && ( !toHide.length || ( toShow.index() < toHide.index() ) ), animate = this.options.animate || {}, options = down && animate.down || animate, complete = function() { that._toggleComplete( data ); }; if ( typeof options === "number" ) { duration = options; } if ( typeof options === "string" ) { easing = options; } // fall back from options to animation in case of partial down settings easing = easing || options.easing || animate.easing; duration = duration || options.duration || animate.duration; if ( !toHide.length ) { return toShow.animate( showProps, duration, easing, complete ); } if ( !toShow.length ) { return toHide.animate( hideProps, duration, easing, complete ); } total = toShow.show().outerHeight(); toHide.animate( hideProps, { duration: duration, easing: easing, step: function( now, fx ) { fx.now = Math.round( now ); } }); toShow .hide() .animate( showProps, { duration: duration, easing: easing, complete: complete, step: function( now, fx ) { fx.now = Math.round( now ); if ( fx.prop !== "height" ) { adjust += fx.now; } else if ( that.options.heightStyle !== "content" ) { fx.now = Math.round( total - toHide.outerHeight() - adjust ); adjust = 0; } } }); }, _toggleComplete: function( data ) { var toHide = data.oldPanel; toHide .removeClass( "ui-accordion-content-active" ) .prev() .removeClass( "ui-corner-top" ) .addClass( "ui-corner-all" ); // Work around for rendering bug in IE (#5421) if ( toHide.length ) { toHide.parent()[0].className = toHide.parent()[0].className; } this._trigger( "activate", null, data ); } }); // DEPRECATED if ( $.uiBackCompat !== false ) { // navigation options (function( $, prototype ) { $.extend( prototype.options, { navigation: false, navigationFilter: function() { return this.href.toLowerCase() === location.href.toLowerCase(); } }); var _create = prototype._create; prototype._create = function() { if ( this.options.navigation ) { var that = this, headers = this.element.find( this.options.header ), content = headers.next(), current = headers.add( content ) .find( "a" ) .filter( this.options.navigationFilter ) [ 0 ]; if ( current ) { headers.add( content ).each( function( index ) { if ( $.contains( this, current ) ) { that.options.active = Math.floor( index / 2 ); return false; } }); } } _create.call( this ); }; }( jQuery, jQuery.ui.accordion.prototype ) ); // height options (function( $, prototype ) { $.extend( prototype.options, { heightStyle: null, // remove default so we fall back to old values autoHeight: true, // use heightStyle: "auto" clearStyle: false, // use heightStyle: "content" fillSpace: false // use heightStyle: "fill" }); var _create = prototype._create, _setOption = prototype._setOption; $.extend( prototype, { _create: function() { this.options.heightStyle = this.options.heightStyle || this._mergeHeightStyle(); _create.call( this ); }, _setOption: function( key ) { if ( key === "autoHeight" || key === "clearStyle" || key === "fillSpace" ) { this.options.heightStyle = this._mergeHeightStyle(); } _setOption.apply( this, arguments ); }, _mergeHeightStyle: function() { var options = this.options; if ( options.fillSpace ) { return "fill"; } if ( options.clearStyle ) { return "content"; } if ( options.autoHeight ) { return "auto"; } } }); }( jQuery, jQuery.ui.accordion.prototype ) ); // icon options (function( $, prototype ) { $.extend( prototype.options.icons, { activeHeader: null, // remove default so we fall back to old values headerSelected: "ui-icon-triangle-1-s" }); var _createIcons = prototype._createIcons; prototype._createIcons = function() { if ( this.options.icons ) { this.options.icons.activeHeader = this.options.icons.activeHeader || this.options.icons.headerSelected; } _createIcons.call( this ); }; }( jQuery, jQuery.ui.accordion.prototype ) ); // expanded active option, activate method (function( $, prototype ) { prototype.activate = prototype._activate; var _findActive = prototype._findActive; prototype._findActive = function( index ) { if ( index === -1 ) { index = false; } if ( index && typeof index !== "number" ) { index = this.headers.index( this.headers.filter( index ) ); if ( index === -1 ) { index = false; } } return _findActive.call( this, index ); }; }( jQuery, jQuery.ui.accordion.prototype ) ); // resize method jQuery.ui.accordion.prototype.resize = jQuery.ui.accordion.prototype.refresh; // change events (function( $, prototype ) { $.extend( prototype.options, { change: null, changestart: null }); var _trigger = prototype._trigger; prototype._trigger = function( type, event, data ) { var ret = _trigger.apply( this, arguments ); if ( !ret ) { return false; } if ( type === "beforeActivate" ) { ret = _trigger.call( this, "changestart", event, { oldHeader: data.oldHeader, oldContent: data.oldPanel, newHeader: data.newHeader, newContent: data.newPanel }); } else if ( type === "activate" ) { ret = _trigger.call( this, "change", event, { oldHeader: data.oldHeader, oldContent: data.oldPanel, newHeader: data.newHeader, newContent: data.newPanel }); } return ret; }; }( jQuery, jQuery.ui.accordion.prototype ) ); // animated option // NOTE: this only provides support for "slide", "bounceslide", and easings // not the full $.ui.accordion.animations API (function( $, prototype ) { $.extend( prototype.options, { animate: null, animated: "slide" }); var _create = prototype._create; prototype._create = function() { var options = this.options; if ( options.animate === null ) { if ( !options.animated ) { options.animate = false; } else if ( options.animated === "slide" ) { options.animate = 300; } else if ( options.animated === "bounceslide" ) { options.animate = { duration: 200, down: { easing: "easeOutBounce", duration: 1000 } }; } else { options.animate = options.animated; } } _create.call( this ); }; }( jQuery, jQuery.ui.accordion.prototype ) ); } })( jQuery ); (function( $, undefined ) { // used to prevent race conditions with remote data sources var requestIndex = 0; $.widget( "ui.autocomplete", { version: "1.9.2", defaultElement: "<input>", options: { appendTo: "body", autoFocus: false, delay: 300, minLength: 1, position: { my: "left top", at: "left bottom", collision: "none" }, source: null, // callbacks change: null, close: null, focus: null, open: null, response: null, search: null, select: null }, pending: 0, _create: function() { // Some browsers only repeat keydown events, not keypress events, // so we use the suppressKeyPress flag to determine if we've already // handled the keydown event. #7269 // Unfortunately the code for & in keypress is the same as the up arrow, // so we use the suppressKeyPressRepeat flag to avoid handling keypress // events when we know the keydown event was used to modify the // search term. #7799 var suppressKeyPress, suppressKeyPressRepeat, suppressInput; this.isMultiLine = this._isMultiLine(); this.valueMethod = this.element[ this.element.is( "input,textarea" ) ? "val" : "text" ]; this.isNewMenu = true; this.element .addClass( "ui-autocomplete-input" ) .attr( "autocomplete", "off" ); this._on( this.element, { keydown: function( event ) { if ( this.element.prop( "readOnly" ) ) { suppressKeyPress = true; suppressInput = true; suppressKeyPressRepeat = true; return; } suppressKeyPress = false; suppressInput = false; suppressKeyPressRepeat = false; var keyCode = $.ui.keyCode; switch( event.keyCode ) { case keyCode.PAGE_UP: suppressKeyPress = true; this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: suppressKeyPress = true; this._move( "nextPage", event ); break; case keyCode.UP: suppressKeyPress = true; this._keyEvent( "previous", event ); break; case keyCode.DOWN: suppressKeyPress = true; this._keyEvent( "next", event ); break; case keyCode.ENTER: case keyCode.NUMPAD_ENTER: // when menu is open and has focus if ( this.menu.active ) { // #6055 - Opera still allows the keypress to occur // which causes forms to submit suppressKeyPress = true; event.preventDefault(); this.menu.select( event ); } break; case keyCode.TAB: if ( this.menu.active ) { this.menu.select( event ); } break; case keyCode.ESCAPE: if ( this.menu.element.is( ":visible" ) ) { this._value( this.term ); this.close( event ); // Different browsers have different default behavior for escape // Single press can mean undo or clear // Double press in IE means clear the whole form event.preventDefault(); } break; default: suppressKeyPressRepeat = true; // search timeout should be triggered before the input value is changed this._searchTimeout( event ); break; } }, keypress: function( event ) { if ( suppressKeyPress ) { suppressKeyPress = false; event.preventDefault(); return; } if ( suppressKeyPressRepeat ) { return; } // replicate some key handlers to allow them to repeat in Firefox and Opera var keyCode = $.ui.keyCode; switch( event.keyCode ) { case keyCode.PAGE_UP: this._move( "previousPage", event ); break; case keyCode.PAGE_DOWN: this._move( "nextPage", event ); break; case keyCode.UP: this._keyEvent( "previous", event ); break; case keyCode.DOWN: this._keyEvent( "next", event ); break; } }, input: function( event ) { if ( suppressInput ) { suppressInput = false; event.preventDefault(); return; } this._searchTimeout( event ); }, focus: function() { this.selectedItem = null; this.previous = this._value(); }, blur: function( event ) { if ( this.cancelBlur ) { delete this.cancelBlur; return; } clearTimeout( this.searching ); this.close( event ); this._change( event ); } }); this._initSource(); this.menu = $( "<ul>" ) .addClass( "ui-autocomplete" ) .appendTo( this.document.find( this.options.appendTo || "body" )[ 0 ] ) .menu({ // custom key handling for now input: $(), // disable ARIA support, the live region takes care of that role: null }) .zIndex( this.element.zIndex() + 1 ) .hide() .data( "menu" ); this._on( this.menu.element, { mousedown: function( event ) { // prevent moving focus out of the text field event.preventDefault(); // IE doesn't prevent moving focus even with event.preventDefault() // so we set a flag to know when we should ignore the blur event this.cancelBlur = true; this._delay(function() { delete this.cancelBlur; }); // clicking on the scrollbar causes focus to shift to the body // but we can't detect a mouseup or a click immediately afterward // so we have to track the next mousedown and close the menu if // the user clicks somewhere outside of the autocomplete var menuElement = this.menu.element[ 0 ]; if ( !$( event.target ).closest( ".ui-menu-item" ).length ) { this._delay(function() { var that = this; this.document.one( "mousedown", function( event ) { if ( event.target !== that.element[ 0 ] && event.target !== menuElement && !$.contains( menuElement, event.target ) ) { that.close(); } }); }); } }, menufocus: function( event, ui ) { // #7024 - Prevent accidental activation of menu items in Firefox if ( this.isNewMenu ) { this.isNewMenu = false; if ( event.originalEvent && /^mouse/.test( event.originalEvent.type ) ) { this.menu.blur(); this.document.one( "mousemove", function() { $( event.target ).trigger( event.originalEvent ); }); return; } } // back compat for _renderItem using item.autocomplete, via #7810 // TODO remove the fallback, see #8156 var item = ui.item.data( "ui-autocomplete-item" ) || ui.item.data( "item.autocomplete" ); if ( false !== this._trigger( "focus", event, { item: item } ) ) { // use value to match what will end up in the input, if it was a key event if ( event.originalEvent && /^key/.test( event.originalEvent.type ) ) { this._value( item.value ); } } else { // Normally the input is populated with the item's value as the // menu is navigated, causing screen readers to notice a change and // announce the item. Since the focus event was canceled, this doesn't // happen, so we update the live region so that screen readers can // still notice the change and announce it. this.liveRegion.text( item.value ); } }, menuselect: function( event, ui ) { // back compat for _renderItem using item.autocomplete, via #7810 // TODO remove the fallback, see #8156 var item = ui.item.data( "ui-autocomplete-item" ) || ui.item.data( "item.autocomplete" ), previous = this.previous; // only trigger when focus was lost (click on menu) if ( this.element[0] !== this.document[0].activeElement ) { this.element.focus(); this.previous = previous; // #6109 - IE triggers two focus events and the second // is asynchronous, so we need to reset the previous // term synchronously and asynchronously :-( this._delay(function() { this.previous = previous; this.selectedItem = item; }); } if ( false !== this._trigger( "select", event, { item: item } ) ) { this._value( item.value ); } // reset the term after the select event // this allows custom select handling to work properly this.term = this._value(); this.close( event ); this.selectedItem = item; } }); this.liveRegion = $( "<span>", { role: "status", "aria-live": "polite" }) .addClass( "ui-helper-hidden-accessible" ) .insertAfter( this.element ); if ( $.fn.bgiframe ) { this.menu.element.bgiframe(); } // turning off autocomplete prevents the browser from remembering the // value when navigating through history, so we re-enable autocomplete // if the page is unloaded before the widget is destroyed. #7790 this._on( this.window, { beforeunload: function() { this.element.removeAttr( "autocomplete" ); } }); }, _destroy: function() { clearTimeout( this.searching ); this.element .removeClass( "ui-autocomplete-input" ) .removeAttr( "autocomplete" ); this.menu.element.remove(); this.liveRegion.remove(); }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "source" ) { this._initSource(); } if ( key === "appendTo" ) { this.menu.element.appendTo( this.document.find( value || "body" )[0] ); } if ( key === "disabled" && value && this.xhr ) { this.xhr.abort(); } }, _isMultiLine: function() { // Textareas are always multi-line if ( this.element.is( "textarea" ) ) { return true; } // Inputs are always single-line, even if inside a contentEditable element // IE also treats inputs as contentEditable if ( this.element.is( "input" ) ) { return false; } // All other element types are determined by whether or not they're contentEditable return this.element.prop( "isContentEditable" ); }, _initSource: function() { var array, url, that = this; if ( $.isArray(this.options.source) ) { array = this.options.source; this.source = function( request, response ) { response( $.ui.autocomplete.filter( array, request.term ) ); }; } else if ( typeof this.options.source === "string" ) { url = this.options.source; this.source = function( request, response ) { if ( that.xhr ) { that.xhr.abort(); } that.xhr = $.ajax({ url: url, data: request, dataType: "json", success: function( data ) { response( data ); }, error: function() { response( [] ); } }); }; } else { this.source = this.options.source; } }, _searchTimeout: function( event ) { clearTimeout( this.searching ); this.searching = this._delay(function() { // only search if the value has changed if ( this.term !== this._value() ) { this.selectedItem = null; this.search( null, event ); } }, this.options.delay ); }, search: function( value, event ) { value = value != null ? value : this._value(); // always save the actual value, not the one passed as an argument this.term = this._value(); if ( value.length < this.options.minLength ) { return this.close( event ); } if ( this._trigger( "search", event ) === false ) { return; } return this._search( value ); }, _search: function( value ) { this.pending++; this.element.addClass( "ui-autocomplete-loading" ); this.cancelSearch = false; this.source( { term: value }, this._response() ); }, _response: function() { var that = this, index = ++requestIndex; return function( content ) { if ( index === requestIndex ) { that.__response( content ); } that.pending--; if ( !that.pending ) { that.element.removeClass( "ui-autocomplete-loading" ); } }; }, __response: function( content ) { if ( content ) { content = this._normalize( content ); } this._trigger( "response", null, { content: content } ); if ( !this.options.disabled && content && content.length && !this.cancelSearch ) { this._suggest( content ); this._trigger( "open" ); } else { // use ._close() instead of .close() so we don't cancel future searches this._close(); } }, close: function( event ) { this.cancelSearch = true; this._close( event ); }, _close: function( event ) { if ( this.menu.element.is( ":visible" ) ) { this.menu.element.hide(); this.menu.blur(); this.isNewMenu = true; this._trigger( "close", event ); } }, _change: function( event ) { if ( this.previous !== this._value() ) { this._trigger( "change", event, { item: this.selectedItem } ); } }, _normalize: function( items ) { // assume all items have the right format when the first item is complete if ( items.length && items[0].label && items[0].value ) { return items; } return $.map( items, function( item ) { if ( typeof item === "string" ) { return { label: item, value: item }; } return $.extend({ label: item.label || item.value, value: item.value || item.label }, item ); }); }, _suggest: function( items ) { var ul = this.menu.element .empty() .zIndex( this.element.zIndex() + 1 ); this._renderMenu( ul, items ); this.menu.refresh(); // size and position menu ul.show(); this._resizeMenu(); ul.position( $.extend({ of: this.element }, this.options.position )); if ( this.options.autoFocus ) { this.menu.next(); } }, _resizeMenu: function() { var ul = this.menu.element; ul.outerWidth( Math.max( // Firefox wraps long text (possibly a rounding bug) // so we add 1px to avoid the wrapping (#7513) ul.width( "" ).outerWidth() + 1, this.element.outerWidth() ) ); }, _renderMenu: function( ul, items ) { var that = this; $.each( items, function( index, item ) { that._renderItemData( ul, item ); }); }, _renderItemData: function( ul, item ) { return this._renderItem( ul, item ).data( "ui-autocomplete-item", item ); }, _renderItem: function( ul, item ) { return $( "<li>" ) .append( $( "<a>" ).text( item.label ) ) .appendTo( ul ); }, _move: function( direction, event ) { if ( !this.menu.element.is( ":visible" ) ) { this.search( null, event ); return; } if ( this.menu.isFirstItem() && /^previous/.test( direction ) || this.menu.isLastItem() && /^next/.test( direction ) ) { this._value( this.term ); this.menu.blur(); return; } this.menu[ direction ]( event ); }, widget: function() { return this.menu.element; }, _value: function() { return this.valueMethod.apply( this.element, arguments ); }, _keyEvent: function( keyEvent, event ) { if ( !this.isMultiLine || this.menu.element.is( ":visible" ) ) { this._move( keyEvent, event ); // prevents moving cursor to beginning/end of the text field in some browsers event.preventDefault(); } } }); $.extend( $.ui.autocomplete, { escapeRegex: function( value ) { return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&"); }, filter: function(array, term) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" ); return $.grep( array, function(value) { return matcher.test( value.label || value.value || value ); }); } }); // live region extension, adding a `messages` option // NOTE: This is an experimental API. We are still investigating // a full solution for string manipulation and internationalization. $.widget( "ui.autocomplete", $.ui.autocomplete, { options: { messages: { noResults: "No search results.", results: function( amount ) { return amount + ( amount > 1 ? " results are" : " result is" ) + " available, use up and down arrow keys to navigate."; } } }, __response: function( content ) { var message; this._superApply( arguments ); if ( this.options.disabled || this.cancelSearch ) { return; } if ( content && content.length ) { message = this.options.messages.results( content.length ); } else { message = this.options.messages.noResults; } this.liveRegion.text( message ); } }); }( jQuery )); (function( $, undefined ) { var lastActive, startXPos, startYPos, clickDragged, baseClasses = "ui-button ui-widget ui-state-default ui-corner-all", stateClasses = "ui-state-hover ui-state-active ", typeClasses = "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", formResetHandler = function() { var buttons = $( this ).find( ":ui-button" ); setTimeout(function() { buttons.button( "refresh" ); }, 1 ); }, radioGroup = function( radio ) { var name = radio.name, form = radio.form, radios = $( [] ); if ( name ) { if ( form ) { radios = $( form ).find( "[name='" + name + "']" ); } else { radios = $( "[name='" + name + "']", radio.ownerDocument ) .filter(function() { return !this.form; }); } } return radios; }; $.widget( "ui.button", { version: "1.9.2", defaultElement: "<button>", options: { disabled: null, text: true, label: null, icons: { primary: null, secondary: null } }, _create: function() { this.element.closest( "form" ) .unbind( "reset" + this.eventNamespace ) .bind( "reset" + this.eventNamespace, formResetHandler ); if ( typeof this.options.disabled !== "boolean" ) { this.options.disabled = !!this.element.prop( "disabled" ); } else { this.element.prop( "disabled", this.options.disabled ); } this._determineButtonType(); this.hasTitle = !!this.buttonElement.attr( "title" ); var that = this, options = this.options, toggleButton = this.type === "checkbox" || this.type === "radio", activeClass = !toggleButton ? "ui-state-active" : "", focusClass = "ui-state-focus"; if ( options.label === null ) { options.label = (this.type === "input" ? this.buttonElement.val() : this.buttonElement.html()); } this._hoverable( this.buttonElement ); this.buttonElement .addClass( baseClasses ) .attr( "role", "button" ) .bind( "mouseenter" + this.eventNamespace, function() { if ( options.disabled ) { return; } if ( this === lastActive ) { $( this ).addClass( "ui-state-active" ); } }) .bind( "mouseleave" + this.eventNamespace, function() { if ( options.disabled ) { return; } $( this ).removeClass( activeClass ); }) .bind( "click" + this.eventNamespace, function( event ) { if ( options.disabled ) { event.preventDefault(); event.stopImmediatePropagation(); } }); this.element .bind( "focus" + this.eventNamespace, function() { // no need to check disabled, focus won't be triggered anyway that.buttonElement.addClass( focusClass ); }) .bind( "blur" + this.eventNamespace, function() { that.buttonElement.removeClass( focusClass ); }); if ( toggleButton ) { this.element.bind( "change" + this.eventNamespace, function() { if ( clickDragged ) { return; } that.refresh(); }); // if mouse moves between mousedown and mouseup (drag) set clickDragged flag // prevents issue where button state changes but checkbox/radio checked state // does not in Firefox (see ticket #6970) this.buttonElement .bind( "mousedown" + this.eventNamespace, function( event ) { if ( options.disabled ) { return; } clickDragged = false; startXPos = event.pageX; startYPos = event.pageY; }) .bind( "mouseup" + this.eventNamespace, function( event ) { if ( options.disabled ) { return; } if ( startXPos !== event.pageX || startYPos !== event.pageY ) { clickDragged = true; } }); } if ( this.type === "checkbox" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled || clickDragged ) { return false; } $( this ).toggleClass( "ui-state-active" ); that.buttonElement.attr( "aria-pressed", that.element[0].checked ); }); } else if ( this.type === "radio" ) { this.buttonElement.bind( "click" + this.eventNamespace, function() { if ( options.disabled || clickDragged ) { return false; } $( this ).addClass( "ui-state-active" ); that.buttonElement.attr( "aria-pressed", "true" ); var radio = that.element[ 0 ]; radioGroup( radio ) .not( radio ) .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-state-active" ) .attr( "aria-pressed", "false" ); }); } else { this.buttonElement .bind( "mousedown" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).addClass( "ui-state-active" ); lastActive = this; that.document.one( "mouseup", function() { lastActive = null; }); }) .bind( "mouseup" + this.eventNamespace, function() { if ( options.disabled ) { return false; } $( this ).removeClass( "ui-state-active" ); }) .bind( "keydown" + this.eventNamespace, function(event) { if ( options.disabled ) { return false; } if ( event.keyCode === $.ui.keyCode.SPACE || event.keyCode === $.ui.keyCode.ENTER ) { $( this ).addClass( "ui-state-active" ); } }) .bind( "keyup" + this.eventNamespace, function() { $( this ).removeClass( "ui-state-active" ); }); if ( this.buttonElement.is("a") ) { this.buttonElement.keyup(function(event) { if ( event.keyCode === $.ui.keyCode.SPACE ) { // TODO pass through original event correctly (just as 2nd argument doesn't work) $( this ).click(); } }); } } // TODO: pull out $.Widget's handling for the disabled option into // $.Widget.prototype._setOptionDisabled so it's easy to proxy and can // be overridden by individual plugins this._setOption( "disabled", options.disabled ); this._resetButton(); }, _determineButtonType: function() { var ancestor, labelSelector, checked; if ( this.element.is("[type=checkbox]") ) { this.type = "checkbox"; } else if ( this.element.is("[type=radio]") ) { this.type = "radio"; } else if ( this.element.is("input") ) { this.type = "input"; } else { this.type = "button"; } if ( this.type === "checkbox" || this.type === "radio" ) { // we don't search against the document in case the element // is disconnected from the DOM ancestor = this.element.parents().last(); labelSelector = "label[for='" + this.element.attr("id") + "']"; this.buttonElement = ancestor.find( labelSelector ); if ( !this.buttonElement.length ) { ancestor = ancestor.length ? ancestor.siblings() : this.element.siblings(); this.buttonElement = ancestor.filter( labelSelector ); if ( !this.buttonElement.length ) { this.buttonElement = ancestor.find( labelSelector ); } } this.element.addClass( "ui-helper-hidden-accessible" ); checked = this.element.is( ":checked" ); if ( checked ) { this.buttonElement.addClass( "ui-state-active" ); } this.buttonElement.prop( "aria-pressed", checked ); } else { this.buttonElement = this.element; } }, widget: function() { return this.buttonElement; }, _destroy: function() { this.element .removeClass( "ui-helper-hidden-accessible" ); this.buttonElement .removeClass( baseClasses + " " + stateClasses + " " + typeClasses ) .removeAttr( "role" ) .removeAttr( "aria-pressed" ) .html( this.buttonElement.find(".ui-button-text").html() ); if ( !this.hasTitle ) { this.buttonElement.removeAttr( "title" ); } }, _setOption: function( key, value ) { this._super( key, value ); if ( key === "disabled" ) { if ( value ) { this.element.prop( "disabled", true ); } else { this.element.prop( "disabled", false ); } return; } this._resetButton(); }, refresh: function() { //See #8237 & #8828 var isDisabled = this.element.is( "input, button" ) ? this.element.is( ":disabled" ) : this.element.hasClass( "ui-button-disabled" ); if ( isDisabled !== this.options.disabled ) { this._setOption( "disabled", isDisabled ); } if ( this.type === "radio" ) { radioGroup( this.element[0] ).each(function() { if ( $( this ).is( ":checked" ) ) { $( this ).button( "widget" ) .addClass( "ui-state-active" ) .attr( "aria-pressed", "true" ); } else { $( 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 buttonElement = this.buttonElement.removeClass( typeClasses ), buttonText = $( "<span></span>", this.document[0] ) .addClass( "ui-button-text" ) .html( this.options.label ) .appendTo( buttonElement.empty() ) .text(), icons = this.options.icons, multipleIcons = icons.primary && icons.secondary, buttonClasses = []; if ( icons.primary || icons.secondary ) { if ( this.options.text ) { buttonClasses.push( "ui-button-text-icon" + ( multipleIcons ? "s" : ( icons.primary ? "-primary" : "-secondary" ) ) ); } if ( icons.primary ) { buttonElement.prepend( "<span class='ui-button-icon-primary ui-icon " + icons.primary + "'></span>" ); } if ( icons.secondary ) { buttonElement.append( "<span class='ui-button-icon-secondary ui-icon " + icons.secondary + "'></span>" ); } if ( !this.options.text ) { buttonClasses.push( multipleIcons ? "ui-button-icons-only" : "ui-button-icon-only" ); if ( !this.hasTitle ) { buttonElement.attr( "title", $.trim( buttonText ) ); } } } else { buttonClasses.push( "ui-button-text-only" ); } buttonElement.addClass( buttonClasses.join( " " ) ); } }); $.widget( "ui.buttonset", { version: "1.9.2", options: { items: "button, input[type=button], input[type=submit], input[type=reset], input[type=checkbox], input[type=radio], a, :data(button)" }, _create: function() { this.element.addClass( "ui-buttonset" ); }, _init: function() { this.refresh(); }, _setOption: function( key, value ) { if ( key === "disabled" ) { this.buttons.button( "option", key, value ); } this._super( key, value ); }, refresh: function() { var rtl = 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 $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-all ui-corner-left ui-corner-right" ) .filter( ":first" ) .addClass( rtl ? "ui-corner-right" : "ui-corner-left" ) .end() .filter( ":last" ) .addClass( rtl ? "ui-corner-left" : "ui-corner-right" ) .end() .end(); }, _destroy: function() { this.element.removeClass( "ui-buttonset" ); this.buttons .map(function() { return $( this ).button( "widget" )[ 0 ]; }) .removeClass( "ui-corner-left ui-corner-right" ) .end() .button( "destroy" ); } }); }( jQuery ) ); (function( $, undefined ) { $.extend($.ui, { datepicker: { version: "1.9.2" } }); var PROP_NAME = 'datepicker'; var dpuuid = new Date().getTime(); var instActive; /* Date picker manager. Use the singleton instance of this class, $.datepicker, to interact with the date picker. Settings for (groups of) date pickers are maintained in an instance object, allowing multiple different settings on the same page. */ function Datepicker() { this.debug = false; // Change this to true to start debugging this._curInst = null; // The current instance in use this._keyEvent = false; // If the last event was a key event this._disabledInputs = []; // List of date picker inputs that have been disabled this._datepickerShowing = false; // True if the popup picker is showing , false if not this._inDialog = false; // True if showing within a "dialog", false if not this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class this._appendClass = 'ui-datepicker-append'; // The name of the append marker class this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class this.regional = []; // Available regional settings, indexed by language code this.regional[''] = { // Default regional settings closeText: 'Done', // Display text for close link prevText: 'Prev', // Display text for previous month link nextText: 'Next', // Display text for next month link currentText: 'Today', // Display text for current month link monthNames: ['January','February','March','April','May','June', 'July','August','September','October','November','December'], // Names of months for drop-down and formatting monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday weekHeader: 'Wk', // Column header for week of the year dateFormat: 'mm/dd/yy', // See format options on parseDate firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ... isRTL: false, // True if right-to-left language, false if left-to-right showMonthAfterYear: false, // True if the year select precedes month, false for month then year yearSuffix: '' // Additional text to append to the year in the month headers }; this._defaults = { // Global defaults for all the date picker instances showOn: 'focus', // 'focus' for popup on focus, // 'button' for trigger button, or 'both' for either showAnim: 'fadeIn', // Name of jQuery animation for popup showOptions: {}, // Options for enhanced animations defaultDate: null, // Used when field is blank: actual date, // +/-number for offset from today, null for today appendText: '', // Display text following the input box, e.g. showing the format buttonText: '...', // Text for trigger button buttonImage: '', // URL for trigger button image buttonImageOnly: false, // True if the image appears alone, false if it appears on a button hideIfNoPrevNext: false, // True to hide next/previous month links // if not applicable, false to just disable them navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links gotoCurrent: false, // True if today link goes back to current selection instead changeMonth: false, // True if month can be selected directly, false if only prev/next changeYear: false, // True if year can be selected directly, false if only prev/next yearRange: 'c-10:c+10', // Range of years to display in drop-down, // either relative to today's year (-nn:+nn), relative to currently displayed year // (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n) showOtherMonths: false, // True to show dates in other months, false to leave blank selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable showWeek: false, // True to show week of the year, false to not show it calculateWeek: this.iso8601Week, // How to calculate the week of the year, // takes a Date and returns the number of the week for it shortYearCutoff: '+10', // Short year values < this are in the current century, // > this are in the previous century, // string value starting with '+' for current year + value minDate: null, // The earliest selectable date, or null for no limit maxDate: null, // The latest selectable date, or null for no limit duration: 'fast', // Duration of display/closure beforeShowDay: null, // Function that takes a date and returns an array with // [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '', // [2] = cell title (optional), e.g. $.datepicker.noWeekends beforeShow: null, // Function that takes an input field and // returns a set of custom settings for the date picker onSelect: null, // Define a callback function when a date is selected onChangeMonthYear: null, // Define a callback function when the month or year is changed onClose: null, // Define a callback function when the datepicker is closed numberOfMonths: 1, // Number of months to show at a time showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0) stepMonths: 1, // Number of months to step back/forward stepBigMonths: 12, // Number of months to step back/forward for the big links altField: '', // Selector for an alternate field to store selected dates into altFormat: '', // The date format to use for the alternate field constrainInput: true, // The input is constrained by the current date format showButtonPanel: false, // True to show button panel, false to not show it autoSize: false, // True to size the input for the date format, false to leave as is disabled: false // The initial disabled state }; $.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, { /* Class name added to elements to indicate already configured with a date picker. */ markerClassName: 'hasDatepicker', //Keep track of the maximum number of rows displayed (see #7043) maxRows: 4, /* Debug logging (if enabled). */ log: function () { if (this.debug) console.log.apply('', arguments); }, // TODO rename to "widget" when switching to widget factory _widgetDatepicker: function() { return this.dpDiv; }, /* Override the default settings for all instances of the date picker. @param settings object - the new settings to use as defaults (anonymous object) @return the manager object */ setDefaults: function(settings) { extendRemove(this._defaults, settings || {}); return this; }, /* Attach the date picker to a jQuery selection. @param target element - the target input field or division or span @param settings object - the new settings to use for this date picker instance (anonymous) */ _attachDatepicker: function(target, settings) { // check for settings on the control itself - in namespace 'date:' 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); } }, /* Create a new instance object. */ _newInst: function(target, inline) { var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars return {id: id, input: target, // associated target selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection drawMonth: 0, drawYear: 0, // month being drawn inline: inline, // is datepicker inline or not dpDiv: (!inline ? this.dpDiv : // presentation div bindHover($('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')))}; }, /* Attach the date picker to an input field. */ _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 disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } }, /* Make attachments based on settings. */ _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') // pop-up date picker when in the marked field input.focus(this._showDatepicker); if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked 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; }); } }, /* Apply the maximum length for the date format. */ _autoSize: function(inst) { if (this._get(inst, 'autoSize') && !inst.inline) { var date = new Date(2009, 12 - 1, 20); // Ensure double digits 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); } }, /* Attach an inline date picker to a div. */ _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 disabled option is true, disable the datepicker before showing it (see ticket #5665) if( inst.settings.disabled ) { this._disableDatepicker( target ); } // Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements // http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height inst.dpDiv.css( "display", "block" ); }, /* Pop-up the date picker in a "dialog" box. @param input element - ignored @param date string or Date - the initial date to display @param onSelect function - the function to call when a date is selected @param settings object - update the dialog date picker instance's settings (anonymous object) @param pos int[2] - coordinates for the dialog's position within the screen or event - with x/y coordinates or leave empty for default (screen centre) @return the manager object */ _dialogDatepicker: function(input, date, onSelect, settings, pos) { var inst = this._dialogInst; // internal instance 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 = // should use actual width/height below [(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY]; } // move input on screen for focus, but hidden behind dialog 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; }, /* Detach a datepicker from its control. @param target element - the target input field or division or span */ _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(); }, /* Enable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _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"). prop("disabled", false); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry }, /* Disable the date picker to a jQuery selection. @param target element - the target input field or division or span */ _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"). prop("disabled", true); } this._disabledInputs = $.map(this._disabledInputs, function(value) { return (value == target ? null : value); }); // delete entry this._disabledInputs[this._disabledInputs.length] = target; }, /* Is the first field in a jQuery collection disabled as a datepicker? @param target element - the target input field or division or span @return boolean - true if disabled, false if enabled */ _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; }, /* Retrieve the instance data for the target control. @param target element - the target input field or division or span @return object - the associated instance data @throws error if a jQuery problem getting data */ _getInst: function(target) { try { return $.data(target, PROP_NAME); } catch (err) { throw 'Missing instance data for this datepicker'; } }, /* Update or retrieve the settings for a date picker attached to an input field or division. @param target element - the target input field or division or span @param name object - the new settings to update or string - the name of the setting to change or retrieve, when retrieving also 'all' for all instance settings or 'defaults' for all global defaults @param value any - the new value for the setting (omit if above is an object or to retrieve a value) */ _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); // reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided 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); } }, // change method deprecated _changeDatepicker: function(target, name, value) { this._optionDatepicker(target, name, value); }, /* Redraw the date picker attached to an input field or division. @param target element - the target input field or division or span */ _refreshDatepicker: function(target) { var inst = this._getInst(target); if (inst) { this._updateDatepicker(inst); } }, /* Set the dates for a jQuery selection. @param target element - the target input field or division or span @param date Date - the new date */ _setDateDatepicker: function(target, date) { var inst = this._getInst(target); if (inst) { this._setDate(inst, date); this._updateDatepicker(inst); this._updateAlternate(inst); } }, /* Get the date(s) for the first entry in a jQuery selection. @param target element - the target input field or division or span @param noDefault boolean - true if no default date is to be used @return Date - the current date */ _getDateDatepicker: function(target, noDefault) { var inst = this._getInst(target); if (inst && !inst.inline) this._setDateFromField(inst, noDefault); return (inst ? this._getDate(inst) : null); }, /* Handle keystrokes. */ _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; // hide on tab out 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); // trigger custom callback onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); } else $.datepicker._hideDatepicker(); return false; // don't submit the form break; // select the value on enter case 27: $.datepicker._hideDatepicker(); break; // hide on escape case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); break; // previous month/year on page up/+ ctrl case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); break; // next month/year on page down/+ ctrl case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target); handled = event.ctrlKey || event.metaKey; break; // clear on ctrl or command +end case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target); handled = event.ctrlKey || event.metaKey; break; // current on ctrl or command +home case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D'); handled = event.ctrlKey || event.metaKey; // -1 day on ctrl or command +left if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? -$.datepicker._get(inst, 'stepBigMonths') : -$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +left on Mac break; case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D'); handled = event.ctrlKey || event.metaKey; break; // -1 week on ctrl or command +up case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D'); handled = event.ctrlKey || event.metaKey; // +1 day on ctrl or command +right if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ? +$.datepicker._get(inst, 'stepBigMonths') : +$.datepicker._get(inst, 'stepMonths')), 'M'); // next month/year on alt +right break; case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D'); handled = event.ctrlKey || event.metaKey; break; // +1 week on ctrl or command +down default: handled = false; } else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home $.datepicker._showDatepicker(this); else { handled = false; } if (handled) { event.preventDefault(); event.stopPropagation(); } }, /* Filter entered characters - based on date format. */ _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); } }, /* Synchronise manual entry and field/alternate field. */ _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) { // only if valid $.datepicker._setDateFromField(inst); $.datepicker._updateAlternate(inst); $.datepicker._updateDatepicker(inst); } } catch (err) { $.datepicker.log(err); } } return true; }, /* Pop-up the date picker for a given input field. If false returned from beforeShow event handler do not show. @param input element - the input field attached to the date picker or event - if triggered by focus */ _showDatepicker: function(input) { input = input.target || input; if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger input = $('input', input.parentNode)[0]; if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here 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){ //false return; } extendRemove(inst.settings, beforeShowSettings); inst.lastVal = null; $.datepicker._lastInput = input; $.datepicker._setDateFromField(inst); if ($.datepicker._inDialog) // hide cursor input.value = ''; if (!$.datepicker._pos) { // position below input $.datepicker._pos = $.datepicker._findPos(input); $.datepicker._pos[1] += input.offsetHeight; // add the height } var isFixed = false; $(input).parents().each(function() { isFixed |= $(this).css('position') == 'fixed'; return !isFixed; }); var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]}; $.datepicker._pos = null; //to avoid flashes on Firefox inst.dpDiv.empty(); // determine sizing offscreen inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'}); $.datepicker._updateDatepicker(inst); // fix width for dynamic number of date pickers // and adjust position before showing 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'); // IE6- only 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; // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed if ( $.effects && ( $.effects.effect[ showAnim ] || $.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; } }, /* Generate the date picker content. */ _updateDatepicker: function(inst) { this.maxRows = 4; //Reset the max number of rows being displayed (see #7043) var borders = $.datepicker._getBorders(inst.dpDiv); instActive = inst; // for delegate hover events inst.dpDiv.empty().append(this._generateHTML(inst)); this._attachHandlers(inst); var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only if( !!cover.length ){ //avoid call to outerXXXX() when not in IE6 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 && // #6694 - don't focus the input if it's already focused // this breaks the change event in IE inst.input.is(':visible') && !inst.input.is(':disabled') && inst.input[0] != document.activeElement) inst.input.focus(); // deffered render of the years select (to avoid flashes on Firefox) if( inst.yearshtml ){ var origyearshtml = inst.yearshtml; setTimeout(function(){ //assure that inst.yearshtml didn't change. if( origyearshtml === inst.yearshtml && inst.yearshtml ){ inst.dpDiv.find('select.ui-datepicker-year:first').replaceWith(inst.yearshtml); } origyearshtml = inst.yearshtml = null; }, 0); } }, /* Retrieve the size of left and top borders for an element. @param elem (jQuery object) the element of interest @return (number[2]) the left and top borders */ _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')))]; }, /* Check positioning to remain on screen. */ _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; // now check if datepicker is showing outside window viewport - move to a better place if so. 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; }, /* Find an object's position on the screen. */ _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]; }, /* Hide the date picker from view. @param input element - the input field attached to the date picker */ _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); }; // DEPRECATED: after BC for 1.8.x $.effects[ showAnim ] is not needed if ( $.effects && ( $.effects.effect[ showAnim ] || $.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; } }, /* Tidy up after a dialog display. */ _tidyDialog: function(inst) { inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar'); }, /* Close date picker if clicked elsewhere. */ _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(); }, /* Adjust one of the date sub-fields. */ _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), // undo positioning period); this._updateDatepicker(inst); }, /* Action for current link. */ _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); }, /* Action for selecting a new month/year. */ _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); }, /* Action for selecting a day. */ _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)); }, /* Erase the input field and hide the date picker. */ _clearDate: function(id) { var target = $(id); var inst = this._getInst(target[0]); this._selectDate(target, ''); }, /* Update the input field with the selected date. */ _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]); // trigger custom callback else if (inst.input) inst.input.trigger('change'); // fire the change event if (inst.inline) this._updateDatepicker(inst); else { this._hideDatepicker(); this._lastInput = inst.input[0]; if (typeof(inst.input[0]) != 'object') inst.input.focus(); // restore focus this._lastInput = null; } }, /* Update any alternate field to synchronise with the main field. */ _updateAlternate: function(inst) { var altField = this._get(inst, 'altField'); if (altField) { // update alternate field too 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); }); } }, /* Set as beforeShowDay function to prevent selection of weekends. @param date Date - the date to customise @return [boolean, string] - is this date selectable?, what is its CSS class? */ noWeekends: function(date) { var day = date.getDay(); return [(day > 0 && day < 6), '']; }, /* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition. @param date Date - the date to get the week for @return number - the number of the week within the year that contains this date */ iso8601Week: function(date) { var checkDate = new Date(date.getTime()); // Find Thursday of this week starting on Monday checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7)); var time = checkDate.getTime(); checkDate.setMonth(0); // Compare with Jan 1 checkDate.setDate(1); return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1; }, /* Parse a string value into a date object. See formatDate below for the possible formats. @param format string - the expected format of the date @param value string - the date in the above format @param settings Object - attributes include: shortYearCutoff number - the cutoff year for determining the century (optional) dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return Date - the extracted date value or null if value is blank */ 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; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Extract a number from the string value 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); }; // Extract a name from the string value and convert to an index 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; }; // Confirm that a literal character matches the string value 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){ var extra = value.substr(iValue); if (!/^\s+/.test(extra)) { throw "Extra/unparsed characters found in date: " + extra; } } 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'; // E.g. 31/02/00 return date; }, /* Standard date formats. */ ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601) 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', // RFC 822 TICKS: '!', TIMESTAMP: '@', W3C: 'yy-mm-dd', // ISO 8601 _ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) + Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000), /* Format a date object into a string value. The format can be combinations of the following: d - day of month (no leading zero) dd - day of month (two digit) o - day of year (no leading zeros) oo - day of year (three digit) D - day name short DD - day name long m - month of year (no leading zero) mm - month of year (two digit) M - month name short MM - month name long y - year (two digit) yy - year (four digit) @ - Unix timestamp (ms since 01/01/1970) ! - Windows ticks (100ns since 01/01/0001) '...' - literal text '' - single quote @param format string - the desired format of the date @param date Date - the date value to format @param settings Object - attributes include: dayNamesShort string[7] - abbreviated names of the days from Sunday (optional) dayNames string[7] - names of the days from Sunday (optional) monthNamesShort string[12] - abbreviated names of the months (optional) monthNames string[12] - names of the months (optional) @return string - the date in the above format */ 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; // Check whether a format character is doubled var lookAhead = function(match) { var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match); if (matches) iFormat++; return matches; }; // Format a number, with leading zero if necessary var formatNumber = function(match, value, len) { var num = '' + value; if (lookAhead(match)) while (num.length < len) num = '0' + num; return num; }; // Format a name, short or long as requested 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; }, /* Extract all possible characters from the date format. */ _possibleChars: function (format) { var chars = ''; var literal = false; // Check whether a format character is doubled 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; // Accept anything case "'": if (lookAhead("'")) chars += "'"; else literal = true; break; default: chars += format.charAt(iFormat); } return chars; }, /* Get a setting value, defaulting if necessary. */ _get: function(inst, name) { return inst.settings[name] !== undefined ? inst.settings[name] : this._defaults[name]; }, /* Parse existing date and initialise date picker. */ _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); }, /* Retrieve the default date shown on opening. */ _getDefaultDate: function(inst) { return this._restrictMinMax(inst, this._determineDate(inst, this._get(inst, 'defaultDate'), new Date())); }, /* A date may be specified as an exact value or a relative one. */ _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) { // Ignore } 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); }, /* Handle switch to/from daylight saving. Hours may be non-zero on daylight saving cut-over: > 12 when midnight changeover, but then cannot generate midnight datetime, so jump to 1AM, otherwise reset. @param date (Date) the date to check @return (Date) the corrected date */ _daylightSavingAdjust: function(date) { if (!date) return null; date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0); return date; }, /* Set the date(s) directly. */ _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)); } }, /* Retrieve the date(s) directly. */ _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; }, /* Attach the onxxx handlers. These are declared statically so * they work with static code transformers like Caja. */ _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')]); }); }, /* Generate the HTML for the current state of the date picker. */ _generateHTML: function(inst) { var today = new Date(); today = this._daylightSavingAdjust( new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time 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) + // draw month headers '</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++) { // days of the week 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); // calculate the number of rows to generate var numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043) this.maxRows = numRows; var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays)); for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows calender += '<tr>'; var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' + this._get(inst, 'calculateWeek')(printDate) + '</td>'); for (var dow = 0; dow < 7; dow++) { // create date picker days 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' : '') + // highlight weekends (otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months ((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key (defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ? // or defaultDate is current printedDate and defaultDate is selectedDate ' ' + this._dayOverClass : '') + // highlight selected day (unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') + // highlight unselectable days (otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates (printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day (printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different) ((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title (unselectable ? '' : ' data-handler="selectDay" data-event="click" data-month="' + printDate.getMonth() + '" data-year="' + printDate.getFullYear() + '"') + '>' + // actions (otherMonth && !showOtherMonths ? '&#xa0;' : // display for other months (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' : '') + // highlight selected day (otherMonth ? ' ui-priority-secondary' : '') + // distinguish dates from other months '" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display selectable date 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 + ($.ui.ie6 && !inst.inline ? '<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : ''); inst._keyEvent = false; return html; }, /* Generate the month and year header. */ _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 = ''; // month selection 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;' : ''); // year selection if ( !inst.yearshtml ) { inst.yearshtml = ''; if (secondary || !changeYear) html += '<span class="ui-datepicker-year">' + drawYear + '</span>'; else { // determine range of years to display 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>'; // Close datepicker_header return html; }, /* Adjust one of the date sub-fields. */ _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); }, /* Ensure a date is within any min/max bounds. */ _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; }, /* Notify change of month/year. */ _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]); }, /* Determine the number of months to show. */ _getNumberOfMonths: function(inst) { var numMonths = this._get(inst, 'numberOfMonths'); return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths)); }, /* Determine the current maximum date - ensure no time components are set. */ _getMinMaxDate: function(inst, minMax) { return this._determineDate(inst, this._get(inst, minMax + 'Date'), null); }, /* Find the number of days in a given month. */ _getDaysInMonth: function(year, month) { return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate(); }, /* Find the day of the week of the first of a month. */ _getFirstDayOfMonth: function(year, month) { return new Date(year, month, 1).getDay(); }, /* Determines if we should allow a "next/prev" month display change. */ _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); }, /* Is the given date in the accepted range? */ _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())); }, /* Provide the configuration settings for formatting/parsing. */ _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')}; }, /* Format the given date for display. */ _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)); } }); /* * Bind hover events for datepicker elements. * Done via delegate so the binding only occurs once in the lifetime of the parent div. * Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker. */ function bindHover(dpDiv) { var selector = 'button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a'; return dpDiv.delegate(selector, 'mouseout', function() { $(this).removeClass('ui-state-hover'); if (this.className.indexOf('ui-datepicker-prev') != -1) $(this).removeClass('ui-datepicker-prev-hover'); if (this.className.indexOf('ui-datepicker-next') != -1) $(this).removeClass('ui-datepicker-next-hover'); }) .delegate(selector, 'mouseover', function(){ if (!$.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0])) { $(this).parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover'); $(this).addClass('ui-state-hover'); if (this.className.indexOf('ui-datepicker-prev') != -1) $(this).addClass('ui-datepicker-prev-hover'); if (this.className.indexOf('ui-datepicker-next') != -1) $(this).addClass('ui-datepicker-next-hover'); } }); } /* jQuery extend now ignores nulls! */ 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; }; /* Invoke the datepicker functionality. @param options string - a command, optionally followed by additional parameters or Object - settings for attaching new datepicker functionality @return jQuery object */ $.fn.datepicker = function(options){ /* Verify an empty collection wasn't passed - Fixes #6976 */ if ( !this.length ) { return this; } /* Initialise the date picker. */ if (!$.datepicker.initialized) { $(document).mousedown($.datepicker._checkExternalClick). find(document.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(); // singleton instance $.datepicker.initialized = false; $.datepicker.uuid = new Date().getTime(); $.datepicker.version = "1.9.2"; // Workaround for #4055 // Add another global to avoid noConflict issues with inline event handlers window['DP_jQuery_' + dpuuid] = $; })(jQuery); (function( $, undefined ) { var uiDialogClasses = "ui-dialog ui-widget ui-widget-content ui-corner-all ", sizeRelatedOptions = { buttons: true, height: true, maxHeight: true, maxWidth: true, minHeight: true, minWidth: true, width: true }, resizableRelatedOptions = { maxHeight: true, maxWidth: true, minHeight: true, minWidth: true }; $.widget("ui.dialog", { version: "1.9.2", 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", of: window, collision: "fit", // ensure that the titlebar is never outside the document using: function( pos ) { var topOffset = $( this ).css( pos ).offset().top; if ( topOffset < 0 ) { $( this ).css( "top", pos.top - topOffset ); } } }, resizable: true, show: null, stack: true, title: "", width: 300, zIndex: 1000 }, _create: function() { this.originalTitle = this.element.attr( "title" ); // #5742 - .attr() might return a DOMElement if ( typeof this.originalTitle !== "string" ) { this.originalTitle = ""; } this.oldPosition = { parent: this.element.parent(), index: this.element.parent().children().index( this.element ) }; this.options.title = this.options.title || this.originalTitle; var that = this, options = this.options, title = options.title || "&#160;", uiDialog, uiDialogTitlebar, uiDialogTitlebarClose, uiDialogTitle, uiDialogButtonPane; uiDialog = ( this.uiDialog = $( "<div>" ) ) .addClass( uiDialogClasses + options.dialogClass ) .css({ display: "none", outline: 0, // TODO: move to stylesheet zIndex: options.zIndex }) // setting tabIndex makes the div focusable .attr( "tabIndex", -1) .keydown(function( event ) { if ( options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE ) { that.close( event ); event.preventDefault(); } }) .mousedown(function( event ) { that.moveToTop( false, event ); }) .appendTo( "body" ); this.element .show() .removeAttr( "title" ) .addClass( "ui-dialog-content ui-widget-content" ) .appendTo( uiDialog ); uiDialogTitlebar = ( this.uiDialogTitlebar = $( "<div>" ) ) .addClass( "ui-dialog-titlebar ui-widget-header " + "ui-corner-all ui-helper-clearfix" ) .bind( "mousedown", function() { // Dialog isn't getting focus when dragging (#8063) uiDialog.focus(); }) .prependTo( uiDialog ); uiDialogTitlebarClose = $( "<a href='#'></a>" ) .addClass( "ui-dialog-titlebar-close ui-corner-all" ) .attr( "role", "button" ) .click(function( event ) { event.preventDefault(); that.close( event ); }) .appendTo( uiDialogTitlebar ); ( this.uiDialogTitlebarCloseText = $( "<span>" ) ) .addClass( "ui-icon ui-icon-closethick" ) .text( options.closeText ) .appendTo( uiDialogTitlebarClose ); uiDialogTitle = $( "<span>" ) .uniqueId() .addClass( "ui-dialog-title" ) .html( title ) .prependTo( uiDialogTitlebar ); uiDialogButtonPane = ( this.uiDialogButtonPane = $( "<div>" ) ) .addClass( "ui-dialog-buttonpane ui-widget-content ui-helper-clearfix" ); ( this.uiButtonSet = $( "<div>" ) ) .addClass( "ui-dialog-buttonset" ) .appendTo( uiDialogButtonPane ); uiDialog.attr({ role: "dialog", "aria-labelledby": uiDialogTitle.attr( "id" ) }); uiDialogTitlebar.find( "*" ).add( uiDialogTitlebar ).disableSelection(); this._hoverable( uiDialogTitlebarClose ); this._focusable( uiDialogTitlebarClose ); if ( options.draggable && $.fn.draggable ) { this._makeDraggable(); } if ( options.resizable && $.fn.resizable ) { this._makeResizable(); } this._createButtons( options.buttons ); this._isOpen = false; if ( $.fn.bgiframe ) { uiDialog.bgiframe(); } // prevent tabbing out of modal dialogs this._on( uiDialog, { keydown: function( event ) { if ( !options.modal || event.keyCode !== $.ui.keyCode.TAB ) { return; } var tabbables = $( ":tabbable", uiDialog ), first = tabbables.filter( ":first" ), last = tabbables.filter( ":last" ); if ( event.target === last[0] && !event.shiftKey ) { first.focus( 1 ); return false; } else if ( event.target === first[0] && event.shiftKey ) { last.focus( 1 ); return false; } }}); }, _init: function() { if ( this.options.autoOpen ) { this.open(); } }, _destroy: function() { var next, oldPosition = this.oldPosition; if ( this.overlay ) { this.overlay.destroy(); } this.uiDialog.hide(); this.element .removeClass( "ui-dialog-content ui-widget-content" ) .hide() .appendTo( "body" ); this.uiDialog.remove(); if ( this.originalTitle ) { this.element.attr( "title", this.originalTitle ); } next = oldPosition.parent.children().eq( oldPosition.index ); // Don't try to place the dialog next to itself (#8613) if ( next.length && next[ 0 ] !== this.element[ 0 ] ) { next.before( this.element ); } else { oldPosition.parent.append( this.element ); } }, widget: function() { return this.uiDialog; }, close: function( event ) { var that = this, maxZ, thisZ; if ( !this._isOpen ) { return; } if ( false === this._trigger( "beforeClose", event ) ) { return; } this._isOpen = false; if ( this.overlay ) { this.overlay.destroy(); } if ( this.options.hide ) { this._hide( this.uiDialog, this.options.hide, function() { that._trigger( "close", event ); }); } else { this.uiDialog.hide(); this._trigger( "close", event ); } $.ui.dialog.overlay.resize(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) if ( this.options.modal ) { maxZ = 0; $( ".ui-dialog" ).each(function() { if ( this !== that.uiDialog[0] ) { thisZ = $( this ).css( "z-index" ); if ( !isNaN( thisZ ) ) { maxZ = Math.max( maxZ, thisZ ); } } }); $.ui.dialog.maxZ = maxZ; } return this; }, isOpen: function() { return this._isOpen; }, // the force parameter allows us to move modal dialogs to their correct // position on open moveToTop: function( force, event ) { var options = this.options, saveScroll; if ( ( options.modal && !force ) || ( !options.stack && !options.modal ) ) { return this._trigger( "focus", event ); } if ( options.zIndex > $.ui.dialog.maxZ ) { $.ui.dialog.maxZ = options.zIndex; } if ( this.overlay ) { $.ui.dialog.maxZ += 1; $.ui.dialog.overlay.maxZ = $.ui.dialog.maxZ; this.overlay.$el.css( "z-index", $.ui.dialog.overlay.maxZ ); } // Save and then restore scroll // Opera 9.5+ resets when parent z-index is changed. // http://bugs.jqueryui.com/ticket/3193 saveScroll = { scrollTop: this.element.scrollTop(), scrollLeft: this.element.scrollLeft() }; $.ui.dialog.maxZ += 1; this.uiDialog.css( "z-index", $.ui.dialog.maxZ ); this.element.attr( saveScroll ); this._trigger( "focus", event ); return this; }, open: function() { if ( this._isOpen ) { return; } var hasFocus, options = this.options, uiDialog = this.uiDialog; this._size(); this._position( options.position ); uiDialog.show( options.show ); this.overlay = options.modal ? new $.ui.dialog.overlay( this ) : null; this.moveToTop( true ); // set focus to the first tabbable element in the content area or the first button // if there are no tabbable elements, set focus on the dialog itself hasFocus = this.element.find( ":tabbable" ); if ( !hasFocus.length ) { hasFocus = this.uiDialogButtonPane.find( ":tabbable" ); if ( !hasFocus.length ) { hasFocus = uiDialog; } } hasFocus.eq( 0 ).focus(); this._isOpen = true; this._trigger( "open" ); return this; }, _createButtons: function( buttons ) { var that = this, hasButtons = false; // if we already have a button pane, remove it this.uiDialogButtonPane.remove(); this.uiButtonSet.empty(); if ( typeof buttons === "object" && buttons !== null ) { $.each( buttons, function() { return !(hasButtons = true); }); } if ( hasButtons ) { $.each( buttons, function( name, props ) { var button, click; props = $.isFunction( props ) ? { click: props, text: name } : props; // Default to a non-submitting button props = $.extend( { type: "button" }, props ); // Change the context for the click callback to be the main element click = props.click; props.click = function() { click.apply( that.element[0], arguments ); }; button = $( "<button></button>", props ) .appendTo( that.uiButtonSet ); if ( $.fn.button ) { button.button(); } }); this.uiDialog.addClass( "ui-dialog-buttons" ); this.uiDialogButtonPane.appendTo( this.uiDialog ); } else { this.uiDialog.removeClass( "ui-dialog-buttons" ); } }, _makeDraggable: function() { var that = this, options = this.options; function filteredUi( ui ) { return { position: ui.position, offset: ui.offset }; } this.uiDialog.draggable({ cancel: ".ui-dialog-content, .ui-dialog-titlebar-close", handle: ".ui-dialog-titlebar", containment: "document", start: function( event, ui ) { $( this ) .addClass( "ui-dialog-dragging" ); that._trigger( "dragStart", event, filteredUi( ui ) ); }, drag: function( event, ui ) { that._trigger( "drag", event, filteredUi( ui ) ); }, stop: function( event, ui ) { options.position = [ ui.position.left - that.document.scrollLeft(), ui.position.top - that.document.scrollTop() ]; $( this ) .removeClass( "ui-dialog-dragging" ); that._trigger( "dragStop", event, filteredUi( ui ) ); $.ui.dialog.overlay.resize(); } }); }, _makeResizable: function( handles ) { handles = (handles === undefined ? this.options.resizable : handles); var that = this, options = this.options, // .ui-resizable has position: relative defined in the stylesheet // but dialogs have to use absolute or fixed positioning position = this.uiDialog.css( "position" ), resizeHandles = typeof handles === 'string' ? handles : "n,e,s,w,se,sw,ne,nw"; function filteredUi( ui ) { return { originalPosition: ui.originalPosition, originalSize: ui.originalSize, position: ui.position, size: ui.size }; } this.uiDialog.resizable({ cancel: ".ui-dialog-content", containment: "document", alsoResize: this.element, maxWidth: options.maxWidth, maxHeight: options.maxHeight, minWidth: options.minWidth, minHeight: this._minHeight(), handles: resizeHandles, start: function( event, ui ) { $( this ).addClass( "ui-dialog-resizing" ); that._trigger( "resizeStart", event, filteredUi( ui ) ); }, resize: function( event, ui ) { that._trigger( "resize", event, filteredUi( ui ) ); }, stop: function( event, ui ) { $( this ).removeClass( "ui-dialog-resizing" ); options.height = $( this ).height(); options.width = $( this ).width(); that._trigger( "resizeStop", event, filteredUi( ui ) ); $.ui.dialog.overlay.resize(); } }) .css( "position", position ) .find( ".ui-resizable-se" ) .addClass( "ui-icon ui-icon-grip-diagonal-se" ); }, _minHeight: function() { var options = this.options; if ( options.height === "auto" ) { return options.minHeight; } else { return Math.min( options.minHeight, options.height ); } }, _position: function( position ) { var myAt = [], offset = [ 0, 0 ], isVisible; if ( position ) { // deep extending converts arrays to objects in jQuery <= 1.3.2 :-( // if (typeof position == 'string' || $.isArray(position)) { // myAt = $.isArray(position) ? position : position.split(' '); if ( typeof position === "string" || (typeof position === "object" && "0" in position ) ) { myAt = position.split ? position.split( " " ) : [ position[ 0 ], position[ 1 ] ]; if ( myAt.length === 1 ) { myAt[ 1 ] = myAt[ 0 ]; } $.each( [ "left", "top" ], function( i, offsetPosition ) { if ( +myAt[ i ] === myAt[ i ] ) { offset[ i ] = myAt[ i ]; myAt[ i ] = offsetPosition; } }); position = { my: myAt[0] + (offset[0] < 0 ? offset[0] : "+" + offset[0]) + " " + myAt[1] + (offset[1] < 0 ? offset[1] : "+" + offset[1]), at: myAt.join( " " ) }; } position = $.extend( {}, $.ui.dialog.prototype.options.position, position ); } else { position = $.ui.dialog.prototype.options.position; } // need to show the dialog to get the actual offset in the position plugin isVisible = this.uiDialog.is( ":visible" ); if ( !isVisible ) { this.uiDialog.show(); } this.uiDialog.position( position ); if ( !isVisible ) { this.uiDialog.hide(); } }, _setOptions: function( options ) { var that = this, resizableOptions = {}, resize = false; $.each( options, function( key, value ) { that._setOption( key, value ); if ( key in sizeRelatedOptions ) { resize = true; } if ( key in resizableRelatedOptions ) { resizableOptions[ key ] = value; } }); if ( resize ) { this._size(); } if ( this.uiDialog.is( ":data(resizable)" ) ) { this.uiDialog.resizable( "option", resizableOptions ); } }, _setOption: function( key, value ) { var isDraggable, isResizable, uiDialog = this.uiDialog; switch ( key ) { case "buttons": this._createButtons( value ); break; case "closeText": // ensure that we always pass a string this.uiDialogTitlebarCloseText.text( "" + value ); break; case "dialogClass": uiDialog .removeClass( this.options.dialogClass ) .addClass( uiDialogClasses + value ); break; case "disabled": if ( value ) { uiDialog.addClass( "ui-dialog-disabled" ); } else { uiDialog.removeClass( "ui-dialog-disabled" ); } break; case "draggable": isDraggable = uiDialog.is( ":data(draggable)" ); if ( isDraggable && !value ) { uiDialog.draggable( "destroy" ); } if ( !isDraggable && value ) { this._makeDraggable(); } break; case "position": this._position( value ); break; case "resizable": // currently resizable, becoming non-resizable isResizable = uiDialog.is( ":data(resizable)" ); if ( isResizable && !value ) { uiDialog.resizable( "destroy" ); } // currently resizable, changing handles if ( isResizable && typeof value === "string" ) { uiDialog.resizable( "option", "handles", value ); } // currently non-resizable, becoming resizable if ( !isResizable && value !== false ) { this._makeResizable( value ); } break; case "title": // convert whatever was passed in o a string, for html() to not throw up $( ".ui-dialog-title", this.uiDialogTitlebar ) .html( "" + ( value || "&#160;" ) ); break; } this._super( key, value ); }, _size: function() { /* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content * divs will both have width and height set, so we need to reset them */ var nonContentHeight, minContentHeight, autoHeight, options = this.options, isVisible = this.uiDialog.is( ":visible" ); // reset content sizing this.element.show().css({ width: "auto", minHeight: 0, height: 0 }); if ( options.minWidth > options.width ) { options.width = options.minWidth; } // reset wrapper sizing // determine the height of all the non-content elements nonContentHeight = this.uiDialog.css({ height: "auto", width: options.width }) .outerHeight(); minContentHeight = Math.max( 0, options.minHeight - nonContentHeight ); if ( options.height === "auto" ) { // only needed for IE6 support if ( $.support.minHeight ) { this.element.css({ minHeight: minContentHeight, height: "auto" }); } else { this.uiDialog.show(); autoHeight = this.element.css( "height", "auto" ).height(); if ( !isVisible ) { this.uiDialog.hide(); } this.element.height( Math.max( autoHeight, minContentHeight ) ); } } else { this.element.height( Math.max( options.height - nonContentHeight, 0 ) ); } if (this.uiDialog.is( ":data(resizable)" ) ) { this.uiDialog.resizable( "option", "minHeight", this._minHeight() ); } } }); $.extend($.ui.dialog, { uuid: 0, maxZ: 0, getTitleId: function($el) { var id = $el.attr( "id" ); if ( !id ) { this.uuid += 1; id = this.uuid; } return "ui-dialog-title-" + id; }, overlay: function( dialog ) { this.$el = $.ui.dialog.overlay.create( dialog ); } }); $.extend( $.ui.dialog.overlay, { instances: [], // reuse old instances due to IE memory leak with alpha transparency (see #5185) oldInstances: [], maxZ: 0, events: $.map( "focus,mousedown,mouseup,keydown,keypress,click".split( "," ), function( event ) { return event + ".dialog-overlay"; } ).join( " " ), create: function( dialog ) { if ( this.instances.length === 0 ) { // prevent use of anchors and inputs // we use a setTimeout in case the overlay is created from an // event that we're going to be cancelling (see #2804) setTimeout(function() { // handle $(el).dialog().dialog('close') (see #4065) if ( $.ui.dialog.overlay.instances.length ) { $( document ).bind( $.ui.dialog.overlay.events, function( event ) { // stop events if the z-index of the target is < the z-index of the overlay // we cannot return true when we don't want to cancel the event (#3523) if ( $( event.target ).zIndex() < $.ui.dialog.overlay.maxZ ) { return false; } }); } }, 1 ); // handle window resize $( window ).bind( "resize.dialog-overlay", $.ui.dialog.overlay.resize ); } var $el = ( this.oldInstances.pop() || $( "<div>" ).addClass( "ui-widget-overlay" ) ); // allow closing by pressing the escape key $( document ).bind( "keydown.dialog-overlay", function( event ) { var instances = $.ui.dialog.overlay.instances; // only react to the event if we're the top overlay if ( instances.length !== 0 && instances[ instances.length - 1 ] === $el && dialog.options.closeOnEscape && !event.isDefaultPrevented() && event.keyCode && event.keyCode === $.ui.keyCode.ESCAPE ) { dialog.close( event ); event.preventDefault(); } }); $el.appendTo( document.body ).css({ width: this.width(), height: this.height() }); if ( $.fn.bgiframe ) { $el.bgiframe(); } this.instances.push( $el ); return $el; }, destroy: function( $el ) { var indexOf = $.inArray( $el, this.instances ), maxZ = 0; if ( indexOf !== -1 ) { this.oldInstances.push( this.instances.splice( indexOf, 1 )[ 0 ] ); } if ( this.instances.length === 0 ) { $( [ document, window ] ).unbind( ".dialog-overlay" ); } $el.height( 0 ).width( 0 ).remove(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) $.each( this.instances, function() { maxZ = Math.max( maxZ, this.css( "z-index" ) ); }); this.maxZ = maxZ; }, height: function() { var scrollHeight, offsetHeight; // handle IE if ( $.ui.ie ) { scrollHeight = Math.max( document.documentElement.scrollHeight, document.body.scrollHeight ); offsetHeight = Math.max( document.documentElement.offsetHeight, document.body.offsetHeight ); if ( scrollHeight < offsetHeight ) { return $( window ).height() + "px"; } else { return scrollHeight + "px"; } // handle "good" browsers } else { return $( document ).height() + "px"; } }, width: function() { var scrollWidth, offsetWidth; // handle IE if ( $.ui.ie ) { scrollWidth = Math.max( document.documentElement.scrollWidth, document.body.scrollWidth ); offsetWidth = Math.max( document.documentElement.offsetWidth, document.body.offsetWidth ); if ( scrollWidth < offsetWidth ) { return $( window ).width() + "px"; } else { return scrollWidth + "px"; } // handle "good" browsers } else { return $( document ).width() + "px"; } }, resize: function() { /* If the dialog is draggable and the user drags it past the * right edge of the window, the document becomes wider so we * need to stretch the overlay. If the user then drags the * dialog back to the left, the document will become narrower, * so we need to shrink the overlay to the appropriate size. * This is handled by shrinking the overlay before setting it * to the full document size. */ var $overlays = $( [] ); $.each( $.ui.dialog.overlay.instances, function() { $overlays = $overlays.add( this ); }); $overlays.css({ width: 0, height: 0 }).css({ width: $.ui.dialog.overlay.width(), height: $.ui.dialog.overlay.height() }); } }); $.extend( $.ui.dialog.overlay.prototype, { destroy: function() { $.ui.dialog.overlay.destroy( this.$el ); } }); }( jQuery ) ); (function( $, undefined ) { $.widget("ui.draggable", $.ui.mouse, { version: "1.9.2", 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() { this.element.removeClass( "ui-draggable ui-draggable-dragging ui-draggable-disabled" ); this._mouseDestroy(); }, _mouseCapture: function(event) { var o = this.options; // among others, prevent a drag on a resizable-handle if (this.helper || o.disabled || $(event.target).is('.ui-resizable-handle')) return false; //Quit if we're not on a valid handle this.handle = this._getHandle(event); if (!this.handle) return false; $(o.iframeFix === true ? "iframe" : o.iframeFix).each(function() { $('<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($(this).offset()) .appendTo("body"); }); return true; }, _mouseStart: function(event) { var o = this.options; //Create and append the visible helper this.helper = this._createHelper(event); this.helper.addClass("ui-draggable-dragging"); //Cache the helper size this._cacheHelperProportions(); //If ddmanager is used for droppables, set the global draggable if($.ui.ddmanager) $.ui.ddmanager.current = this; /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Store the helper's css position this.cssPosition = this.helper.css("position"); this.scrollParent = this.helper.scrollParent(); //The element's absolute position on the page minus margins this.offset = this.positionAbs = this.element.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); //Generate the original position this.originalPosition = this.position = this._generatePosition(event); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if 'cursorAt' is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Set a containment if given in the options if(o.containment) this._setContainment(); //Trigger event + callbacks if(this._trigger("start", event) === false) { this._clear(); return false; } //Recache the helper size this._cacheHelperProportions(); //Prepare the droppable offsets if ($.ui.ddmanager && !o.dropBehaviour) $.ui.ddmanager.prepareOffsets(this, event); this._mouseDrag(event, true); //Execute the drag once - this causes the helper not to be visible before getting its correct position //If the ddmanager is used for droppables, inform the manager that dragging has started (see #5003) if ( $.ui.ddmanager ) $.ui.ddmanager.dragStart(this, event); return true; }, _mouseDrag: function(event, noPropagation) { //Compute the helpers position this.position = this._generatePosition(event); this.positionAbs = this._convertPositionTo("absolute"); //Call plugins and callbacks and use the resulting position if something is returned if (!noPropagation) { var ui = this._uiHash(); if(this._trigger('drag', event, ui) === false) { this._mouseUp({}); return false; } this.position = ui.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($.ui.ddmanager) $.ui.ddmanager.drag(this, event); return false; }, _mouseStop: function(event) { //If we are using droppables, inform the manager about the drop var dropped = false; if ($.ui.ddmanager && !this.options.dropBehaviour) dropped = $.ui.ddmanager.drop(this, event); //if a drop comes from outside (a sortable) if(this.dropped) { dropped = this.dropped; this.dropped = false; } //if the original element is no longer in the DOM don't bother to continue (see #8269) var element = this.element[0], elementInDom = false; while ( element && (element = element.parentNode) ) { if (element == document ) { elementInDom = true; } } if ( !elementInDom && this.options.helper === "original" ) return false; if((this.options.revert == "invalid" && !dropped) || (this.options.revert == "valid" && dropped) || this.options.revert === true || ($.isFunction(this.options.revert) && this.options.revert.call(this.element, dropped))) { var that = this; $(this.helper).animate(this.originalPosition, parseInt(this.options.revertDuration, 10), function() { if(that._trigger("stop", event) !== false) { that._clear(); } }); } else { if(this._trigger("stop", event) !== false) { this._clear(); } } return false; }, _mouseUp: function(event) { //Remove frame helpers $("div.ui-draggable-iframeFix").each(function() { this.parentNode.removeChild(this); }); //If the ddmanager is used for droppables, inform the manager that dragging has stopped (see #5003) if( $.ui.ddmanager ) $.ui.ddmanager.dragStop(this, event); return $.ui.mouse.prototype._mouseUp.call(this, event); }, cancel: function() { if(this.helper.is(".ui-draggable-dragging")) { this._mouseUp({}); } else { this._clear(); } return this; }, _getHandle: function(event) { var handle = !this.options.handle || !$(this.options.handle, this.element).length ? true : false; $(this.options.handle, this.element) .find("*") .andSelf() .each(function() { if(this == event.target) handle = true; }); return handle; }, _createHelper: function(event) { var o = this.options; var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event])) : (o.helper == 'clone' ? this.element.clone().removeAttr('id') : this.element); if(!helper.parents('body').length) helper.appendTo((o.appendTo == 'parent' ? this.element[0].parentNode : o.appendTo)); if(helper[0] != this.element[0] && !(/(fixed|absolute)/).test(helper.css("position"))) helper.css("position", "absolute"); return helper; }, _adjustOffsetFromHelper: function(obj) { if (typeof obj == 'string') { obj = obj.split(' '); } if ($.isArray(obj)) { obj = {left: +obj[0], top: +obj[1] || 0}; } if ('left' in obj) { this.offset.click.left = obj.left + this.margins.left; } if ('right' in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ('top' in obj) { this.offset.click.top = obj.top + this.margins.top; } if ('bottom' in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _getParentOffset: function() { //Get the offsetParent and cache its position this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset(); // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.ui.ie)) //Ugly IE fix po = { top: 0, left: 0 }; return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if(this.cssPosition == "relative") { var p = this.element.position(); return { top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), left: p.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 o = this.options; if(o.containment == 'parent') o.containment = this.helper[0].parentNode; if(o.containment == 'document' || o.containment == 'window') this.containment = [ o.containment == 'document' ? 0 : $(window).scrollLeft() - this.offset.relative.left - this.offset.parent.left, o.containment == 'document' ? 0 : $(window).scrollTop() - this.offset.relative.top - this.offset.parent.top, (o.containment == 'document' ? 0 : $(window).scrollLeft()) + $(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left, (o.containment == 'document' ? 0 : $(window).scrollTop()) + ($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top ]; if(!(/^(document|window|parent)$/).test(o.containment) && o.containment.constructor != Array) { var c = $(o.containment); var ce = c[0]; if(!ce) return; var co = c.offset(); var over = ($(ce).css("overflow") != 'hidden'); this.containment = [ (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0), (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0), (over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left - this.margins.right, (over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top - this.margins.bottom ]; this.relative_container = c; } else if(o.containment.constructor == Array) { this.containment = o.containment; } }, _convertPositionTo: function(d, pos) { if(!pos) pos = this.position; var mod = d == "absolute" ? 1 : -1; var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); return { top: ( pos.top // The absolute mouse position + this.offset.relative.top * mod // Only for relative positioned nodes: Relative offset from element to offset parent + this.offset.parent.top * mod // The offsetParent's offset without borders (offset + border) - ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod) ), left: ( pos.left // The absolute mouse position + this.offset.relative.left * mod // Only for relative positioned nodes: Relative offset from element to offset parent + this.offset.parent.left * mod // The offsetParent's offset without borders (offset + border) - ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod) ) }; }, _generatePosition: function(event) { var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); var pageX = event.pageX; var pageY = event.pageY; /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ if(this.originalPosition) { //If we are not dragging yet, we won't check for options var containment; if(this.containment) { if (this.relative_container){ var co = this.relative_container.offset(); containment = [ this.containment[0] + co.left, this.containment[1] + co.top, this.containment[2] + co.left, this.containment[3] + co.top ]; } else { containment = this.containment; } if(event.pageX - this.offset.click.left < containment[0]) pageX = containment[0] + this.offset.click.left; if(event.pageY - this.offset.click.top < containment[1]) pageY = containment[1] + this.offset.click.top; if(event.pageX - this.offset.click.left > containment[2]) pageX = containment[2] + this.offset.click.left; if(event.pageY - this.offset.click.top > containment[3]) pageY = containment[3] + this.offset.click.top; } if(o.grid) { //Check for grid elements set to 0 to prevent divide by 0 error causing invalid argument errors in IE (see ticket #6950) var top = o.grid[1] ? this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1] : this.originalPageY; pageY = containment ? (!(top - this.offset.click.top < containment[1] || top - this.offset.click.top > containment[3]) ? top : (!(top - this.offset.click.top < containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; var left = o.grid[0] ? this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0] : this.originalPageX; pageX = containment ? (!(left - this.offset.click.left < containment[0] || left - this.offset.click.left > containment[2]) ? left : (!(left - this.offset.click.left < containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } } return { top: ( pageY // The absolute mouse position - this.offset.click.top // Click offset (relative to the element) - this.offset.relative.top // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.top // The offsetParent's offset without borders (offset + border) + ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )) ), left: ( pageX // The absolute mouse position - this.offset.click.left // Click offset (relative to the element) - this.offset.relative.left // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.left // The offsetParent's offset without borders (offset + border) + ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )) ) }; }, _clear: function() { this.helper.removeClass("ui-draggable-dragging"); if(this.helper[0] != this.element[0] && !this.cancelHelperRemoval) this.helper.remove(); //if($.ui.ddmanager) $.ui.ddmanager.current = null; this.helper = null; this.cancelHelperRemoval = false; }, // From now on bulk stuff - mainly helpers _trigger: function(type, event, ui) { ui = ui || this._uiHash(); $.ui.plugin.call(this, type, [event, ui]); if(type == "drag") this.positionAbs = this._convertPositionTo("absolute"); //The absolute position has to be recalculated after plugins return $.Widget.prototype._trigger.call(this, type, event, ui); }, plugins: {}, _uiHash: function(event) { return { helper: this.helper, position: this.position, originalPosition: this.originalPosition, offset: this.positionAbs }; } }); $.ui.plugin.add("draggable", "connectToSortable", { start: function(event, ui) { var inst = $(this).data("draggable"), o = inst.options, uiSortable = $.extend({}, ui, { item: inst.element }); inst.sortables = []; $(o.connectToSortable).each(function() { var sortable = $.data(this, 'sortable'); if (sortable && !sortable.options.disabled) { inst.sortables.push({ instance: sortable, shouldRevert: sortable.options.revert }); sortable.refreshPositions(); // Call the sortable's refreshPositions at drag start to refresh the containerCache since the sortable container cache is used in drag and needs to be up to date (this will ensure it's initialised as well as being kept in step with any changes that might have happened on the page). sortable._trigger("activate", event, uiSortable); } }); }, stop: function(event, ui) { //If we are still over the sortable, we fake the stop event of the sortable, but also remove helper var inst = $(this).data("draggable"), uiSortable = $.extend({}, ui, { item: inst.element }); $.each(inst.sortables, function() { if(this.instance.isOver) { this.instance.isOver = 0; inst.cancelHelperRemoval = true; //Don't remove the helper in the draggable instance this.instance.cancelHelperRemoval = false; //Remove it in the sortable instance (so sortable plugins like revert still work) //The sortable revert is supported, and we have to set a temporary dropped variable on the draggable to support revert: 'valid/invalid' if(this.shouldRevert) this.instance.options.revert = true; //Trigger the stop of the sortable this.instance._mouseStop(event); this.instance.options.helper = this.instance.options._helper; //If the helper has been the original item, restore properties in the sortable if(inst.options.helper == 'original') this.instance.currentItem.css({ top: 'auto', left: 'auto' }); } else { this.instance.cancelHelperRemoval = false; //Remove the helper in the sortable instance this.instance._trigger("deactivate", event, uiSortable); } }); }, drag: function(event, ui) { var inst = $(this).data("draggable"), that = this; var checkPos = function(o) { var dyClick = this.offset.click.top, dxClick = this.offset.click.left; var helperTop = this.positionAbs.top, helperLeft = this.positionAbs.left; var itemHeight = o.height, itemWidth = o.width; var itemTop = o.top, itemLeft = o.left; return $.ui.isOver(helperTop + dyClick, helperLeft + dxClick, itemTop, itemLeft, itemHeight, itemWidth); }; $.each(inst.sortables, function(i) { var innermostIntersecting = false; var thisSortable = this; //Copy over some variables to allow calling the sortable's native _intersectsWith this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if(this.instance._intersectsWith(this.instance.containerCache)) { innermostIntersecting = true; $.each(inst.sortables, function () { this.instance.positionAbs = inst.positionAbs; this.instance.helperProportions = inst.helperProportions; this.instance.offset.click = inst.offset.click; if (this != thisSortable && this.instance._intersectsWith(this.instance.containerCache) && $.ui.contains(thisSortable.instance.element[0], this.instance.element[0])) innermostIntersecting = false; return innermostIntersecting; }); } if(innermostIntersecting) { //If it intersects, we use a little isOver variable and set it once, so our move-in stuff gets fired only once if(!this.instance.isOver) { this.instance.isOver = 1; //Now we fake the start of dragging for the sortable instance, //by cloning the list group item, appending it to the sortable and using it as inst.currentItem //We can then fire the start event of the sortable with our passed browser event, and our own helper (so it doesn't create a new one) this.instance.currentItem = $(that).clone().removeAttr('id').appendTo(this.instance.element).data("sortable-item", true); this.instance.options._helper = this.instance.options.helper; //Store helper option to later restore it this.instance.options.helper = function() { return ui.helper[0]; }; event.target = this.instance.currentItem[0]; this.instance._mouseCapture(event, true); this.instance._mouseStart(event, true, true); //Because the browser event is way off the new appended portlet, we modify a couple of variables to reflect the changes this.instance.offset.click.top = inst.offset.click.top; this.instance.offset.click.left = inst.offset.click.left; this.instance.offset.parent.left -= inst.offset.parent.left - this.instance.offset.parent.left; this.instance.offset.parent.top -= inst.offset.parent.top - this.instance.offset.parent.top; inst._trigger("toSortable", event); inst.dropped = this.instance.element; //draggable revert needs that //hack so receive/update callbacks work (mostly) inst.currentItem = inst.element; this.instance.fromOutside = inst; } //Provided we did all the previous steps, we can fire the drag event of the sortable on every draggable drag, when it intersects with the sortable if(this.instance.currentItem) this.instance._mouseDrag(event); } else { //If it doesn't intersect with the sortable, and it intersected before, //we fake the drag stop of the sortable, but make sure it doesn't remove the helper by using cancelHelperRemoval if(this.instance.isOver) { this.instance.isOver = 0; this.instance.cancelHelperRemoval = true; //Prevent reverting on this forced stop this.instance.options.revert = false; // The out event needs to be triggered independently this.instance._trigger('out', event, this.instance._uiHash(this.instance)); this.instance._mouseStop(event, true); this.instance.options.helper = this.instance.options._helper; //Now we remove our currentItem, the list group clone again, and the placeholder, and animate the helper back to it's original size this.instance.currentItem.remove(); if(this.instance.placeholder) this.instance.placeholder.remove(); inst._trigger("fromSortable", event); inst.dropped = false; //draggable revert needs that } }; }); } }); $.ui.plugin.add("draggable", "cursor", { start: function(event, ui) { var t = $('body'), o = $(this).data('draggable').options; if (t.css("cursor")) o._cursor = t.css("cursor"); t.css("cursor", o.cursor); }, stop: function(event, ui) { var o = $(this).data('draggable').options; if (o._cursor) $('body').css("cursor", o._cursor); } }); $.ui.plugin.add("draggable", "opacity", { start: function(event, ui) { var t = $(ui.helper), o = $(this).data('draggable').options; if(t.css("opacity")) o._opacity = t.css("opacity"); t.css('opacity', o.opacity); }, stop: function(event, ui) { var o = $(this).data('draggable').options; if(o._opacity) $(ui.helper).css('opacity', o._opacity); } }); $.ui.plugin.add("draggable", "scroll", { start: function(event, ui) { var i = $(this).data("draggable"); if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') i.overflowOffset = i.scrollParent.offset(); }, drag: function(event, ui) { var i = $(this).data("draggable"), o = i.options, scrolled = false; if(i.scrollParent[0] != document && i.scrollParent[0].tagName != 'HTML') { if(!o.axis || o.axis != 'x') { if((i.overflowOffset.top + i.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop + o.scrollSpeed; else if(event.pageY - i.overflowOffset.top < o.scrollSensitivity) i.scrollParent[0].scrollTop = scrolled = i.scrollParent[0].scrollTop - o.scrollSpeed; } if(!o.axis || o.axis != 'y') { if((i.overflowOffset.left + i.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft + o.scrollSpeed; else if(event.pageX - i.overflowOffset.left < o.scrollSensitivity) i.scrollParent[0].scrollLeft = scrolled = i.scrollParent[0].scrollLeft - o.scrollSpeed; } } else { if(!o.axis || o.axis != 'x') { if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); } if(!o.axis || o.axis != 'y') { if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } } if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) $.ui.ddmanager.prepareOffsets(i, event); } }); $.ui.plugin.add("draggable", "snap", { start: function(event, ui) { var i = $(this).data("draggable"), o = i.options; i.snapElements = []; $(o.snap.constructor != String ? ( o.snap.items || ':data(draggable)' ) : o.snap).each(function() { var $t = $(this); var $o = $t.offset(); if(this != i.element[0]) i.snapElements.push({ item: this, width: $t.outerWidth(), height: $t.outerHeight(), top: $o.top, left: $o.left }); }); }, drag: function(event, ui) { var inst = $(this).data("draggable"), o = inst.options; var d = o.snapTolerance; var x1 = ui.offset.left, x2 = x1 + inst.helperProportions.width, y1 = ui.offset.top, y2 = y1 + inst.helperProportions.height; for (var i = inst.snapElements.length - 1; i >= 0; i--){ var l = inst.snapElements[i].left, r = l + inst.snapElements[i].width, t = inst.snapElements[i].top, b = t + inst.snapElements[i].height; //Yes, I know, this is insane ;) if(!((l-d < x1 && x1 < r+d && t-d < y1 && y1 < b+d) || (l-d < x1 && x1 < r+d && t-d < y2 && y2 < b+d) || (l-d < x2 && x2 < r+d && t-d < y1 && y1 < b+d) || (l-d < x2 && x2 < r+d && t-d < y2 && y2 < b+d))) { if(inst.snapElements[i].snapping) (inst.options.snap.release && inst.options.snap.release.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); inst.snapElements[i].snapping = false; continue; } if(o.snapMode != 'inner') { var ts = Math.abs(t - y2) <= d; var bs = Math.abs(b - y1) <= d; var ls = Math.abs(l - x2) <= d; var rs = Math.abs(r - x1) <= d; if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t - inst.helperProportions.height, left: 0 }).top - inst.margins.top; if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b, left: 0 }).top - inst.margins.top; if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l - inst.helperProportions.width }).left - inst.margins.left; if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r }).left - inst.margins.left; } var first = (ts || bs || ls || rs); if(o.snapMode != 'outer') { var ts = Math.abs(t - y1) <= d; var bs = Math.abs(b - y2) <= d; var ls = Math.abs(l - x1) <= d; var rs = Math.abs(r - x2) <= d; if(ts) ui.position.top = inst._convertPositionTo("relative", { top: t, left: 0 }).top - inst.margins.top; if(bs) ui.position.top = inst._convertPositionTo("relative", { top: b - inst.helperProportions.height, left: 0 }).top - inst.margins.top; if(ls) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: l }).left - inst.margins.left; if(rs) ui.position.left = inst._convertPositionTo("relative", { top: 0, left: r - inst.helperProportions.width }).left - inst.margins.left; } if(!inst.snapElements[i].snapping && (ts || bs || ls || rs || first)) (inst.options.snap.snap && inst.options.snap.snap.call(inst.element, event, $.extend(inst._uiHash(), { snapItem: inst.snapElements[i].item }))); inst.snapElements[i].snapping = (ts || bs || ls || rs || first); }; } }); $.ui.plugin.add("draggable", "stack", { start: function(event, ui) { var o = $(this).data("draggable").options; var group = $.makeArray($(o.stack)).sort(function(a,b) { return (parseInt($(a).css("zIndex"),10) || 0) - (parseInt($(b).css("zIndex"),10) || 0); }); if (!group.length) { return; } var min = parseInt(group[0].style.zIndex) || 0; $(group).each(function(i) { this.style.zIndex = min + i; }); this[0].style.zIndex = min + group.length; } }); $.ui.plugin.add("draggable", "zIndex", { start: function(event, ui) { var t = $(ui.helper), o = $(this).data("draggable").options; if(t.css("zIndex")) o._zIndex = t.css("zIndex"); t.css('zIndex', o.zIndex); }, stop: function(event, ui) { var o = $(this).data("draggable").options; if(o._zIndex) $(ui.helper).css('zIndex', o._zIndex); } }); })(jQuery); (function( $, undefined ) { $.widget("ui.droppable", { version: "1.9.2", widgetEventPrefix: "drop", options: { accept: '*', activeClass: false, addClasses: true, greedy: false, hoverClass: false, scope: 'default', tolerance: 'intersect' }, _create: function() { var o = this.options, accept = o.accept; this.isover = 0; this.isout = 1; this.accept = $.isFunction(accept) ? accept : function(d) { return d.is(accept); }; //Store the droppable's proportions this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight }; // Add the reference and positions to the manager $.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || []; $.ui.ddmanager.droppables[o.scope].push(this); (o.addClasses && this.element.addClass("ui-droppable")); }, _destroy: function() { var drop = $.ui.ddmanager.droppables[this.options.scope]; for ( var i = 0; i < drop.length; i++ ) if ( drop[i] == this ) drop.splice(i, 1); this.element.removeClass("ui-droppable ui-droppable-disabled"); }, _setOption: function(key, value) { if(key == 'accept') { this.accept = $.isFunction(value) ? value : function(d) { return d.is(value); }; } $.Widget.prototype._setOption.apply(this, arguments); }, _activate: function(event) { var draggable = $.ui.ddmanager.current; if(this.options.activeClass) this.element.addClass(this.options.activeClass); (draggable && this._trigger('activate', event, this.ui(draggable))); }, _deactivate: function(event) { var draggable = $.ui.ddmanager.current; if(this.options.activeClass) this.element.removeClass(this.options.activeClass); (draggable && this._trigger('deactivate', event, this.ui(draggable))); }, _over: function(event) { var draggable = $.ui.ddmanager.current; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.hoverClass) this.element.addClass(this.options.hoverClass); this._trigger('over', event, this.ui(draggable)); } }, _out: function(event) { var draggable = $.ui.ddmanager.current; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return; // Bail if draggable and droppable are same element if (this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass); this._trigger('out', event, this.ui(draggable)); } }, _drop: function(event,custom) { var draggable = custom || $.ui.ddmanager.current; if (!draggable || (draggable.currentItem || draggable.element)[0] == this.element[0]) return false; // Bail if draggable and droppable are same element var childrenIntersection = false; this.element.find(":data(droppable)").not(".ui-draggable-dragging").each(function() { var inst = $.data(this, 'droppable'); if( inst.options.greedy && !inst.options.disabled && inst.options.scope == draggable.options.scope && inst.accept.call(inst.element[0], (draggable.currentItem || draggable.element)) && $.ui.intersect(draggable, $.extend(inst, { offset: inst.element.offset() }), inst.options.tolerance) ) { childrenIntersection = true; return false; } }); if(childrenIntersection) return false; if(this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { if(this.options.activeClass) this.element.removeClass(this.options.activeClass); if(this.options.hoverClass) this.element.removeClass(this.options.hoverClass); this._trigger('drop', event, this.ui(draggable)); return this.element; } return false; }, ui: function(c) { return { draggable: (c.currentItem || c.element), helper: c.helper, position: c.position, offset: c.positionAbs }; } }); $.ui.intersect = function(draggable, droppable, toleranceMode) { if (!droppable.offset) return false; var x1 = (draggable.positionAbs || draggable.position.absolute).left, x2 = x1 + draggable.helperProportions.width, y1 = (draggable.positionAbs || draggable.position.absolute).top, y2 = y1 + draggable.helperProportions.height; var l = droppable.offset.left, r = l + droppable.proportions.width, t = droppable.offset.top, b = t + droppable.proportions.height; switch (toleranceMode) { case 'fit': return (l <= x1 && x2 <= r && t <= y1 && y2 <= b); break; case 'intersect': return (l < x1 + (draggable.helperProportions.width / 2) // Right Half && x2 - (draggable.helperProportions.width / 2) < r // Left Half && t < y1 + (draggable.helperProportions.height / 2) // Bottom Half && y2 - (draggable.helperProportions.height / 2) < b ); // Top Half break; case 'pointer': var draggableLeft = ((draggable.positionAbs || draggable.position.absolute).left + (draggable.clickOffset || draggable.offset.click).left), draggableTop = ((draggable.positionAbs || draggable.position.absolute).top + (draggable.clickOffset || draggable.offset.click).top), isOver = $.ui.isOver(draggableTop, draggableLeft, t, l, droppable.proportions.height, droppable.proportions.width); return isOver; break; case 'touch': return ( (y1 >= t && y1 <= b) || // Top edge touching (y2 >= t && y2 <= b) || // Bottom edge touching (y1 < t && y2 > b) // Surrounded vertically ) && ( (x1 >= l && x1 <= r) || // Left edge touching (x2 >= l && x2 <= r) || // Right edge touching (x1 < l && x2 > r) // Surrounded horizontally ); break; default: return false; break; } }; /* This manager tracks offsets of draggables and droppables */ $.ui.ddmanager = { current: null, droppables: { 'default': [] }, prepareOffsets: function(t, event) { var m = $.ui.ddmanager.droppables[t.options.scope] || []; var type = event ? event.type : null; // workaround for #2317 var list = (t.currentItem || t.element).find(":data(droppable)").andSelf(); droppablesLoop: for (var i = 0; i < m.length; i++) { if(m[i].options.disabled || (t && !m[i].accept.call(m[i].element[0],(t.currentItem || t.element)))) continue; //No disabled and non-accepted for (var j=0; j < list.length; j++) { if(list[j] == m[i].element[0]) { m[i].proportions.height = 0; continue droppablesLoop; } }; //Filter out elements in the current dragged item m[i].visible = m[i].element.css("display") != "none"; if(!m[i].visible) continue; //If the element is not visible, continue if(type == "mousedown") m[i]._activate.call(m[i], event); //Activate the droppable if used directly from draggables m[i].offset = m[i].element.offset(); m[i].proportions = { width: m[i].element[0].offsetWidth, height: m[i].element[0].offsetHeight }; } }, drop: function(draggable, event) { var dropped = false; $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() { if(!this.options) return; if (!this.options.disabled && this.visible && $.ui.intersect(draggable, this, this.options.tolerance)) dropped = this._drop.call(this, event) || dropped; if (!this.options.disabled && this.visible && this.accept.call(this.element[0],(draggable.currentItem || draggable.element))) { this.isout = 1; this.isover = 0; this._deactivate.call(this, event); } }); return dropped; }, dragStart: function( draggable, event ) { //Listen for scrolling so that if the dragging causes scrolling the position of the droppables can be recalculated (see #5003) draggable.element.parentsUntil( "body" ).bind( "scroll.droppable", function() { if( !draggable.options.refreshPositions ) $.ui.ddmanager.prepareOffsets( draggable, event ); }); }, drag: function(draggable, event) { //If you have a highly dynamic page, you might try this option. It renders positions every time you move the mouse. if(draggable.options.refreshPositions) $.ui.ddmanager.prepareOffsets(draggable, event); //Run through all droppables and check their positions based on specific tolerance options $.each($.ui.ddmanager.droppables[draggable.options.scope] || [], function() { if(this.options.disabled || this.greedyChild || !this.visible) return; var intersects = $.ui.intersect(draggable, this, this.options.tolerance); var c = !intersects && this.isover == 1 ? 'isout' : (intersects && this.isover == 0 ? 'isover' : null); if(!c) return; var parentInstance; if (this.options.greedy) { // find droppable parents with same scope var scope = this.options.scope; var parent = this.element.parents(':data(droppable)').filter(function () { return $.data(this, 'droppable').options.scope === scope; }); if (parent.length) { parentInstance = $.data(parent[0], 'droppable'); parentInstance.greedyChild = (c == 'isover' ? 1 : 0); } } // we just moved into a greedy child if (parentInstance && c == 'isover') { parentInstance['isover'] = 0; parentInstance['isout'] = 1; parentInstance._out.call(parentInstance, event); } this[c] = 1; this[c == 'isout' ? 'isover' : 'isout'] = 0; this[c == "isover" ? "_over" : "_out"].call(this, event); // we just moved out of a greedy child if (parentInstance && c == 'isout') { parentInstance['isout'] = 0; parentInstance['isover'] = 1; parentInstance._over.call(parentInstance, event); } }); }, dragStop: function( draggable, event ) { draggable.element.parentsUntil( "body" ).unbind( "scroll.droppable" ); //Call prepareOffsets one final time since IE does not fire return scroll events when overflow was caused by drag (see #5003) if( !draggable.options.refreshPositions ) $.ui.ddmanager.prepareOffsets( draggable, event ); } }; })(jQuery); ;(jQuery.effects || (function($, undefined) { var backCompat = $.uiBackCompat !== false, // prefix used for storing data on .data() dataSpace = "ui-effects-"; $.effects = { effect: {} }; /*! * jQuery Color Animations v2.0.0 * http://jquery.com/ * * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license. * http://jquery.org/license * * Date: Mon Aug 13 13:41:02 2012 -0500 */ (function( jQuery, undefined ) { var stepHooks = "backgroundColor borderBottomColor borderLeftColor borderRightColor borderTopColor color columnRuleColor outlineColor textDecorationColor textEmphasisColor".split(" "), // plusequals test for += 100 -= 100 rplusequals = /^([\-+])=\s*(\d+\.?\d*)/, // a set of RE's that can match strings and generate color tuples. stringParsers = [{ re: /rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ], execResult[ 3 ], execResult[ 4 ] ]; } }, { re: /rgba?\(\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/, parse: function( execResult ) { return [ execResult[ 1 ] * 2.55, execResult[ 2 ] * 2.55, execResult[ 3 ] * 2.55, execResult[ 4 ] ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9]{2})([a-f0-9]{2})([a-f0-9]{2})/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ], 16 ), parseInt( execResult[ 2 ], 16 ), parseInt( execResult[ 3 ], 16 ) ]; } }, { // this regex ignores A-F because it's compared against an already lowercased string re: /#([a-f0-9])([a-f0-9])([a-f0-9])/, parse: function( execResult ) { return [ parseInt( execResult[ 1 ] + execResult[ 1 ], 16 ), parseInt( execResult[ 2 ] + execResult[ 2 ], 16 ), parseInt( execResult[ 3 ] + execResult[ 3 ], 16 ) ]; } }, { re: /hsla?\(\s*(\d+(?:\.\d+)?)\s*,\s*(\d+(?:\.\d+)?)\%\s*,\s*(\d+(?:\.\d+)?)\%\s*(?:,\s*(\d+(?:\.\d+)?)\s*)?\)/, space: "hsla", parse: function( execResult ) { return [ execResult[ 1 ], execResult[ 2 ] / 100, execResult[ 3 ] / 100, execResult[ 4 ] ]; } }], // jQuery.Color( ) color = jQuery.Color = function( color, green, blue, alpha ) { return new jQuery.Color.fn.parse( color, green, blue, alpha ); }, spaces = { rgba: { props: { red: { idx: 0, type: "byte" }, green: { idx: 1, type: "byte" }, blue: { idx: 2, type: "byte" } } }, hsla: { props: { hue: { idx: 0, type: "degrees" }, saturation: { idx: 1, type: "percent" }, lightness: { idx: 2, type: "percent" } } } }, propTypes = { "byte": { floor: true, max: 255 }, "percent": { max: 1 }, "degrees": { mod: 360, floor: true } }, support = color.support = {}, // element for support tests supportElem = jQuery( "<p>" )[ 0 ], // colors = jQuery.Color.names colors, // local aliases of functions called often each = jQuery.each; // determine rgba support immediately supportElem.style.cssText = "background-color:rgba(1,1,1,.5)"; support.rgba = supportElem.style.backgroundColor.indexOf( "rgba" ) > -1; // define cache name and alpha properties // for rgba and hsla spaces each( spaces, function( spaceName, space ) { space.cache = "_" + spaceName; space.props.alpha = { idx: 3, type: "percent", def: 1 }; }); function clamp( value, prop, allowEmpty ) { var type = propTypes[ prop.type ] || {}; if ( value == null ) { return (allowEmpty || !prop.def) ? null : prop.def; } // ~~ is an short way of doing floor for positive numbers value = type.floor ? ~~value : parseFloat( value ); // IE will pass in empty strings as value for alpha, // which will hit this case if ( isNaN( value ) ) { return prop.def; } if ( type.mod ) { // we add mod before modding to make sure that negatives values // get converted properly: -10 -> 350 return (value + type.mod) % type.mod; } // for now all property types without mod have min and max return 0 > value ? 0 : type.max < value ? type.max : value; } function stringParse( string ) { var inst = color(), rgba = inst._rgba = []; string = string.toLowerCase(); each( stringParsers, function( i, parser ) { var parsed, match = parser.re.exec( string ), values = match && parser.parse( match ), spaceName = parser.space || "rgba"; if ( values ) { parsed = inst[ spaceName ]( values ); // if this was an rgba parse the assignment might happen twice // oh well.... inst[ spaces[ spaceName ].cache ] = parsed[ spaces[ spaceName ].cache ]; rgba = inst._rgba = parsed._rgba; // exit each( stringParsers ) here because we matched return false; } }); // Found a stringParser that handled it if ( rgba.length ) { // if this came from a parsed string, force "transparent" when alpha is 0 // chrome, (and maybe others) return "transparent" as rgba(0,0,0,0) if ( rgba.join() === "0,0,0,0" ) { jQuery.extend( rgba, colors.transparent ); } return inst; } // named colors return colors[ string ]; } color.fn = jQuery.extend( color.prototype, { parse: function( red, green, blue, alpha ) { if ( red === undefined ) { this._rgba = [ null, null, null, null ]; return this; } if ( red.jquery || red.nodeType ) { red = jQuery( red ).css( green ); green = undefined; } var inst = this, type = jQuery.type( red ), rgba = this._rgba = []; // more than 1 argument specified - assume ( red, green, blue, alpha ) if ( green !== undefined ) { red = [ red, green, blue, alpha ]; type = "array"; } if ( type === "string" ) { return this.parse( stringParse( red ) || colors._default ); } if ( type === "array" ) { each( spaces.rgba.props, function( key, prop ) { rgba[ prop.idx ] = clamp( red[ prop.idx ], prop ); }); return this; } if ( type === "object" ) { if ( red instanceof color ) { each( spaces, function( spaceName, space ) { if ( red[ space.cache ] ) { inst[ space.cache ] = red[ space.cache ].slice(); } }); } else { each( spaces, function( spaceName, space ) { var cache = space.cache; each( space.props, function( key, prop ) { // if the cache doesn't exist, and we know how to convert if ( !inst[ cache ] && space.to ) { // if the value was null, we don't need to copy it // if the key was alpha, we don't need to copy it either if ( key === "alpha" || red[ key ] == null ) { return; } inst[ cache ] = space.to( inst._rgba ); } // this is the only case where we allow nulls for ALL properties. // call clamp with alwaysAllowEmpty inst[ cache ][ prop.idx ] = clamp( red[ key ], prop, true ); }); // everything defined but alpha? if ( inst[ cache ] && $.inArray( null, inst[ cache ].slice( 0, 3 ) ) < 0 ) { // use the default of 1 inst[ cache ][ 3 ] = 1; if ( space.from ) { inst._rgba = space.from( inst[ cache ] ); } } }); } return this; } }, is: function( compare ) { var is = color( compare ), same = true, inst = this; each( spaces, function( _, space ) { var localCache, isCache = is[ space.cache ]; if (isCache) { localCache = inst[ space.cache ] || space.to && space.to( inst._rgba ) || []; each( space.props, function( _, prop ) { if ( isCache[ prop.idx ] != null ) { same = ( isCache[ prop.idx ] === localCache[ prop.idx ] ); return same; } }); } return same; }); return same; }, _space: function() { var used = [], inst = this; each( spaces, function( spaceName, space ) { if ( inst[ space.cache ] ) { used.push( spaceName ); } }); return used.pop(); }, transition: function( other, distance ) { var end = color( other ), spaceName = end._space(), space = spaces[ spaceName ], startColor = this.alpha() === 0 ? color( "transparent" ) : this, start = startColor[ space.cache ] || space.to( startColor._rgba ), result = start.slice(); end = end[ space.cache ]; each( space.props, function( key, prop ) { var index = prop.idx, startValue = start[ index ], endValue = end[ index ], type = propTypes[ prop.type ] || {}; // if null, don't override start value if ( endValue === null ) { return; } // if null - use end if ( startValue === null ) { result[ index ] = endValue; } else { if ( type.mod ) { if ( endValue - startValue > type.mod / 2 ) { startValue += type.mod; } else if ( startValue - endValue > type.mod / 2 ) { startValue -= type.mod; } } result[ index ] = clamp( ( endValue - startValue ) * distance + startValue, prop ); } }); return this[ spaceName ]( result ); }, blend: function( opaque ) { // if we are already opaque - return ourself if ( this._rgba[ 3 ] === 1 ) { return this; } var rgb = this._rgba.slice(), a = rgb.pop(), blend = color( opaque )._rgba; return color( jQuery.map( rgb, function( v, i ) { return ( 1 - a ) * blend[ i ] + a * v; })); }, toRgbaString: function() { var prefix = "rgba(", rgba = jQuery.map( this._rgba, function( v, i ) { return v == null ? ( i > 2 ? 1 : 0 ) : v; }); if ( rgba[ 3 ] === 1 ) { rgba.pop(); prefix = "rgb("; } return prefix + rgba.join() + ")"; }, toHslaString: function() { var prefix = "hsla(", hsla = jQuery.map( this.hsla(), function( v, i ) { if ( v == null ) { v = i > 2 ? 1 : 0; } // catch 1 and 2 if ( i && i < 3 ) { v = Math.round( v * 100 ) + "%"; } return v; }); if ( hsla[ 3 ] === 1 ) { hsla.pop(); prefix = "hsl("; } return prefix + hsla.join() + ")"; }, toHexString: function( includeAlpha ) { var rgba = this._rgba.slice(), alpha = rgba.pop(); if ( includeAlpha ) { rgba.push( ~~( alpha * 255 ) ); } return "#" + jQuery.map( rgba, function( v ) { // default to 0 when nulls exist v = ( v || 0 ).toString( 16 ); return v.length === 1 ? "0" + v : v; }).join(""); }, toString: function() { return this._rgba[ 3 ] === 0 ? "transparent" : this.toRgbaString(); } }); color.fn.parse.prototype = color.fn; // hsla conversions adapted from: // https://code.google.com/p/maashaack/source/browse/packages/graphics/trunk/src/graphics/colors/HUE2RGB.as?r=5021 function hue2rgb( p, q, h ) { h = ( h + 1 ) % 1; if ( h * 6 < 1 ) { return p + (q - p) * h * 6; } if ( h * 2 < 1) { return q; } if ( h * 3 < 2 ) { return p + (q - p) * ((2/3) - h) * 6; } return p; } spaces.hsla.to = function ( rgba ) { if ( rgba[ 0 ] == null || rgba[ 1 ] == null || rgba[ 2 ] == null ) { return [ null, null, null, rgba[ 3 ] ]; } var r = rgba[ 0 ] / 255, g = rgba[ 1 ] / 255, b = rgba[ 2 ] / 255, a = rgba[ 3 ], max = Math.max( r, g, b ), min = Math.min( r, g, b ), diff = max - min, add = max + min, l = add * 0.5, h, s; if ( min === max ) { h = 0; } else if ( r === max ) { h = ( 60 * ( g - b ) / diff ) + 360; } else if ( g === max ) { h = ( 60 * ( b - r ) / diff ) + 120; } else { h = ( 60 * ( r - g ) / diff ) + 240; } if ( l === 0 || l === 1 ) { s = l; } else if ( l <= 0.5 ) { s = diff / add; } else { s = diff / ( 2 - add ); } return [ Math.round(h) % 360, s, l, a == null ? 1 : a ]; }; spaces.hsla.from = function ( hsla ) { if ( hsla[ 0 ] == null || hsla[ 1 ] == null || hsla[ 2 ] == null ) { return [ null, null, null, hsla[ 3 ] ]; } var h = hsla[ 0 ] / 360, s = hsla[ 1 ], l = hsla[ 2 ], a = hsla[ 3 ], q = l <= 0.5 ? l * ( 1 + s ) : l + s - l * s, p = 2 * l - q; return [ Math.round( hue2rgb( p, q, h + ( 1 / 3 ) ) * 255 ), Math.round( hue2rgb( p, q, h ) * 255 ), Math.round( hue2rgb( p, q, h - ( 1 / 3 ) ) * 255 ), a ]; }; each( spaces, function( spaceName, space ) { var props = space.props, cache = space.cache, to = space.to, from = space.from; // makes rgba() and hsla() color.fn[ spaceName ] = function( value ) { // generate a cache for this space if it doesn't exist if ( to && !this[ cache ] ) { this[ cache ] = to( this._rgba ); } if ( value === undefined ) { return this[ cache ].slice(); } var ret, type = jQuery.type( value ), arr = ( type === "array" || type === "object" ) ? value : arguments, local = this[ cache ].slice(); each( props, function( key, prop ) { var val = arr[ type === "object" ? key : prop.idx ]; if ( val == null ) { val = local[ prop.idx ]; } local[ prop.idx ] = clamp( val, prop ); }); if ( from ) { ret = color( from( local ) ); ret[ cache ] = local; return ret; } else { return color( local ); } }; // makes red() green() blue() alpha() hue() saturation() lightness() each( props, function( key, prop ) { // alpha is included in more than one space if ( color.fn[ key ] ) { return; } color.fn[ key ] = function( value ) { var vtype = jQuery.type( value ), fn = ( key === "alpha" ? ( this._hsla ? "hsla" : "rgba" ) : spaceName ), local = this[ fn ](), cur = local[ prop.idx ], match; if ( vtype === "undefined" ) { return cur; } if ( vtype === "function" ) { value = value.call( this, cur ); vtype = jQuery.type( value ); } if ( value == null && prop.empty ) { return this; } if ( vtype === "string" ) { match = rplusequals.exec( value ); if ( match ) { value = cur + parseFloat( match[ 2 ] ) * ( match[ 1 ] === "+" ? 1 : -1 ); } } local[ prop.idx ] = value; return this[ fn ]( local ); }; }); }); // add .fx.step functions each( stepHooks, function( i, hook ) { jQuery.cssHooks[ hook ] = { set: function( elem, value ) { var parsed, curElem, backgroundColor = ""; if ( jQuery.type( value ) !== "string" || ( parsed = stringParse( value ) ) ) { value = color( parsed || value ); if ( !support.rgba && value._rgba[ 3 ] !== 1 ) { curElem = hook === "backgroundColor" ? elem.parentNode : elem; while ( (backgroundColor === "" || backgroundColor === "transparent") && curElem && curElem.style ) { try { backgroundColor = jQuery.css( curElem, "backgroundColor" ); curElem = curElem.parentNode; } catch ( e ) { } } value = value.blend( backgroundColor && backgroundColor !== "transparent" ? backgroundColor : "_default" ); } value = value.toRgbaString(); } try { elem.style[ hook ] = value; } catch( error ) { // wrapped to prevent IE from throwing errors on "invalid" values like 'auto' or 'inherit' } } }; jQuery.fx.step[ hook ] = function( fx ) { if ( !fx.colorInit ) { fx.start = color( fx.elem, hook ); fx.end = color( fx.end ); fx.colorInit = true; } jQuery.cssHooks[ hook ].set( fx.elem, fx.start.transition( fx.end, fx.pos ) ); }; }); jQuery.cssHooks.borderColor = { expand: function( value ) { var expanded = {}; each( [ "Top", "Right", "Bottom", "Left" ], function( i, part ) { expanded[ "border" + part + "Color" ] = value; }); return expanded; } }; // Basic color names only. // Usage of any of the other color names requires adding yourself or including // jquery.color.svg-names.js. colors = jQuery.Color.names = { // 4.1. Basic color keywords aqua: "#00ffff", black: "#000000", blue: "#0000ff", fuchsia: "#ff00ff", gray: "#808080", green: "#008000", lime: "#00ff00", maroon: "#800000", navy: "#000080", olive: "#808000", purple: "#800080", red: "#ff0000", silver: "#c0c0c0", teal: "#008080", white: "#ffffff", yellow: "#ffff00", // 4.2.3. "transparent" color keyword transparent: [ null, null, null, 0 ], _default: "#ffffff" }; })( jQuery ); /******************************************************************************/ /****************************** CLASS ANIMATIONS ******************************/ /******************************************************************************/ (function() { var classAnimationActions = [ "add", "remove", "toggle" ], shorthandStyles = { border: 1, borderBottom: 1, borderColor: 1, borderLeft: 1, borderRight: 1, borderTop: 1, borderWidth: 1, margin: 1, padding: 1 }; $.each([ "borderLeftStyle", "borderRightStyle", "borderBottomStyle", "borderTopStyle" ], function( _, prop ) { $.fx.step[ prop ] = function( fx ) { if ( fx.end !== "none" && !fx.setAttr || fx.pos === 1 && !fx.setAttr ) { jQuery.style( fx.elem, prop, fx.end ); fx.setAttr = true; } }; }); function getElementStyles() { var style = this.ownerDocument.defaultView ? this.ownerDocument.defaultView.getComputedStyle( this, null ) : this.currentStyle, newStyle = {}, key, len; // webkit enumerates style porperties if ( style && style.length && style[ 0 ] && style[ style[ 0 ] ] ) { len = style.length; while ( len-- ) { key = style[ len ]; if ( typeof style[ key ] === "string" ) { newStyle[ $.camelCase( key ) ] = style[ key ]; } } } else { for ( key in style ) { if ( typeof style[ key ] === "string" ) { newStyle[ key ] = style[ key ]; } } } return newStyle; } function styleDifference( oldStyle, newStyle ) { var diff = {}, name, value; for ( name in newStyle ) { value = newStyle[ name ]; if ( oldStyle[ name ] !== value ) { if ( !shorthandStyles[ name ] ) { if ( $.fx.step[ name ] || !isNaN( parseFloat( value ) ) ) { diff[ name ] = value; } } } } return diff; } $.effects.animateClass = function( value, duration, easing, callback ) { var o = $.speed( duration, easing, callback ); return this.queue( function() { var animated = $( this ), baseClass = animated.attr( "class" ) || "", applyClassChange, allAnimations = o.children ? animated.find( "*" ).andSelf() : animated; // map the animated objects to store the original styles. allAnimations = allAnimations.map(function() { var el = $( this ); return { el: el, start: getElementStyles.call( this ) }; }); // apply class change applyClassChange = function() { $.each( classAnimationActions, function(i, action) { if ( value[ action ] ) { animated[ action + "Class" ]( value[ action ] ); } }); }; applyClassChange(); // map all animated objects again - calculate new styles and diff allAnimations = allAnimations.map(function() { this.end = getElementStyles.call( this.el[ 0 ] ); this.diff = styleDifference( this.start, this.end ); return this; }); // apply original class animated.attr( "class", baseClass ); // map all animated objects again - this time collecting a promise allAnimations = allAnimations.map(function() { var styleInfo = this, dfd = $.Deferred(), opts = jQuery.extend({}, o, { queue: false, complete: function() { dfd.resolve( styleInfo ); } }); this.el.animate( this.diff, opts ); return dfd.promise(); }); // once all animations have completed: $.when.apply( $, allAnimations.get() ).done(function() { // set the final class applyClassChange(); // for each animated element, // clear all css properties that were animated $.each( arguments, function() { var el = this.el; $.each( this.diff, function(key) { el.css( key, '' ); }); }); // this is guarnteed to be there if you use jQuery.speed() // it also handles dequeuing the next anim... o.complete.call( animated[ 0 ] ); }); }); }; $.fn.extend({ _addClass: $.fn.addClass, addClass: function( classNames, speed, easing, callback ) { return speed ? $.effects.animateClass.call( this, { add: classNames }, speed, easing, callback ) : this._addClass( classNames ); }, _removeClass: $.fn.removeClass, removeClass: function( classNames, speed, easing, callback ) { return speed ? $.effects.animateClass.call( this, { remove: classNames }, speed, easing, callback ) : this._removeClass( classNames ); }, _toggleClass: $.fn.toggleClass, toggleClass: function( classNames, force, speed, easing, callback ) { if ( typeof force === "boolean" || force === undefined ) { if ( !speed ) { // without speed parameter return this._toggleClass( classNames, force ); } else { return $.effects.animateClass.call( this, (force ? { add: classNames } : { remove: classNames }), speed, easing, callback ); } } else { // without force parameter return $.effects.animateClass.call( this, { toggle: classNames }, force, speed, easing ); } }, switchClass: function( remove, add, speed, easing, callback) { return $.effects.animateClass.call( this, { add: add, remove: remove }, speed, easing, callback ); } }); })(); /******************************************************************************/ /*********************************** EFFECTS **********************************/ /******************************************************************************/ (function() { $.extend( $.effects, { version: "1.9.2", // Saves a set of properties in a data storage save: function( element, set ) { for( var i=0; i < set.length; i++ ) { if ( set[ i ] !== null ) { element.data( dataSpace + set[ i ], element[ 0 ].style[ set[ i ] ] ); } } }, // Restores a set of previously saved properties from a data storage restore: function( element, set ) { var val, i; for( i=0; i < set.length; i++ ) { if ( set[ i ] !== null ) { val = element.data( dataSpace + set[ i ] ); // support: jQuery 1.6.2 // http://bugs.jquery.com/ticket/9917 // jQuery 1.6.2 incorrectly returns undefined for any falsy value. // We can't differentiate between "" and 0 here, so we just assume // empty string since it's likely to be a more common value... if ( val === undefined ) { val = ""; } element.css( set[ i ], val ); } } }, setMode: function( el, mode ) { if (mode === "toggle") { mode = el.is( ":hidden" ) ? "show" : "hide"; } return mode; }, // Translates a [top,left] array into a baseline value // this should be a little more flexible in the future to handle a string & hash getBaseline: function( origin, original ) { var y, x; switch ( origin[ 0 ] ) { case "top": y = 0; break; case "middle": y = 0.5; break; case "bottom": y = 1; break; default: y = origin[ 0 ] / original.height; } switch ( origin[ 1 ] ) { case "left": x = 0; break; case "center": x = 0.5; break; case "right": x = 1; break; default: x = origin[ 1 ] / original.width; } return { x: x, y: y }; }, // Wraps the element around a wrapper that copies position properties createWrapper: function( element ) { // if the element is already wrapped, return it if ( element.parent().is( ".ui-effects-wrapper" )) { return element.parent(); } // wrap the element var props = { width: element.outerWidth(true), height: element.outerHeight(true), "float": element.css( "float" ) }, wrapper = $( "<div></div>" ) .addClass( "ui-effects-wrapper" ) .css({ fontSize: "100%", background: "transparent", border: "none", margin: 0, padding: 0 }), // Store the size in case width/height are defined in % - Fixes #5245 size = { width: element.width(), height: element.height() }, active = document.activeElement; // support: Firefox // Firefox incorrectly exposes anonymous content // https://bugzilla.mozilla.org/show_bug.cgi?id=561664 try { active.id; } catch( e ) { active = document.body; } element.wrap( wrapper ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } wrapper = element.parent(); //Hotfix for jQuery 1.4 since some change in wrap() seems to actually lose the reference to the wrapped element // transfer positioning properties to the wrapper if ( element.css( "position" ) === "static" ) { wrapper.css({ position: "relative" }); element.css({ position: "relative" }); } else { $.extend( props, { position: element.css( "position" ), zIndex: element.css( "z-index" ) }); $.each([ "top", "left", "bottom", "right" ], function(i, pos) { props[ pos ] = element.css( pos ); if ( isNaN( parseInt( props[ pos ], 10 ) ) ) { props[ pos ] = "auto"; } }); element.css({ position: "relative", top: 0, left: 0, right: "auto", bottom: "auto" }); } element.css(size); return wrapper.css( props ).show(); }, removeWrapper: function( element ) { var active = document.activeElement; if ( element.parent().is( ".ui-effects-wrapper" ) ) { element.parent().replaceWith( element ); // Fixes #7595 - Elements lose focus when wrapped. if ( element[ 0 ] === active || $.contains( element[ 0 ], active ) ) { $( active ).focus(); } } return element; }, setTransition: function( element, list, factor, value ) { value = value || {}; $.each( list, function( i, x ) { var unit = element.cssUnit( x ); if ( unit[ 0 ] > 0 ) { value[ x ] = unit[ 0 ] * factor + unit[ 1 ]; } }); return value; } }); // return an effect options object for the given parameters: function _normalizeArguments( effect, options, speed, callback ) { // allow passing all options as the first parameter if ( $.isPlainObject( effect ) ) { options = effect; effect = effect.effect; } // convert to an object effect = { effect: effect }; // catch (effect, null, ...) if ( options == null ) { options = {}; } // catch (effect, callback) if ( $.isFunction( options ) ) { callback = options; speed = null; options = {}; } // catch (effect, speed, ?) if ( typeof options === "number" || $.fx.speeds[ options ] ) { callback = speed; speed = options; options = {}; } // catch (effect, options, callback) if ( $.isFunction( speed ) ) { callback = speed; speed = null; } // add options to effect if ( options ) { $.extend( effect, options ); } speed = speed || options.duration; effect.duration = $.fx.off ? 0 : typeof speed === "number" ? speed : speed in $.fx.speeds ? $.fx.speeds[ speed ] : $.fx.speeds._default; effect.complete = callback || options.complete; return effect; } function standardSpeed( speed ) { // valid standard speeds if ( !speed || typeof speed === "number" || $.fx.speeds[ speed ] ) { return true; } // invalid strings - treat as "normal" speed if ( typeof speed === "string" && !$.effects.effect[ speed ] ) { // TODO: remove in 2.0 (#7115) if ( backCompat && $.effects[ speed ] ) { return false; } return true; } return false; } $.fn.extend({ effect: function( /* effect, options, speed, callback */ ) { var args = _normalizeArguments.apply( this, arguments ), mode = args.mode, queue = args.queue, effectMethod = $.effects.effect[ args.effect ], // DEPRECATED: remove in 2.0 (#7115) oldEffectMethod = !effectMethod && backCompat && $.effects[ args.effect ]; if ( $.fx.off || !( effectMethod || oldEffectMethod ) ) { // delegate to the original method (e.g., .show()) if possible if ( mode ) { return this[ mode ]( args.duration, args.complete ); } else { return this.each( function() { if ( args.complete ) { args.complete.call( this ); } }); } } function run( next ) { var elem = $( this ), complete = args.complete, mode = args.mode; function done() { if ( $.isFunction( complete ) ) { complete.call( elem[0] ); } if ( $.isFunction( next ) ) { next(); } } // if the element is hiddden and mode is hide, // or element is visible and mode is show if ( elem.is( ":hidden" ) ? mode === "hide" : mode === "show" ) { done(); } else { effectMethod.call( elem[0], args, done ); } } // TODO: remove this check in 2.0, effectMethod will always be true if ( effectMethod ) { return queue === false ? this.each( run ) : this.queue( queue || "fx", run ); } else { // DEPRECATED: remove in 2.0 (#7115) return oldEffectMethod.call(this, { options: args, duration: args.duration, callback: args.complete, mode: args.mode }); } }, _show: $.fn.show, show: function( speed ) { if ( standardSpeed( speed ) ) { return this._show.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "show"; return this.effect.call( this, args ); } }, _hide: $.fn.hide, hide: function( speed ) { if ( standardSpeed( speed ) ) { return this._hide.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "hide"; return this.effect.call( this, args ); } }, // jQuery core overloads toggle and creates _toggle __toggle: $.fn.toggle, toggle: function( speed ) { if ( standardSpeed( speed ) || typeof speed === "boolean" || $.isFunction( speed ) ) { return this.__toggle.apply( this, arguments ); } else { var args = _normalizeArguments.apply( this, arguments ); args.mode = "toggle"; return this.effect.call( this, args ); } }, // helper functions cssUnit: function(key) { var style = this.css( key ), val = []; $.each( [ "em", "px", "%", "pt" ], function( i, unit ) { if ( style.indexOf( unit ) > 0 ) { val = [ parseFloat( style ), unit ]; } }); return val; } }); })(); /******************************************************************************/ /*********************************** EASING ***********************************/ /******************************************************************************/ (function() { // based on easing equations from Robert Penner (http://www.robertpenner.com/easing) var baseEasings = {}; $.each( [ "Quad", "Cubic", "Quart", "Quint", "Expo" ], function( i, name ) { baseEasings[ name ] = function( p ) { return Math.pow( p, i + 2 ); }; }); $.extend( baseEasings, { Sine: function ( p ) { return 1 - Math.cos( p * Math.PI / 2 ); }, Circ: function ( p ) { return 1 - Math.sqrt( 1 - p * p ); }, Elastic: function( p ) { return p === 0 || p === 1 ? p : -Math.pow( 2, 8 * (p - 1) ) * Math.sin( ( (p - 1) * 80 - 7.5 ) * Math.PI / 15 ); }, Back: function( p ) { return p * p * ( 3 * p - 2 ); }, Bounce: function ( p ) { var pow2, bounce = 4; while ( p < ( ( pow2 = Math.pow( 2, --bounce ) ) - 1 ) / 11 ) {} return 1 / Math.pow( 4, 3 - bounce ) - 7.5625 * Math.pow( ( pow2 * 3 - 2 ) / 22 - p, 2 ); } }); $.each( baseEasings, function( name, easeIn ) { $.easing[ "easeIn" + name ] = easeIn; $.easing[ "easeOut" + name ] = function( p ) { return 1 - easeIn( 1 - p ); }; $.easing[ "easeInOut" + name ] = function( p ) { return p < 0.5 ? easeIn( p * 2 ) / 2 : 1 - easeIn( p * -2 + 2 ) / 2; }; }); })(); })(jQuery)); (function( $, undefined ) { var rvertical = /up|down|vertical/, rpositivemotion = /up|left|vertical|horizontal/; $.effects.effect.blind = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), direction = o.direction || "up", vertical = rvertical.test( direction ), ref = vertical ? "height" : "width", ref2 = vertical ? "top" : "left", motion = rpositivemotion.test( direction ), animation = {}, show = mode === "show", wrapper, distance, margin; // if already wrapped, the wrapper's properties are my property. #6245 if ( el.parent().is( ".ui-effects-wrapper" ) ) { $.effects.save( el.parent(), props ); } else { $.effects.save( el, props ); } el.show(); wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); distance = wrapper[ ref ](); margin = parseFloat( wrapper.css( ref2 ) ) || 0; animation[ ref ] = show ? distance : 0; if ( !motion ) { el .css( vertical ? "bottom" : "right", 0 ) .css( vertical ? "top" : "left", "auto" ) .css({ position: "absolute" }); animation[ ref2 ] = show ? margin : distance + margin; } // start at 0 if we are showing if ( show ) { wrapper.css( ref, 0 ); if ( ! motion ) { wrapper.css( ref2, margin + distance ); } } // Animate wrapper.animate( animation, { duration: o.duration, easing: o.easing, queue: false, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.bounce = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], // defaults: mode = $.effects.setMode( el, o.mode || "effect" ), hide = mode === "hide", show = mode === "show", direction = o.direction || "up", distance = o.distance, times = o.times || 5, // number of internal animations anims = times * 2 + ( show || hide ? 1 : 0 ), speed = o.duration / anims, easing = o.easing, // utility: ref = ( direction === "up" || direction === "down" ) ? "top" : "left", motion = ( direction === "up" || direction === "left" ), i, upAnim, downAnim, // we will need to re-assemble the queue to stack our animations in place queue = el.queue(), queuelen = queue.length; // Avoid touching opacity to prevent clearType and PNG issues in IE if ( show || hide ) { props.push( "opacity" ); } $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); // Create Wrapper // default distance for the BIGGEST bounce is the outer Distance / 3 if ( !distance ) { distance = el[ ref === "top" ? "outerHeight" : "outerWidth" ]() / 3; } if ( show ) { downAnim = { opacity: 1 }; downAnim[ ref ] = 0; // if we are showing, force opacity 0 and set the initial position // then do the "first" animation el.css( "opacity", 0 ) .css( ref, motion ? -distance * 2 : distance * 2 ) .animate( downAnim, speed, easing ); } // start at the smallest distance if we are hiding if ( hide ) { distance = distance / Math.pow( 2, times - 1 ); } downAnim = {}; downAnim[ ref ] = 0; // Bounces up/down/left/right then back to 0 -- times * 2 animations happen here for ( i = 0; i < times; i++ ) { upAnim = {}; upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; el.animate( upAnim, speed, easing ) .animate( downAnim, speed, easing ); distance = hide ? distance * 2 : distance / 2; } // Last Bounce when Hiding if ( hide ) { upAnim = { opacity: 0 }; upAnim[ ref ] = ( motion ? "-=" : "+=" ) + distance; el.animate( upAnim, speed, easing ); } el.queue(function() { if ( hide ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); // inject all the animations we just queued to be first in line (after "inprogress") if ( queuelen > 1) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } el.dequeue(); }; })(jQuery); (function( $, undefined ) { $.effects.effect.clip = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", direction = o.direction || "vertical", vert = direction === "vertical", size = vert ? "height" : "width", position = vert ? "top" : "left", animation = {}, wrapper, animate, distance; // Save & Show $.effects.save( el, props ); el.show(); // Create Wrapper wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); animate = ( el[0].tagName === "IMG" ) ? wrapper : el; distance = animate[ size ](); // Shift if ( show ) { animate.css( size, 0 ); animate.css( position, distance / 2 ); } // Create Animation Object: animation[ size ] = show ? distance : 0; animation[ position ] = show ? 0 : distance / 2; // Animate animate.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( !show ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.drop = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "opacity", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", direction = o.direction || "left", ref = ( direction === "up" || direction === "down" ) ? "top" : "left", motion = ( direction === "up" || direction === "left" ) ? "pos" : "neg", animation = { opacity: show ? 1 : 0 }, distance; // Adjust $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); distance = o.distance || el[ ref === "top" ? "outerHeight": "outerWidth" ]( true ) / 2; if ( show ) { el .css( "opacity", 0 ) .css( ref, motion === "pos" ? -distance : distance ); } // Animation animation[ ref ] = ( show ? ( motion === "pos" ? "+=" : "-=" ) : ( motion === "pos" ? "-=" : "+=" ) ) + distance; // Animate el.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.explode = function( o, done ) { var rows = o.pieces ? Math.round( Math.sqrt( o.pieces ) ) : 3, cells = rows, el = $( this ), mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", // show and then visibility:hidden the element before calculating offset offset = el.show().css( "visibility", "hidden" ).offset(), // width and height of a piece width = Math.ceil( el.outerWidth() / cells ), height = Math.ceil( el.outerHeight() / rows ), pieces = [], // loop i, j, left, top, mx, my; // children animate complete: function childComplete() { pieces.push( this ); if ( pieces.length === rows * cells ) { animComplete(); } } // clone the element for each row and cell. for( i = 0; i < rows ; i++ ) { // ===> top = offset.top + i * height; my = i - ( rows - 1 ) / 2 ; for( j = 0; j < cells ; j++ ) { // ||| left = offset.left + j * width; mx = j - ( cells - 1 ) / 2 ; // Create a clone of the now hidden main element that will be absolute positioned // within a wrapper div off the -left and -top equal to size of our pieces el .clone() .appendTo( "body" ) .wrap( "<div></div>" ) .css({ position: "absolute", visibility: "visible", left: -j * width, top: -i * height }) // select the wrapper - make it overflow: hidden and absolute positioned based on // where the original was located +left and +top equal to the size of pieces .parent() .addClass( "ui-effects-explode" ) .css({ position: "absolute", overflow: "hidden", width: width, height: height, left: left + ( show ? mx * width : 0 ), top: top + ( show ? my * height : 0 ), opacity: show ? 0 : 1 }).animate({ left: left + ( show ? 0 : mx * width ), top: top + ( show ? 0 : my * height ), opacity: show ? 1 : 0 }, o.duration || 500, o.easing, childComplete ); } } function animComplete() { el.css({ visibility: "visible" }); $( pieces ).remove(); if ( !show ) { el.hide(); } done(); } }; })(jQuery); (function( $, undefined ) { $.effects.effect.fade = function( o, done ) { var el = $( this ), mode = $.effects.setMode( el, o.mode || "toggle" ); el.animate({ opacity: mode }, { queue: false, duration: o.duration, easing: o.easing, complete: done }); }; })( jQuery ); (function( $, undefined ) { $.effects.effect.fold = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "hide" ), show = mode === "show", hide = mode === "hide", size = o.size || 15, percent = /([0-9]+)%/.exec( size ), horizFirst = !!o.horizFirst, widthFirst = show !== horizFirst, ref = widthFirst ? [ "width", "height" ] : [ "height", "width" ], duration = o.duration / 2, wrapper, distance, animation1 = {}, animation2 = {}; $.effects.save( el, props ); el.show(); // Create Wrapper wrapper = $.effects.createWrapper( el ).css({ overflow: "hidden" }); distance = widthFirst ? [ wrapper.width(), wrapper.height() ] : [ wrapper.height(), wrapper.width() ]; if ( percent ) { size = parseInt( percent[ 1 ], 10 ) / 100 * distance[ hide ? 0 : 1 ]; } if ( show ) { wrapper.css( horizFirst ? { height: 0, width: size } : { height: size, width: 0 }); } // Animation animation1[ ref[ 0 ] ] = show ? distance[ 0 ] : size; animation2[ ref[ 1 ] ] = show ? distance[ 1 ] : 0; // Animate wrapper .animate( animation1, duration, o.easing ) .animate( animation2, duration, o.easing, function() { if ( hide ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.highlight = function( o, done ) { var elem = $( this ), props = [ "backgroundImage", "backgroundColor", "opacity" ], mode = $.effects.setMode( elem, o.mode || "show" ), animation = { backgroundColor: elem.css( "backgroundColor" ) }; if (mode === "hide") { animation.opacity = 0; } $.effects.save( elem, props ); elem .show() .css({ backgroundImage: "none", backgroundColor: o.color || "#ffff99" }) .animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { elem.hide(); } $.effects.restore( elem, props ); done(); } }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.pulsate = function( o, done ) { var elem = $( this ), mode = $.effects.setMode( elem, o.mode || "show" ), show = mode === "show", hide = mode === "hide", showhide = ( show || mode === "hide" ), // showing or hiding leaves of the "last" animation anims = ( ( o.times || 5 ) * 2 ) + ( showhide ? 1 : 0 ), duration = o.duration / anims, animateTo = 0, queue = elem.queue(), queuelen = queue.length, i; if ( show || !elem.is(":visible")) { elem.css( "opacity", 0 ).show(); animateTo = 1; } // anims - 1 opacity "toggles" for ( i = 1; i < anims; i++ ) { elem.animate({ opacity: animateTo }, duration, o.easing ); animateTo = 1 - animateTo; } elem.animate({ opacity: animateTo }, duration, o.easing); elem.queue(function() { if ( hide ) { elem.hide(); } done(); }); // We just queued up "anims" animations, we need to put them next in the queue if ( queuelen > 1 ) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } elem.dequeue(); }; })(jQuery); (function( $, undefined ) { $.effects.effect.puff = function( o, done ) { var elem = $( this ), mode = $.effects.setMode( elem, o.mode || "hide" ), hide = mode === "hide", percent = parseInt( o.percent, 10 ) || 150, factor = percent / 100, original = { height: elem.height(), width: elem.width(), outerHeight: elem.outerHeight(), outerWidth: elem.outerWidth() }; $.extend( o, { effect: "scale", queue: false, fade: true, mode: mode, complete: done, percent: hide ? percent : 100, from: hide ? original : { height: original.height * factor, width: original.width * factor, outerHeight: original.outerHeight * factor, outerWidth: original.outerWidth * factor } }); elem.effect( o ); }; $.effects.effect.scale = function( o, done ) { // Create element var el = $( this ), options = $.extend( true, {}, o ), mode = $.effects.setMode( el, o.mode || "effect" ), percent = parseInt( o.percent, 10 ) || ( parseInt( o.percent, 10 ) === 0 ? 0 : ( mode === "hide" ? 0 : 100 ) ), direction = o.direction || "both", origin = o.origin, original = { height: el.height(), width: el.width(), outerHeight: el.outerHeight(), outerWidth: el.outerWidth() }, factor = { y: direction !== "horizontal" ? (percent / 100) : 1, x: direction !== "vertical" ? (percent / 100) : 1 }; // We are going to pass this effect to the size effect: options.effect = "size"; options.queue = false; options.complete = done; // Set default origin and restore for show/hide if ( mode !== "effect" ) { options.origin = origin || ["middle","center"]; options.restore = true; } options.from = o.from || ( mode === "show" ? { height: 0, width: 0, outerHeight: 0, outerWidth: 0 } : original ); options.to = { height: original.height * factor.y, width: original.width * factor.x, outerHeight: original.outerHeight * factor.y, outerWidth: original.outerWidth * factor.x }; // Fade option to support puff if ( options.fade ) { if ( mode === "show" ) { options.from.opacity = 0; options.to.opacity = 1; } if ( mode === "hide" ) { options.from.opacity = 1; options.to.opacity = 0; } } // Animate el.effect( options ); }; $.effects.effect.size = function( o, done ) { // Create element var original, baseline, factor, el = $( this ), props0 = [ "position", "top", "bottom", "left", "right", "width", "height", "overflow", "opacity" ], // Always restore props1 = [ "position", "top", "bottom", "left", "right", "overflow", "opacity" ], // Copy for children props2 = [ "width", "height", "overflow" ], cProps = [ "fontSize" ], vProps = [ "borderTopWidth", "borderBottomWidth", "paddingTop", "paddingBottom" ], hProps = [ "borderLeftWidth", "borderRightWidth", "paddingLeft", "paddingRight" ], // Set options mode = $.effects.setMode( el, o.mode || "effect" ), restore = o.restore || mode !== "effect", scale = o.scale || "both", origin = o.origin || [ "middle", "center" ], position = el.css( "position" ), props = restore ? props0 : props1, zero = { height: 0, width: 0, outerHeight: 0, outerWidth: 0 }; if ( mode === "show" ) { el.show(); } original = { height: el.height(), width: el.width(), outerHeight: el.outerHeight(), outerWidth: el.outerWidth() }; if ( o.mode === "toggle" && mode === "show" ) { el.from = o.to || zero; el.to = o.from || original; } else { el.from = o.from || ( mode === "show" ? zero : original ); el.to = o.to || ( mode === "hide" ? zero : original ); } // Set scaling factor factor = { from: { y: el.from.height / original.height, x: el.from.width / original.width }, to: { y: el.to.height / original.height, x: el.to.width / original.width } }; // Scale the css box if ( scale === "box" || scale === "both" ) { // Vertical props scaling if ( factor.from.y !== factor.to.y ) { props = props.concat( vProps ); el.from = $.effects.setTransition( el, vProps, factor.from.y, el.from ); el.to = $.effects.setTransition( el, vProps, factor.to.y, el.to ); } // Horizontal props scaling if ( factor.from.x !== factor.to.x ) { props = props.concat( hProps ); el.from = $.effects.setTransition( el, hProps, factor.from.x, el.from ); el.to = $.effects.setTransition( el, hProps, factor.to.x, el.to ); } } // Scale the content if ( scale === "content" || scale === "both" ) { // Vertical props scaling if ( factor.from.y !== factor.to.y ) { props = props.concat( cProps ).concat( props2 ); el.from = $.effects.setTransition( el, cProps, factor.from.y, el.from ); el.to = $.effects.setTransition( el, cProps, factor.to.y, el.to ); } } $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); el.css( "overflow", "hidden" ).css( el.from ); // Adjust if (origin) { // Calculate baseline shifts baseline = $.effects.getBaseline( origin, original ); el.from.top = ( original.outerHeight - el.outerHeight() ) * baseline.y; el.from.left = ( original.outerWidth - el.outerWidth() ) * baseline.x; el.to.top = ( original.outerHeight - el.to.outerHeight ) * baseline.y; el.to.left = ( original.outerWidth - el.to.outerWidth ) * baseline.x; } el.css( el.from ); // set top & left // Animate if ( scale === "content" || scale === "both" ) { // Scale the children // Add margins/font-size vProps = vProps.concat([ "marginTop", "marginBottom" ]).concat(cProps); hProps = hProps.concat([ "marginLeft", "marginRight" ]); props2 = props0.concat(vProps).concat(hProps); el.find( "*[width]" ).each( function(){ var child = $( this ), c_original = { height: child.height(), width: child.width(), outerHeight: child.outerHeight(), outerWidth: child.outerWidth() }; if (restore) { $.effects.save(child, props2); } child.from = { height: c_original.height * factor.from.y, width: c_original.width * factor.from.x, outerHeight: c_original.outerHeight * factor.from.y, outerWidth: c_original.outerWidth * factor.from.x }; child.to = { height: c_original.height * factor.to.y, width: c_original.width * factor.to.x, outerHeight: c_original.height * factor.to.y, outerWidth: c_original.width * factor.to.x }; // Vertical props scaling if ( factor.from.y !== factor.to.y ) { child.from = $.effects.setTransition( child, vProps, factor.from.y, child.from ); child.to = $.effects.setTransition( child, vProps, factor.to.y, child.to ); } // Horizontal props scaling if ( factor.from.x !== factor.to.x ) { child.from = $.effects.setTransition( child, hProps, factor.from.x, child.from ); child.to = $.effects.setTransition( child, hProps, factor.to.x, child.to ); } // Animate children child.css( child.from ); child.animate( child.to, o.duration, o.easing, function() { // Restore children if ( restore ) { $.effects.restore( child, props2 ); } }); }); } // Animate el.animate( el.to, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( el.to.opacity === 0 ) { el.css( "opacity", el.from.opacity ); } if( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); if ( !restore ) { // we need to calculate our new positioning based on the scaling if ( position === "static" ) { el.css({ position: "relative", top: el.to.top, left: el.to.left }); } else { $.each([ "top", "left" ], function( idx, pos ) { el.css( pos, function( _, str ) { var val = parseInt( str, 10 ), toRef = idx ? el.to.left : el.to.top; // if original was "auto", recalculate the new value from wrapper if ( str === "auto" ) { return toRef + "px"; } return val + toRef + "px"; }); }); } } $.effects.removeWrapper( el ); done(); } }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.shake = function( o, done ) { var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "height", "width" ], mode = $.effects.setMode( el, o.mode || "effect" ), direction = o.direction || "left", distance = o.distance || 20, times = o.times || 3, anims = times * 2 + 1, speed = Math.round(o.duration/anims), ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), animation = {}, animation1 = {}, animation2 = {}, i, // we will need to re-assemble the queue to stack our animations in place queue = el.queue(), queuelen = queue.length; $.effects.save( el, props ); el.show(); $.effects.createWrapper( el ); // Animation animation[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance; animation1[ ref ] = ( positiveMotion ? "+=" : "-=" ) + distance * 2; animation2[ ref ] = ( positiveMotion ? "-=" : "+=" ) + distance * 2; // Animate el.animate( animation, speed, o.easing ); // Shakes for ( i = 1; i < times; i++ ) { el.animate( animation1, speed, o.easing ).animate( animation2, speed, o.easing ); } el .animate( animation1, speed, o.easing ) .animate( animation, speed / 2, o.easing ) .queue(function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); }); // inject all the animations we just queued to be first in line (after "inprogress") if ( queuelen > 1) { queue.splice.apply( queue, [ 1, 0 ].concat( queue.splice( queuelen, anims + 1 ) ) ); } el.dequeue(); }; })(jQuery); (function( $, undefined ) { $.effects.effect.slide = function( o, done ) { // Create element var el = $( this ), props = [ "position", "top", "bottom", "left", "right", "width", "height" ], mode = $.effects.setMode( el, o.mode || "show" ), show = mode === "show", direction = o.direction || "left", ref = (direction === "up" || direction === "down") ? "top" : "left", positiveMotion = (direction === "up" || direction === "left"), distance, animation = {}; // Adjust $.effects.save( el, props ); el.show(); distance = o.distance || el[ ref === "top" ? "outerHeight" : "outerWidth" ]( true ); $.effects.createWrapper( el ).css({ overflow: "hidden" }); if ( show ) { el.css( ref, positiveMotion ? (isNaN(distance) ? "-" + distance : -distance) : distance ); } // Animation animation[ ref ] = ( show ? ( positiveMotion ? "+=" : "-=") : ( positiveMotion ? "-=" : "+=")) + distance; // Animate el.animate( animation, { queue: false, duration: o.duration, easing: o.easing, complete: function() { if ( mode === "hide" ) { el.hide(); } $.effects.restore( el, props ); $.effects.removeWrapper( el ); done(); } }); }; })(jQuery); (function( $, undefined ) { $.effects.effect.transfer = function( o, done ) { var elem = $( this ), target = $( o.to ), targetFixed = target.css( "position" ) === "fixed", body = $("body"), fixTop = targetFixed ? body.scrollTop() : 0, fixLeft = targetFixed ? body.scrollLeft() : 0, endPosition = target.offset(), animation = { top: endPosition.top - fixTop , left: endPosition.left - fixLeft , height: target.innerHeight(), width: target.innerWidth() }, startPosition = elem.offset(), transfer = $( '<div class="ui-effects-transfer"></div>' ) .appendTo( document.body ) .addClass( o.className ) .css({ top: startPosition.top - fixTop , left: startPosition.left - fixLeft , height: elem.innerHeight(), width: elem.innerWidth(), position: targetFixed ? "fixed" : "absolute" }) .animate( animation, o.duration, o.easing, function() { transfer.remove(); done(); }); }; })(jQuery); (function( $, undefined ) { var mouseHandled = false; $.widget( "ui.menu", { version: "1.9.2", defaultElement: "<ul>", delay: 300, options: { icons: { submenu: "ui-icon-carat-1-e" }, menus: "ul", position: { my: "left top", at: "right top" }, role: "menu", // callbacks blur: null, focus: null, select: null }, _create: function() { this.activeMenu = this.element; this.element .uniqueId() .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" ) .toggleClass( "ui-menu-icons", !!this.element.find( ".ui-icon" ).length ) .attr({ role: this.options.role, tabIndex: 0 }) // need to catch all clicks on disabled menu // not possible through _on .bind( "click" + this.eventNamespace, $.proxy(function( event ) { if ( this.options.disabled ) { event.preventDefault(); } }, this )); if ( this.options.disabled ) { this.element .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } this._on({ // Prevent focus from sticking to links inside menu after clicking // them (focus should always stay on UL during navigation). "mousedown .ui-menu-item > a": function( event ) { event.preventDefault(); }, "click .ui-state-disabled > a": function( event ) { event.preventDefault(); }, "click .ui-menu-item:has(a)": function( event ) { var target = $( event.target ).closest( ".ui-menu-item" ); if ( !mouseHandled && target.not( ".ui-state-disabled" ).length ) { mouseHandled = true; this.select( event ); // Open submenu on click if ( target.has( ".ui-menu" ).length ) { this.expand( event ); } else if ( !this.element.is( ":focus" ) ) { // Redirect focus to the menu this.element.trigger( "focus", [ true ] ); // If the active item is on the top level, let it stay active. // Otherwise, blur the active item since it is no longer visible. if ( this.active && this.active.parents( ".ui-menu" ).length === 1 ) { clearTimeout( this.timer ); } } } }, "mouseenter .ui-menu-item": function( event ) { var target = $( event.currentTarget ); // Remove ui-state-active class from siblings of the newly focused menu item // to avoid a jump caused by adjacent elements both having a class with a border target.siblings().children( ".ui-state-active" ).removeClass( "ui-state-active" ); this.focus( event, target ); }, mouseleave: "collapseAll", "mouseleave .ui-menu": "collapseAll", focus: function( event, keepActiveItem ) { // If there's already an active item, keep it active // If not, activate the first item var item = this.active || this.element.children( ".ui-menu-item" ).eq( 0 ); if ( !keepActiveItem ) { this.focus( event, item ); } }, blur: function( event ) { this._delay(function() { if ( !$.contains( this.element[0], this.document[0].activeElement ) ) { this.collapseAll( event ); } }); }, keydown: "_keydown" }); this.refresh(); // Clicks outside of a menu collapse any open menus this._on( this.document, { click: function( event ) { if ( !$( event.target ).closest( ".ui-menu" ).length ) { this.collapseAll( event ); } // Reset the mouseHandled flag mouseHandled = false; } }); }, _destroy: function() { // Destroy (sub)menus this.element .removeAttr( "aria-activedescendant" ) .find( ".ui-menu" ).andSelf() .removeClass( "ui-menu ui-widget ui-widget-content ui-corner-all ui-menu-icons" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-expanded" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-disabled" ) .removeUniqueId() .show(); // Destroy menu items this.element.find( ".ui-menu-item" ) .removeClass( "ui-menu-item" ) .removeAttr( "role" ) .removeAttr( "aria-disabled" ) .children( "a" ) .removeUniqueId() .removeClass( "ui-corner-all ui-state-hover" ) .removeAttr( "tabIndex" ) .removeAttr( "role" ) .removeAttr( "aria-haspopup" ) .children().each( function() { var elem = $( this ); if ( elem.data( "ui-menu-submenu-carat" ) ) { elem.remove(); } }); // Destroy menu dividers this.element.find( ".ui-menu-divider" ).removeClass( "ui-menu-divider ui-widget-content" ); }, _keydown: function( event ) { var match, prev, character, skip, regex, preventDefault = true; function escape( value ) { return value.replace( /[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&" ); } switch ( event.keyCode ) { case $.ui.keyCode.PAGE_UP: this.previousPage( event ); break; case $.ui.keyCode.PAGE_DOWN: this.nextPage( event ); break; case $.ui.keyCode.HOME: this._move( "first", "first", event ); break; case $.ui.keyCode.END: this._move( "last", "last", event ); break; case $.ui.keyCode.UP: this.previous( event ); break; case $.ui.keyCode.DOWN: this.next( event ); break; case $.ui.keyCode.LEFT: this.collapse( event ); break; case $.ui.keyCode.RIGHT: if ( this.active && !this.active.is( ".ui-state-disabled" ) ) { this.expand( event ); } break; case $.ui.keyCode.ENTER: case $.ui.keyCode.SPACE: this._activate( event ); break; case $.ui.keyCode.ESCAPE: this.collapse( event ); break; default: preventDefault = false; prev = this.previousFilter || ""; character = String.fromCharCode( event.keyCode ); skip = false; clearTimeout( this.filterTimer ); if ( character === prev ) { skip = true; } else { character = prev + character; } regex = new RegExp( "^" + escape( character ), "i" ); match = this.activeMenu.children( ".ui-menu-item" ).filter(function() { return regex.test( $( this ).children( "a" ).text() ); }); match = skip && match.index( this.active.next() ) !== -1 ? this.active.nextAll( ".ui-menu-item" ) : match; // If no matches on the current filter, reset to the last character pressed // to move down the menu to the first item that starts with that character if ( !match.length ) { character = String.fromCharCode( event.keyCode ); regex = new RegExp( "^" + escape( character ), "i" ); match = this.activeMenu.children( ".ui-menu-item" ).filter(function() { return regex.test( $( this ).children( "a" ).text() ); }); } if ( match.length ) { this.focus( event, match ); if ( match.length > 1 ) { this.previousFilter = character; this.filterTimer = this._delay(function() { delete this.previousFilter; }, 1000 ); } else { delete this.previousFilter; } } else { delete this.previousFilter; } } if ( preventDefault ) { event.preventDefault(); } }, _activate: function( event ) { if ( !this.active.is( ".ui-state-disabled" ) ) { if ( this.active.children( "a[aria-haspopup='true']" ).length ) { this.expand( event ); } else { this.select( event ); } } }, refresh: function() { var menus, icon = this.options.icons.submenu, submenus = this.element.find( this.options.menus ); // Initialize nested menus submenus.filter( ":not(.ui-menu)" ) .addClass( "ui-menu ui-widget ui-widget-content ui-corner-all" ) .hide() .attr({ role: this.options.role, "aria-hidden": "true", "aria-expanded": "false" }) .each(function() { var menu = $( this ), item = menu.prev( "a" ), submenuCarat = $( "<span>" ) .addClass( "ui-menu-icon ui-icon " + icon ) .data( "ui-menu-submenu-carat", true ); item .attr( "aria-haspopup", "true" ) .prepend( submenuCarat ); menu.attr( "aria-labelledby", item.attr( "id" ) ); }); menus = submenus.add( this.element ); // Don't refresh list items that are already adapted menus.children( ":not(.ui-menu-item):has(a)" ) .addClass( "ui-menu-item" ) .attr( "role", "presentation" ) .children( "a" ) .uniqueId() .addClass( "ui-corner-all" ) .attr({ tabIndex: -1, role: this._itemRole() }); // Initialize unlinked menu-items containing spaces and/or dashes only as dividers menus.children( ":not(.ui-menu-item)" ).each(function() { var item = $( this ); // hyphen, em dash, en dash if ( !/[^\-—–\s]/.test( item.text() ) ) { item.addClass( "ui-widget-content ui-menu-divider" ); } }); // Add aria-disabled attribute to any disabled menu item menus.children( ".ui-state-disabled" ).attr( "aria-disabled", "true" ); // If the active item has been removed, blur the menu if ( this.active && !$.contains( this.element[ 0 ], this.active[ 0 ] ) ) { this.blur(); } }, _itemRole: function() { return { menu: "menuitem", listbox: "option" }[ this.options.role ]; }, focus: function( event, item ) { var nested, focused; this.blur( event, event && event.type === "focus" ); this._scrollIntoView( item ); this.active = item.first(); focused = this.active.children( "a" ).addClass( "ui-state-focus" ); // Only update aria-activedescendant if there's a role // otherwise we assume focus is managed elsewhere if ( this.options.role ) { this.element.attr( "aria-activedescendant", focused.attr( "id" ) ); } // Highlight active parent menu item, if any this.active .parent() .closest( ".ui-menu-item" ) .children( "a:first" ) .addClass( "ui-state-active" ); if ( event && event.type === "keydown" ) { this._close(); } else { this.timer = this._delay(function() { this._close(); }, this.delay ); } nested = item.children( ".ui-menu" ); if ( nested.length && ( /^mouse/.test( event.type ) ) ) { this._startOpening(nested); } this.activeMenu = item.parent(); this._trigger( "focus", event, { item: item } ); }, _scrollIntoView: function( item ) { var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight; if ( this._hasScroll() ) { borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0; paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0; offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop; scroll = this.activeMenu.scrollTop(); elementHeight = this.activeMenu.height(); itemHeight = item.height(); if ( offset < 0 ) { this.activeMenu.scrollTop( scroll + offset ); } else if ( offset + itemHeight > elementHeight ) { this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight ); } } }, blur: function( event, fromFocus ) { if ( !fromFocus ) { clearTimeout( this.timer ); } if ( !this.active ) { return; } this.active.children( "a" ).removeClass( "ui-state-focus" ); this.active = null; this._trigger( "blur", event, { item: this.active } ); }, _startOpening: function( submenu ) { clearTimeout( this.timer ); // Don't open if already open fixes a Firefox bug that caused a .5 pixel // shift in the submenu position when mousing over the carat icon if ( submenu.attr( "aria-hidden" ) !== "true" ) { return; } this.timer = this._delay(function() { this._close(); this._open( submenu ); }, this.delay ); }, _open: function( submenu ) { var position = $.extend({ of: this.active }, this.options.position ); clearTimeout( this.timer ); this.element.find( ".ui-menu" ).not( submenu.parents( ".ui-menu" ) ) .hide() .attr( "aria-hidden", "true" ); submenu .show() .removeAttr( "aria-hidden" ) .attr( "aria-expanded", "true" ) .position( position ); }, collapseAll: function( event, all ) { clearTimeout( this.timer ); this.timer = this._delay(function() { // If we were passed an event, look for the submenu that contains the event var currentMenu = all ? this.element : $( event && event.target ).closest( this.element.find( ".ui-menu" ) ); // If we found no valid submenu ancestor, use the main menu to close all sub menus anyway if ( !currentMenu.length ) { currentMenu = this.element; } this._close( currentMenu ); this.blur( event ); this.activeMenu = currentMenu; }, this.delay ); }, // With no arguments, closes the currently active menu - if nothing is active // it closes all menus. If passed an argument, it will search for menus BELOW _close: function( startMenu ) { if ( !startMenu ) { startMenu = this.active ? this.active.parent() : this.element; } startMenu .find( ".ui-menu" ) .hide() .attr( "aria-hidden", "true" ) .attr( "aria-expanded", "false" ) .end() .find( "a.ui-state-active" ) .removeClass( "ui-state-active" ); }, collapse: function( event ) { var newItem = this.active && this.active.parent().closest( ".ui-menu-item", this.element ); if ( newItem && newItem.length ) { this._close(); this.focus( event, newItem ); } }, expand: function( event ) { var newItem = this.active && this.active .children( ".ui-menu " ) .children( ".ui-menu-item" ) .first(); if ( newItem && newItem.length ) { this._open( newItem.parent() ); // Delay so Firefox will not hide activedescendant change in expanding submenu from AT this._delay(function() { this.focus( event, newItem ); }); } }, next: function( event ) { this._move( "next", "first", event ); }, previous: function( event ) { this._move( "prev", "last", event ); }, isFirstItem: function() { return this.active && !this.active.prevAll( ".ui-menu-item" ).length; }, isLastItem: function() { return this.active && !this.active.nextAll( ".ui-menu-item" ).length; }, _move: function( direction, filter, event ) { var next; if ( this.active ) { if ( direction === "first" || direction === "last" ) { next = this.active [ direction === "first" ? "prevAll" : "nextAll" ]( ".ui-menu-item" ) .eq( -1 ); } else { next = this.active [ direction + "All" ]( ".ui-menu-item" ) .eq( 0 ); } } if ( !next || !next.length || !this.active ) { next = this.activeMenu.children( ".ui-menu-item" )[ filter ](); } this.focus( event, next ); }, nextPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isLastItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.nextAll( ".ui-menu-item" ).each(function() { item = $( this ); return item.offset().top - base - height < 0; }); this.focus( event, item ); } else { this.focus( event, this.activeMenu.children( ".ui-menu-item" ) [ !this.active ? "first" : "last" ]() ); } }, previousPage: function( event ) { var item, base, height; if ( !this.active ) { this.next( event ); return; } if ( this.isFirstItem() ) { return; } if ( this._hasScroll() ) { base = this.active.offset().top; height = this.element.height(); this.active.prevAll( ".ui-menu-item" ).each(function() { item = $( this ); return item.offset().top - base + height > 0; }); this.focus( event, item ); } else { this.focus( event, this.activeMenu.children( ".ui-menu-item" ).first() ); } }, _hasScroll: function() { return this.element.outerHeight() < this.element.prop( "scrollHeight" ); }, select: function( event ) { // TODO: It should never be possible to not have an active item at this // point, but the tests don't trigger mouseenter before click. this.active = this.active || $( event.target ).closest( ".ui-menu-item" ); var ui = { item: this.active }; if ( !this.active.has( ".ui-menu" ).length ) { this.collapseAll( event, true ); } this._trigger( "select", event, ui ); } }); }( jQuery )); (function( $, undefined ) { $.widget( "ui.progressbar", { version: "1.9.2", 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 = $( "<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(); }, value: function( newValue ) { if ( newValue === undefined ) { return this._value(); } this._setOption( "value", newValue ); return this; }, _setOption: function( key, value ) { if ( key === "value" ) { this.options.value = value; this._refreshValue(); if ( this._value() === this.options.max ) { this._trigger( "complete" ); } } this._super( key, value ); }, _value: function() { var val = this.options.value; // normalize invalid value if ( typeof val !== "number" ) { val = 0; } return Math.min( this.options.max, Math.max( this.min, val ) ); }, _percentage: function() { return 100 * this._value() / this.options.max; }, _refreshValue: function() { var value = this.value(), percentage = this._percentage(); if ( this.oldValue !== value ) { this.oldValue = value; this._trigger( "change" ); } this.valueDiv .toggle( value > this.min ) .toggleClass( "ui-corner-right", value === this.options.max ) .width( percentage.toFixed(0) + "%" ); this.element.attr( "aria-valuenow", value ); } }); })( jQuery ); (function( $, undefined ) { $.widget("ui.resizable", $.ui.mouse, { version: "1.9.2", 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 that = this, o = this.options; this.element.addClass("ui-resizable"); $.extend(this, { _aspectRatio: !!(o.aspectRatio), aspectRatio: o.aspectRatio, originalElement: this.element, _proportionallyResizeElements: [], _helper: o.helper || o.ghost || o.animate ? o.helper || 'ui-resizable-helper' : null }); //Wrap the element if it cannot hold child nodes if(this.element[0].nodeName.match(/canvas|textarea|input|select|button|img/i)) { //Create a wrapper element and set the wrapper to the new current internal element this.element.wrap( $('<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') }) ); //Overwrite the original this.element this.element = this.element.parent().data( "resizable", this.element.data('resizable') ); this.elementIsWrapper = true; //Move margins to the wrapper 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}); //Prevent Safari textarea resize this.originalResizeStyle = this.originalElement.css('resize'); this.originalElement.css('resize', 'none'); //Push the actual element to our proportionallyResize internal array this._proportionallyResizeElements.push(this.originalElement.css({ position: 'static', zoom: 1, display: 'block' })); // avoid IE jump (hard set the margin) this.originalElement.css({ margin: this.originalElement.css('margin') }); // fix handlers offset this._proportionallyResize(); } this.handles = o.handles || (!$('.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 n = this.handles.split(","); this.handles = {}; for(var i = 0; i < n.length; i++) { var handle = $.trim(n[i]), hname = 'ui-resizable-'+handle; var axis = $('<div class="ui-resizable-handle ' + hname + '"></div>'); // Apply zIndex to all handles - see #7960 axis.css({ zIndex: o.zIndex }); //TODO : What's going on here? if ('se' == handle) { axis.addClass('ui-icon ui-icon-gripsmall-diagonal-se'); }; //Insert into internal handles object and append to element this.handles[handle] = '.ui-resizable-'+handle; this.element.append(axis); } } this._renderAxis = function(target) { target = target || this.element; for(var i in this.handles) { if(this.handles[i].constructor == String) this.handles[i] = $(this.handles[i], this.element).show(); //Apply pad to wrapper element, needed to fix axis position (textarea, inputs, scrolls) if (this.elementIsWrapper && this.originalElement[0].nodeName.match(/textarea|input|select|button/i)) { var axis = $(this.handles[i], this.element), padWrapper = 0; //Checking the correct pad and border padWrapper = /sw|ne|nw|se|n|s/.test(i) ? axis.outerHeight() : axis.outerWidth(); //The padding type i have to apply... var padPos = [ 'padding', /ne|nw|n/.test(i) ? 'Top' : /se|sw|s/.test(i) ? 'Bottom' : /^e$/.test(i) ? 'Right' : 'Left' ].join(""); target.css(padPos, padWrapper); this._proportionallyResize(); } //TODO: What's that good for? There's not anything to be executed left if(!$(this.handles[i]).length) continue; } }; //TODO: make renderAxis a prototype function this._renderAxis(this.element); this._handles = $('.ui-resizable-handle', this.element) .disableSelection(); //Matching axis name this._handles.mouseover(function() { if (!that.resizing) { if (this.className) var axis = this.className.match(/ui-resizable-(se|sw|ne|nw|n|e|s|w)/i); //Axis, default = se that.axis = axis && axis[1] ? axis[1] : 'se'; } }); //If we want to auto hide the elements if (o.autoHide) { this._handles.hide(); $(this.element) .addClass("ui-resizable-autohide") .mouseenter(function() { if (o.disabled) return; $(this).removeClass("ui-resizable-autohide"); that._handles.show(); }) .mouseleave(function(){ if (o.disabled) return; if (!that.resizing) { $(this).addClass("ui-resizable-autohide"); that._handles.hide(); } }); } //Initialize the mouse interaction this._mouseInit(); }, _destroy: function() { this._mouseDestroy(); var _destroy = function(exp) { $(exp).removeClass("ui-resizable ui-resizable-disabled ui-resizable-resizing") .removeData("resizable").removeData("ui-resizable").unbind(".resizable").find('.ui-resizable-handle').remove(); }; //TODO: Unwrap at same DOM position if (this.elementIsWrapper) { _destroy(this.element); var wrapper = this.element; this.originalElement.css({ position: wrapper.css('position'), width: wrapper.outerWidth(), height: wrapper.outerHeight(), top: wrapper.css('top'), left: wrapper.css('left') }).insertAfter( wrapper ); wrapper.remove(); } this.originalElement.css('resize', this.originalResizeStyle); _destroy(this.originalElement); return this; }, _mouseCapture: function(event) { var handle = false; for (var i in this.handles) { if ($(this.handles[i])[0] == event.target) { handle = true; } } return !this.options.disabled && handle; }, _mouseStart: function(event) { var o = this.options, iniPos = this.element.position(), el = this.element; this.resizing = true; this.documentScroll = { top: $(document).scrollTop(), left: $(document).scrollLeft() }; // bugfix for http://dev.jquery.com/ticket/1749 if (el.is('.ui-draggable') || (/absolute/).test(el.css('position'))) { el.css({ position: 'absolute', top: iniPos.top, left: iniPos.left }); } this._renderProxy(); var curleft = num(this.helper.css('left')), curtop = num(this.helper.css('top')); if (o.containment) { curleft += $(o.containment).scrollLeft() || 0; curtop += $(o.containment).scrollTop() || 0; } //Store needed variables this.offset = this.helper.offset(); this.position = { left: curleft, top: curtop }; this.size = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalSize = this._helper ? { width: el.outerWidth(), height: el.outerHeight() } : { width: el.width(), height: el.height() }; this.originalPosition = { left: curleft, top: curtop }; this.sizeDiff = { width: el.outerWidth() - el.width(), height: el.outerHeight() - el.height() }; this.originalMousePosition = { left: event.pageX, top: event.pageY }; //Aspect Ratio this.aspectRatio = (typeof o.aspectRatio == 'number') ? o.aspectRatio : ((this.originalSize.width / this.originalSize.height) || 1); var cursor = $('.ui-resizable-' + this.axis).css('cursor'); $('body').css('cursor', cursor == 'auto' ? this.axis + '-resize' : cursor); el.addClass("ui-resizable-resizing"); this._propagate("start", event); return true; }, _mouseDrag: function(event) { //Increase performance, avoid regex var el = this.helper, o = this.options, props = {}, that = this, smp = this.originalMousePosition, a = this.axis; var dx = (event.pageX-smp.left)||0, dy = (event.pageY-smp.top)||0; var trigger = this._change[a]; if (!trigger) return false; // Calculate the attrs that will be change var data = trigger.apply(this, [event, dx, dy]); // Put this in the mouseDrag handler since the user can start pressing shift while resizing this._updateVirtualBoundaries(event.shiftKey); if (this._aspectRatio || event.shiftKey) data = this._updateRatio(data, event); data = this._respectSize(data, event); // plugins callbacks need to be called first this._propagate("resize", event); el.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(data); // calling the user callback at the end this._trigger('resize', event, this.ui()); return false; }, _mouseStop: function(event) { this.resizing = false; var o = this.options, that = this; if(this._helper) { var pr = this._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : that.sizeDiff.height, soffsetw = ista ? 0 : that.sizeDiff.width; var s = { width: (that.helper.width() - soffsetw), height: (that.helper.height() - soffseth) }, left = (parseInt(that.element.css('left'), 10) + (that.position.left - that.originalPosition.left)) || null, top = (parseInt(that.element.css('top'), 10) + (that.position.top - that.originalPosition.top)) || null; if (!o.animate) this.element.css($.extend(s, { top: top, left: left })); that.helper.height(that.size.height); that.helper.width(that.size.width); if (this._helper && !o.animate) this._proportionallyResize(); } $('body').css('cursor', 'auto'); this.element.removeClass("ui-resizable-resizing"); this._propagate("stop", event); if (this._helper) this.helper.remove(); return false; }, _updateVirtualBoundaries: function(forceAspectRatio) { var o = this.options, pMinWidth, pMaxWidth, pMinHeight, pMaxHeight, b; b = { minWidth: isNumber(o.minWidth) ? o.minWidth : 0, maxWidth: isNumber(o.maxWidth) ? o.maxWidth : Infinity, minHeight: isNumber(o.minHeight) ? o.minHeight : 0, maxHeight: isNumber(o.maxHeight) ? o.maxHeight : Infinity }; if(this._aspectRatio || forceAspectRatio) { // We want to create an enclosing box whose aspect ration is the requested one // First, compute the "projected" size for each dimension based on the aspect ratio and other dimension pMinWidth = b.minHeight * this.aspectRatio; pMinHeight = b.minWidth / this.aspectRatio; pMaxWidth = b.maxHeight * this.aspectRatio; pMaxHeight = b.maxWidth / this.aspectRatio; if(pMinWidth > b.minWidth) b.minWidth = pMinWidth; if(pMinHeight > b.minHeight) b.minHeight = pMinHeight; if(pMaxWidth < b.maxWidth) b.maxWidth = pMaxWidth; if(pMaxHeight < b.maxHeight) b.maxHeight = pMaxHeight; } this._vBoundaries = b; }, _updateCache: function(data) { var o = this.options; this.offset = this.helper.offset(); if (isNumber(data.left)) this.position.left = data.left; if (isNumber(data.top)) this.position.top = data.top; if (isNumber(data.height)) this.size.height = data.height; if (isNumber(data.width)) this.size.width = data.width; }, _updateRatio: function(data, event) { var o = this.options, cpos = this.position, csize = this.size, a = this.axis; if (isNumber(data.height)) data.width = (data.height * this.aspectRatio); else if (isNumber(data.width)) data.height = (data.width / this.aspectRatio); if (a == 'sw') { data.left = cpos.left + (csize.width - data.width); data.top = null; } if (a == 'nw') { data.top = cpos.top + (csize.height - data.height); data.left = cpos.left + (csize.width - data.width); } return data; }, _respectSize: function(data, event) { var el = this.helper, o = this._vBoundaries, pRatio = this._aspectRatio || event.shiftKey, a = this.axis, ismaxw = isNumber(data.width) && o.maxWidth && (o.maxWidth < data.width), ismaxh = isNumber(data.height) && o.maxHeight && (o.maxHeight < data.height), isminw = isNumber(data.width) && o.minWidth && (o.minWidth > data.width), isminh = isNumber(data.height) && o.minHeight && (o.minHeight > data.height); if (isminw) data.width = o.minWidth; if (isminh) data.height = o.minHeight; if (ismaxw) data.width = o.maxWidth; if (ismaxh) data.height = o.maxHeight; var dw = this.originalPosition.left + this.originalSize.width, dh = this.position.top + this.size.height; var cw = /sw|nw|w/.test(a), ch = /nw|ne|n/.test(a); if (isminw && cw) data.left = dw - o.minWidth; if (ismaxw && cw) data.left = dw - o.maxWidth; if (isminh && ch) data.top = dh - o.minHeight; if (ismaxh && ch) data.top = dh - o.maxHeight; // fixing jump error on top/left - bug #2330 var isNotwh = !data.width && !data.height; if (isNotwh && !data.left && data.top) data.top = null; else if (isNotwh && !data.top && data.left) data.left = null; return data; }, _proportionallyResize: function() { var o = this.options; if (!this._proportionallyResizeElements.length) return; var element = this.helper || this.element; for (var i=0; i < this._proportionallyResizeElements.length; i++) { var prel = this._proportionallyResizeElements[i]; if (!this.borderDif) { var b = [prel.css('borderTopWidth'), prel.css('borderRightWidth'), prel.css('borderBottomWidth'), prel.css('borderLeftWidth')], p = [prel.css('paddingTop'), prel.css('paddingRight'), prel.css('paddingBottom'), prel.css('paddingLeft')]; this.borderDif = $.map(b, function(v, i) { var border = parseInt(v,10)||0, padding = parseInt(p[i],10)||0; return border + padding; }); } prel.css({ height: (element.height() - this.borderDif[0] - this.borderDif[2]) || 0, width: (element.width() - this.borderDif[1] - this.borderDif[3]) || 0 }); }; }, _renderProxy: function() { var el = this.element, o = this.options; this.elementOffset = el.offset(); if(this._helper) { this.helper = this.helper || $('<div style="overflow:hidden;"></div>'); // fix ie6 offset TODO: This seems broken var ie6offset = ($.ui.ie6 ? 1 : 0), pxyoffset = ( $.ui.ie6 ? 2 : -1 ); this.helper.addClass(this._helper).css({ width: this.element.outerWidth() + pxyoffset, height: this.element.outerHeight() + pxyoffset, position: 'absolute', left: this.elementOffset.left - ie6offset +'px', top: this.elementOffset.top - ie6offset +'px', zIndex: ++o.zIndex //TODO: Don't modify option }); this.helper .appendTo("body") .disableSelection(); } else { this.helper = this.element; } }, _change: { e: function(event, dx, dy) { return { width: this.originalSize.width + dx }; }, w: function(event, dx, dy) { var o = this.options, cs = this.originalSize, sp = this.originalPosition; return { left: sp.left + dx, width: cs.width - dx }; }, n: function(event, dx, dy) { var o = this.options, cs = this.originalSize, sp = this.originalPosition; return { top: sp.top + dy, height: cs.height - dy }; }, s: function(event, dx, dy) { return { height: this.originalSize.height + dy }; }, se: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, sw: function(event, dx, dy) { return $.extend(this._change.s.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); }, ne: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.e.apply(this, [event, dx, dy])); }, nw: function(event, dx, dy) { return $.extend(this._change.n.apply(this, arguments), this._change.w.apply(this, [event, dx, dy])); } }, _propagate: function(n, event) { $.ui.plugin.call(this, n, [event, this.ui()]); (n != "resize" && this._trigger(n, event, 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 }; } }); /* * Resizable Extensions */ $.ui.plugin.add("resizable", "alsoResize", { start: function (event, ui) { var that = $(this).data("resizable"), o = that.options; var _store = function (exp) { $(exp).each(function() { var el = $(this); el.data("resizable-alsoresize", { width: parseInt(el.width(), 10), height: parseInt(el.height(), 10), left: parseInt(el.css('left'), 10), top: parseInt(el.css('top'), 10) }); }); }; if (typeof(o.alsoResize) == 'object' && !o.alsoResize.parentNode) { if (o.alsoResize.length) { o.alsoResize = o.alsoResize[0]; _store(o.alsoResize); } else { $.each(o.alsoResize, function (exp) { _store(exp); }); } }else{ _store(o.alsoResize); } }, resize: function (event, ui) { var that = $(this).data("resizable"), o = that.options, os = that.originalSize, op = that.originalPosition; var delta = { height: (that.size.height - os.height) || 0, width: (that.size.width - os.width) || 0, top: (that.position.top - op.top) || 0, left: (that.position.left - op.left) || 0 }, _alsoResize = function (exp, c) { $(exp).each(function() { var el = $(this), start = $(this).data("resizable-alsoresize"), style = {}, css = c && c.length ? c : el.parents(ui.originalElement[0]).length ? ['width', 'height'] : ['width', 'height', 'top', 'left']; $.each(css, function (i, prop) { var sum = (start[prop]||0) + (delta[prop]||0); if (sum && sum >= 0) style[prop] = sum || null; }); el.css(style); }); }; if (typeof(o.alsoResize) == 'object' && !o.alsoResize.nodeType) { $.each(o.alsoResize, function (exp, c) { _alsoResize(exp, c); }); }else{ _alsoResize(o.alsoResize); } }, stop: function (event, ui) { $(this).removeData("resizable-alsoresize"); } }); $.ui.plugin.add("resizable", "animate", { stop: function(event, ui) { var that = $(this).data("resizable"), o = that.options; var pr = that._proportionallyResizeElements, ista = pr.length && (/textarea/i).test(pr[0].nodeName), soffseth = ista && $.ui.hasScroll(pr[0], 'left') /* TODO - jump height */ ? 0 : that.sizeDiff.height, soffsetw = ista ? 0 : that.sizeDiff.width; var style = { width: (that.size.width - soffsetw), height: (that.size.height - soffseth) }, left = (parseInt(that.element.css('left'), 10) + (that.position.left - that.originalPosition.left)) || null, top = (parseInt(that.element.css('top'), 10) + (that.position.top - that.originalPosition.top)) || null; that.element.animate( $.extend(style, top && left ? { top: top, left: left } : {}), { duration: o.animateDuration, easing: o.animateEasing, step: function() { var data = { width: parseInt(that.element.css('width'), 10), height: parseInt(that.element.css('height'), 10), top: parseInt(that.element.css('top'), 10), left: parseInt(that.element.css('left'), 10) }; if (pr && pr.length) $(pr[0]).css({ width: data.width, height: data.height }); // propagating resize, and updating values for each animation step that._updateCache(data); that._propagate("resize", event); } } ); } }); $.ui.plugin.add("resizable", "containment", { start: function(event, ui) { var that = $(this).data("resizable"), o = that.options, el = that.element; var oc = o.containment, ce = (oc instanceof $) ? oc.get(0) : (/parent/.test(oc)) ? el.parent().get(0) : oc; if (!ce) return; that.containerElement = $(ce); if (/document/.test(oc) || oc == document) { that.containerOffset = { left: 0, top: 0 }; that.containerPosition = { left: 0, top: 0 }; that.parentData = { element: $(document), left: 0, top: 0, width: $(document).width(), height: $(document).height() || document.body.parentNode.scrollHeight }; } // i'm a node, so compute top, left, right, bottom else { var element = $(ce), p = []; $([ "Top", "Right", "Left", "Bottom" ]).each(function(i, name) { p[i] = num(element.css("padding" + name)); }); that.containerOffset = element.offset(); that.containerPosition = element.position(); that.containerSize = { height: (element.innerHeight() - p[3]), width: (element.innerWidth() - p[1]) }; var co = that.containerOffset, ch = that.containerSize.height, cw = that.containerSize.width, width = ($.ui.hasScroll(ce, "left") ? ce.scrollWidth : cw ), height = ($.ui.hasScroll(ce) ? ce.scrollHeight : ch); that.parentData = { element: ce, left: co.left, top: co.top, width: width, height: height }; } }, resize: function(event, ui) { var that = $(this).data("resizable"), o = that.options, ps = that.containerSize, co = that.containerOffset, cs = that.size, cp = that.position, pRatio = that._aspectRatio || event.shiftKey, cop = { top:0, left:0 }, ce = that.containerElement; if (ce[0] != document && (/static/).test(ce.css('position'))) cop = co; if (cp.left < (that._helper ? co.left : 0)) { that.size.width = that.size.width + (that._helper ? (that.position.left - co.left) : (that.position.left - cop.left)); if (pRatio) that.size.height = that.size.width / that.aspectRatio; that.position.left = o.helper ? co.left : 0; } if (cp.top < (that._helper ? co.top : 0)) { that.size.height = that.size.height + (that._helper ? (that.position.top - co.top) : that.position.top); if (pRatio) that.size.width = that.size.height * that.aspectRatio; that.position.top = that._helper ? co.top : 0; } that.offset.left = that.parentData.left+that.position.left; that.offset.top = that.parentData.top+that.position.top; var woset = Math.abs( (that._helper ? that.offset.left - cop.left : (that.offset.left - cop.left)) + that.sizeDiff.width ), hoset = Math.abs( (that._helper ? that.offset.top - cop.top : (that.offset.top - co.top)) + that.sizeDiff.height ); var isParent = that.containerElement.get(0) == that.element.parent().get(0), isOffsetRelative = /relative|absolute/.test(that.containerElement.css('position')); if(isParent && isOffsetRelative) woset -= that.parentData.left; if (woset + that.size.width >= that.parentData.width) { that.size.width = that.parentData.width - woset; if (pRatio) that.size.height = that.size.width / that.aspectRatio; } if (hoset + that.size.height >= that.parentData.height) { that.size.height = that.parentData.height - hoset; if (pRatio) that.size.width = that.size.height * that.aspectRatio; } }, stop: function(event, ui){ var that = $(this).data("resizable"), o = that.options, cp = that.position, co = that.containerOffset, cop = that.containerPosition, ce = that.containerElement; var helper = $(that.helper), ho = helper.offset(), w = helper.outerWidth() - that.sizeDiff.width, h = helper.outerHeight() - that.sizeDiff.height; if (that._helper && !o.animate && (/relative/).test(ce.css('position'))) $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); if (that._helper && !o.animate && (/static/).test(ce.css('position'))) $(this).css({ left: ho.left - cop.left - co.left, width: w, height: h }); } }); $.ui.plugin.add("resizable", "ghost", { start: function(event, ui) { var that = $(this).data("resizable"), o = that.options, cs = that.size; that.ghost = that.originalElement.clone(); that.ghost .css({ opacity: .25, display: 'block', position: 'relative', height: cs.height, width: cs.width, margin: 0, left: 0, top: 0 }) .addClass('ui-resizable-ghost') .addClass(typeof o.ghost == 'string' ? o.ghost : ''); that.ghost.appendTo(that.helper); }, resize: function(event, ui){ var that = $(this).data("resizable"), o = that.options; if (that.ghost) that.ghost.css({ position: 'relative', height: that.size.height, width: that.size.width }); }, stop: function(event, ui){ var that = $(this).data("resizable"), o = that.options; if (that.ghost && that.helper) that.helper.get(0).removeChild(that.ghost.get(0)); } }); $.ui.plugin.add("resizable", "grid", { resize: function(event, ui) { var that = $(this).data("resizable"), o = that.options, cs = that.size, os = that.originalSize, op = that.originalPosition, a = that.axis, ratio = o._aspectRatio || event.shiftKey; o.grid = typeof o.grid == "number" ? [o.grid, o.grid] : o.grid; var ox = Math.round((cs.width - os.width) / (o.grid[0]||1)) * (o.grid[0]||1), oy = Math.round((cs.height - os.height) / (o.grid[1]||1)) * (o.grid[1]||1); if (/^(se|s|e)$/.test(a)) { that.size.width = os.width + ox; that.size.height = os.height + oy; } else if (/^(ne)$/.test(a)) { that.size.width = os.width + ox; that.size.height = os.height + oy; that.position.top = op.top - oy; } else if (/^(sw)$/.test(a)) { that.size.width = os.width + ox; that.size.height = os.height + oy; that.position.left = op.left - ox; } else { that.size.width = os.width + ox; that.size.height = os.height + oy; that.position.top = op.top - oy; that.position.left = op.left - ox; } } }); var num = function(v) { return parseInt(v, 10) || 0; }; var isNumber = function(value) { return !isNaN(parseInt(value, 10)); }; })(jQuery); (function( $, undefined ) { $.widget("ui.selectable", $.ui.mouse, { version: "1.9.2", options: { appendTo: 'body', autoRefresh: true, distance: 0, filter: '*', tolerance: 'touch' }, _create: function() { var that = this; this.element.addClass("ui-selectable"); this.dragged = false; // cache selectee children based on filter var selectees; this.refresh = function() { selectees = $(that.options.filter, that.element[0]); selectees.addClass("ui-selectee"); selectees.each(function() { var $this = $(this); var pos = $this.offset(); $.data(this, "selectable-item", { element: this, $element: $this, left: pos.left, top: pos.top, right: pos.left + $this.outerWidth(), bottom: pos.top + $this.outerHeight(), startselected: false, selected: $this.hasClass('ui-selected'), selecting: $this.hasClass('ui-selecting'), unselecting: $this.hasClass('ui-unselecting') }); }); }; this.refresh(); this.selectees = selectees.addClass("ui-selectee"); this._mouseInit(); this.helper = $("<div class='ui-selectable-helper'></div>"); }, _destroy: function() { this.selectees .removeClass("ui-selectee") .removeData("selectable-item"); this.element .removeClass("ui-selectable ui-selectable-disabled"); this._mouseDestroy(); }, _mouseStart: function(event) { var that = this; this.opos = [event.pageX, event.pageY]; if (this.options.disabled) return; var options = this.options; this.selectees = $(options.filter, this.element[0]); this._trigger("start", event); $(options.appendTo).append(this.helper); // position helper (lasso) this.helper.css({ "left": event.clientX, "top": event.clientY, "width": 0, "height": 0 }); if (options.autoRefresh) { this.refresh(); } this.selectees.filter('.ui-selected').each(function() { var selectee = $.data(this, "selectable-item"); selectee.startselected = true; if (!event.metaKey && !event.ctrlKey) { selectee.$element.removeClass('ui-selected'); selectee.selected = false; selectee.$element.addClass('ui-unselecting'); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } }); $(event.target).parents().andSelf().each(function() { var selectee = $.data(this, "selectable-item"); if (selectee) { var doSelect = (!event.metaKey && !event.ctrlKey) || !selectee.$element.hasClass('ui-selected'); selectee.$element .removeClass(doSelect ? "ui-unselecting" : "ui-selected") .addClass(doSelect ? "ui-selecting" : "ui-unselecting"); selectee.unselecting = !doSelect; selectee.selecting = doSelect; selectee.selected = doSelect; // selectable (UN)SELECTING callback if (doSelect) { that._trigger("selecting", event, { selecting: selectee.element }); } else { that._trigger("unselecting", event, { unselecting: selectee.element }); } return false; } }); }, _mouseDrag: function(event) { var that = this; this.dragged = true; if (this.options.disabled) return; var options = this.options; var x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY; if (x1 > x2) { var tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { var tmp = y2; y2 = y1; y1 = tmp; } this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1}); this.selectees.each(function() { var selectee = $.data(this, "selectable-item"); //prevent helper from being selected if appendTo: selectable if (!selectee || selectee.element == that.element[0]) return; var hit = false; if (options.tolerance == 'touch') { hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) ); } else if (options.tolerance == 'fit') { hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2); } if (hit) { // SELECT if (selectee.selected) { selectee.$element.removeClass('ui-selected'); selectee.selected = false; } if (selectee.unselecting) { selectee.$element.removeClass('ui-unselecting'); selectee.unselecting = false; } if (!selectee.selecting) { selectee.$element.addClass('ui-selecting'); selectee.selecting = true; // selectable SELECTING callback that._trigger("selecting", event, { selecting: selectee.element }); } } else { // UNSELECT if (selectee.selecting) { if ((event.metaKey || event.ctrlKey) && selectee.startselected) { selectee.$element.removeClass('ui-selecting'); selectee.selecting = false; selectee.$element.addClass('ui-selected'); selectee.selected = true; } else { selectee.$element.removeClass('ui-selecting'); selectee.selecting = false; if (selectee.startselected) { selectee.$element.addClass('ui-unselecting'); selectee.unselecting = true; } // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } if (selectee.selected) { if (!event.metaKey && !event.ctrlKey && !selectee.startselected) { selectee.$element.removeClass('ui-selected'); selectee.selected = false; selectee.$element.addClass('ui-unselecting'); selectee.unselecting = true; // selectable UNSELECTING callback that._trigger("unselecting", event, { unselecting: selectee.element }); } } } }); return false; }, _mouseStop: function(event) { var that = this; this.dragged = false; var options = this.options; $('.ui-unselecting', this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass('ui-unselecting'); selectee.unselecting = false; selectee.startselected = false; that._trigger("unselected", event, { unselected: selectee.element }); }); $('.ui-selecting', this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass('ui-selecting').addClass('ui-selected'); selectee.selecting = false; selectee.selected = true; selectee.startselected = true; that._trigger("selected", event, { selected: selectee.element }); }); this._trigger("stop", event); this.helper.remove(); return false; } }); })(jQuery); (function( $, undefined ) { // number of pages in a slider // (how many times can you page up/down to go through the whole range) var numPages = 5; $.widget( "ui.slider", $.ui.mouse, { version: "1.9.2", widgetEventPrefix: "slide", options: { animate: false, distance: 0, max: 100, min: 0, orientation: "horizontal", range: false, step: 1, value: 0, values: null }, _create: function() { var i, handleCount, o = this.options, existingHandles = this.element.find( ".ui-slider-handle" ).addClass( "ui-state-default ui-corner-all" ), handle = "<a class='ui-slider-handle ui-state-default ui-corner-all' href='#'></a>", handles = []; 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" + ( o.disabled ? " ui-slider-disabled ui-disabled" : "" ) ); this.range = $([]); if ( o.range ) { if ( o.range === true ) { if ( !o.values ) { o.values = [ this._valueMin(), this._valueMin() ]; } if ( o.values.length && o.values.length !== 2 ) { o.values = [ o.values[0], o.values[0] ]; } } this.range = $( "<div></div>" ) .appendTo( this.element ) .addClass( "ui-slider-range" + // note: this isn't the most fittingly semantic framework class for this element, // but worked best visually with a variety of themes " ui-widget-header" + ( ( o.range === "min" || o.range === "max" ) ? " ui-slider-range-" + o.range : "" ) ); } handleCount = ( o.values && o.values.length ) || 1; for ( i = existingHandles.length; i < handleCount; i++ ) { handles.push( handle ); } this.handles = existingHandles.add( $( handles.join( "" ) ).appendTo( this.element ) ); this.handle = this.handles.eq( 0 ); this.handles.add( this.range ).filter( "a" ) .click(function( event ) { event.preventDefault(); }) .mouseenter(function() { if ( !o.disabled ) { $( this ).addClass( "ui-state-hover" ); } }) .mouseleave(function() { $( this ).removeClass( "ui-state-hover" ); }) .focus(function() { if ( !o.disabled ) { $( ".ui-slider .ui-state-focus" ).removeClass( "ui-state-focus" ); $( this ).addClass( "ui-state-focus" ); } else { $( this ).blur(); } }) .blur(function() { $( this ).removeClass( "ui-state-focus" ); }); this.handles.each(function( i ) { $( this ).data( "ui-slider-handle-index", i ); }); this._on( this.handles, { keydown: function( event ) { var allowed, curVal, newVal, step, index = $( event.target ).data( "ui-slider-handle-index" ); switch ( event.keyCode ) { case $.ui.keyCode.HOME: case $.ui.keyCode.END: case $.ui.keyCode.PAGE_UP: case $.ui.keyCode.PAGE_DOWN: case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: event.preventDefault(); if ( !this._keySliding ) { this._keySliding = true; $( event.target ).addClass( "ui-state-active" ); allowed = this._start( event, index ); if ( allowed === false ) { return; } } break; } step = this.options.step; if ( this.options.values && this.options.values.length ) { curVal = newVal = this.values( index ); } else { curVal = newVal = this.value(); } switch ( event.keyCode ) { case $.ui.keyCode.HOME: newVal = this._valueMin(); break; case $.ui.keyCode.END: newVal = this._valueMax(); break; case $.ui.keyCode.PAGE_UP: newVal = this._trimAlignValue( curVal + ( (this._valueMax() - this._valueMin()) / numPages ) ); break; case $.ui.keyCode.PAGE_DOWN: newVal = this._trimAlignValue( curVal - ( (this._valueMax() - this._valueMin()) / numPages ) ); break; case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: if ( curVal === this._valueMax() ) { return; } newVal = this._trimAlignValue( curVal + step ); break; case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: if ( curVal === this._valueMin() ) { return; } newVal = this._trimAlignValue( curVal - step ); break; } this._slide( event, index, newVal ); }, keyup: function( event ) { var index = $( event.target ).data( "ui-slider-handle-index" ); if ( this._keySliding ) { this._keySliding = false; this._stop( event, index ); this._change( event, index ); $( event.target ).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" ); this._mouseDestroy(); }, _mouseCapture: function( event ) { var position, normValue, distance, closestHandle, index, allowed, offset, mouseOverHandle, that = this, o = this.options; if ( o.disabled ) { return false; } this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); position = { x: event.pageX, y: event.pageY }; normValue = this._normValueFromMouse( position ); distance = this._valueMax() - this._valueMin() + 1; this.handles.each(function( i ) { var thisDistance = Math.abs( normValue - that.values(i) ); if ( distance > thisDistance ) { distance = thisDistance; closestHandle = $( this ); index = i; } }); // workaround for bug #3736 (if both handles of a range are at 0, // the first is always used as the one with least distance, // and moving it is obviously prevented by preventing negative ranges) if( o.range === true && this.values(1) === o.min ) { index += 1; closestHandle = $( this.handles[index] ); } allowed = this._start( event, index ); if ( allowed === false ) { return false; } this._mouseSliding = true; this._handleIndex = index; closestHandle .addClass( "ui-state-active" ) .focus(); offset = closestHandle.offset(); mouseOverHandle = !$( event.target ).parents().andSelf().is( ".ui-slider-handle" ); this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { left: event.pageX - offset.left - ( closestHandle.width() / 2 ), top: event.pageY - offset.top - ( closestHandle.height() / 2 ) - ( parseInt( closestHandle.css("borderTopWidth"), 10 ) || 0 ) - ( parseInt( closestHandle.css("borderBottomWidth"), 10 ) || 0) + ( parseInt( closestHandle.css("marginTop"), 10 ) || 0) }; if ( !this.handles.hasClass( "ui-state-hover" ) ) { this._slide( event, index, normValue ); } this._animateOff = true; return true; }, _mouseStart: function() { return true; }, _mouseDrag: function( event ) { var position = { x: event.pageX, y: event.pageY }, normValue = this._normValueFromMouse( position ); this._slide( event, this._handleIndex, normValue ); return false; }, _mouseStop: function( event ) { this.handles.removeClass( "ui-state-active" ); this._mouseSliding = false; this._stop( event, this._handleIndex ); this._change( event, 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( position ) { var pixelTotal, pixelMouse, percentMouse, valueTotal, valueMouse; if ( this.orientation === "horizontal" ) { pixelTotal = this.elementSize.width; pixelMouse = position.x - this.elementOffset.left - ( this._clickOffset ? this._clickOffset.left : 0 ); } else { pixelTotal = this.elementSize.height; pixelMouse = position.y - this.elementOffset.top - ( this._clickOffset ? this._clickOffset.top : 0 ); } percentMouse = ( pixelMouse / pixelTotal ); if ( percentMouse > 1 ) { percentMouse = 1; } if ( percentMouse < 0 ) { percentMouse = 0; } if ( this.orientation === "vertical" ) { percentMouse = 1 - percentMouse; } valueTotal = this._valueMax() - this._valueMin(); valueMouse = this._valueMin() + percentMouse * valueTotal; return this._trimAlignValue( valueMouse ); }, _start: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } return this._trigger( "start", event, uiHash ); }, _slide: function( event, index, newVal ) { var otherVal, newValues, allowed; if ( this.options.values && this.options.values.length ) { otherVal = this.values( index ? 0 : 1 ); if ( ( this.options.values.length === 2 && this.options.range === true ) && ( ( index === 0 && newVal > otherVal) || ( index === 1 && newVal < otherVal ) ) ) { newVal = otherVal; } if ( newVal !== this.values( index ) ) { newValues = this.values(); newValues[ index ] = newVal; // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal, values: newValues } ); otherVal = this.values( index ? 0 : 1 ); if ( allowed !== false ) { this.values( index, newVal, true ); } } } else { if ( newVal !== this.value() ) { // A slide can be canceled by returning false from the slide callback allowed = this._trigger( "slide", event, { handle: this.handles[ index ], value: newVal } ); if ( allowed !== false ) { this.value( newVal ); } } } }, _stop: function( event, index ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } this._trigger( "stop", event, uiHash ); }, _change: function( event, index ) { if ( !this._keySliding && !this._mouseSliding ) { var uiHash = { handle: this.handles[ index ], value: this.value() }; if ( this.options.values && this.options.values.length ) { uiHash.value = this.values( index ); uiHash.values = this.values(); } this._trigger( "change", event, uiHash ); } }, value: function( newValue ) { if ( arguments.length ) { this.options.value = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, 0 ); return; } return this._value(); }, values: function( index, newValue ) { var vals, newValues, i; if ( arguments.length > 1 ) { this.options.values[ index ] = this._trimAlignValue( newValue ); this._refreshValue(); this._change( null, index ); return; } if ( arguments.length ) { if ( $.isArray( arguments[ 0 ] ) ) { vals = this.options.values; newValues = arguments[ 0 ]; for ( i = 0; i < vals.length; i += 1 ) { vals[ i ] = this._trimAlignValue( newValues[ i ] ); this._change( null, i ); } this._refreshValue(); } else { if ( this.options.values && this.options.values.length ) { return this._values( index ); } else { return this.value(); } } } else { return this._values(); } }, _setOption: function( key, value ) { var i, valsLength = 0; if ( $.isArray( this.options.values ) ) { valsLength = this.options.values.length; } $.Widget.prototype._setOption.apply( this, arguments ); switch ( key ) { case "disabled": if ( value ) { this.handles.filter( ".ui-state-focus" ).blur(); this.handles.removeClass( "ui-state-hover" ); this.handles.prop( "disabled", true ); this.element.addClass( "ui-disabled" ); } else { this.handles.prop( "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 ( i = 0; i < valsLength; i += 1 ) { this._change( null, i ); } this._animateOff = false; break; case "min": case "max": this._animateOff = true; this._refreshValue(); this._animateOff = false; break; } }, //internal value getter // _value() returns value trimmed by min and max, aligned by step _value: function() { var val = this.options.value; val = this._trimAlignValue( val ); return val; }, //internal values getter // _values() returns array of values trimmed by min and max, aligned by step // _values( index ) returns single value trimmed by min and max, aligned by step _values: function( index ) { var val, vals, i; if ( arguments.length ) { val = this.options.values[ index ]; val = this._trimAlignValue( val ); return val; } else { // .slice() creates a copy of the array // this copy gets trimmed by min and max and then returned vals = this.options.values.slice(); for ( i = 0; i < vals.length; i+= 1) { vals[ i ] = this._trimAlignValue( vals[ i ] ); } return vals; } }, // returns the step-aligned value that val is closest to, between (inclusive) min and max _trimAlignValue: function( val ) { if ( val <= this._valueMin() ) { return this._valueMin(); } if ( val >= this._valueMax() ) { return this._valueMax(); } var step = ( this.options.step > 0 ) ? this.options.step : 1, valModStep = (val - this._valueMin()) % step, alignValue = val - valModStep; if ( Math.abs(valModStep) * 2 >= step ) { alignValue += ( valModStep > 0 ) ? step : ( -step ); } // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see #4124) return parseFloat( alignValue.toFixed(5) ); }, _valueMin: function() { return this.options.min; }, _valueMax: function() { return this.options.max; }, _refreshValue: function() { var lastValPercent, valPercent, value, valueMin, valueMax, oRange = this.options.range, o = this.options, that = this, animate = ( !this._animateOff ) ? o.animate : false, _set = {}; if ( this.options.values && this.options.values.length ) { this.handles.each(function( i ) { valPercent = ( that.values(i) - that._valueMin() ) / ( that._valueMax() - that._valueMin() ) * 100; _set[ that.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; $( this ).stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( that.options.range === true ) { if ( that.orientation === "horizontal" ) { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { left: valPercent + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { width: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } else { if ( i === 0 ) { that.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { bottom: ( valPercent ) + "%" }, o.animate ); } if ( i === 1 ) { that.range[ animate ? "animate" : "css" ]( { height: ( valPercent - lastValPercent ) + "%" }, { queue: false, duration: o.animate } ); } } } lastValPercent = valPercent; }); } else { value = this.value(); valueMin = this._valueMin(); valueMax = this._valueMax(); valPercent = ( valueMax !== valueMin ) ? ( value - valueMin ) / ( valueMax - valueMin ) * 100 : 0; _set[ this.orientation === "horizontal" ? "left" : "bottom" ] = valPercent + "%"; this.handle.stop( 1, 1 )[ animate ? "animate" : "css" ]( _set, o.animate ); if ( oRange === "min" && this.orientation === "horizontal" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { width: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "horizontal" ) { this.range[ animate ? "animate" : "css" ]( { width: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } if ( oRange === "min" && this.orientation === "vertical" ) { this.range.stop( 1, 1 )[ animate ? "animate" : "css" ]( { height: valPercent + "%" }, o.animate ); } if ( oRange === "max" && this.orientation === "vertical" ) { this.range[ animate ? "animate" : "css" ]( { height: ( 100 - valPercent ) + "%" }, { queue: false, duration: o.animate } ); } } } }); }(jQuery)); (function( $, undefined ) { $.widget("ui.sortable", $.ui.mouse, { version: "1.9.2", 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 o = this.options; this.containerCache = {}; this.element.addClass("ui-sortable"); //Get the items this.refresh(); //Let's determine if the items are being displayed horizontally this.floating = this.items.length ? o.axis === 'x' || (/left|right/).test(this.items[0].item.css('float')) || (/inline|table-cell/).test(this.items[0].item.css('display')) : false; //Let's determine the parent's offset this.offset = this.element.offset(); //Initialize mouse events for interaction this._mouseInit(); //We're ready to go this.ready = true }, _destroy: function() { this.element .removeClass("ui-sortable ui-sortable-disabled"); this._mouseDestroy(); for ( var i = this.items.length - 1; i >= 0; i-- ) this.items[i].item.removeData(this.widgetName + "-item"); return this; }, _setOption: function(key, value){ if ( key === "disabled" ) { this.options[ key ] = value; this.widget().toggleClass( "ui-sortable-disabled", !!value ); } else { // Don't call widget base _setOption for disable as it adds ui-state-disabled class $.Widget.prototype._setOption.apply(this, arguments); } }, _mouseCapture: function(event, overrideHandle) { var that = this; if (this.reverting) { return false; } if(this.options.disabled || this.options.type == 'static') return false; //We have to refresh the items data once first this._refreshItems(event); //Find out if the clicked node (or one of its parents) is a actual item in this.items var currentItem = null, nodes = $(event.target).parents().each(function() { if($.data(this, that.widgetName + '-item') == that) { currentItem = $(this); return false; } }); if($.data(event.target, that.widgetName + '-item') == that) currentItem = $(event.target); if(!currentItem) return false; if(this.options.handle && !overrideHandle) { var validHandle = false; $(this.options.handle, currentItem).find("*").andSelf().each(function() { if(this == event.target) validHandle = true; }); if(!validHandle) return false; } this.currentItem = currentItem; this._removeCurrentsFromItems(); return true; }, _mouseStart: function(event, overrideHandle, noActivation) { var o = this.options; this.currentContainer = this; //We only need to call refreshPositions, because the refreshItems call has been moved to mouseCapture this.refreshPositions(); //Create and append the visible helper this.helper = this._createHelper(event); //Cache the helper size this._cacheHelperProportions(); /* * - Position generation - * This block generates everything position related - it's the core of draggables. */ //Cache the margins of the original element this._cacheMargins(); //Get the next scrolling parent this.scrollParent = this.helper.scrollParent(); //The element's absolute position on the page minus margins this.offset = this.currentItem.offset(); this.offset = { top: this.offset.top - this.margins.top, left: this.offset.left - this.margins.left }; $.extend(this.offset, { click: { //Where the click happened, relative to the element left: event.pageX - this.offset.left, top: event.pageY - this.offset.top }, parent: this._getParentOffset(), relative: this._getRelativeOffset() //This is a relative to absolute position minus the actual position calculation - only used for relative positioned helper }); // Only after we got the offset, we can change the helper's position to absolute // TODO: Still need to figure out a way to make relative sorting possible this.helper.css("position", "absolute"); this.cssPosition = this.helper.css("position"); //Generate the original position this.originalPosition = this._generatePosition(event); this.originalPageX = event.pageX; this.originalPageY = event.pageY; //Adjust the mouse offset relative to the helper if 'cursorAt' is supplied (o.cursorAt && this._adjustOffsetFromHelper(o.cursorAt)); //Cache the former DOM position this.domPosition = { prev: this.currentItem.prev()[0], parent: this.currentItem.parent()[0] }; //If the helper is not the original, hide the original so it's not playing any role during the drag, won't cause anything bad this way if(this.helper[0] != this.currentItem[0]) { this.currentItem.hide(); } //Create the placeholder this._createPlaceholder(); //Set a containment if given in the options if(o.containment) this._setContainment(); if(o.cursor) { // cursor option if ($('body').css("cursor")) this._storedCursor = $('body').css("cursor"); $('body').css("cursor", o.cursor); } if(o.opacity) { // opacity option if (this.helper.css("opacity")) this._storedOpacity = this.helper.css("opacity"); this.helper.css("opacity", o.opacity); } if(o.zIndex) { // zIndex option if (this.helper.css("zIndex")) this._storedZIndex = this.helper.css("zIndex"); this.helper.css("zIndex", o.zIndex); } //Prepare scrolling if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') this.overflowOffset = this.scrollParent.offset(); //Call callbacks this._trigger("start", event, this._uiHash()); //Recache the helper size if(!this._preserveHelperProportions) this._cacheHelperProportions(); //Post 'activate' events to possible containers if(!noActivation) { for (var i = this.containers.length - 1; i >= 0; i--) { this.containers[i]._trigger("activate", event, this._uiHash(this)); } } //Prepare possible droppables if($.ui.ddmanager) $.ui.ddmanager.current = this; if ($.ui.ddmanager && !o.dropBehaviour) $.ui.ddmanager.prepareOffsets(this, event); this.dragging = true; this.helper.addClass("ui-sortable-helper"); this._mouseDrag(event); //Execute the drag once - this causes the helper not to be visible before getting its correct position return true; }, _mouseDrag: function(event) { //Compute the helpers position this.position = this._generatePosition(event); this.positionAbs = this._convertPositionTo("absolute"); if (!this.lastPositionAbs) { this.lastPositionAbs = this.positionAbs; } //Do scrolling if(this.options.scroll) { var o = this.options, scrolled = false; if(this.scrollParent[0] != document && this.scrollParent[0].tagName != 'HTML') { if((this.overflowOffset.top + this.scrollParent[0].offsetHeight) - event.pageY < o.scrollSensitivity) this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop + o.scrollSpeed; else if(event.pageY - this.overflowOffset.top < o.scrollSensitivity) this.scrollParent[0].scrollTop = scrolled = this.scrollParent[0].scrollTop - o.scrollSpeed; if((this.overflowOffset.left + this.scrollParent[0].offsetWidth) - event.pageX < o.scrollSensitivity) this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft + o.scrollSpeed; else if(event.pageX - this.overflowOffset.left < o.scrollSensitivity) this.scrollParent[0].scrollLeft = scrolled = this.scrollParent[0].scrollLeft - o.scrollSpeed; } else { if(event.pageY - $(document).scrollTop() < o.scrollSensitivity) scrolled = $(document).scrollTop($(document).scrollTop() - o.scrollSpeed); else if($(window).height() - (event.pageY - $(document).scrollTop()) < o.scrollSensitivity) scrolled = $(document).scrollTop($(document).scrollTop() + o.scrollSpeed); if(event.pageX - $(document).scrollLeft() < o.scrollSensitivity) scrolled = $(document).scrollLeft($(document).scrollLeft() - o.scrollSpeed); else if($(window).width() - (event.pageX - $(document).scrollLeft()) < o.scrollSensitivity) scrolled = $(document).scrollLeft($(document).scrollLeft() + o.scrollSpeed); } if(scrolled !== false && $.ui.ddmanager && !o.dropBehaviour) $.ui.ddmanager.prepareOffsets(this, event); } //Regenerate the absolute position used for position checks this.positionAbs = this._convertPositionTo("absolute"); //Set the helper 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'; //Rearrange for (var i = this.items.length - 1; i >= 0; i--) { //Cache variables and intersection, continue if no intersection var item = this.items[i], itemElement = item.item[0], intersection = this._intersectsWithPointer(item); if (!intersection) continue; // Only put the placeholder inside the current Container, skip all // items form other containers. This works because when moving // an item from one container to another the // currentContainer is switched before the placeholder is moved. // // Without this moving items in "sub-sortables" can cause the placeholder to jitter // beetween the outer and inner container. if (item.instance !== this.currentContainer) continue; if (itemElement != this.currentItem[0] //cannot intersect with itself && this.placeholder[intersection == 1 ? "next" : "prev"]()[0] != itemElement //no useless actions that have been done before && !$.contains(this.placeholder[0], itemElement) //no action if the item moved is the parent of the item checked && (this.options.type == 'semi-dynamic' ? !$.contains(this.element[0], itemElement) : true) //&& itemElement.parentNode == this.placeholder[0].parentNode // only rearrange items within the same container ) { this.direction = intersection == 1 ? "down" : "up"; if (this.options.tolerance == "pointer" || this._intersectsWithSides(item)) { this._rearrange(event, item); } else { break; } this._trigger("change", event, this._uiHash()); break; } } //Post events to containers this._contactContainers(event); //Interconnect with droppables if($.ui.ddmanager) $.ui.ddmanager.drag(this, event); //Call callbacks this._trigger('sort', event, this._uiHash()); this.lastPositionAbs = this.positionAbs; return false; }, _mouseStop: function(event, noPropagation) { if(!event) return; //If we are using droppables, inform the manager about the drop if ($.ui.ddmanager && !this.options.dropBehaviour) $.ui.ddmanager.drop(this, event); if(this.options.revert) { var that = this; var cur = this.placeholder.offset(); this.reverting = true; $(this.helper).animate({ left: cur.left - this.offset.parent.left - this.margins.left + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollLeft), top: cur.top - this.offset.parent.top - this.margins.top + (this.offsetParent[0] == document.body ? 0 : this.offsetParent[0].scrollTop) }, parseInt(this.options.revert, 10) || 500, function() { that._clear(event); }); } else { this._clear(event, noPropagation); } return false; }, cancel: function() { 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(); //Post deactivating events to containers for (var i = this.containers.length - 1; i >= 0; i--){ this.containers[i]._trigger("deactivate", null, this._uiHash(this)); if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", null, this._uiHash(this)); this.containers[i].containerCache.over = 0; } } } if (this.placeholder) { //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! 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(); $.extend(this, { helper: null, dragging: false, reverting: false, _noFinalSort: null }); if(this.domPosition.prev) { $(this.domPosition.prev).after(this.currentItem); } else { $(this.domPosition.parent).prepend(this.currentItem); } } return this; }, serialize: function(o) { var items = this._getItemsAsjQuery(o && o.connected); var str = []; o = o || {}; $(items).each(function() { var res = ($(o.item || this).attr(o.attribute || 'id') || '').match(o.expression || (/(.+)[-=_](.+)/)); if(res) str.push((o.key || res[1]+'[]')+'='+(o.key && o.expression ? res[1] : res[2])); }); if(!str.length && o.key) { str.push(o.key + '='); } return str.join('&'); }, toArray: function(o) { var items = this._getItemsAsjQuery(o && o.connected); var ret = []; o = o || {}; items.each(function() { ret.push($(o.item || this).attr(o.attribute || 'id') || ''); }); return ret; }, /* Be careful with the following core functions */ _intersectsWith: function(item) { var x1 = this.positionAbs.left, x2 = x1 + this.helperProportions.width, y1 = this.positionAbs.top, y2 = y1 + this.helperProportions.height; var l = item.left, r = l + item.width, t = item.top, b = t + item.height; var dyClick = this.offset.click.top, dxClick = this.offset.click.left; var isOverElement = (y1 + dyClick) > t && (y1 + dyClick) < b && (x1 + dxClick) > l && (x1 + dxClick) < r; if( this.options.tolerance == "pointer" || this.options.forcePointerForContainers || (this.options.tolerance != "pointer" && this.helperProportions[this.floating ? 'width' : 'height'] > item[this.floating ? 'width' : 'height']) ) { return isOverElement; } else { return (l < x1 + (this.helperProportions.width / 2) // Right Half && x2 - (this.helperProportions.width / 2) < r // Left Half && t < y1 + (this.helperProportions.height / 2) // Bottom Half && y2 - (this.helperProportions.height / 2) < b ); // Top Half } }, _intersectsWithPointer: function(item) { var isOverElementHeight = (this.options.axis === 'x') || $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top, item.height), isOverElementWidth = (this.options.axis === 'y') || $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left, item.width), isOverElement = isOverElementHeight && isOverElementWidth, verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (!isOverElement) return false; return this.floating ? ( ((horizontalDirection && horizontalDirection == "right") || verticalDirection == "down") ? 2 : 1 ) : ( verticalDirection && (verticalDirection == "down" ? 2 : 1) ); }, _intersectsWithSides: function(item) { var isOverBottomHalf = $.ui.isOverAxis(this.positionAbs.top + this.offset.click.top, item.top + (item.height/2), item.height), isOverRightHalf = $.ui.isOverAxis(this.positionAbs.left + this.offset.click.left, item.left + (item.width/2), item.width), verticalDirection = this._getDragVerticalDirection(), horizontalDirection = this._getDragHorizontalDirection(); if (this.floating && horizontalDirection) { return ((horizontalDirection == "right" && isOverRightHalf) || (horizontalDirection == "left" && !isOverRightHalf)); } else { return verticalDirection && ((verticalDirection == "down" && isOverBottomHalf) || (verticalDirection == "up" && !isOverBottomHalf)); } }, _getDragVerticalDirection: function() { var delta = this.positionAbs.top - this.lastPositionAbs.top; return delta != 0 && (delta > 0 ? "down" : "up"); }, _getDragHorizontalDirection: function() { var delta = this.positionAbs.left - this.lastPositionAbs.left; return delta != 0 && (delta > 0 ? "right" : "left"); }, refresh: function(event) { this._refreshItems(event); this.refreshPositions(); return this; }, _connectWith: function() { var options = this.options; return options.connectWith.constructor == String ? [options.connectWith] : options.connectWith; }, _getItemsAsjQuery: function(connected) { var items = []; var queries = []; var connectWith = this._connectWith(); if(connectWith && connected) { for (var i = connectWith.length - 1; i >= 0; i--){ var cur = $(connectWith[i]); for (var j = cur.length - 1; j >= 0; j--){ var inst = $.data(cur[j], this.widgetName); if(inst && inst != this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element) : $(inst.options.items, inst.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'), inst]); } }; }; } queries.push([$.isFunction(this.options.items) ? this.options.items.call(this.element, null, { options: this.options, item: this.currentItem }) : $(this.options.items, this.element).not(".ui-sortable-helper").not('.ui-sortable-placeholder'), this]); for (var i = queries.length - 1; i >= 0; i--){ queries[i][0].each(function() { items.push(this); }); }; return $(items); }, _removeCurrentsFromItems: function() { var list = this.currentItem.find(":data(" + this.widgetName + "-item)"); this.items = $.grep(this.items, function (item) { for (var j=0; j < list.length; j++) { if(list[j] == item.item[0]) return false; }; return true; }); }, _refreshItems: function(event) { this.items = []; this.containers = [this]; var items = this.items; var queries = [[$.isFunction(this.options.items) ? this.options.items.call(this.element[0], event, { item: this.currentItem }) : $(this.options.items, this.element), this]]; var connectWith = this._connectWith(); if(connectWith && this.ready) { //Shouldn't be run the first time through due to massive slow-down for (var i = connectWith.length - 1; i >= 0; i--){ var cur = $(connectWith[i]); for (var j = cur.length - 1; j >= 0; j--){ var inst = $.data(cur[j], this.widgetName); if(inst && inst != this && !inst.options.disabled) { queries.push([$.isFunction(inst.options.items) ? inst.options.items.call(inst.element[0], event, { item: this.currentItem }) : $(inst.options.items, inst.element), inst]); this.containers.push(inst); } }; }; } for (var i = queries.length - 1; i >= 0; i--) { var targetData = queries[i][1]; var _queries = queries[i][0]; for (var j=0, queriesLength = _queries.length; j < queriesLength; j++) { var item = $(_queries[j]); item.data(this.widgetName + '-item', targetData); // Data for target checking (mouse manager) items.push({ item: item, instance: targetData, width: 0, height: 0, left: 0, top: 0 }); }; }; }, refreshPositions: function(fast) { //This has to be redone because due to the item being moved out/into the offsetParent, the offsetParent's position will change if(this.offsetParent && this.helper) { this.offset.parent = this._getParentOffset(); } for (var i = this.items.length - 1; i >= 0; i--){ var item = this.items[i]; //We ignore calculating positions of all connected containers when we're not over them if(item.instance != this.currentContainer && this.currentContainer && item.item[0] != this.currentItem[0]) continue; var t = this.options.toleranceElement ? $(this.options.toleranceElement, item.item) : item.item; if (!fast) { item.width = t.outerWidth(); item.height = t.outerHeight(); } var p = t.offset(); item.left = p.left; item.top = p.top; }; if(this.options.custom && this.options.custom.refreshContainers) { this.options.custom.refreshContainers.call(this); } else { for (var i = this.containers.length - 1; i >= 0; i--){ var p = this.containers[i].element.offset(); this.containers[i].containerCache.left = p.left; this.containers[i].containerCache.top = p.top; this.containers[i].containerCache.width = this.containers[i].element.outerWidth(); this.containers[i].containerCache.height = this.containers[i].element.outerHeight(); }; } return this; }, _createPlaceholder: function(that) { that = that || this; var o = that.options; if(!o.placeholder || o.placeholder.constructor == String) { var className = o.placeholder; o.placeholder = { element: function() { var el = $(document.createElement(that.currentItem[0].nodeName)) .addClass(className || that.currentItem[0].className+" ui-sortable-placeholder") .removeClass("ui-sortable-helper")[0]; if(!className) el.style.visibility = "hidden"; return el; }, update: function(container, p) { // 1. If a className is set as 'placeholder option, we don't force sizes - the class is responsible for that // 2. The option 'forcePlaceholderSize can be enabled to force it even if a class name is specified if(className && !o.forcePlaceholderSize) return; //If the element doesn't have a actual height by itself (without styles coming from a stylesheet), it receives the inline height from the dragged item if(!p.height()) { p.height(that.currentItem.innerHeight() - parseInt(that.currentItem.css('paddingTop')||0, 10) - parseInt(that.currentItem.css('paddingBottom')||0, 10)); }; if(!p.width()) { p.width(that.currentItem.innerWidth() - parseInt(that.currentItem.css('paddingLeft')||0, 10) - parseInt(that.currentItem.css('paddingRight')||0, 10)); }; } }; } //Create the placeholder that.placeholder = $(o.placeholder.element.call(that.element, that.currentItem)); //Append it after the actual current item that.currentItem.after(that.placeholder); //Update the size of the placeholder (TODO: Logic to fuzzy, see line 316/317) o.placeholder.update(that, that.placeholder); }, _contactContainers: function(event) { // get innermost container that intersects with item var innermostContainer = null, innermostIndex = null; for (var i = this.containers.length - 1; i >= 0; i--){ // never consider a container that's located within the item itself if($.contains(this.currentItem[0], this.containers[i].element[0])) continue; if(this._intersectsWith(this.containers[i].containerCache)) { // if we've already found a container and it's more "inner" than this, then continue if(innermostContainer && $.contains(this.containers[i].element[0], innermostContainer.element[0])) continue; innermostContainer = this.containers[i]; innermostIndex = i; } else { // container doesn't intersect. trigger "out" event if necessary if(this.containers[i].containerCache.over) { this.containers[i]._trigger("out", event, this._uiHash(this)); this.containers[i].containerCache.over = 0; } } } // if no intersecting containers found, return if(!innermostContainer) return; // move the item into the container if it's not there already if(this.containers.length === 1) { this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); this.containers[innermostIndex].containerCache.over = 1; } else { //When entering a new container, we will find the item with the least distance and append our item near it var dist = 10000; var itemWithLeastDistance = null; var posProperty = this.containers[innermostIndex].floating ? 'left' : 'top'; var sizeProperty = this.containers[innermostIndex].floating ? 'width' : 'height'; var base = this.positionAbs[posProperty] + this.offset.click[posProperty]; for (var j = this.items.length - 1; j >= 0; j--) { if(!$.contains(this.containers[innermostIndex].element[0], this.items[j].item[0])) continue; if(this.items[j].item[0] == this.currentItem[0]) continue; var cur = this.items[j].item.offset()[posProperty]; var nearBottom = false; if(Math.abs(cur - base) > Math.abs(cur + this.items[j][sizeProperty] - base)){ nearBottom = true; cur += this.items[j][sizeProperty]; } if(Math.abs(cur - base) < dist) { dist = Math.abs(cur - base); itemWithLeastDistance = this.items[j]; this.direction = nearBottom ? "up": "down"; } } if(!itemWithLeastDistance && !this.options.dropOnEmpty) //Check if dropOnEmpty is enabled return; this.currentContainer = this.containers[innermostIndex]; itemWithLeastDistance ? this._rearrange(event, itemWithLeastDistance, null, true) : this._rearrange(event, null, this.containers[innermostIndex].element, true); this._trigger("change", event, this._uiHash()); this.containers[innermostIndex]._trigger("change", event, this._uiHash(this)); //Update the placeholder this.options.placeholder.update(this.currentContainer, this.placeholder); this.containers[innermostIndex]._trigger("over", event, this._uiHash(this)); this.containers[innermostIndex].containerCache.over = 1; } }, _createHelper: function(event) { var o = this.options; var helper = $.isFunction(o.helper) ? $(o.helper.apply(this.element[0], [event, this.currentItem])) : (o.helper == 'clone' ? this.currentItem.clone() : this.currentItem); if(!helper.parents('body').length) //Add the helper to the DOM if that didn't happen already $(o.appendTo != 'parent' ? o.appendTo : this.currentItem[0].parentNode)[0].appendChild(helper[0]); if(helper[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(helper[0].style.width == '' || o.forceHelperSize) helper.width(this.currentItem.width()); if(helper[0].style.height == '' || o.forceHelperSize) helper.height(this.currentItem.height()); return helper; }, _adjustOffsetFromHelper: function(obj) { if (typeof obj == 'string') { obj = obj.split(' '); } if ($.isArray(obj)) { obj = {left: +obj[0], top: +obj[1] || 0}; } if ('left' in obj) { this.offset.click.left = obj.left + this.margins.left; } if ('right' in obj) { this.offset.click.left = this.helperProportions.width - obj.right + this.margins.left; } if ('top' in obj) { this.offset.click.top = obj.top + this.margins.top; } if ('bottom' in obj) { this.offset.click.top = this.helperProportions.height - obj.bottom + this.margins.top; } }, _getParentOffset: function() { //Get the offsetParent and cache its position this.offsetParent = this.helper.offsetParent(); var po = this.offsetParent.offset(); // This is a special case where we need to modify a offset calculated on start, since the following happened: // 1. The position of the helper is absolute, so it's position is calculated based on the next positioned parent // 2. The actual offset parent is a child of the scroll parent, and the scroll parent isn't the document, which means that // the scroll is included in the initial calculation of the offset of the parent, and never recalculated upon drag if(this.cssPosition == 'absolute' && this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) { po.left += this.scrollParent.scrollLeft(); po.top += this.scrollParent.scrollTop(); } if((this.offsetParent[0] == document.body) //This needs to be actually done for all browsers, since pageX/pageY includes this information || (this.offsetParent[0].tagName && this.offsetParent[0].tagName.toLowerCase() == 'html' && $.ui.ie)) //Ugly IE fix po = { top: 0, left: 0 }; return { top: po.top + (parseInt(this.offsetParent.css("borderTopWidth"),10) || 0), left: po.left + (parseInt(this.offsetParent.css("borderLeftWidth"),10) || 0) }; }, _getRelativeOffset: function() { if(this.cssPosition == "relative") { var p = this.currentItem.position(); return { top: p.top - (parseInt(this.helper.css("top"),10) || 0) + this.scrollParent.scrollTop(), left: p.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 o = this.options; if(o.containment == 'parent') o.containment = this.helper[0].parentNode; if(o.containment == 'document' || o.containment == 'window') this.containment = [ 0 - this.offset.relative.left - this.offset.parent.left, 0 - this.offset.relative.top - this.offset.parent.top, $(o.containment == 'document' ? document : window).width() - this.helperProportions.width - this.margins.left, ($(o.containment == 'document' ? document : window).height() || document.body.parentNode.scrollHeight) - this.helperProportions.height - this.margins.top ]; if(!(/^(document|window|parent)$/).test(o.containment)) { var ce = $(o.containment)[0]; var co = $(o.containment).offset(); var over = ($(ce).css("overflow") != 'hidden'); this.containment = [ co.left + (parseInt($(ce).css("borderLeftWidth"),10) || 0) + (parseInt($(ce).css("paddingLeft"),10) || 0) - this.margins.left, co.top + (parseInt($(ce).css("borderTopWidth"),10) || 0) + (parseInt($(ce).css("paddingTop"),10) || 0) - this.margins.top, co.left+(over ? Math.max(ce.scrollWidth,ce.offsetWidth) : ce.offsetWidth) - (parseInt($(ce).css("borderLeftWidth"),10) || 0) - (parseInt($(ce).css("paddingRight"),10) || 0) - this.helperProportions.width - this.margins.left, co.top+(over ? Math.max(ce.scrollHeight,ce.offsetHeight) : ce.offsetHeight) - (parseInt($(ce).css("borderTopWidth"),10) || 0) - (parseInt($(ce).css("paddingBottom"),10) || 0) - this.helperProportions.height - this.margins.top ]; } }, _convertPositionTo: function(d, pos) { if(!pos) pos = this.position; var mod = d == "absolute" ? 1 : -1; var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); return { top: ( pos.top // The absolute mouse position + this.offset.relative.top * mod // Only for relative positioned nodes: Relative offset from element to offset parent + this.offset.parent.top * mod // The offsetParent's offset without borders (offset + border) - ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) ) * mod) ), left: ( pos.left // The absolute mouse position + this.offset.relative.left * mod // Only for relative positioned nodes: Relative offset from element to offset parent + this.offset.parent.left * mod // The offsetParent's offset without borders (offset + border) - ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() ) * mod) ) }; }, _generatePosition: function(event) { var o = this.options, scroll = this.cssPosition == 'absolute' && !(this.scrollParent[0] != document && $.contains(this.scrollParent[0], this.offsetParent[0])) ? this.offsetParent : this.scrollParent, scrollIsRootNode = (/(html|body)/i).test(scroll[0].tagName); // This is another very weird special case that only happens for relative elements: // 1. If the css position is relative // 2. and the scroll parent is the document or similar to the offset parent // we have to refresh the relative offset during the scroll so there are no jumps if(this.cssPosition == 'relative' && !(this.scrollParent[0] != document && this.scrollParent[0] != this.offsetParent[0])) { this.offset.relative = this._getRelativeOffset(); } var pageX = event.pageX; var pageY = event.pageY; /* * - Position constraining - * Constrain the position to a mix of grid, containment. */ if(this.originalPosition) { //If we are not dragging yet, we won't check for options if(this.containment) { if(event.pageX - this.offset.click.left < this.containment[0]) pageX = this.containment[0] + this.offset.click.left; if(event.pageY - this.offset.click.top < this.containment[1]) pageY = this.containment[1] + this.offset.click.top; if(event.pageX - this.offset.click.left > this.containment[2]) pageX = this.containment[2] + this.offset.click.left; if(event.pageY - this.offset.click.top > this.containment[3]) pageY = this.containment[3] + this.offset.click.top; } if(o.grid) { var top = this.originalPageY + Math.round((pageY - this.originalPageY) / o.grid[1]) * o.grid[1]; pageY = this.containment ? (!(top - this.offset.click.top < this.containment[1] || top - this.offset.click.top > this.containment[3]) ? top : (!(top - this.offset.click.top < this.containment[1]) ? top - o.grid[1] : top + o.grid[1])) : top; var left = this.originalPageX + Math.round((pageX - this.originalPageX) / o.grid[0]) * o.grid[0]; pageX = this.containment ? (!(left - this.offset.click.left < this.containment[0] || left - this.offset.click.left > this.containment[2]) ? left : (!(left - this.offset.click.left < this.containment[0]) ? left - o.grid[0] : left + o.grid[0])) : left; } } return { top: ( pageY // The absolute mouse position - this.offset.click.top // Click offset (relative to the element) - this.offset.relative.top // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.top // The offsetParent's offset without borders (offset + border) + ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollTop() : ( scrollIsRootNode ? 0 : scroll.scrollTop() ) )) ), left: ( pageX // The absolute mouse position - this.offset.click.left // Click offset (relative to the element) - this.offset.relative.left // Only for relative positioned nodes: Relative offset from element to offset parent - this.offset.parent.left // The offsetParent's offset without borders (offset + border) + ( ( this.cssPosition == 'fixed' ? -this.scrollParent.scrollLeft() : scrollIsRootNode ? 0 : scroll.scrollLeft() )) ) }; }, _rearrange: function(event, i, a, hardRefresh) { a ? a[0].appendChild(this.placeholder[0]) : i.item[0].parentNode.insertBefore(this.placeholder[0], (this.direction == 'down' ? i.item[0] : i.item[0].nextSibling)); //Various things done here to improve the performance: // 1. we create a setTimeout, that calls refreshPositions // 2. on the instance, we have a counter variable, that get's higher after every append // 3. on the local scope, we copy the counter variable, and check in the timeout, if it's still the same // 4. this lets only the last addition to the timeout stack through this.counter = this.counter ? ++this.counter : 1; var counter = this.counter; this._delay(function() { if(counter == this.counter) this.refreshPositions(!hardRefresh); //Precompute after each DOM insertion, NOT on mousemove }); }, _clear: function(event, noPropagation) { this.reverting = false; // We delay all events that have to be triggered to after the point where the placeholder has been removed and // everything else normalized again var delayedTriggers = []; // We first have to update the dom position of the actual currentItem // Note: don't do it if the current item is already removed (by a user), or it gets reappended (see #4088) if(!this._noFinalSort && this.currentItem.parent().length) this.placeholder.before(this.currentItem); this._noFinalSort = null; if(this.helper[0] == this.currentItem[0]) { for(var i in this._storedCSS) { if(this._storedCSS[i] == 'auto' || this._storedCSS[i] == 'static') this._storedCSS[i] = ''; } this.currentItem.css(this._storedCSS).removeClass("ui-sortable-helper"); } else { this.currentItem.show(); } if(this.fromOutside && !noPropagation) delayedTriggers.push(function(event) { this._trigger("receive", event, 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]) && !noPropagation) delayedTriggers.push(function(event) { this._trigger("update", event, this._uiHash()); }); //Trigger update callback if the DOM position has changed // Check if the items Container has Changed and trigger appropriate // events. if (this !== this.currentContainer) { if(!noPropagation) { delayedTriggers.push(function(event) { this._trigger("remove", event, this._uiHash()); }); delayedTriggers.push((function(c) { return function(event) { c._trigger("receive", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); delayedTriggers.push((function(c) { return function(event) { c._trigger("update", event, this._uiHash(this)); }; }).call(this, this.currentContainer)); } } //Post events to containers for (var i = this.containers.length - 1; i >= 0; i--){ if(!noPropagation) delayedTriggers.push((function(c) { return function(event) { c._trigger("deactivate", event, this._uiHash(this)); }; }).call(this, this.containers[i])); if(this.containers[i].containerCache.over) { delayedTriggers.push((function(c) { return function(event) { c._trigger("out", event, this._uiHash(this)); }; }).call(this, this.containers[i])); this.containers[i].containerCache.over = 0; } } //Do what was originally in plugins if(this._storedCursor) $('body').css("cursor", this._storedCursor); //Reset cursor if(this._storedOpacity) this.helper.css("opacity", this._storedOpacity); //Reset opacity if(this._storedZIndex) this.helper.css("zIndex", this._storedZIndex == 'auto' ? '' : this._storedZIndex); //Reset z-index this.dragging = false; if(this.cancelHelperRemoval) { if(!noPropagation) { this._trigger("beforeStop", event, this._uiHash()); for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events this._trigger("stop", event, this._uiHash()); } this.fromOutside = false; return false; } if(!noPropagation) this._trigger("beforeStop", event, this._uiHash()); //$(this.placeholder[0]).remove(); would have been the jQuery way - unfortunately, it unbinds ALL events from the original node! this.placeholder[0].parentNode.removeChild(this.placeholder[0]); if(this.helper[0] != this.currentItem[0]) this.helper.remove(); this.helper = null; if(!noPropagation) { for (var i=0; i < delayedTriggers.length; i++) { delayedTriggers[i].call(this, event); }; //Trigger all delayed events this._trigger("stop", event, this._uiHash()); } this.fromOutside = false; return true; }, _trigger: function() { if ($.Widget.prototype._trigger.apply(this, arguments) === false) { this.cancel(); } }, _uiHash: function(_inst) { var inst = _inst || this; return { helper: inst.helper, placeholder: inst.placeholder || $([]), position: inst.position, originalPosition: inst.originalPosition, offset: inst.positionAbs, item: inst.currentItem, sender: _inst ? _inst.element : null }; } }); })(jQuery); (function( $ ) { function modifier( fn ) { return function() { var previous = this.element.val(); fn.apply( this, arguments ); this._refresh(); if ( previous !== this.element.val() ) { this._trigger( "change" ); } }; } $.widget( "ui.spinner", { version: "1.9.2", defaultElement: "<input>", widgetEventPrefix: "spin", options: { culture: null, icons: { down: "ui-icon-triangle-1-s", up: "ui-icon-triangle-1-n" }, incremental: true, max: null, min: null, numberFormat: null, page: 10, step: 1, change: null, spin: null, start: null, stop: null }, _create: function() { // handle string values that need to be parsed this._setOption( "max", this.options.max ); this._setOption( "min", this.options.min ); this._setOption( "step", this.options.step ); // format the value, but don't constrain this._value( this.element.val(), true ); this._draw(); this._on( this._events ); this._refresh(); // turning off autocomplete prevents the browser from remembering the // value when navigating through history, so we re-enable autocomplete // if the page is unloaded before the widget is destroyed. #7790 this._on( this.window, { beforeunload: function() { this.element.removeAttr( "autocomplete" ); } }); }, _getCreateOptions: function() { var options = {}, element = this.element; $.each( [ "min", "max", "step" ], function( i, option ) { var value = element.attr( option ); if ( value !== undefined && value.length ) { options[ option ] = value; } }); return options; }, _events: { keydown: function( event ) { if ( this._start( event ) && this._keydown( event ) ) { event.preventDefault(); } }, keyup: "_stop", focus: function() { this.previous = this.element.val(); }, blur: function( event ) { if ( this.cancelBlur ) { delete this.cancelBlur; return; } this._refresh(); if ( this.previous !== this.element.val() ) { this._trigger( "change", event ); } }, mousewheel: function( event, delta ) { if ( !delta ) { return; } if ( !this.spinning && !this._start( event ) ) { return false; } this._spin( (delta > 0 ? 1 : -1) * this.options.step, event ); clearTimeout( this.mousewheelTimer ); this.mousewheelTimer = this._delay(function() { if ( this.spinning ) { this._stop( event ); } }, 100 ); event.preventDefault(); }, "mousedown .ui-spinner-button": function( event ) { var previous; // We never want the buttons to have focus; whenever the user is // interacting with the spinner, the focus should be on the input. // If the input is focused then this.previous is properly set from // when the input first received focus. If the input is not focused // then we need to set this.previous based on the value before spinning. previous = this.element[0] === this.document[0].activeElement ? this.previous : this.element.val(); function checkFocus() { var isActive = this.element[0] === this.document[0].activeElement; if ( !isActive ) { this.element.focus(); this.previous = previous; // support: IE // IE sets focus asynchronously, so we need to check if focus // moved off of the input because the user clicked on the button. this._delay(function() { this.previous = previous; }); } } // ensure focus is on (or stays on) the text field event.preventDefault(); checkFocus.call( this ); // support: IE // IE doesn't prevent moving focus even with event.preventDefault() // so we set a flag to know when we should ignore the blur event // and check (again) if focus moved off of the input. this.cancelBlur = true; this._delay(function() { delete this.cancelBlur; checkFocus.call( this ); }); if ( this._start( event ) === false ) { return; } this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); }, "mouseup .ui-spinner-button": "_stop", "mouseenter .ui-spinner-button": function( event ) { // button will add ui-state-active if mouse was down while mouseleave and kept down if ( !$( event.currentTarget ).hasClass( "ui-state-active" ) ) { return; } if ( this._start( event ) === false ) { return false; } this._repeat( null, $( event.currentTarget ).hasClass( "ui-spinner-up" ) ? 1 : -1, event ); }, // TODO: do we really want to consider this a stop? // shouldn't we just stop the repeater and wait until mouseup before // we trigger the stop event? "mouseleave .ui-spinner-button": "_stop" }, _draw: function() { var uiSpinner = this.uiSpinner = this.element .addClass( "ui-spinner-input" ) .attr( "autocomplete", "off" ) .wrap( this._uiSpinnerHtml() ) .parent() // add buttons .append( this._buttonHtml() ); this.element.attr( "role", "spinbutton" ); // button bindings this.buttons = uiSpinner.find( ".ui-spinner-button" ) .attr( "tabIndex", -1 ) .button() .removeClass( "ui-corner-all" ); // IE 6 doesn't understand height: 50% for the buttons // unless the wrapper has an explicit height if ( this.buttons.height() > Math.ceil( uiSpinner.height() * 0.5 ) && uiSpinner.height() > 0 ) { uiSpinner.height( uiSpinner.height() ); } // disable spinner if element was already disabled if ( this.options.disabled ) { this.disable(); } }, _keydown: function( event ) { var options = this.options, keyCode = $.ui.keyCode; switch ( event.keyCode ) { case keyCode.UP: this._repeat( null, 1, event ); return true; case keyCode.DOWN: this._repeat( null, -1, event ); return true; case keyCode.PAGE_UP: this._repeat( null, options.page, event ); return true; case keyCode.PAGE_DOWN: this._repeat( null, -options.page, event ); return true; } return false; }, _uiSpinnerHtml: function() { return "<span class='ui-spinner ui-widget ui-widget-content ui-corner-all'></span>"; }, _buttonHtml: function() { return "" + "<a class='ui-spinner-button ui-spinner-up ui-corner-tr'>" + "<span class='ui-icon " + this.options.icons.up + "'>&#9650;</span>" + "</a>" + "<a class='ui-spinner-button ui-spinner-down ui-corner-br'>" + "<span class='ui-icon " + this.options.icons.down + "'>&#9660;</span>" + "</a>"; }, _start: function( event ) { if ( !this.spinning && this._trigger( "start", event ) === false ) { return false; } if ( !this.counter ) { this.counter = 1; } this.spinning = true; return true; }, _repeat: function( i, steps, event ) { i = i || 500; clearTimeout( this.timer ); this.timer = this._delay(function() { this._repeat( 40, steps, event ); }, i ); this._spin( steps * this.options.step, event ); }, _spin: function( step, event ) { var value = this.value() || 0; if ( !this.counter ) { this.counter = 1; } value = this._adjustValue( value + step * this._increment( this.counter ) ); if ( !this.spinning || this._trigger( "spin", event, { value: value } ) !== false) { this._value( value ); this.counter++; } }, _increment: function( i ) { var incremental = this.options.incremental; if ( incremental ) { return $.isFunction( incremental ) ? incremental( i ) : Math.floor( i*i*i/50000 - i*i/500 + 17*i/200 + 1 ); } return 1; }, _precision: function() { var precision = this._precisionOf( this.options.step ); if ( this.options.min !== null ) { precision = Math.max( precision, this._precisionOf( this.options.min ) ); } return precision; }, _precisionOf: function( num ) { var str = num.toString(), decimal = str.indexOf( "." ); return decimal === -1 ? 0 : str.length - decimal - 1; }, _adjustValue: function( value ) { var base, aboveMin, options = this.options; // make sure we're at a valid step // - find out where we are relative to the base (min or 0) base = options.min !== null ? options.min : 0; aboveMin = value - base; // - round to the nearest step aboveMin = Math.round(aboveMin / options.step) * options.step; // - rounding is based on 0, so adjust back to our base value = base + aboveMin; // fix precision from bad JS floating point math value = parseFloat( value.toFixed( this._precision() ) ); // clamp the value if ( options.max !== null && value > options.max) { return options.max; } if ( options.min !== null && value < options.min ) { return options.min; } return value; }, _stop: function( event ) { if ( !this.spinning ) { return; } clearTimeout( this.timer ); clearTimeout( this.mousewheelTimer ); this.counter = 0; this.spinning = false; this._trigger( "stop", event ); }, _setOption: function( key, value ) { if ( key === "culture" || key === "numberFormat" ) { var prevValue = this._parse( this.element.val() ); this.options[ key ] = value; this.element.val( this._format( prevValue ) ); return; } if ( key === "max" || key === "min" || key === "step" ) { if ( typeof value === "string" ) { value = this._parse( value ); } } this._super( key, value ); if ( key === "disabled" ) { if ( value ) { this.element.prop( "disabled", true ); this.buttons.button( "disable" ); } else { this.element.prop( "disabled", false ); this.buttons.button( "enable" ); } } }, _setOptions: modifier(function( options ) { this._super( options ); this._value( this.element.val() ); }), _parse: function( val ) { if ( typeof val === "string" && val !== "" ) { val = window.Globalize && this.options.numberFormat ? Globalize.parseFloat( val, 10, this.options.culture ) : +val; } return val === "" || isNaN( val ) ? null : val; }, _format: function( value ) { if ( value === "" ) { return ""; } return window.Globalize && this.options.numberFormat ? Globalize.format( value, this.options.numberFormat, this.options.culture ) : value; }, _refresh: function() { this.element.attr({ "aria-valuemin": this.options.min, "aria-valuemax": this.options.max, // TODO: what should we do with values that can't be parsed? "aria-valuenow": this._parse( this.element.val() ) }); }, // update the value without triggering change _value: function( value, allowAny ) { var parsed; if ( value !== "" ) { parsed = this._parse( value ); if ( parsed !== null ) { if ( !allowAny ) { parsed = this._adjustValue( parsed ); } value = this._format( parsed ); } } this.element.val( value ); this._refresh(); }, _destroy: function() { this.element .removeClass( "ui-spinner-input" ) .prop( "disabled", false ) .removeAttr( "autocomplete" ) .removeAttr( "role" ) .removeAttr( "aria-valuemin" ) .removeAttr( "aria-valuemax" ) .removeAttr( "aria-valuenow" ); this.uiSpinner.replaceWith( this.element ); }, stepUp: modifier(function( steps ) { this._stepUp( steps ); }), _stepUp: function( steps ) { this._spin( (steps || 1) * this.options.step ); }, stepDown: modifier(function( steps ) { this._stepDown( steps ); }), _stepDown: function( steps ) { this._spin( (steps || 1) * -this.options.step ); }, pageUp: modifier(function( pages ) { this._stepUp( (pages || 1) * this.options.page ); }), pageDown: modifier(function( pages ) { this._stepDown( (pages || 1) * this.options.page ); }), value: function( newVal ) { if ( !arguments.length ) { return this._parse( this.element.val() ); } modifier( this._value ).call( this, newVal ); }, widget: function() { return this.uiSpinner; } }); }( jQuery ) ); (function( $, undefined ) { var tabId = 0, rhash = /#.*$/; function getNextTabId() { return ++tabId; } function isLocal( anchor ) { return anchor.hash.length > 1 && anchor.href.replace( rhash, "" ) === location.href.replace( rhash, "" ) // support: Safari 5.1 // Safari 5.1 doesn't encode spaces in window.location // but it does encode spaces from anchors (#8777) .replace( /\s/g, "%20" ); } $.widget( "ui.tabs", { version: "1.9.2", delay: 300, options: { active: null, collapsible: false, event: "click", heightStyle: "content", hide: null, show: null, // callbacks activate: null, beforeActivate: null, beforeLoad: null, load: null }, _create: function() { var that = this, options = this.options, active = options.active, locationHash = location.hash.substring( 1 ); this.running = false; this.element .addClass( "ui-tabs ui-widget ui-widget-content ui-corner-all" ) .toggleClass( "ui-tabs-collapsible", options.collapsible ) // Prevent users from focusing disabled tabs via click .delegate( ".ui-tabs-nav > li", "mousedown" + this.eventNamespace, function( event ) { if ( $( this ).is( ".ui-state-disabled" ) ) { event.preventDefault(); } }) // support: IE <9 // Preventing the default action in mousedown doesn't prevent IE // from focusing the element, so if the anchor gets focused, blur. // We don't have to worry about focusing the previously focused // element since clicking on a non-focusable element should focus // the body anyway. .delegate( ".ui-tabs-anchor", "focus" + this.eventNamespace, function() { if ( $( this ).closest( "li" ).is( ".ui-state-disabled" ) ) { this.blur(); } }); this._processTabs(); if ( active === null ) { // check the fragment identifier in the URL if ( locationHash ) { this.tabs.each(function( i, tab ) { if ( $( tab ).attr( "aria-controls" ) === locationHash ) { active = i; return false; } }); } // check for a tab marked active via a class if ( active === null ) { active = this.tabs.index( this.tabs.filter( ".ui-tabs-active" ) ); } // no active tab, set to false if ( active === null || active === -1 ) { active = this.tabs.length ? 0 : false; } } // handle numbers: negative, out of range if ( active !== false ) { active = this.tabs.index( this.tabs.eq( active ) ); if ( active === -1 ) { active = options.collapsible ? false : 0; } } options.active = active; // don't allow collapsible: false and active: false if ( !options.collapsible && options.active === false && this.anchors.length ) { options.active = 0; } // Take disabling tabs via class attribute from HTML // into account and update option properly. if ( $.isArray( options.disabled ) ) { options.disabled = $.unique( options.disabled.concat( $.map( this.tabs.filter( ".ui-state-disabled" ), function( li ) { return that.tabs.index( li ); }) ) ).sort(); } // check for length avoids error when initializing empty list if ( this.options.active !== false && this.anchors.length ) { this.active = this._findActive( this.options.active ); } else { this.active = $(); } this._refresh(); if ( this.active.length ) { this.load( options.active ); } }, _getCreateEventData: function() { return { tab: this.active, panel: !this.active.length ? $() : this._getPanelForTab( this.active ) }; }, _tabKeydown: function( event ) { var focusedTab = $( this.document[0].activeElement ).closest( "li" ), selectedIndex = this.tabs.index( focusedTab ), goingForward = true; if ( this._handlePageNav( event ) ) { return; } switch ( event.keyCode ) { case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: selectedIndex++; break; case $.ui.keyCode.UP: case $.ui.keyCode.LEFT: goingForward = false; selectedIndex--; break; case $.ui.keyCode.END: selectedIndex = this.anchors.length - 1; break; case $.ui.keyCode.HOME: selectedIndex = 0; break; case $.ui.keyCode.SPACE: // Activate only, no collapsing event.preventDefault(); clearTimeout( this.activating ); this._activate( selectedIndex ); return; case $.ui.keyCode.ENTER: // Toggle (cancel delayed activation, allow collapsing) event.preventDefault(); clearTimeout( this.activating ); // Determine if we should collapse or activate this._activate( selectedIndex === this.options.active ? false : selectedIndex ); return; default: return; } // Focus the appropriate tab, based on which key was pressed event.preventDefault(); clearTimeout( this.activating ); selectedIndex = this._focusNextTab( selectedIndex, goingForward ); // Navigating with control key will prevent automatic activation if ( !event.ctrlKey ) { // Update aria-selected immediately so that AT think the tab is already selected. // Otherwise AT may confuse the user by stating that they need to activate the tab, // but the tab will already be activated by the time the announcement finishes. focusedTab.attr( "aria-selected", "false" ); this.tabs.eq( selectedIndex ).attr( "aria-selected", "true" ); this.activating = this._delay(function() { this.option( "active", selectedIndex ); }, this.delay ); } }, _panelKeydown: function( event ) { if ( this._handlePageNav( event ) ) { return; } // Ctrl+up moves focus to the current tab if ( event.ctrlKey && event.keyCode === $.ui.keyCode.UP ) { event.preventDefault(); this.active.focus(); } }, // Alt+page up/down moves focus to the previous/next tab (and activates) _handlePageNav: function( event ) { if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_UP ) { this._activate( this._focusNextTab( this.options.active - 1, false ) ); return true; } if ( event.altKey && event.keyCode === $.ui.keyCode.PAGE_DOWN ) { this._activate( this._focusNextTab( this.options.active + 1, true ) ); return true; } }, _findNextTab: function( index, goingForward ) { var lastTabIndex = this.tabs.length - 1; function constrain() { if ( index > lastTabIndex ) { index = 0; } if ( index < 0 ) { index = lastTabIndex; } return index; } while ( $.inArray( constrain(), this.options.disabled ) !== -1 ) { index = goingForward ? index + 1 : index - 1; } return index; }, _focusNextTab: function( index, goingForward ) { index = this._findNextTab( index, goingForward ); this.tabs.eq( index ).focus(); return index; }, _setOption: function( key, value ) { if ( key === "active" ) { // _activate() will handle invalid values and update this.options this._activate( value ); return; } if ( key === "disabled" ) { // don't use the widget factory's disabled handling this._setupDisabled( value ); return; } this._super( key, value); if ( key === "collapsible" ) { this.element.toggleClass( "ui-tabs-collapsible", value ); // Setting collapsible: false while collapsed; open first panel if ( !value && this.options.active === false ) { this._activate( 0 ); } } if ( key === "event" ) { this._setupEvents( value ); } if ( key === "heightStyle" ) { this._setupHeightStyle( value ); } }, _tabId: function( tab ) { return tab.attr( "aria-controls" ) || "ui-tabs-" + getNextTabId(); }, _sanitizeSelector: function( hash ) { return hash ? hash.replace( /[!"$%&'()*+,.\/:;<=>?@\[\]\^`{|}~]/g, "\\$&" ) : ""; }, refresh: function() { var options = this.options, lis = this.tablist.children( ":has(a[href])" ); // get disabled tabs from class attribute from HTML // this will get converted to a boolean if needed in _refresh() options.disabled = $.map( lis.filter( ".ui-state-disabled" ), function( tab ) { return lis.index( tab ); }); this._processTabs(); // was collapsed or no tabs if ( options.active === false || !this.anchors.length ) { options.active = false; this.active = $(); // was active, but active tab is gone } else if ( this.active.length && !$.contains( this.tablist[ 0 ], this.active[ 0 ] ) ) { // all remaining tabs are disabled if ( this.tabs.length === options.disabled.length ) { options.active = false; this.active = $(); // activate previous tab } else { this._activate( this._findNextTab( Math.max( 0, options.active - 1 ), false ) ); } // was active, active tab still exists } else { // make sure active index is correct options.active = this.tabs.index( this.active ); } this._refresh(); }, _refresh: function() { this._setupDisabled( this.options.disabled ); this._setupEvents( this.options.event ); this._setupHeightStyle( this.options.heightStyle ); this.tabs.not( this.active ).attr({ "aria-selected": "false", tabIndex: -1 }); this.panels.not( this._getPanelForTab( this.active ) ) .hide() .attr({ "aria-expanded": "false", "aria-hidden": "true" }); // Make sure one tab is in the tab order if ( !this.active.length ) { this.tabs.eq( 0 ).attr( "tabIndex", 0 ); } else { this.active .addClass( "ui-tabs-active ui-state-active" ) .attr({ "aria-selected": "true", tabIndex: 0 }); this._getPanelForTab( this.active ) .show() .attr({ "aria-expanded": "true", "aria-hidden": "false" }); } }, _processTabs: function() { var that = this; this.tablist = this._getList() .addClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .attr( "role", "tablist" ); this.tabs = this.tablist.find( "> li:has(a[href])" ) .addClass( "ui-state-default ui-corner-top" ) .attr({ role: "tab", tabIndex: -1 }); this.anchors = this.tabs.map(function() { return $( "a", this )[ 0 ]; }) .addClass( "ui-tabs-anchor" ) .attr({ role: "presentation", tabIndex: -1 }); this.panels = $(); this.anchors.each(function( i, anchor ) { var selector, panel, panelId, anchorId = $( anchor ).uniqueId().attr( "id" ), tab = $( anchor ).closest( "li" ), originalAriaControls = tab.attr( "aria-controls" ); // inline tab if ( isLocal( anchor ) ) { selector = anchor.hash; panel = that.element.find( that._sanitizeSelector( selector ) ); // remote tab } else { panelId = that._tabId( tab ); selector = "#" + panelId; panel = that.element.find( selector ); if ( !panel.length ) { panel = that._createPanel( panelId ); panel.insertAfter( that.panels[ i - 1 ] || that.tablist ); } panel.attr( "aria-live", "polite" ); } if ( panel.length) { that.panels = that.panels.add( panel ); } if ( originalAriaControls ) { tab.data( "ui-tabs-aria-controls", originalAriaControls ); } tab.attr({ "aria-controls": selector.substring( 1 ), "aria-labelledby": anchorId }); panel.attr( "aria-labelledby", anchorId ); }); this.panels .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .attr( "role", "tabpanel" ); }, // allow overriding how to find the list for rare usage scenarios (#7715) _getList: function() { return this.element.find( "ol,ul" ).eq( 0 ); }, _createPanel: function( id ) { return $( "<div>" ) .attr( "id", id ) .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .data( "ui-tabs-destroy", true ); }, _setupDisabled: function( disabled ) { if ( $.isArray( disabled ) ) { if ( !disabled.length ) { disabled = false; } else if ( disabled.length === this.anchors.length ) { disabled = true; } } // disable tabs for ( var i = 0, li; ( li = this.tabs[ i ] ); i++ ) { if ( disabled === true || $.inArray( i, disabled ) !== -1 ) { $( li ) .addClass( "ui-state-disabled" ) .attr( "aria-disabled", "true" ); } else { $( li ) .removeClass( "ui-state-disabled" ) .removeAttr( "aria-disabled" ); } } this.options.disabled = disabled; }, _setupEvents: function( event ) { var events = { click: function( event ) { event.preventDefault(); } }; if ( event ) { $.each( event.split(" "), function( index, eventName ) { events[ eventName ] = "_eventHandler"; }); } this._off( this.anchors.add( this.tabs ).add( this.panels ) ); this._on( this.anchors, events ); this._on( this.tabs, { keydown: "_tabKeydown" } ); this._on( this.panels, { keydown: "_panelKeydown" } ); this._focusable( this.tabs ); this._hoverable( this.tabs ); }, _setupHeightStyle: function( heightStyle ) { var maxHeight, overflow, parent = this.element.parent(); if ( heightStyle === "fill" ) { // IE 6 treats height like minHeight, so we need to turn off overflow // in order to get a reliable height // we use the minHeight support test because we assume that only // browsers that don't support minHeight will treat height as minHeight if ( !$.support.minHeight ) { overflow = parent.css( "overflow" ); parent.css( "overflow", "hidden"); } maxHeight = parent.height(); this.element.siblings( ":visible" ).each(function() { var elem = $( this ), position = elem.css( "position" ); if ( position === "absolute" || position === "fixed" ) { return; } maxHeight -= elem.outerHeight( true ); }); if ( overflow ) { parent.css( "overflow", overflow ); } this.element.children().not( this.panels ).each(function() { maxHeight -= $( this ).outerHeight( true ); }); this.panels.each(function() { $( this ).height( Math.max( 0, maxHeight - $( this ).innerHeight() + $( this ).height() ) ); }) .css( "overflow", "auto" ); } else if ( heightStyle === "auto" ) { maxHeight = 0; this.panels.each(function() { maxHeight = Math.max( maxHeight, $( this ).height( "" ).height() ); }).height( maxHeight ); } }, _eventHandler: function( event ) { var options = this.options, active = this.active, anchor = $( event.currentTarget ), tab = anchor.closest( "li" ), clickedIsActive = tab[ 0 ] === active[ 0 ], collapsing = clickedIsActive && options.collapsible, toShow = collapsing ? $() : this._getPanelForTab( tab ), toHide = !active.length ? $() : this._getPanelForTab( active ), eventData = { oldTab: active, oldPanel: toHide, newTab: collapsing ? $() : tab, newPanel: toShow }; event.preventDefault(); if ( tab.hasClass( "ui-state-disabled" ) || // tab is already loading tab.hasClass( "ui-tabs-loading" ) || // can't switch durning an animation this.running || // click on active header, but not collapsible ( clickedIsActive && !options.collapsible ) || // allow canceling activation ( this._trigger( "beforeActivate", event, eventData ) === false ) ) { return; } options.active = collapsing ? false : this.tabs.index( tab ); this.active = clickedIsActive ? $() : tab; if ( this.xhr ) { this.xhr.abort(); } if ( !toHide.length && !toShow.length ) { $.error( "jQuery UI Tabs: Mismatching fragment identifier." ); } if ( toShow.length ) { this.load( this.tabs.index( tab ), event ); } this._toggle( event, eventData ); }, // handles show/hide for selecting tabs _toggle: function( event, eventData ) { var that = this, toShow = eventData.newPanel, toHide = eventData.oldPanel; this.running = true; function complete() { that.running = false; that._trigger( "activate", event, eventData ); } function show() { eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" ); if ( toShow.length && that.options.show ) { that._show( toShow, that.options.show, complete ); } else { toShow.show(); complete(); } } // start out by hiding, then showing, then completing if ( toHide.length && this.options.hide ) { this._hide( toHide, this.options.hide, function() { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); show(); }); } else { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); toHide.hide(); show(); } toHide.attr({ "aria-expanded": "false", "aria-hidden": "true" }); eventData.oldTab.attr( "aria-selected", "false" ); // If we're switching tabs, remove the old tab from the tab order. // If we're opening from collapsed state, remove the previous tab from the tab order. // If we're collapsing, then keep the collapsing tab in the tab order. if ( toShow.length && toHide.length ) { eventData.oldTab.attr( "tabIndex", -1 ); } else if ( toShow.length ) { this.tabs.filter(function() { return $( this ).attr( "tabIndex" ) === 0; }) .attr( "tabIndex", -1 ); } toShow.attr({ "aria-expanded": "true", "aria-hidden": "false" }); eventData.newTab.attr({ "aria-selected": "true", tabIndex: 0 }); }, _activate: function( index ) { var anchor, active = this._findActive( index ); // trying to activate the already active panel if ( active[ 0 ] === this.active[ 0 ] ) { return; } // trying to collapse, simulate a click on the current active header if ( !active.length ) { active = this.active; } anchor = active.find( ".ui-tabs-anchor" )[ 0 ]; this._eventHandler({ target: anchor, currentTarget: anchor, preventDefault: $.noop }); }, _findActive: function( index ) { return index === false ? $() : this.tabs.eq( index ); }, _getIndex: function( index ) { // meta-function to give users option to provide a href string instead of a numerical index. if ( typeof index === "string" ) { index = this.anchors.index( this.anchors.filter( "[href$='" + index + "']" ) ); } return index; }, _destroy: function() { if ( this.xhr ) { this.xhr.abort(); } this.element.removeClass( "ui-tabs ui-widget ui-widget-content ui-corner-all ui-tabs-collapsible" ); this.tablist .removeClass( "ui-tabs-nav ui-helper-reset ui-helper-clearfix ui-widget-header ui-corner-all" ) .removeAttr( "role" ); this.anchors .removeClass( "ui-tabs-anchor" ) .removeAttr( "role" ) .removeAttr( "tabIndex" ) .removeData( "href.tabs" ) .removeData( "load.tabs" ) .removeUniqueId(); this.tabs.add( this.panels ).each(function() { if ( $.data( this, "ui-tabs-destroy" ) ) { $( this ).remove(); } else { $( this ) .removeClass( "ui-state-default ui-state-active ui-state-disabled " + "ui-corner-top ui-corner-bottom ui-widget-content ui-tabs-active ui-tabs-panel" ) .removeAttr( "tabIndex" ) .removeAttr( "aria-live" ) .removeAttr( "aria-busy" ) .removeAttr( "aria-selected" ) .removeAttr( "aria-labelledby" ) .removeAttr( "aria-hidden" ) .removeAttr( "aria-expanded" ) .removeAttr( "role" ); } }); this.tabs.each(function() { var li = $( this ), prev = li.data( "ui-tabs-aria-controls" ); if ( prev ) { li.attr( "aria-controls", prev ); } else { li.removeAttr( "aria-controls" ); } }); this.panels.show(); if ( this.options.heightStyle !== "content" ) { this.panels.css( "height", "" ); } }, enable: function( index ) { var disabled = this.options.disabled; if ( disabled === false ) { return; } if ( index === undefined ) { disabled = false; } else { index = this._getIndex( index ); if ( $.isArray( disabled ) ) { disabled = $.map( disabled, function( num ) { return num !== index ? num : null; }); } else { disabled = $.map( this.tabs, function( li, num ) { return num !== index ? num : null; }); } } this._setupDisabled( disabled ); }, disable: function( index ) { var disabled = this.options.disabled; if ( disabled === true ) { return; } if ( index === undefined ) { disabled = true; } else { index = this._getIndex( index ); if ( $.inArray( index, disabled ) !== -1 ) { return; } if ( $.isArray( disabled ) ) { disabled = $.merge( [ index ], disabled ).sort(); } else { disabled = [ index ]; } } this._setupDisabled( disabled ); }, load: function( index, event ) { index = this._getIndex( index ); var that = this, tab = this.tabs.eq( index ), anchor = tab.find( ".ui-tabs-anchor" ), panel = this._getPanelForTab( tab ), eventData = { tab: tab, panel: panel }; // not remote if ( isLocal( anchor[ 0 ] ) ) { return; } this.xhr = $.ajax( this._ajaxSettings( anchor, event, eventData ) ); // support: jQuery <1.8 // jQuery <1.8 returns false if the request is canceled in beforeSend, // but as of 1.8, $.ajax() always returns a jqXHR object. if ( this.xhr && this.xhr.statusText !== "canceled" ) { tab.addClass( "ui-tabs-loading" ); panel.attr( "aria-busy", "true" ); this.xhr .success(function( response ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { panel.html( response ); that._trigger( "load", event, eventData ); }, 1 ); }) .complete(function( jqXHR, status ) { // support: jQuery <1.8 // http://bugs.jquery.com/ticket/11778 setTimeout(function() { if ( status === "abort" ) { that.panels.stop( false, true ); } tab.removeClass( "ui-tabs-loading" ); panel.removeAttr( "aria-busy" ); if ( jqXHR === that.xhr ) { delete that.xhr; } }, 1 ); }); } }, // TODO: Remove this function in 1.10 when ajaxOptions is removed _ajaxSettings: function( anchor, event, eventData ) { var that = this; return { url: anchor.attr( "href" ), beforeSend: function( jqXHR, settings ) { return that._trigger( "beforeLoad", event, $.extend( { jqXHR : jqXHR, ajaxSettings: settings }, eventData ) ); } }; }, _getPanelForTab: function( tab ) { var id = $( tab ).attr( "aria-controls" ); return this.element.find( this._sanitizeSelector( "#" + id ) ); } }); // DEPRECATED if ( $.uiBackCompat !== false ) { // helper method for a lot of the back compat extensions $.ui.tabs.prototype._ui = function( tab, panel ) { return { tab: tab, panel: panel, index: this.anchors.index( tab ) }; }; // url method $.widget( "ui.tabs", $.ui.tabs, { url: function( index, url ) { this.anchors.eq( index ).attr( "href", url ); } }); // TODO: Remove _ajaxSettings() method when removing this extension // ajaxOptions and cache options $.widget( "ui.tabs", $.ui.tabs, { options: { ajaxOptions: null, cache: false }, _create: function() { this._super(); var that = this; this._on({ tabsbeforeload: function( event, ui ) { // tab is already cached if ( $.data( ui.tab[ 0 ], "cache.tabs" ) ) { event.preventDefault(); return; } ui.jqXHR.success(function() { if ( that.options.cache ) { $.data( ui.tab[ 0 ], "cache.tabs", true ); } }); }}); }, _ajaxSettings: function( anchor, event, ui ) { var ajaxOptions = this.options.ajaxOptions; return $.extend( {}, ajaxOptions, { error: function( xhr, status ) { try { // Passing index avoid a race condition when this method is // called after the user has selected another tab. // Pass the anchor that initiated this request allows // loadError to manipulate the tab content panel via $(a.hash) ajaxOptions.error( xhr, status, ui.tab.closest( "li" ).index(), ui.tab[ 0 ] ); } catch ( error ) {} } }, this._superApply( arguments ) ); }, _setOption: function( key, value ) { // reset cache if switching from cached to not cached if ( key === "cache" && value === false ) { this.anchors.removeData( "cache.tabs" ); } this._super( key, value ); }, _destroy: function() { this.anchors.removeData( "cache.tabs" ); this._super(); }, url: function( index ){ this.anchors.eq( index ).removeData( "cache.tabs" ); this._superApply( arguments ); } }); // abort method $.widget( "ui.tabs", $.ui.tabs, { abort: function() { if ( this.xhr ) { this.xhr.abort(); } } }); // spinner $.widget( "ui.tabs", $.ui.tabs, { options: { spinner: "<em>Loading&#8230;</em>" }, _create: function() { this._super(); this._on({ tabsbeforeload: function( event, ui ) { // Don't react to nested tabs or tabs that don't use a spinner if ( event.target !== this.element[ 0 ] || !this.options.spinner ) { return; } var span = ui.tab.find( "span" ), html = span.html(); span.html( this.options.spinner ); ui.jqXHR.complete(function() { span.html( html ); }); } }); } }); // enable/disable events $.widget( "ui.tabs", $.ui.tabs, { options: { enable: null, disable: null }, enable: function( index ) { var options = this.options, trigger; if ( index && options.disabled === true || ( $.isArray( options.disabled ) && $.inArray( index, options.disabled ) !== -1 ) ) { trigger = true; } this._superApply( arguments ); if ( trigger ) { this._trigger( "enable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); } }, disable: function( index ) { var options = this.options, trigger; if ( index && options.disabled === false || ( $.isArray( options.disabled ) && $.inArray( index, options.disabled ) === -1 ) ) { trigger = true; } this._superApply( arguments ); if ( trigger ) { this._trigger( "disable", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); } } }); // add/remove methods and events $.widget( "ui.tabs", $.ui.tabs, { options: { add: null, remove: null, tabTemplate: "<li><a href='#{href}'><span>#{label}</span></a></li>" }, add: function( url, label, index ) { if ( index === undefined ) { index = this.anchors.length; } var doInsertAfter, panel, options = this.options, li = $( options.tabTemplate .replace( /#\{href\}/g, url ) .replace( /#\{label\}/g, label ) ), id = !url.indexOf( "#" ) ? url.replace( "#", "" ) : this._tabId( li ); li.addClass( "ui-state-default ui-corner-top" ).data( "ui-tabs-destroy", true ); li.attr( "aria-controls", id ); doInsertAfter = index >= this.tabs.length; // try to find an existing element before creating a new one panel = this.element.find( "#" + id ); if ( !panel.length ) { panel = this._createPanel( id ); if ( doInsertAfter ) { if ( index > 0 ) { panel.insertAfter( this.panels.eq( -1 ) ); } else { panel.appendTo( this.element ); } } else { panel.insertBefore( this.panels[ index ] ); } } panel.addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ).hide(); if ( doInsertAfter ) { li.appendTo( this.tablist ); } else { li.insertBefore( this.tabs[ index ] ); } options.disabled = $.map( options.disabled, function( n ) { return n >= index ? ++n : n; }); this.refresh(); if ( this.tabs.length === 1 && options.active === false ) { this.option( "active", 0 ); } this._trigger( "add", null, this._ui( this.anchors[ index ], this.panels[ index ] ) ); return this; }, remove: function( index ) { index = this._getIndex( index ); var options = this.options, tab = this.tabs.eq( index ).remove(), panel = this._getPanelForTab( tab ).remove(); // If selected tab was removed focus tab to the right or // in case the last tab was removed the tab to the left. // We check for more than 2 tabs, because if there are only 2, // then when we remove this tab, there will only be one tab left // so we don't need to detect which tab to activate. if ( tab.hasClass( "ui-tabs-active" ) && this.anchors.length > 2 ) { this._activate( index + ( index + 1 < this.anchors.length ? 1 : -1 ) ); } options.disabled = $.map( $.grep( options.disabled, function( n ) { return n !== index; }), function( n ) { return n >= index ? --n : n; }); this.refresh(); this._trigger( "remove", null, this._ui( tab.find( "a" )[ 0 ], panel[ 0 ] ) ); return this; } }); // length method $.widget( "ui.tabs", $.ui.tabs, { length: function() { return this.anchors.length; } }); // panel ids (idPrefix option + title attribute) $.widget( "ui.tabs", $.ui.tabs, { options: { idPrefix: "ui-tabs-" }, _tabId: function( tab ) { var a = tab.is( "li" ) ? tab.find( "a[href]" ) : tab; a = a[0]; return $( a ).closest( "li" ).attr( "aria-controls" ) || a.title && a.title.replace( /\s/g, "_" ).replace( /[^\w\u00c0-\uFFFF\-]/g, "" ) || this.options.idPrefix + getNextTabId(); } }); // _createPanel method $.widget( "ui.tabs", $.ui.tabs, { options: { panelTemplate: "<div></div>" }, _createPanel: function( id ) { return $( this.options.panelTemplate ) .attr( "id", id ) .addClass( "ui-tabs-panel ui-widget-content ui-corner-bottom" ) .data( "ui-tabs-destroy", true ); } }); // selected option $.widget( "ui.tabs", $.ui.tabs, { _create: function() { var options = this.options; if ( options.active === null && options.selected !== undefined ) { options.active = options.selected === -1 ? false : options.selected; } this._super(); options.selected = options.active; if ( options.selected === false ) { options.selected = -1; } }, _setOption: function( key, value ) { if ( key !== "selected" ) { return this._super( key, value ); } var options = this.options; this._super( "active", value === -1 ? false : value ); options.selected = options.active; if ( options.selected === false ) { options.selected = -1; } }, _eventHandler: function() { this._superApply( arguments ); this.options.selected = this.options.active; if ( this.options.selected === false ) { this.options.selected = -1; } } }); // show and select event $.widget( "ui.tabs", $.ui.tabs, { options: { show: null, select: null }, _create: function() { this._super(); if ( this.options.active !== false ) { this._trigger( "show", null, this._ui( this.active.find( ".ui-tabs-anchor" )[ 0 ], this._getPanelForTab( this.active )[ 0 ] ) ); } }, _trigger: function( type, event, data ) { var tab, panel, ret = this._superApply( arguments ); if ( !ret ) { return false; } if ( type === "beforeActivate" ) { tab = data.newTab.length ? data.newTab : data.oldTab; panel = data.newPanel.length ? data.newPanel : data.oldPanel; ret = this._super( "select", event, { tab: tab.find( ".ui-tabs-anchor" )[ 0], panel: panel[ 0 ], index: tab.closest( "li" ).index() }); } else if ( type === "activate" && data.newTab.length ) { ret = this._super( "show", event, { tab: data.newTab.find( ".ui-tabs-anchor" )[ 0 ], panel: data.newPanel[ 0 ], index: data.newTab.closest( "li" ).index() }); } return ret; } }); // select method $.widget( "ui.tabs", $.ui.tabs, { select: function( index ) { index = this._getIndex( index ); if ( index === -1 ) { if ( this.options.collapsible && this.options.selected !== -1 ) { index = this.options.selected; } else { return; } } this.anchors.eq( index ).trigger( this.options.event + this.eventNamespace ); } }); // cookie option (function() { var listId = 0; $.widget( "ui.tabs", $.ui.tabs, { options: { cookie: null // e.g. { expires: 7, path: '/', domain: 'jquery.com', secure: true } }, _create: function() { var options = this.options, active; if ( options.active == null && options.cookie ) { active = parseInt( this._cookie(), 10 ); if ( active === -1 ) { active = false; } options.active = active; } this._super(); }, _cookie: function( active ) { var cookie = [ this.cookie || ( this.cookie = this.options.cookie.name || "ui-tabs-" + (++listId) ) ]; if ( arguments.length ) { cookie.push( active === false ? -1 : active ); cookie.push( this.options.cookie ); } return $.cookie.apply( null, cookie ); }, _refresh: function() { this._super(); if ( this.options.cookie ) { this._cookie( this.options.active, this.options.cookie ); } }, _eventHandler: function() { this._superApply( arguments ); if ( this.options.cookie ) { this._cookie( this.options.active, this.options.cookie ); } }, _destroy: function() { this._super(); if ( this.options.cookie ) { this._cookie( null, this.options.cookie ); } } }); })(); // load event $.widget( "ui.tabs", $.ui.tabs, { _trigger: function( type, event, data ) { var _data = $.extend( {}, data ); if ( type === "load" ) { _data.panel = _data.panel[ 0 ]; _data.tab = _data.tab.find( ".ui-tabs-anchor" )[ 0 ]; } return this._super( type, event, _data ); } }); // fx option // The new animation options (show, hide) conflict with the old show callback. // The old fx option wins over show/hide anyway (always favor back-compat). // If a user wants to use the new animation API, they must give up the old API. $.widget( "ui.tabs", $.ui.tabs, { options: { fx: null // e.g. { height: "toggle", opacity: "toggle", duration: 200 } }, _getFx: function() { var hide, show, fx = this.options.fx; if ( fx ) { if ( $.isArray( fx ) ) { hide = fx[ 0 ]; show = fx[ 1 ]; } else { hide = show = fx; } } return fx ? { show: show, hide: hide } : null; }, _toggle: function( event, eventData ) { var that = this, toShow = eventData.newPanel, toHide = eventData.oldPanel, fx = this._getFx(); if ( !fx ) { return this._super( event, eventData ); } that.running = true; function complete() { that.running = false; that._trigger( "activate", event, eventData ); } function show() { eventData.newTab.closest( "li" ).addClass( "ui-tabs-active ui-state-active" ); if ( toShow.length && fx.show ) { toShow .animate( fx.show, fx.show.duration, function() { complete(); }); } else { toShow.show(); complete(); } } // start out by hiding, then showing, then completing if ( toHide.length && fx.hide ) { toHide.animate( fx.hide, fx.hide.duration, function() { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); show(); }); } else { eventData.oldTab.closest( "li" ).removeClass( "ui-tabs-active ui-state-active" ); toHide.hide(); show(); } } }); } })( jQuery ); (function( $ ) { var increments = 0; function addDescribedBy( elem, id ) { var describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ); describedby.push( id ); elem .data( "ui-tooltip-id", id ) .attr( "aria-describedby", $.trim( describedby.join( " " ) ) ); } function removeDescribedBy( elem ) { var id = elem.data( "ui-tooltip-id" ), describedby = (elem.attr( "aria-describedby" ) || "").split( /\s+/ ), index = $.inArray( id, describedby ); if ( index !== -1 ) { describedby.splice( index, 1 ); } elem.removeData( "ui-tooltip-id" ); describedby = $.trim( describedby.join( " " ) ); if ( describedby ) { elem.attr( "aria-describedby", describedby ); } else { elem.removeAttr( "aria-describedby" ); } } $.widget( "ui.tooltip", { version: "1.9.2", options: { content: function() { return $( this ).attr( "title" ); }, hide: true, // Disabled elements have inconsistent behavior across browsers (#8661) items: "[title]:not([disabled])", position: { my: "left top+15", at: "left bottom", collision: "flipfit flip" }, show: true, tooltipClass: null, track: false, // callbacks close: null, open: null }, _create: function() { this._on({ mouseover: "open", focusin: "open" }); // IDs of generated tooltips, needed for destroy this.tooltips = {}; // IDs of parent tooltips where we removed the title attribute this.parents = {}; if ( this.options.disabled ) { this._disable(); } }, _setOption: function( key, value ) { var that = this; if ( key === "disabled" ) { this[ value ? "_disable" : "_enable" ](); this.options[ key ] = value; // disable element style changes return; } this._super( key, value ); if ( key === "content" ) { $.each( this.tooltips, function( id, element ) { that._updateContent( element ); }); } }, _disable: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, element ) { var event = $.Event( "blur" ); event.target = event.currentTarget = element[0]; that.close( event, true ); }); // remove title attributes to prevent native tooltips this.element.find( this.options.items ).andSelf().each(function() { var element = $( this ); if ( element.is( "[title]" ) ) { element .data( "ui-tooltip-title", element.attr( "title" ) ) .attr( "title", "" ); } }); }, _enable: function() { // restore title attributes this.element.find( this.options.items ).andSelf().each(function() { var element = $( this ); if ( element.data( "ui-tooltip-title" ) ) { element.attr( "title", element.data( "ui-tooltip-title" ) ); } }); }, open: function( event ) { var that = this, target = $( event ? event.target : this.element ) // we need closest here due to mouseover bubbling, // but always pointing at the same event target .closest( this.options.items ); // No element to show a tooltip for or the tooltip is already open if ( !target.length || target.data( "ui-tooltip-id" ) ) { return; } if ( target.attr( "title" ) ) { target.data( "ui-tooltip-title", target.attr( "title" ) ); } target.data( "ui-tooltip-open", true ); // kill parent tooltips, custom or native, for hover if ( event && event.type === "mouseover" ) { target.parents().each(function() { var parent = $( this ), blurEvent; if ( parent.data( "ui-tooltip-open" ) ) { blurEvent = $.Event( "blur" ); blurEvent.target = blurEvent.currentTarget = this; that.close( blurEvent, true ); } if ( parent.attr( "title" ) ) { parent.uniqueId(); that.parents[ this.id ] = { element: this, title: parent.attr( "title" ) }; parent.attr( "title", "" ); } }); } this._updateContent( target, event ); }, _updateContent: function( target, event ) { var content, contentOption = this.options.content, that = this, eventType = event ? event.type : null; if ( typeof contentOption === "string" ) { return this._open( event, target, contentOption ); } content = contentOption.call( target[0], function( response ) { // ignore async response if tooltip was closed already if ( !target.data( "ui-tooltip-open" ) ) { return; } // IE may instantly serve a cached response for ajax requests // delay this call to _open so the other call to _open runs first that._delay(function() { // jQuery creates a special event for focusin when it doesn't // exist natively. To improve performance, the native event // object is reused and the type is changed. Therefore, we can't // rely on the type being correct after the event finished // bubbling, so we set it back to the previous value. (#8740) if ( event ) { event.type = eventType; } this._open( event, target, response ); }); }); if ( content ) { this._open( event, target, content ); } }, _open: function( event, target, content ) { var tooltip, events, delayedShow, positionOption = $.extend( {}, this.options.position ); if ( !content ) { return; } // Content can be updated multiple times. If the tooltip already // exists, then just update the content and bail. tooltip = this._find( target ); if ( tooltip.length ) { tooltip.find( ".ui-tooltip-content" ).html( content ); return; } // if we have a title, clear it to prevent the native tooltip // we have to check first to avoid defining a title if none exists // (we don't want to cause an element to start matching [title]) // // We use removeAttr only for key events, to allow IE to export the correct // accessible attributes. For mouse events, set to empty string to avoid // native tooltip showing up (happens only when removing inside mouseover). if ( target.is( "[title]" ) ) { if ( event && event.type === "mouseover" ) { target.attr( "title", "" ); } else { target.removeAttr( "title" ); } } tooltip = this._tooltip( target ); addDescribedBy( target, tooltip.attr( "id" ) ); tooltip.find( ".ui-tooltip-content" ).html( content ); function position( event ) { positionOption.of = event; if ( tooltip.is( ":hidden" ) ) { return; } tooltip.position( positionOption ); } if ( this.options.track && event && /^mouse/.test( event.type ) ) { this._on( this.document, { mousemove: position }); // trigger once to override element-relative positioning position( event ); } else { tooltip.position( $.extend({ of: target }, this.options.position ) ); } tooltip.hide(); this._show( tooltip, this.options.show ); // Handle tracking tooltips that are shown with a delay (#8644). As soon // as the tooltip is visible, position the tooltip using the most recent // event. if ( this.options.show && this.options.show.delay ) { delayedShow = setInterval(function() { if ( tooltip.is( ":visible" ) ) { position( positionOption.of ); clearInterval( delayedShow ); } }, $.fx.interval ); } this._trigger( "open", event, { tooltip: tooltip } ); events = { keyup: function( event ) { if ( event.keyCode === $.ui.keyCode.ESCAPE ) { var fakeEvent = $.Event(event); fakeEvent.currentTarget = target[0]; this.close( fakeEvent, true ); } }, remove: function() { this._removeTooltip( tooltip ); } }; if ( !event || event.type === "mouseover" ) { events.mouseleave = "close"; } if ( !event || event.type === "focusin" ) { events.focusout = "close"; } this._on( true, target, events ); }, close: function( event ) { var that = this, target = $( event ? event.currentTarget : this.element ), tooltip = this._find( target ); // disabling closes the tooltip, so we need to track when we're closing // to avoid an infinite loop in case the tooltip becomes disabled on close if ( this.closing ) { return; } // only set title if we had one before (see comment in _open()) if ( target.data( "ui-tooltip-title" ) ) { target.attr( "title", target.data( "ui-tooltip-title" ) ); } removeDescribedBy( target ); tooltip.stop( true ); this._hide( tooltip, this.options.hide, function() { that._removeTooltip( $( this ) ); }); target.removeData( "ui-tooltip-open" ); this._off( target, "mouseleave focusout keyup" ); // Remove 'remove' binding only on delegated targets if ( target[0] !== this.element[0] ) { this._off( target, "remove" ); } this._off( this.document, "mousemove" ); if ( event && event.type === "mouseleave" ) { $.each( this.parents, function( id, parent ) { $( parent.element ).attr( "title", parent.title ); delete that.parents[ id ]; }); } this.closing = true; this._trigger( "close", event, { tooltip: tooltip } ); this.closing = false; }, _tooltip: function( element ) { var id = "ui-tooltip-" + increments++, tooltip = $( "<div>" ) .attr({ id: id, role: "tooltip" }) .addClass( "ui-tooltip ui-widget ui-corner-all ui-widget-content " + ( this.options.tooltipClass || "" ) ); $( "<div>" ) .addClass( "ui-tooltip-content" ) .appendTo( tooltip ); tooltip.appendTo( this.document[0].body ); if ( $.fn.bgiframe ) { tooltip.bgiframe(); } this.tooltips[ id ] = element; return tooltip; }, _find: function( target ) { var id = target.data( "ui-tooltip-id" ); return id ? $( "#" + id ) : $(); }, _removeTooltip: function( tooltip ) { tooltip.remove(); delete this.tooltips[ tooltip.attr( "id" ) ]; }, _destroy: function() { var that = this; // close open tooltips $.each( this.tooltips, function( id, element ) { // Delegate to close method to handle common cleanup var event = $.Event( "blur" ); event.target = event.currentTarget = element[0]; that.close( event, true ); // Remove immediately; destroying an open tooltip doesn't use the // hide animation $( "#" + id ).remove(); // Restore the title if ( element.data( "ui-tooltip-title" ) ) { element.attr( "title", element.data( "ui-tooltip-title" ) ); element.removeData( "ui-tooltip-title" ); } }); } }); }( jQuery ) );
admin/client/App/screens/Item/index.js
linhanyang/keystone
/** * Item View * * This is the item view, it is rendered when users visit a page of a specific * item. This mainly renders the form to edit the item content in. */ import React from 'react'; import { Center, Container, Spinner } from '../../elemental'; import { connect } from 'react-redux'; import { Link } from 'react-router'; import { listsByKey } from '../../../utils/lists'; import CreateForm from '../../shared/CreateForm'; import Alert from '../../elemental/Alert'; import EditForm from './components/EditForm'; import EditFormHeader from './components/EditFormHeader'; import RelatedItemsList from './components/RelatedItemsList/RelatedItemsList'; // import FlashMessages from '../../shared/FlashMessages'; import { selectItem, loadItemData, } from './actions'; import { selectList, } from '../List/actions'; var ItemView = React.createClass({ displayName: 'ItemView', contextTypes: { router: React.PropTypes.object.isRequired, }, getInitialState () { return { createIsOpen: false, }; }, componentDidMount () { // When we directly navigate to an item without coming from another client // side routed page before, we need to select the list before initializing the item // We also need to update when the list id has changed if (!this.props.currentList || this.props.currentList.id !== this.props.params.listId) { this.props.dispatch(selectList(this.props.params.listId)); } this.initializeItem(this.props.params.itemId); }, componentWillReceiveProps (nextProps) { // We've opened a new item from the client side routing, so initialize // again with the new item id if (nextProps.params.itemId !== this.props.params.itemId) { this.props.dispatch(selectList(nextProps.params.listId)); this.initializeItem(nextProps.params.itemId); } }, // Initialize an item initializeItem (itemId) { this.props.dispatch(selectItem(itemId)); this.props.dispatch(loadItemData()); }, // Called when a new item is created onCreate (item) { // Hide the create form this.toggleCreateModal(false); // Redirect to newly created item path const list = this.props.currentList; this.context.router.push(`${Keystone.adminPath}/${list.path}/${item.id}`); }, // Open and close the create new item modal toggleCreateModal (visible) { this.setState({ createIsOpen: visible, }); }, // Render this items relationships renderRelationships () { const { relationships } = this.props.currentList; const keys = Object.keys(relationships); if (!keys.length) return; return ( <div className="Relationships"> <Container> <h2>Relationships</h2> {keys.map(key => { const relationship = relationships[key]; const refList = listsByKey[relationship.ref]; const { currentList, params, relationshipData, drag } = this.props; return ( <RelatedItemsList key={relationship.path} list={currentList} refList={refList} relatedItemId={params.itemId} relationship={relationship} items={relationshipData[relationship.path]} dragNewSortOrder={drag.newSortOrder} dispatch={this.props.dispatch} /> ); })} </Container> </div> ); }, // Handle errors handleError (error) { const detail = error.detail; if (detail) { // Item not found if (detail.name === 'CastError' && detail.path === '_id') { return ( <Container> <Alert color="danger" style={{ marginTop: '2em' }}> No item matching id "{this.props.routeParams.itemId}".&nbsp; <Link to={`${Keystone.adminPath}/${this.props.routeParams.listId}`}> Got back to {this.props.routeParams.listId}? </Link> </Alert> </Container> ); } } if (error.message) { // Server down + possibly other errors if (error.message === 'Internal XMLHttpRequest Error') { return ( <Container> <Alert color="danger" style={{ marginTop: '2em' }}> We encountered some network problems, please refresh. </Alert> </Container> ); } } return ( <Container> <Alert color="danger" style={{ marginTop: '2em' }}> An unknown error has ocurred, please refresh. </Alert> </Container> ); }, render () { // If we don't have any data yet, show the loading indicator if (!this.props.ready) { return ( <Center height="50vh" data-screen-id="item"> <Spinner /> </Center> ); } // When we have the data, render the item view with it return ( <div data-screen-id="item"> {(this.props.error) ? this.handleError(this.props.error) : ( <div> <Container> <EditFormHeader list={this.props.currentList} data={this.props.data} toggleCreate={this.toggleCreateModal} /> <CreateForm list={this.props.currentList} isOpen={this.state.createIsOpen} onCancel={() => this.toggleCreateModal(false)} onCreate={(item) => this.onCreate(item)} /> <EditForm list={this.props.currentList} data={this.props.data} dispatch={this.props.dispatch} router={this.context.router} /> </Container> {this.renderRelationships()} </div> )} </div> ); }, }); module.exports = connect((state) => ({ data: state.item.data, loading: state.item.loading, ready: state.item.ready, error: state.item.error, currentList: state.lists.currentList, relationshipData: state.item.relationshipData, drag: state.item.drag, }))(ItemView);
src/components/common/AsyncElement.js
cs-rodolfo-costa/devops-projeto
import React from 'react'; import Router from 'react-router'; import { Route, RouteHandler, Link } from 'react-router'; var AsyncElement = { loadedComponent: null, load: function () { if (this.constructor.loadedComponent) return; this.bundle(function (component) { this.constructor.loadedComponent = component; this.forceUpdate(); }.bind(this)); }, componentDidMount: function () { setTimeout(this.load, 1000); }, render: function () { var Component = this.constructor.loadedComponent; if (Component) { // can't find RouteHandler in the loaded component, so we just grab // it here first. this.props.activeRoute = <RouteHandler/>; return <Component {...this.props}/>; } return this.preRender(); } }; export default AsyncElement;
loc8-react-redux-front-end/src/components/Home/index.js
uberslackin/django-redux-loc8-ARweb
import Banner from './Banner'; import MainView from './MainView'; import React from 'react'; import Tags from './Tags'; import agent from '../../agent'; import { connect } from 'react-redux'; const Promise = global.Promise; const mapStateToProps = state => ({ ...state.home, appName: state.common.appName, token: state.common.token }); const mapDispatchToProps = dispatch => ({ onClickTag: (tag, payload) => dispatch({ type: 'APPLY_TAG_FILTER', tag, payload }), onLoad: (tab, payload) => dispatch({ type: 'HOME_PAGE_LOADED', tab, payload }), onUnload: () => dispatch({ type: 'HOME_PAGE_UNLOADED' }) }); class Home extends React.Component { componentWillMount() { const tab = this.props.token ? 'feed' : 'all'; const articlesPromise = this.props.token ? agent.Articles.feed() : agent.Articles.all(); this.props.onLoad(tab, Promise.all([agent.Tags.getAll(), articlesPromise])); } componentWillUnmount() { this.props.onUnload(); } render() { return ( <div className="home-page"> <Banner token={this.props.token} appName={this.props.appName} /> <div className="container page"> <div className="row"> <MainView /> <div className="col-md-3"> <div className="sidebar"> <p>Popular Tags</p> <Tags tags={this.props.tags} onClickTag={this.props.onClickTag} /> </div> </div> </div> </div> </div> ); } } export default connect(mapStateToProps, mapDispatchToProps)(Home);
assets/routes.js
apolishch/react-article
'use strict' import React from 'react' import { TextBody, Container, Composition } from './components' import { Route, IndexRoute } from 'react-router' export default <Route path='/' component={Container}> <Route path='/textBody'> <IndexRoute component={TextBody} /> </Route> <Route path='/composition'> <IndexRoute component={Composition} /> </Route> </Route>
jekyll-strapi-tutorial/api/plugins/content-type-builder/admin/src/components/OldInput/index.js
strapi/strapi-examples
/** * * Input * */ import React from 'react'; import PropTypes from 'prop-types'; import { get, isEmpty, map, mapKeys, isObject, reject, includes } from 'lodash'; import { FormattedMessage } from 'react-intl'; import styles from './styles.scss'; /* eslint-disable react/jsx-wrap-multilines */ /* eslint-disable react/require-default-props */ class Input extends React.Component { // eslint-disable-line react/prefer-stateless-function constructor(props) { super(props); this.state = { errors: [], hasInitialValue: false, }; } componentDidMount() { if (this.props.value && !isEmpty(this.props.value)) { this.setState({ hasInitialValue: true }); } if (!isEmpty(this.props.errors)) { this.setState({ errors: this.props.errors }); } } componentWillReceiveProps(nextProps) { // Check if errors have been updated during validations if (this.props.didCheckErrors !== nextProps.didCheckErrors) { // Remove from the state errors that are already set const errors = isEmpty(nextProps.errors) ? [] : nextProps.errors; this.setState({ errors }); } } handleBlur = ({ target }) => { // prevent error display if input is initially empty if (!isEmpty(target.value) || this.state.hasInitialValue) { // validates basic string validations // add custom logic here such as alerts... const errors = this.validate(target.value); this.setState({ errors, hasInitialValue: true }); } } validate = (value) => { let errors = []; // handle i18n const requiredError = { id: `${this.props.pluginId}.error.validation.required` }; mapKeys(this.props.validations, (validationValue, validationKey) => { switch (validationKey) { case 'max': if (parseInt(value, 10) > validationValue) { errors.push({ id: `${this.props.pluginId}.error.validation.max` }); } break; case 'maxLength': if (value.length > validationValue) { errors.push({ id: `${this.props.pluginId}.error.validation.maxLength` }); } break; case 'min': if (parseInt(value, 10) < validationValue) { errors.push({ id: `${this.props.pluginId}.error.validation.min` }); } break; case 'minLength': if (value.length < validationValue) { errors.push({ id: `${this.props.pluginId}.error.validation.minLength` }); } break; case 'required': if (value.length === 0) { errors.push({ id: `${this.props.pluginId}.error.validation.required` }); } break; case 'regex': if (!new RegExp(validationValue).test(value)) { errors.push({ id: `${this.props.pluginId}.error.validation.regex` }); } break; default: errors = []; } }); if (includes(errors, requiredError)) { errors = reject(errors, (error) => error !== requiredError); } return errors; } handleChangeCheckbox = () => { const target = { type: 'checkbox', value: !this.props.value, name: this.props.name, }; this.props.onChange({ target }); } renderErrors = (errorStyles) => { // eslint-disable-line consistent-return if (!this.props.noErrorsDescription) { const divStyle = errorStyles || styles.errorContainer; return ( map(this.state.errors, (error, key) => { const displayError = isObject(error) && error.id ? <FormattedMessage {...error} /> : error; return ( <div key={key} className={`form-control-feedback ${divStyle}`}>{displayError}</div> ); }) ); } } renderInputCheckbox = (requiredClass, inputDescription) => { const title = !isEmpty(this.props.title) ? <div className={styles.inputTitle}><FormattedMessage id={this.props.title} /></div> : ''; const spacer = !inputDescription ? <div /> : <div style={{ marginBottom: '.5rem'}}></div>; return ( <div className={`${styles.inputCheckbox} col-md-12 ${requiredClass}`}> <div className="form-check"> {title} <FormattedMessage id={this.props.label}> {(message) => ( <label className={`${styles.checkboxLabel} form-check-label`} htmlFor={this.props.label} onClick={this.handleChangeCheckbox} style={{ cursor: 'pointer' }}> <input className="form-check-input" type="checkbox" checked={this.props.value} onChange={this.handleChangeCheckbox} name={this.props.name} tabIndex={this.props.tabIndex} /> {message} </label> )} </FormattedMessage> <div className={styles.inputCheckboxDescriptionContainer}> <small>{inputDescription}</small> </div> </div> {spacer} </div> ); } renderInputSelect = (bootStrapClass, requiredClass, inputDescription, bootStrapClassDanger, handleBlur) => { let spacer = !isEmpty(this.props.inputDescription) ? <div className={styles.spacer} /> : <div />; if (!this.props.noErrorsDescription && !isEmpty(this.state.errors)) { spacer = <div />; } return ( <div className={`${styles.input} ${requiredClass} ${bootStrapClass} ${bootStrapClassDanger}`}> <label htmlFor={this.props.label}> <FormattedMessage id={`${this.props.label}`} /> </label> <select className="form-control" id={this.props.label} name={this.props.name} onChange={this.props.onChange} value={this.props.value} disabled={this.props.disabled} onBlur={handleBlur} tabIndex={this.props.tabIndex} > {map(this.props.selectOptions, (option, key) => ( option.name ? <FormattedMessage id={option.name} defaultMessage={option.name} values={{ option: option.name }} key={key}> {(message) => ( <option value={option.value}> {message} </option> )} </FormattedMessage> : <option value={option.value} key={key}>{option.name}</option> ))} </select> <div className={styles.inputDescriptionContainer}> <small>{inputDescription}</small> </div> {this.renderErrors()} {spacer} </div> ); } renderInputTextArea = (bootStrapClass, requiredClass, bootStrapClassDanger, inputDescription, handleBlur) => { let spacer = !isEmpty(this.props.inputDescription) ? <div className={styles.spacer} /> : <div />; if (!this.props.noErrorsDescription && !isEmpty(this.state.errors)) { spacer = <div />; } return ( <div className={`${styles.inputTextArea} ${bootStrapClass} ${requiredClass} ${bootStrapClassDanger}`}> <label htmlFor={this.props.label}> <FormattedMessage id={`${this.props.label}`} /> </label> <FormattedMessage id={this.props.placeholder || this.props.label}> {(placeholder) => ( <textarea className="form-control" onChange={this.props.onChange} value={this.props.value} name={this.props.name} id={this.props.label} onBlur={handleBlur} onFocus={this.props.onFocus} placeholder={placeholder} disabled={this.props.disabled} tabIndex={this.props.tabIndex} /> )} </FormattedMessage> <div className={styles.inputTextAreaDescriptionContainer}> <small>{inputDescription}</small> </div> {this.renderErrors(styles.errorContainerTextArea)} {spacer} </div> ); } renderFormattedInput = (handleBlur, inputValue, placeholder) => ( <FormattedMessage id={`${placeholder}`} defaultMessage='{placeholder}' values={{ placeholder }}> {(message) => ( <input name={this.props.name} id={this.props.label} onBlur={handleBlur} onFocus={this.props.onFocus} onChange={this.props.onChange} value={inputValue} type={this.props.type} className={`form-control ${this.state.errors? 'form-control-danger' : ''}`} placeholder={message} autoComplete="off" disabled={this.props.disabled} tabIndex={this.props.tabIndex} /> )} </FormattedMessage> ) render() { const inputValue = this.props.value || ''; // override default onBlur const handleBlur = this.props.onBlur || this.handleBlur; // override bootStrapClass const bootStrapClass = this.props.customBootstrapClass ? this.props.customBootstrapClass : 'col-md-6'; // set error class with override possibility const bootStrapClassDanger = !this.props.deactivateErrorHighlight && !isEmpty(this.state.errors) ? 'has-danger' : ''; const placeholder = this.props.placeholder || this.props.label; const label = this.props.label ? <label htmlFor={this.props.label}><FormattedMessage id={`${this.props.label}`} /></label> : <label htmlFor={this.props.label} />; // eslint-disable-line jsx-a11y/label-has-for const requiredClass = get(this.props.validations, 'required') && this.props.addRequiredInputDesign ? styles.requiredClass : ''; const input = placeholder ? this.renderFormattedInput(handleBlur, inputValue, placeholder) : <input name={this.props.name} id={this.props.label} onBlur={handleBlur} onFocus={this.props.onFocus} onChange={this.props.onChange} value={inputValue} type={this.props.type} className={`form-control ${this.state.errors? 'form-control-danger' : ''}`} placeholder={placeholder} disabled={this.props.disabled} tabIndex={this.props.tabIndex} />; const link = !isEmpty(this.props.linkContent) ? <a href={this.props.linkContent.link} target="_blank"><FormattedMessage id={this.props.linkContent.description} /></a> : ''; let inputDescription = !isEmpty(this.props.inputDescription) ? <FormattedMessage id={this.props.inputDescription} /> : ''; if (!isEmpty(this.props.linkContent) && !isEmpty(this.props.inputDescription)) { inputDescription = <FormattedMessage id='input.description' defaultMessage={`{description}, {link}`} values={{link, description: <FormattedMessage id={this.props.inputDescription} /> }} />; } let spacer = !isEmpty(this.props.inputDescription) ? <div className={styles.spacer} /> : <div />; if (!this.props.noErrorsDescription && !isEmpty(this.state.errors)) { spacer = <div />; } switch (this.props.type) { case 'select': return this.renderInputSelect(bootStrapClass, requiredClass, inputDescription, bootStrapClassDanger, handleBlur); case 'textarea': return this.renderInputTextArea(bootStrapClass, requiredClass, bootStrapClassDanger, inputDescription, handleBlur); case 'checkbox': return this.renderInputCheckbox(requiredClass, inputDescription); default: } const addonInput = this.props.addon ? <div className={`input-group ${styles.input}`} style={{ marginBottom: '1rem'}}> <span className={`input-group-addon ${styles.addon}`}><FormattedMessage id={this.props.addon} values={{ addon: this.props.addon }} defaultMessage='{addon}' /></span> {input} </div> : input; return ( <div className={`${styles.input} ${bootStrapClass} ${requiredClass} ${bootStrapClassDanger}`}> {label} {addonInput} <div className={styles.inputDescriptionContainer}> <small>{inputDescription}</small> </div> {this.renderErrors()} {spacer} </div> ); } } Input.propTypes = { addon: PropTypes.oneOfType([ PropTypes.bool, PropTypes.string, ]), addRequiredInputDesign: PropTypes.bool, customBootstrapClass: PropTypes.string, deactivateErrorHighlight: PropTypes.bool, didCheckErrors: PropTypes.bool, disabled: PropTypes.bool, errors: PropTypes.array, inputDescription: PropTypes.string, label: PropTypes.string.isRequired, linkContent: PropTypes.shape({ link: PropTypes.string, description: PropTypes.string.isRequired, }), name: PropTypes.string.isRequired, noErrorsDescription: PropTypes.bool, onBlur: PropTypes.oneOfType([ PropTypes.func, PropTypes.bool, ]), onChange: PropTypes.func.isRequired, onFocus: PropTypes.func, placeholder: PropTypes.string, pluginId: PropTypes.string, selectOptions: PropTypes.array, tabIndex: PropTypes.string, title: PropTypes.string, type: PropTypes.string.isRequired, validations: PropTypes.object.isRequired, value: PropTypes.oneOfType([ PropTypes.string, PropTypes.bool, PropTypes.number, ]), }; export default Input;
src/Affix.js
coderstudy/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import AffixMixin from './AffixMixin'; import domUtils from './utils/domUtils'; const Affix = React.createClass({ statics: { domUtils }, mixins: [AffixMixin], render() { let holderStyle = {top: this.state.affixPositionTop}; return ( <div {...this.props} className={classNames(this.props.className, this.state.affixClass)} style={holderStyle}> {this.props.children} </div> ); } }); export default Affix;
IQMail_App/src/components/common/Input.js
victorditadi/IQApp
import React, { Component } from 'react'; import { TextInput, View, Text } from 'react-native'; const Input = ({ label, value, onChangeText, placeholder, secure }) => { const { inputStyle, labelStyle, containerStyle } = styles; return ( <View style={containerStyle}> <Text style={labelStyle}>{label}</Text> <TextInput secureTextEntry={secure} placeholder={placeholder} autoCorrect={false} style={inputStyle} value={value} onChangeText={onChangeText} /> </View> ); }; const styles = { inputStyle: { color: '#000', paddingRight: 2, paddingLeft: 2, fontSize: 18, lineHeight: 23, flex: 2 }, labelStyle: { fontSize: 18, paddingLeft: 20, flex: 1 }, containerStyle: { height: 40, flex: 1, flexDirection: 'row', alignItems: 'center' } } export { Input };
Auth/website/src/components/LegalFooter.js
awslabs/aws-serverless-workshops
/* * Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ import React from 'react'; const LegalFooter = () => { return ( <div className="row column"> <div className="footer-legal"> &copy;WildRydes Inc<br/> All Rights Reserved </div> </div> ); }; export default LegalFooter;
client/components/landingPageFeatured.js
VaRt-io/V-aRt
import React, { Component } from 'react'; import {Carousel} from 'react-bootstrap'; export default class ourCarousel extends Component{ render(){ return ( <div> <Carousel className="carousel" interval={3000} > <Carousel.Item> <img className="carImg" width="100%" height='100%' src="/COVERIMAGES/theDesert.png" border="0" /> <Carousel.Caption> <h3>The Desert</h3> <p>Surrealistic Landscapes</p> </Carousel.Caption> </Carousel.Item> <Carousel.Item> <img className="carImg" width="100%" height='100%' src="/COVERIMAGES/theRoom.png" border="0" /> <Carousel.Caption> <h3>VanGogh</h3> <p>A Celestial Scene</p> </Carousel.Caption> </Carousel.Item> <Carousel.Item> <img className="carImg" width="100%" height='100%' src="/COVERIMAGES/halloween.png" border="0" /> <Carousel.Caption> <h3>Nightscene</h3> <p>Spook your friends with a Halloween theme</p> </Carousel.Caption> </Carousel.Item> </Carousel> </div> ); } }
packages/material-ui-icons/src/SaveAltTwoTone.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 12v7H5v-7H3v7c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-7h-2zm-6 .67l2.59-2.58L17 11.5l-5 5-5-5 1.41-1.41L11 12.67V3h2v9.67z" /></React.Fragment> , 'SaveAltTwoTone');
js/src/ui/Warning/warning.js
jesuscript/parity
// Copyright 2015, 2016 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React, { Component } from 'react'; import { nodeOrStringProptype } from '~/util/proptypes'; import styles from './warning.css'; export default class Warning extends Component { static propTypes = { warning: nodeOrStringProptype() }; render () { const { warning } = this.props; if (!warning) { return null; } return ( <div className={ styles.warning }> { warning } </div> ); } }
ajax/libs/react-data-grid/1.0.74/react-data-grid.ui-plugins.js
kennynaoh/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom"], factory); else if(typeof exports === 'object') exports["ReactDataGrid"] = factory(require("react"), require("react-dom")); else root["ReactDataGrid"] = factory(root["React"], root["ReactDOM"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__, __WEBPACK_EXTERNAL_MODULE_5__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ((function(modules) { // Check all modules for deduplicated modules for(var i in modules) { if(Object.prototype.hasOwnProperty.call(modules, i)) { switch(typeof modules[i]) { case "function": break; case "object": // Module can be created from a template modules[i] = (function(_m) { var args = _m.slice(1), fn = modules[_m[0]]; return function (a,b,c) { fn.apply(this, [a,b,c].concat(args)); }; }(modules[i])); break; default: // Module is a copy of another module modules[i] = modules[modules[i]]; break; } } } return modules; }([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.Utils = exports.Filters = exports.Draggable = exports.ToolsPanel = exports.Data = exports.Menu = exports.Toolbar = exports.Formatters = exports.Editors = undefined; var _draggable = __webpack_require__(134); var _draggable2 = _interopRequireDefault(_draggable); var _RowComparer = __webpack_require__(57); var _RowComparer2 = _interopRequireDefault(_RowComparer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var Editors = __webpack_require__(139); var Formatters = __webpack_require__(142); var Toolbar = __webpack_require__(149); var ToolsPanel = __webpack_require__(150); var Data = __webpack_require__(129); var Menu = __webpack_require__(145); var Filters = __webpack_require__(124); var Utils = { rowComparer: _RowComparer2['default'] }; window.ReactDataGridPlugins = { Editors: Editors, Formatters: Formatters, Toolbar: Toolbar, Menu: Menu, Data: Data, ToolsPanel: ToolsPanel, Draggable: _draggable2['default'], Filters: Filters, Utils: Utils }; exports.Editors = Editors; exports.Formatters = Formatters; exports.Toolbar = Toolbar; exports.Menu = Menu; exports.Data = Data; exports.ToolsPanel = ToolsPanel; exports.Draggable = _draggable2['default']; exports.Filters = Filters; exports.Utils = Utils; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ 'use strict'; /** * Use invariant() to assert state which your program assumes to be true. * * Provide sprintf-style format (only %s is supported) and arguments * to provide information about what broke and what you were * expecting. * * The invariant message will be stripped in production, but the invariant * will remain to ensure logic does not differ in production. */ var invariant = function(condition, format, a, b, c, d, e, f) { if (false) { 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; /***/ }, /* 3 */ /***/ function(module, exports) { /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; module.exports = isArray; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { var freeGlobal = __webpack_require__(84); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; /***/ }, /* 5 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_5__; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(10), getPrototype = __webpack_require__(234), isObjectLike = __webpack_require__(9); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } module.exports = isPlainObject; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var baseIsNative = __webpack_require__(210), getValue = __webpack_require__(237); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } module.exports = getNative; /***/ }, /* 8 */ /***/ function(module, exports) { /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 9 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), getRawTag = __webpack_require__(235), objectToString = __webpack_require__(263); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } value = Object(value); return (symToStringTag && symToStringTag in value) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var identity = __webpack_require__(46), overRest = __webpack_require__(264), setToString = __webpack_require__(267); /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } module.exports = baseRest; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequire(obj) { return obj && obj.__esModule ? obj['default'] : obj; } var _DragDropContext = __webpack_require__(305); exports.DragDropContext = _interopRequire(_DragDropContext); var _DragLayer = __webpack_require__(306); exports.DragLayer = _interopRequire(_DragLayer); var _DragSource = __webpack_require__(307); exports.DragSource = _interopRequire(_DragSource); var _DropTarget = __webpack_require__(308); exports.DropTarget = _interopRequire(_DropTarget); /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(1); var ExcelColumnShape = { name: React.PropTypes.node.isRequired, key: React.PropTypes.string.isRequired, width: React.PropTypes.number.isRequired, filterable: React.PropTypes.bool }; module.exports = ExcelColumnShape; /***/ }, /* 14 */ /***/ function(module, exports) { 'use strict'; module.exports = !!(typeof window !== 'undefined' && window.document && window.document.createElement); /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(4); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }, /* 16 */ /***/ function(module, exports) { /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } module.exports = eq; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(91), isLength = __webpack_require__(48); /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } module.exports = isArrayLike; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.beginDrag = beginDrag; exports.publishDragSource = publishDragSource; exports.hover = hover; exports.drop = drop; exports.endDrag = endDrag; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsMatchesType = __webpack_require__(67); var _utilsMatchesType2 = _interopRequireDefault(_utilsMatchesType); var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodashIsArray = __webpack_require__(3); var _lodashIsArray2 = _interopRequireDefault(_lodashIsArray); var _lodashIsObject = __webpack_require__(8); var _lodashIsObject2 = _interopRequireDefault(_lodashIsObject); var BEGIN_DRAG = 'dnd-core/BEGIN_DRAG'; exports.BEGIN_DRAG = BEGIN_DRAG; var PUBLISH_DRAG_SOURCE = 'dnd-core/PUBLISH_DRAG_SOURCE'; exports.PUBLISH_DRAG_SOURCE = PUBLISH_DRAG_SOURCE; var HOVER = 'dnd-core/HOVER'; exports.HOVER = HOVER; var DROP = 'dnd-core/DROP'; exports.DROP = DROP; var END_DRAG = 'dnd-core/END_DRAG'; exports.END_DRAG = END_DRAG; function beginDrag(sourceIds) { var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var _ref$publishSource = _ref.publishSource; var publishSource = _ref$publishSource === undefined ? true : _ref$publishSource; var _ref$clientOffset = _ref.clientOffset; var clientOffset = _ref$clientOffset === undefined ? null : _ref$clientOffset; var getSourceClientOffset = _ref.getSourceClientOffset; _invariant2['default'](_lodashIsArray2['default'](sourceIds), 'Expected sourceIds to be an array.'); var monitor = this.getMonitor(); var registry = this.getRegistry(); _invariant2['default'](!monitor.isDragging(), 'Cannot call beginDrag while dragging.'); for (var i = 0; i < sourceIds.length; i++) { _invariant2['default'](registry.getSource(sourceIds[i]), 'Expected sourceIds to be registered.'); } var sourceId = null; for (var i = sourceIds.length - 1; i >= 0; i--) { if (monitor.canDragSource(sourceIds[i])) { sourceId = sourceIds[i]; break; } } if (sourceId === null) { return; } var sourceClientOffset = null; if (clientOffset) { _invariant2['default'](typeof getSourceClientOffset === 'function', 'When clientOffset is provided, getSourceClientOffset must be a function.'); sourceClientOffset = getSourceClientOffset(sourceId); } var source = registry.getSource(sourceId); var item = source.beginDrag(monitor, sourceId); _invariant2['default'](_lodashIsObject2['default'](item), 'Item must be an object.'); registry.pinSource(sourceId); var itemType = registry.getSourceType(sourceId); return { type: BEGIN_DRAG, itemType: itemType, item: item, sourceId: sourceId, clientOffset: clientOffset, sourceClientOffset: sourceClientOffset, isSourcePublic: publishSource }; } function publishDragSource(manager) { var monitor = this.getMonitor(); if (!monitor.isDragging()) { return; } return { type: PUBLISH_DRAG_SOURCE }; } function hover(targetIds) { var _ref2 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var _ref2$clientOffset = _ref2.clientOffset; var clientOffset = _ref2$clientOffset === undefined ? null : _ref2$clientOffset; _invariant2['default'](_lodashIsArray2['default'](targetIds), 'Expected targetIds to be an array.'); targetIds = targetIds.slice(0); var monitor = this.getMonitor(); var registry = this.getRegistry(); _invariant2['default'](monitor.isDragging(), 'Cannot call hover while not dragging.'); _invariant2['default'](!monitor.didDrop(), 'Cannot call hover after drop.'); // First check invariants. for (var i = 0; i < targetIds.length; i++) { var targetId = targetIds[i]; _invariant2['default'](targetIds.lastIndexOf(targetId) === i, 'Expected targetIds to be unique in the passed array.'); var target = registry.getTarget(targetId); _invariant2['default'](target, 'Expected targetIds to be registered.'); } var draggedItemType = monitor.getItemType(); // Remove those targetIds that don't match the targetType. This // fixes shallow isOver which would only be non-shallow because of // non-matching targets. for (var i = targetIds.length - 1; i >= 0; i--) { var targetId = targetIds[i]; var targetType = registry.getTargetType(targetId); if (!_utilsMatchesType2['default'](targetType, draggedItemType)) { targetIds.splice(i, 1); } } // Finally call hover on all matching targets. for (var i = 0; i < targetIds.length; i++) { var targetId = targetIds[i]; var target = registry.getTarget(targetId); target.hover(monitor, targetId); } return { type: HOVER, targetIds: targetIds, clientOffset: clientOffset }; } function drop() { var _this = this; var monitor = this.getMonitor(); var registry = this.getRegistry(); _invariant2['default'](monitor.isDragging(), 'Cannot call drop while not dragging.'); _invariant2['default'](!monitor.didDrop(), 'Cannot call drop twice during one drag operation.'); var targetIds = monitor.getTargetIds().filter(monitor.canDropOnTarget, monitor); targetIds.reverse(); targetIds.forEach(function (targetId, index) { var target = registry.getTarget(targetId); var dropResult = target.drop(monitor, targetId); _invariant2['default'](typeof dropResult === 'undefined' || _lodashIsObject2['default'](dropResult), 'Drop result must either be an object or undefined.'); if (typeof dropResult === 'undefined') { dropResult = index === 0 ? {} : monitor.getDropResult(); } _this.store.dispatch({ type: DROP, dropResult: dropResult }); }); } function endDrag() { var monitor = this.getMonitor(); var registry = this.getRegistry(); _invariant2['default'](monitor.isDragging(), 'Cannot call endDrag while not dragging.'); var sourceId = monitor.getSourceId(); var source = registry.getSource(sourceId, true); source.endDrag(monitor, sourceId); registry.unpinSource(); return { type: END_DRAG }; } /***/ }, /* 19 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports.addSource = addSource; exports.addTarget = addTarget; exports.removeSource = removeSource; exports.removeTarget = removeTarget; var ADD_SOURCE = 'dnd-core/ADD_SOURCE'; exports.ADD_SOURCE = ADD_SOURCE; var ADD_TARGET = 'dnd-core/ADD_TARGET'; exports.ADD_TARGET = ADD_TARGET; var REMOVE_SOURCE = 'dnd-core/REMOVE_SOURCE'; exports.REMOVE_SOURCE = REMOVE_SOURCE; var REMOVE_TARGET = 'dnd-core/REMOVE_TARGET'; exports.REMOVE_TARGET = REMOVE_TARGET; function addSource(sourceId) { return { type: ADD_SOURCE, sourceId: sourceId }; } function addTarget(targetId) { return { type: ADD_TARGET, targetId: targetId }; } function removeSource(sourceId) { return { type: REMOVE_SOURCE, sourceId: sourceId }; } function removeTarget(targetId) { return { type: REMOVE_TARGET, targetId: targetId }; } /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(248), listCacheDelete = __webpack_require__(249), listCacheGet = __webpack_require__(250), listCacheHas = __webpack_require__(251), listCacheSet = __webpack_require__(252); /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; module.exports = ListCache; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(38), setCacheAdd = __webpack_require__(265), setCacheHas = __webpack_require__(266); /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; module.exports = SetCache; /***/ }, /* 22 */ /***/ function(module, exports) { /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(16); /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } module.exports = assocIndexOf; /***/ }, /* 24 */ /***/ function(module, exports) { /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } module.exports = cacheHas; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { var isKeyable = __webpack_require__(246); /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } module.exports = getMapData; /***/ }, /* 26 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(7); /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(49); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = toKey; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(17), isObjectLike = __webpack_require__(9); /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } module.exports = isArrayLikeObject; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _redux = __webpack_require__(336); var _reducers = __webpack_require__(294); var _reducers2 = _interopRequireDefault(_reducers); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = (0, _redux.createStore)(_reducers2.default); /***/ }, /* 30 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = checkDecoratorArguments; function checkDecoratorArguments(functionName, signature) { if (false) { for (var _len = arguments.length, args = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { args[_key - 2] = arguments[_key]; } for (var i = 0; i < args.length; i++) { var arg = args[i]; if (arg && arg.prototype && arg.prototype.render) { console.error( // eslint-disable-line no-console 'You seem to be applying the arguments in the wrong order. ' + ('It should be ' + functionName + '(' + signature + ')(Component), not the other way around. ') + 'Read more: http://gaearon.github.io/react-dnd/docs-troubleshooting.html#you-seem-to-be-applying-the-arguments-in-the-wrong-order'); return; } } } } module.exports = exports['default']; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { /*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/react-select */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); var _reactInputAutosize = __webpack_require__(318); var _reactInputAutosize2 = _interopRequireDefault(_reactInputAutosize); var _classnames = __webpack_require__(32); var _classnames2 = _interopRequireDefault(_classnames); var _utilsDefaultArrowRenderer = __webpack_require__(332); var _utilsDefaultArrowRenderer2 = _interopRequireDefault(_utilsDefaultArrowRenderer); var _utilsDefaultFilterOptions = __webpack_require__(109); var _utilsDefaultFilterOptions2 = _interopRequireDefault(_utilsDefaultFilterOptions); var _utilsDefaultMenuRenderer = __webpack_require__(110); var _utilsDefaultMenuRenderer2 = _interopRequireDefault(_utilsDefaultMenuRenderer); var _Async = __webpack_require__(327); var _Async2 = _interopRequireDefault(_Async); var _AsyncCreatable = __webpack_require__(328); var _AsyncCreatable2 = _interopRequireDefault(_AsyncCreatable); var _Creatable = __webpack_require__(329); var _Creatable2 = _interopRequireDefault(_Creatable); var _Option = __webpack_require__(330); var _Option2 = _interopRequireDefault(_Option); var _Value = __webpack_require__(331); var _Value2 = _interopRequireDefault(_Value); function stringifyValue(value) { var valueType = typeof value; if (valueType === 'string') { return value; } else if (valueType === 'object') { return JSON.stringify(value); } else if (valueType === 'number' || valueType === 'boolean') { return String(value); } else { return ''; } } var stringOrNode = _react2['default'].PropTypes.oneOfType([_react2['default'].PropTypes.string, _react2['default'].PropTypes.node]); var instanceId = 1; var Select = _react2['default'].createClass({ displayName: 'Select', propTypes: { addLabelText: _react2['default'].PropTypes.string, // placeholder displayed when you want to add a label on a multi-value input 'aria-label': _react2['default'].PropTypes.string, // Aria label (for assistive tech) 'aria-labelledby': _react2['default'].PropTypes.string, // HTML ID of an element that should be used as the label (for assistive tech) arrowRenderer: _react2['default'].PropTypes.func, // Create drop-down caret element autoBlur: _react2['default'].PropTypes.bool, // automatically blur the component when an option is selected autofocus: _react2['default'].PropTypes.bool, // autofocus the component on mount autosize: _react2['default'].PropTypes.bool, // whether to enable autosizing or not backspaceRemoves: _react2['default'].PropTypes.bool, // whether backspace removes an item if there is no text input backspaceToRemoveMessage: _react2['default'].PropTypes.string, // Message to use for screenreaders to press backspace to remove the current item - {label} is replaced with the item label className: _react2['default'].PropTypes.string, // className for the outer element clearAllText: stringOrNode, // title for the "clear" control when multi: true clearValueText: stringOrNode, // title for the "clear" control clearable: _react2['default'].PropTypes.bool, // should it be possible to reset value delimiter: _react2['default'].PropTypes.string, // delimiter to use to join multiple values for the hidden field value disabled: _react2['default'].PropTypes.bool, // whether the Select is disabled or not escapeClearsValue: _react2['default'].PropTypes.bool, // whether escape clears the value when the menu is closed filterOption: _react2['default'].PropTypes.func, // method to filter a single option (option, filterString) filterOptions: _react2['default'].PropTypes.any, // boolean to enable default filtering or function to filter the options array ([options], filterString, [values]) ignoreAccents: _react2['default'].PropTypes.bool, // whether to strip diacritics when filtering ignoreCase: _react2['default'].PropTypes.bool, // whether to perform case-insensitive filtering inputProps: _react2['default'].PropTypes.object, // custom attributes for the Input inputRenderer: _react2['default'].PropTypes.func, // returns a custom input component instanceId: _react2['default'].PropTypes.string, // set the components instanceId isLoading: _react2['default'].PropTypes.bool, // whether the Select is loading externally or not (such as options being loaded) joinValues: _react2['default'].PropTypes.bool, // joins multiple values into a single form field with the delimiter (legacy mode) labelKey: _react2['default'].PropTypes.string, // path of the label value in option objects matchPos: _react2['default'].PropTypes.string, // (any|start) match the start or entire string when filtering matchProp: _react2['default'].PropTypes.string, // (any|label|value) which option property to filter on menuBuffer: _react2['default'].PropTypes.number, // optional buffer (in px) between the bottom of the viewport and the bottom of the menu menuContainerStyle: _react2['default'].PropTypes.object, // optional style to apply to the menu container menuRenderer: _react2['default'].PropTypes.func, // renders a custom menu with options menuStyle: _react2['default'].PropTypes.object, // optional style to apply to the menu multi: _react2['default'].PropTypes.bool, // multi-value input name: _react2['default'].PropTypes.string, // generates a hidden <input /> tag with this field name for html forms noResultsText: stringOrNode, // placeholder displayed when there are no matching search results onBlur: _react2['default'].PropTypes.func, // onBlur handler: function (event) {} onBlurResetsInput: _react2['default'].PropTypes.bool, // whether input is cleared on blur onChange: _react2['default'].PropTypes.func, // onChange handler: function (newValue) {} onClose: _react2['default'].PropTypes.func, // fires when the menu is closed onCloseResetsInput: _react2['default'].PropTypes.bool, // whether input is cleared when menu is closed through the arrow onFocus: _react2['default'].PropTypes.func, // onFocus handler: function (event) {} onInputChange: _react2['default'].PropTypes.func, // onInputChange handler: function (inputValue) {} onInputKeyDown: _react2['default'].PropTypes.func, // input keyDown handler: function (event) {} onMenuScrollToBottom: _react2['default'].PropTypes.func, // fires when the menu is scrolled to the bottom; can be used to paginate options onOpen: _react2['default'].PropTypes.func, // fires when the menu is opened onValueClick: _react2['default'].PropTypes.func, // onClick handler for value labels: function (value, event) {} openAfterFocus: _react2['default'].PropTypes.bool, // boolean to enable opening dropdown when focused openOnFocus: _react2['default'].PropTypes.bool, // always open options menu on focus optionClassName: _react2['default'].PropTypes.string, // additional class(es) to apply to the <Option /> elements optionComponent: _react2['default'].PropTypes.func, // option component to render in dropdown optionRenderer: _react2['default'].PropTypes.func, // optionRenderer: function (option) {} options: _react2['default'].PropTypes.array, // array of options pageSize: _react2['default'].PropTypes.number, // number of entries to page when using page up/down keys placeholder: stringOrNode, // field placeholder, displayed when there's no value required: _react2['default'].PropTypes.bool, // applies HTML5 required attribute when needed resetValue: _react2['default'].PropTypes.any, // value to use when you clear the control scrollMenuIntoView: _react2['default'].PropTypes.bool, // boolean to enable the viewport to shift so that the full menu fully visible when engaged searchable: _react2['default'].PropTypes.bool, // whether to enable searching feature or not simpleValue: _react2['default'].PropTypes.bool, // pass the value to onChange as a simple value (legacy pre 1.0 mode), defaults to false style: _react2['default'].PropTypes.object, // optional style to apply to the control tabIndex: _react2['default'].PropTypes.string, // optional tab index of the control tabSelectsValue: _react2['default'].PropTypes.bool, // whether to treat tabbing out while focused to be value selection value: _react2['default'].PropTypes.any, // initial field value valueComponent: _react2['default'].PropTypes.func, // value component to render valueKey: _react2['default'].PropTypes.string, // path of the label value in option objects valueRenderer: _react2['default'].PropTypes.func, // valueRenderer: function (option) {} wrapperStyle: _react2['default'].PropTypes.object }, // optional style to apply to the component wrapper statics: { Async: _Async2['default'], AsyncCreatable: _AsyncCreatable2['default'], Creatable: _Creatable2['default'] }, getDefaultProps: function getDefaultProps() { return { addLabelText: 'Add "{label}"?', arrowRenderer: _utilsDefaultArrowRenderer2['default'], autosize: true, backspaceRemoves: true, backspaceToRemoveMessage: 'Press backspace to remove {label}', clearable: true, clearAllText: 'Clear all', clearValueText: 'Clear value', delimiter: ',', disabled: false, escapeClearsValue: true, filterOptions: _utilsDefaultFilterOptions2['default'], ignoreAccents: true, ignoreCase: true, inputProps: {}, isLoading: false, joinValues: false, labelKey: 'label', matchPos: 'any', matchProp: 'any', menuBuffer: 0, menuRenderer: _utilsDefaultMenuRenderer2['default'], multi: false, noResultsText: 'No results found', onBlurResetsInput: true, onCloseResetsInput: true, openAfterFocus: false, optionComponent: _Option2['default'], pageSize: 5, placeholder: 'Select...', required: false, scrollMenuIntoView: true, searchable: true, simpleValue: false, tabSelectsValue: true, valueComponent: _Value2['default'], valueKey: 'value' }; }, getInitialState: function getInitialState() { return { inputValue: '', isFocused: false, isOpen: false, isPseudoFocused: false, required: false }; }, componentWillMount: function componentWillMount() { this._instancePrefix = 'react-select-' + (this.props.instanceId || ++instanceId) + '-'; var valueArray = this.getValueArray(this.props.value); if (this.props.required) { this.setState({ required: this.handleRequired(valueArray[0], this.props.multi) }); } }, componentDidMount: function componentDidMount() { if (this.props.autofocus) { this.focus(); } }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var valueArray = this.getValueArray(nextProps.value, nextProps); if (nextProps.required) { this.setState({ required: this.handleRequired(valueArray[0], nextProps.multi) }); } }, componentWillUpdate: function componentWillUpdate(nextProps, nextState) { if (nextState.isOpen !== this.state.isOpen) { this.toggleTouchOutsideEvent(nextState.isOpen); var handler = nextState.isOpen ? nextProps.onOpen : nextProps.onClose; handler && handler(); } }, componentDidUpdate: function componentDidUpdate(prevProps, prevState) { // focus to the selected option if (this.menu && this.focused && this.state.isOpen && !this.hasScrolledToOption) { var focusedOptionNode = _reactDom2['default'].findDOMNode(this.focused); var menuNode = _reactDom2['default'].findDOMNode(this.menu); menuNode.scrollTop = focusedOptionNode.offsetTop; this.hasScrolledToOption = true; } else if (!this.state.isOpen) { this.hasScrolledToOption = false; } if (this._scrollToFocusedOptionOnUpdate && this.focused && this.menu) { this._scrollToFocusedOptionOnUpdate = false; var focusedDOM = _reactDom2['default'].findDOMNode(this.focused); var menuDOM = _reactDom2['default'].findDOMNode(this.menu); var focusedRect = focusedDOM.getBoundingClientRect(); var menuRect = menuDOM.getBoundingClientRect(); if (focusedRect.bottom > menuRect.bottom || focusedRect.top < menuRect.top) { menuDOM.scrollTop = focusedDOM.offsetTop + focusedDOM.clientHeight - menuDOM.offsetHeight; } } if (this.props.scrollMenuIntoView && this.menuContainer) { var menuContainerRect = this.menuContainer.getBoundingClientRect(); if (window.innerHeight < menuContainerRect.bottom + this.props.menuBuffer) { window.scrollBy(0, menuContainerRect.bottom + this.props.menuBuffer - window.innerHeight); } } if (prevProps.disabled !== this.props.disabled) { this.setState({ isFocused: false }); // eslint-disable-line react/no-did-update-set-state this.closeMenu(); } }, componentWillUnmount: function componentWillUnmount() { document.removeEventListener('touchstart', this.handleTouchOutside); }, toggleTouchOutsideEvent: function toggleTouchOutsideEvent(enabled) { if (enabled) { document.addEventListener('touchstart', this.handleTouchOutside); } else { document.removeEventListener('touchstart', this.handleTouchOutside); } }, handleTouchOutside: function handleTouchOutside(event) { // handle touch outside on ios to dismiss menu if (this.wrapper && !this.wrapper.contains(event.target)) { this.closeMenu(); } }, focus: function focus() { if (!this.input) return; this.input.focus(); if (this.props.openAfterFocus) { this.setState({ isOpen: true }); } }, blurInput: function blurInput() { if (!this.input) return; this.input.blur(); }, handleTouchMove: function handleTouchMove(event) { // Set a flag that the view is being dragged this.dragging = true; }, handleTouchStart: function handleTouchStart(event) { // Set a flag that the view is not being dragged this.dragging = false; }, handleTouchEnd: function handleTouchEnd(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Fire the mouse events this.handleMouseDown(event); }, handleTouchEndClearValue: function handleTouchEndClearValue(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Clear the value this.clearValue(event); }, handleMouseDown: function handleMouseDown(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } if (event.target.tagName === 'INPUT') { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // for the non-searchable select, toggle the menu if (!this.props.searchable) { this.focus(); return this.setState({ isOpen: !this.state.isOpen }); } if (this.state.isFocused) { // On iOS, we can get into a state where we think the input is focused but it isn't really, // since iOS ignores programmatic calls to input.focus() that weren't triggered by a click event. // Call focus() again here to be safe. this.focus(); var input = this.input; if (typeof input.getInput === 'function') { // Get the actual DOM input if the ref is an <AutosizeInput /> component input = input.getInput(); } // clears the value so that the cursor will be at the end of input when the component re-renders input.value = ''; // if the input is focused, ensure the menu is open this.setState({ isOpen: true, isPseudoFocused: false }); } else { // otherwise, focus the input and open the menu this._openAfterFocus = true; this.focus(); } }, handleMouseDownOnArrow: function handleMouseDownOnArrow(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } // If the menu isn't open, let the event bubble to the main handleMouseDown if (!this.state.isOpen) { return; } // prevent default event handlers event.stopPropagation(); event.preventDefault(); // close the menu this.closeMenu(); }, handleMouseDownOnMenu: function handleMouseDownOnMenu(event) { // if the event was triggered by a mousedown and not the primary // button, or if the component is disabled, ignore it. if (this.props.disabled || event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this._openAfterFocus = true; this.focus(); }, closeMenu: function closeMenu() { if (this.props.onCloseResetsInput) { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi, inputValue: '' }); } else { this.setState({ isOpen: false, isPseudoFocused: this.state.isFocused && !this.props.multi, inputValue: this.state.inputValue }); } this.hasScrolledToOption = false; }, handleInputFocus: function handleInputFocus(event) { if (this.props.disabled) return; var isOpen = this.state.isOpen || this._openAfterFocus || this.props.openOnFocus; if (this.props.onFocus) { this.props.onFocus(event); } this.setState({ isFocused: true, isOpen: isOpen }); this._openAfterFocus = false; }, handleInputBlur: function handleInputBlur(event) { // The check for menu.contains(activeElement) is necessary to prevent IE11's scrollbar from closing the menu in certain contexts. if (this.menu && (this.menu === document.activeElement || this.menu.contains(document.activeElement))) { this.focus(); return; } if (this.props.onBlur) { this.props.onBlur(event); } var onBlurredState = { isFocused: false, isOpen: false, isPseudoFocused: false }; if (this.props.onBlurResetsInput) { onBlurredState.inputValue = ''; } this.setState(onBlurredState); }, handleInputChange: function handleInputChange(event) { var newInputValue = event.target.value; if (this.state.inputValue !== event.target.value && this.props.onInputChange) { var nextState = this.props.onInputChange(newInputValue); // Note: != used deliberately here to catch undefined and null if (nextState != null && typeof nextState !== 'object') { newInputValue = '' + nextState; } } this.setState({ isOpen: true, isPseudoFocused: false, inputValue: newInputValue }); }, handleKeyDown: function handleKeyDown(event) { if (this.props.disabled) return; if (typeof this.props.onInputKeyDown === 'function') { this.props.onInputKeyDown(event); if (event.defaultPrevented) { return; } } switch (event.keyCode) { case 8: // backspace if (!this.state.inputValue && this.props.backspaceRemoves) { event.preventDefault(); this.popValue(); } return; case 9: // tab if (event.shiftKey || !this.state.isOpen || !this.props.tabSelectsValue) { return; } this.selectFocusedOption(); return; case 13: // enter if (!this.state.isOpen) return; event.stopPropagation(); this.selectFocusedOption(); break; case 27: // escape if (this.state.isOpen) { this.closeMenu(); event.stopPropagation(); } else if (this.props.clearable && this.props.escapeClearsValue) { this.clearValue(event); event.stopPropagation(); } break; case 38: // up this.focusPreviousOption(); break; case 40: // down this.focusNextOption(); break; case 33: // page up this.focusPageUpOption(); break; case 34: // page down this.focusPageDownOption(); break; case 35: // end key if (event.shiftKey) { return; } this.focusEndOption(); break; case 36: // home key if (event.shiftKey) { return; } this.focusStartOption(); break; default: return; } event.preventDefault(); }, handleValueClick: function handleValueClick(option, event) { if (!this.props.onValueClick) return; this.props.onValueClick(option, event); }, handleMenuScroll: function handleMenuScroll(event) { if (!this.props.onMenuScrollToBottom) return; var target = event.target; if (target.scrollHeight > target.offsetHeight && !(target.scrollHeight - target.offsetHeight - target.scrollTop)) { this.props.onMenuScrollToBottom(); } }, handleRequired: function handleRequired(value, multi) { if (!value) return true; return multi ? value.length === 0 : Object.keys(value).length === 0; }, getOptionLabel: function getOptionLabel(op) { return op[this.props.labelKey]; }, /** * Turns a value into an array from the given options * @param {String|Number|Array} value - the value of the select input * @param {Object} nextProps - optionally specify the nextProps so the returned array uses the latest configuration * @returns {Array} the value of the select represented in an array */ getValueArray: function getValueArray(value, nextProps) { var _this = this; /** support optionally passing in the `nextProps` so `componentWillReceiveProps` updates will function as expected */ var props = typeof nextProps === 'object' ? nextProps : this.props; if (props.multi) { if (typeof value === 'string') value = value.split(props.delimiter); if (!Array.isArray(value)) { if (value === null || value === undefined) return []; value = [value]; } return value.map(function (value) { return _this.expandValue(value, props); }).filter(function (i) { return i; }); } var expandedValue = this.expandValue(value, props); return expandedValue ? [expandedValue] : []; }, /** * Retrieve a value from the given options and valueKey * @param {String|Number|Array} value - the selected value(s) * @param {Object} props - the Select component's props (or nextProps) */ expandValue: function expandValue(value, props) { var valueType = typeof value; if (valueType !== 'string' && valueType !== 'number' && valueType !== 'boolean') return value; var options = props.options; var valueKey = props.valueKey; if (!options) return; for (var i = 0; i < options.length; i++) { if (options[i][valueKey] === value) return options[i]; } }, setValue: function setValue(value) { var _this2 = this; if (this.props.autoBlur) { this.blurInput(); } if (!this.props.onChange) return; if (this.props.required) { var required = this.handleRequired(value, this.props.multi); this.setState({ required: required }); } if (this.props.simpleValue && value) { value = this.props.multi ? value.map(function (i) { return i[_this2.props.valueKey]; }).join(this.props.delimiter) : value[this.props.valueKey]; } this.props.onChange(value); }, selectValue: function selectValue(value) { var _this3 = this; //NOTE: update value in the callback to make sure the input value is empty so that there are no styling issues (Chrome had issue otherwise) this.hasScrolledToOption = false; if (this.props.multi) { this.setState({ inputValue: '', focusedIndex: null }, function () { _this3.addValue(value); }); } else { this.setState({ isOpen: false, inputValue: '', isPseudoFocused: this.state.isFocused }, function () { _this3.setValue(value); }); } }, addValue: function addValue(value) { var valueArray = this.getValueArray(this.props.value); this.setValue(valueArray.concat(value)); }, popValue: function popValue() { var valueArray = this.getValueArray(this.props.value); if (!valueArray.length) return; if (valueArray[valueArray.length - 1].clearableValue === false) return; this.setValue(valueArray.slice(0, valueArray.length - 1)); }, removeValue: function removeValue(value) { var valueArray = this.getValueArray(this.props.value); this.setValue(valueArray.filter(function (i) { return i !== value; })); this.focus(); }, clearValue: function clearValue(event) { // if the event was triggered by a mousedown and not the primary // button, ignore it. if (event && event.type === 'mousedown' && event.button !== 0) { return; } event.stopPropagation(); event.preventDefault(); this.setValue(this.getResetValue()); this.setState({ isOpen: false, inputValue: '' }, this.focus); }, getResetValue: function getResetValue() { if (this.props.resetValue !== undefined) { return this.props.resetValue; } else if (this.props.multi) { return []; } else { return null; } }, focusOption: function focusOption(option) { this.setState({ focusedOption: option }); }, focusNextOption: function focusNextOption() { this.focusAdjacentOption('next'); }, focusPreviousOption: function focusPreviousOption() { this.focusAdjacentOption('previous'); }, focusPageUpOption: function focusPageUpOption() { this.focusAdjacentOption('page_up'); }, focusPageDownOption: function focusPageDownOption() { this.focusAdjacentOption('page_down'); }, focusStartOption: function focusStartOption() { this.focusAdjacentOption('start'); }, focusEndOption: function focusEndOption() { this.focusAdjacentOption('end'); }, focusAdjacentOption: function focusAdjacentOption(dir) { var options = this._visibleOptions.map(function (option, index) { return { option: option, index: index }; }).filter(function (option) { return !option.option.disabled; }); this._scrollToFocusedOptionOnUpdate = true; if (!this.state.isOpen) { this.setState({ isOpen: true, inputValue: '', focusedOption: this._focusedOption || options[dir === 'next' ? 0 : options.length - 1].option }); return; } if (!options.length) return; var focusedIndex = -1; for (var i = 0; i < options.length; i++) { if (this._focusedOption === options[i].option) { focusedIndex = i; break; } } if (dir === 'next' && focusedIndex !== -1) { focusedIndex = (focusedIndex + 1) % options.length; } else if (dir === 'previous') { if (focusedIndex > 0) { focusedIndex = focusedIndex - 1; } else { focusedIndex = options.length - 1; } } else if (dir === 'start') { focusedIndex = 0; } else if (dir === 'end') { focusedIndex = options.length - 1; } else if (dir === 'page_up') { var potentialIndex = focusedIndex - this.props.pageSize; if (potentialIndex < 0) { focusedIndex = 0; } else { focusedIndex = potentialIndex; } } else if (dir === 'page_down') { var potentialIndex = focusedIndex + this.props.pageSize; if (potentialIndex > options.length - 1) { focusedIndex = options.length - 1; } else { focusedIndex = potentialIndex; } } if (focusedIndex === -1) { focusedIndex = 0; } this.setState({ focusedIndex: options[focusedIndex].index, focusedOption: options[focusedIndex].option }); }, getFocusedOption: function getFocusedOption() { return this._focusedOption; }, getInputValue: function getInputValue() { return this.state.inputValue; }, selectFocusedOption: function selectFocusedOption() { if (this._focusedOption) { return this.selectValue(this._focusedOption); } }, renderLoading: function renderLoading() { if (!this.props.isLoading) return; return _react2['default'].createElement( 'span', { className: 'Select-loading-zone', 'aria-hidden': 'true' }, _react2['default'].createElement('span', { className: 'Select-loading' }) ); }, renderValue: function renderValue(valueArray, isOpen) { var _this4 = this; var renderLabel = this.props.valueRenderer || this.getOptionLabel; var ValueComponent = this.props.valueComponent; if (!valueArray.length) { return !this.state.inputValue ? _react2['default'].createElement( 'div', { className: 'Select-placeholder' }, this.props.placeholder ) : null; } var onClick = this.props.onValueClick ? this.handleValueClick : null; if (this.props.multi) { return valueArray.map(function (value, i) { return _react2['default'].createElement( ValueComponent, { id: _this4._instancePrefix + '-value-' + i, instancePrefix: _this4._instancePrefix, disabled: _this4.props.disabled || value.clearableValue === false, key: 'value-' + i + '-' + value[_this4.props.valueKey], onClick: onClick, onRemove: _this4.removeValue, value: value }, renderLabel(value, i), _react2['default'].createElement( 'span', { className: 'Select-aria-only' }, ' ' ) ); }); } else if (!this.state.inputValue) { if (isOpen) onClick = null; return _react2['default'].createElement( ValueComponent, { id: this._instancePrefix + '-value-item', disabled: this.props.disabled, instancePrefix: this._instancePrefix, onClick: onClick, value: valueArray[0] }, renderLabel(valueArray[0]) ); } }, renderInput: function renderInput(valueArray, focusedOptionIndex) { var _this5 = this; if (this.props.inputRenderer) { return this.props.inputRenderer(); } else { var _classNames; var className = (0, _classnames2['default'])('Select-input', this.props.inputProps.className); var isOpen = !!this.state.isOpen; var ariaOwns = (0, _classnames2['default'])((_classNames = {}, _defineProperty(_classNames, this._instancePrefix + '-list', isOpen), _defineProperty(_classNames, this._instancePrefix + '-backspace-remove-message', this.props.multi && !this.props.disabled && this.state.isFocused && !this.state.inputValue), _classNames)); // TODO: Check how this project includes Object.assign() var inputProps = _extends({}, this.props.inputProps, { role: 'combobox', 'aria-expanded': '' + isOpen, 'aria-owns': ariaOwns, 'aria-haspopup': '' + isOpen, 'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value', 'aria-labelledby': this.props['aria-labelledby'], 'aria-label': this.props['aria-label'], className: className, tabIndex: this.props.tabIndex, onBlur: this.handleInputBlur, onChange: this.handleInputChange, onFocus: this.handleInputFocus, ref: function ref(_ref) { return _this5.input = _ref; }, required: this.state.required, value: this.state.inputValue }); if (this.props.disabled || !this.props.searchable) { var _props$inputProps = this.props.inputProps; var inputClassName = _props$inputProps.inputClassName; var divProps = _objectWithoutProperties(_props$inputProps, ['inputClassName']); return _react2['default'].createElement('div', _extends({}, divProps, { role: 'combobox', 'aria-expanded': isOpen, 'aria-owns': isOpen ? this._instancePrefix + '-list' : this._instancePrefix + '-value', 'aria-activedescendant': isOpen ? this._instancePrefix + '-option-' + focusedOptionIndex : this._instancePrefix + '-value', className: className, tabIndex: this.props.tabIndex || 0, onBlur: this.handleInputBlur, onFocus: this.handleInputFocus, ref: function (ref) { return _this5.input = ref; }, 'aria-readonly': '' + !!this.props.disabled, style: { border: 0, width: 1, display: 'inline-block' } })); } if (this.props.autosize) { return _react2['default'].createElement(_reactInputAutosize2['default'], _extends({}, inputProps, { minWidth: '5px' })); } return _react2['default'].createElement( 'div', { className: className }, _react2['default'].createElement('input', inputProps) ); } }, renderClear: function renderClear() { if (!this.props.clearable || !this.props.value || this.props.value === 0 || this.props.multi && !this.props.value.length || this.props.disabled || this.props.isLoading) return; return _react2['default'].createElement( 'span', { className: 'Select-clear-zone', title: this.props.multi ? this.props.clearAllText : this.props.clearValueText, 'aria-label': this.props.multi ? this.props.clearAllText : this.props.clearValueText, onMouseDown: this.clearValue, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove, onTouchEnd: this.handleTouchEndClearValue }, _react2['default'].createElement('span', { className: 'Select-clear', dangerouslySetInnerHTML: { __html: '&times;' } }) ); }, renderArrow: function renderArrow() { var onMouseDown = this.handleMouseDownOnArrow; var arrow = this.props.arrowRenderer({ onMouseDown: onMouseDown }); return _react2['default'].createElement( 'span', { className: 'Select-arrow-zone', onMouseDown: onMouseDown }, arrow ); }, filterOptions: function filterOptions(excludeOptions) { var filterValue = this.state.inputValue; var options = this.props.options || []; if (this.props.filterOptions) { // Maintain backwards compatibility with boolean attribute var filterOptions = typeof this.props.filterOptions === 'function' ? this.props.filterOptions : _utilsDefaultFilterOptions2['default']; return filterOptions(options, filterValue, excludeOptions, { filterOption: this.props.filterOption, ignoreAccents: this.props.ignoreAccents, ignoreCase: this.props.ignoreCase, labelKey: this.props.labelKey, matchPos: this.props.matchPos, matchProp: this.props.matchProp, valueKey: this.props.valueKey }); } else { return options; } }, onOptionRef: function onOptionRef(ref, isFocused) { if (isFocused) { this.focused = ref; } }, renderMenu: function renderMenu(options, valueArray, focusedOption) { if (options && options.length) { return this.props.menuRenderer({ focusedOption: focusedOption, focusOption: this.focusOption, instancePrefix: this._instancePrefix, labelKey: this.props.labelKey, onFocus: this.focusOption, onSelect: this.selectValue, optionClassName: this.props.optionClassName, optionComponent: this.props.optionComponent, optionRenderer: this.props.optionRenderer || this.getOptionLabel, options: options, selectValue: this.selectValue, valueArray: valueArray, valueKey: this.props.valueKey, onOptionRef: this.onOptionRef }); } else if (this.props.noResultsText) { return _react2['default'].createElement( 'div', { className: 'Select-noresults' }, this.props.noResultsText ); } else { return null; } }, renderHiddenField: function renderHiddenField(valueArray) { var _this6 = this; if (!this.props.name) return; if (this.props.joinValues) { var value = valueArray.map(function (i) { return stringifyValue(i[_this6.props.valueKey]); }).join(this.props.delimiter); return _react2['default'].createElement('input', { type: 'hidden', ref: function (ref) { return _this6.value = ref; }, name: this.props.name, value: value, disabled: this.props.disabled }); } return valueArray.map(function (item, index) { return _react2['default'].createElement('input', { key: 'hidden.' + index, type: 'hidden', ref: 'value' + index, name: _this6.props.name, value: stringifyValue(item[_this6.props.valueKey]), disabled: _this6.props.disabled }); }); }, getFocusableOptionIndex: function getFocusableOptionIndex(selectedOption) { var options = this._visibleOptions; if (!options.length) return null; var focusedOption = this.state.focusedOption || selectedOption; if (focusedOption && !focusedOption.disabled) { var focusedOptionIndex = options.indexOf(focusedOption); if (focusedOptionIndex !== -1) { return focusedOptionIndex; } } for (var i = 0; i < options.length; i++) { if (!options[i].disabled) return i; } return null; }, renderOuter: function renderOuter(options, valueArray, focusedOption) { var _this7 = this; var menu = this.renderMenu(options, valueArray, focusedOption); if (!menu) { return null; } return _react2['default'].createElement( 'div', { ref: function (ref) { return _this7.menuContainer = ref; }, className: 'Select-menu-outer', style: this.props.menuContainerStyle }, _react2['default'].createElement( 'div', { ref: function (ref) { return _this7.menu = ref; }, role: 'listbox', className: 'Select-menu', id: this._instancePrefix + '-list', style: this.props.menuStyle, onScroll: this.handleMenuScroll, onMouseDown: this.handleMouseDownOnMenu }, menu ) ); }, render: function render() { var _this8 = this; var valueArray = this.getValueArray(this.props.value); var options = this._visibleOptions = this.filterOptions(this.props.multi ? this.getValueArray(this.props.value) : null); var isOpen = this.state.isOpen; if (this.props.multi && !options.length && valueArray.length && !this.state.inputValue) isOpen = false; var focusedOptionIndex = this.getFocusableOptionIndex(valueArray[0]); var focusedOption = null; if (focusedOptionIndex !== null) { focusedOption = this._focusedOption = options[focusedOptionIndex]; } else { focusedOption = this._focusedOption = null; } var className = (0, _classnames2['default'])('Select', this.props.className, { 'Select--multi': this.props.multi, 'Select--single': !this.props.multi, 'is-disabled': this.props.disabled, 'is-focused': this.state.isFocused, 'is-loading': this.props.isLoading, 'is-open': isOpen, 'is-pseudo-focused': this.state.isPseudoFocused, 'is-searchable': this.props.searchable, 'has-value': valueArray.length }); var removeMessage = null; if (this.props.multi && !this.props.disabled && valueArray.length && !this.state.inputValue && this.state.isFocused && this.props.backspaceRemoves) { removeMessage = _react2['default'].createElement( 'span', { id: this._instancePrefix + '-backspace-remove-message', className: 'Select-aria-only', 'aria-live': 'assertive' }, this.props.backspaceToRemoveMessage.replace('{label}', valueArray[valueArray.length - 1][this.props.labelKey]) ); } return _react2['default'].createElement( 'div', { ref: function (ref) { return _this8.wrapper = ref; }, className: className, style: this.props.wrapperStyle }, this.renderHiddenField(valueArray), _react2['default'].createElement( 'div', { ref: function (ref) { return _this8.control = ref; }, className: 'Select-control', style: this.props.style, onKeyDown: this.handleKeyDown, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleTouchEnd, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove }, _react2['default'].createElement( 'span', { className: 'Select-multi-value-wrapper', id: this._instancePrefix + '-value' }, this.renderValue(valueArray, isOpen), this.renderInput(valueArray, focusedOptionIndex) ), removeMessage, this.renderLoading(), this.renderClear(), this.renderArrow() ), isOpen ? this.renderOuter(options, !this.props.multi ? valueArray : null, focusedOption) : null ); } }); exports['default'] = Select; module.exports = exports['default']; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2016 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ /* global define */ (function () { 'use strict'; var hasOwn = {}.hasOwnProperty; function classNames () { var classes = []; for (var i = 0; i < arguments.length; i++) { var arg = arguments[i]; if (!arg) continue; var argType = typeof arg; if (argType === 'string' || argType === 'number') { classes.push(arg); } else if (Array.isArray(arg)) { classes.push(classNames.apply(null, arg)); } else if (argType === 'object') { for (var key in arg) { if (hasOwn.call(arg, key) && arg[key]) { classes.push(key); } } } } return classes.join(' '); } if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } else if (true) { // register as 'classnames', consistent with npm package name !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function () { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { window.classNames = classNames; } }()); /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _immutable = __webpack_require__(71); var isImmutableCollection = function isImmutableCollection(objToVerify) { return _immutable.Iterable.isIterable(objToVerify); }; exports['default'] = isImmutableCollection; /***/ }, /* 34 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; var getMixedTypeValueRetriever = function getMixedTypeValueRetriever(isImmutable) { var retObj = {}; var retriever = function retriever(item, key) { return item[key]; }; var immutableRetriever = function immutableRetriever(immutable, key) { return immutable.get(key); }; retObj.getValue = isImmutable ? immutableRetriever : retriever; return retObj; }; exports["default"] = getMixedTypeValueRetriever; /***/ }, /* 35 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = isDisposable; function isDisposable(obj) { return Boolean(obj && typeof obj.dispose === 'function'); } module.exports = exports['default']; /***/ }, /* 36 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = ownerDocument; function ownerDocument(node) { return node && node.ownerDocument || document; } module.exports = exports["default"]; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(7), root = __webpack_require__(4); /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'); module.exports = Map; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { var mapCacheClear = __webpack_require__(253), mapCacheDelete = __webpack_require__(254), mapCacheGet = __webpack_require__(255), mapCacheHas = __webpack_require__(256), mapCacheSet = __webpack_require__(257); /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; module.exports = MapCache; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(204); /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } module.exports = arrayIncludes; /***/ }, /* 40 */ /***/ function(module, exports) { /** * This function is like `arrayIncludes` except that it accepts a comparator. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @param {Function} comparator The comparator invoked per element. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludesWith(array, value, comparator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (comparator(value, array[index])) { return true; } } return false; } module.exports = arrayIncludesWith; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { var defineProperty = __webpack_require__(82); /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } module.exports = baseAssignValue; /***/ }, /* 42 */ /***/ function(module, exports) { /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } module.exports = baseUnary; /***/ }, /* 43 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } module.exports = isIndex; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(3), isSymbol = __webpack_require__(49); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } module.exports = isKey; /***/ }, /* 45 */ /***/ function(module, exports) { /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } module.exports = setToArray; /***/ }, /* 46 */ /***/ function(module, exports) { /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 47 */ /***/ function(module, exports, __webpack_require__) { var baseIsArguments = __webpack_require__(206), isObjectLike = __webpack_require__(9); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; module.exports = isArguments; /***/ }, /* 48 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(10), isObjectLike = __webpack_require__(9); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } module.exports = isSymbol; /***/ }, /* 50 */ /***/ function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(75), baseKeys = __webpack_require__(213), isArrayLike = __webpack_require__(17); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } module.exports = keys; /***/ }, /* 51 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _store = __webpack_require__(29); var _store2 = _interopRequireDefault(_store); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { getItem: function getItem() { return _store2.default.getState().currentItem; }, getPosition: function getPosition() { var _store$getState = _store2.default.getState(); var x = _store$getState.x; var y = _store$getState.y; return { x: x, y: y }; }, hideMenu: function hideMenu() { _store2.default.dispatch({ type: "SET_PARAMS", data: { isVisible: false, currentItem: {} } }); } }; /* eslint-disable object-property-newline */ /***/ }, /* 52 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; var FILE = '__NATIVE_FILE__'; exports.FILE = FILE; var URL = '__NATIVE_URL__'; exports.URL = URL; var TEXT = '__NATIVE_TEXT__'; exports.TEXT = TEXT; /***/ }, /* 53 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = shallowEqual; function shallowEqual(objA, objB) { if (objA === objB) { return true; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i]) || objA[keysA[i]] !== objB[keysA[i]]) { return false; } var valA = objA[keysA[i]]; var valB = objB[keysA[i]]; if (valA !== valB) { return false; } } return true; } module.exports = exports["default"]; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ActionTypes = undefined; exports['default'] = createStore; var _isPlainObject = __webpack_require__(6); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _symbolObservable = __webpack_require__(339); var _symbolObservable2 = _interopRequireDefault(_symbolObservable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * These are private action types reserved by Redux. * For any unknown actions, you must return the current state. * If the current state is undefined, you must return the initial state. * Do not reference these action types directly in your code. */ var ActionTypes = exports.ActionTypes = { INIT: '@@redux/INIT' }; /** * Creates a Redux store that holds the state tree. * The only way to change the data in the store is to call `dispatch()` on it. * * There should only be a single store in your app. To specify how different * parts of the state tree respond to actions, you may combine several reducers * into a single reducer function by using `combineReducers`. * * @param {Function} reducer A function that returns the next state tree, given * the current state tree and the action to handle. * * @param {any} [preloadedState] The initial state. You may optionally specify it * to hydrate the state from the server in universal apps, or to restore a * previously serialized user session. * If you use `combineReducers` to produce the root reducer function, this must be * an object with the same shape as `combineReducers` keys. * * @param {Function} enhancer The store enhancer. You may optionally specify it * to enhance the store with third-party capabilities such as middleware, * time travel, persistence, etc. The only store enhancer that ships with Redux * is `applyMiddleware()`. * * @returns {Store} A Redux store that lets you read the state, dispatch actions * and subscribe to changes. */ function createStore(reducer, preloadedState, enhancer) { var _ref2; if (typeof preloadedState === 'function' && typeof enhancer === 'undefined') { enhancer = preloadedState; preloadedState = undefined; } if (typeof enhancer !== 'undefined') { if (typeof enhancer !== 'function') { throw new Error('Expected the enhancer to be a function.'); } return enhancer(createStore)(reducer, preloadedState); } if (typeof reducer !== 'function') { throw new Error('Expected the reducer to be a function.'); } var currentReducer = reducer; var currentState = preloadedState; var currentListeners = []; var nextListeners = currentListeners; var isDispatching = false; function ensureCanMutateNextListeners() { if (nextListeners === currentListeners) { nextListeners = currentListeners.slice(); } } /** * Reads the state tree managed by the store. * * @returns {any} The current state tree of your application. */ function getState() { return currentState; } /** * Adds a change listener. It will be called any time an action is dispatched, * and some part of the state tree may potentially have changed. You may then * call `getState()` to read the current state tree inside the callback. * * You may call `dispatch()` from a change listener, with the following * caveats: * * 1. The subscriptions are snapshotted just before every `dispatch()` call. * If you subscribe or unsubscribe while the listeners are being invoked, this * will not have any effect on the `dispatch()` that is currently in progress. * However, the next `dispatch()` call, whether nested or not, will use a more * recent snapshot of the subscription list. * * 2. The listener should not expect to see all state changes, as the state * might have been updated multiple times during a nested `dispatch()` before * the listener is called. It is, however, guaranteed that all subscribers * registered before the `dispatch()` started will be called with the latest * state by the time it exits. * * @param {Function} listener A callback to be invoked on every dispatch. * @returns {Function} A function to remove this change listener. */ function subscribe(listener) { if (typeof listener !== 'function') { throw new Error('Expected listener to be a function.'); } var isSubscribed = true; ensureCanMutateNextListeners(); nextListeners.push(listener); return function unsubscribe() { if (!isSubscribed) { return; } isSubscribed = false; ensureCanMutateNextListeners(); var index = nextListeners.indexOf(listener); nextListeners.splice(index, 1); }; } /** * Dispatches an action. It is the only way to trigger a state change. * * The `reducer` function, used to create the store, will be called with the * current state tree and the given `action`. Its return value will * be considered the **next** state of the tree, and the change listeners * will be notified. * * The base implementation only supports plain object actions. If you want to * dispatch a Promise, an Observable, a thunk, or something else, you need to * wrap your store creating function into the corresponding middleware. For * example, see the documentation for the `redux-thunk` package. Even the * middleware will eventually dispatch plain object actions using this method. * * @param {Object} action A plain object representing “what changed”. It is * a good idea to keep actions serializable so you can record and replay user * sessions, or use the time travelling `redux-devtools`. An action must have * a `type` property which may not be `undefined`. It is a good idea to use * string constants for action types. * * @returns {Object} For convenience, the same action object you dispatched. * * Note that, if you use a custom middleware, it may wrap `dispatch()` to * return something else (for example, a Promise you can await). */ function dispatch(action) { if (!(0, _isPlainObject2['default'])(action)) { throw new Error('Actions must be plain objects. ' + 'Use custom middleware for async actions.'); } if (typeof action.type === 'undefined') { throw new Error('Actions may not have an undefined "type" property. ' + 'Have you misspelled a constant?'); } if (isDispatching) { throw new Error('Reducers may not dispatch actions.'); } try { isDispatching = true; currentState = currentReducer(currentState, action); } finally { isDispatching = false; } var listeners = currentListeners = nextListeners; for (var i = 0; i < listeners.length; i++) { listeners[i](); } return action; } /** * Replaces the reducer currently used by the store to calculate the state. * * You might need this if your app implements code splitting and you want to * load some of the reducers dynamically. You might also need this if you * implement a hot reloading mechanism for Redux. * * @param {Function} nextReducer The reducer for the store to use instead. * @returns {void} */ function replaceReducer(nextReducer) { if (typeof nextReducer !== 'function') { throw new Error('Expected the nextReducer to be a function.'); } currentReducer = nextReducer; dispatch({ type: ActionTypes.INIT }); } /** * Interoperability point for observable/reactive libraries. * @returns {observable} A minimal observable of state changes. * For more information, see the observable proposal: * https://github.com/zenparsing/es-observable */ function observable() { var _ref; var outerSubscribe = subscribe; return _ref = { /** * The minimal observable subscription method. * @param {Object} observer Any object that can be used as an observer. * The observer object should have a `next` method. * @returns {subscription} An object with an `unsubscribe` method that can * be used to unsubscribe the observable from the store, and prevent further * emission of values from the observable. */ subscribe: function subscribe(observer) { if (typeof observer !== 'object') { throw new TypeError('Expected the observer to be an object.'); } function observeState() { if (observer.next) { observer.next(getState()); } } observeState(); var unsubscribe = outerSubscribe(observeState); return { unsubscribe: unsubscribe }; } }, _ref[_symbolObservable2['default']] = function () { return this; }, _ref; } // When a store is created, an "INIT" action is dispatched so that every // reducer returns their initial state. This effectively populates // the initial state tree. dispatch({ type: ActionTypes.INIT }); return _ref2 = { dispatch: dispatch, subscribe: subscribe, getState: getState, replaceReducer: replaceReducer }, _ref2[_symbolObservable2['default']] = observable, _ref2; } /***/ }, /* 55 */ /***/ function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 56 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; var DragItemTypes = exports.DragItemTypes = { Column: 'column' }; /***/ }, /* 57 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.shouldRowUpdate = undefined; var _ColumnMetrics = __webpack_require__(117); var _ColumnMetrics2 = _interopRequireDefault(_ColumnMetrics); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function doesRowContainSelectedCell(props) { var selected = props.cellMetaData.selected; if (selected && selected.rowIdx === props.idx) { return true; } return false; } function willRowBeDraggedOver(props) { var dragged = props.cellMetaData.dragged; return dragged != null && (dragged.rowIdx >= 0 || dragged.complete === true); } function hasRowBeenCopied(props) { var copied = props.cellMetaData.copied; return copied != null && copied.rowIdx === props.idx; } var shouldRowUpdate = exports.shouldRowUpdate = function shouldRowUpdate(nextProps, currentProps) { return !_ColumnMetrics2['default'].sameColumns(currentProps.columns, nextProps.columns, _ColumnMetrics2['default'].sameColumn) || doesRowContainSelectedCell(currentProps) || doesRowContainSelectedCell(nextProps) || willRowBeDraggedOver(nextProps) || nextProps.row !== currentProps.row || currentProps.colDisplayStart !== nextProps.colDisplayStart || currentProps.colDisplayEnd !== nextProps.colDisplayEnd || currentProps.colVisibleStart !== nextProps.colVisibleStart || currentProps.colVisibleEnd !== nextProps.colVisibleEnd || hasRowBeenCopied(currentProps) || currentProps.isSelected !== nextProps.isSelected || nextProps.height !== currentProps.height || currentProps.isOver !== nextProps.isOver || currentProps.canDrop !== nextProps.canDrop || currentProps.forceUpdate === true; }; exports['default'] = shouldRowUpdate; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _reselect = __webpack_require__(337); var _isEmptyObject = __webpack_require__(151); var _isEmptyObject2 = _interopRequireDefault(_isEmptyObject); var _isEmptyArray = __webpack_require__(62); var _isEmptyArray2 = _interopRequireDefault(_isEmptyArray); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var groupRows = __webpack_require__(126); var filterRows = __webpack_require__(125); var sortRows = __webpack_require__(128); var getInputRows = function getInputRows(state) { return state.rows; }; var getFilters = function getFilters(state) { return state.filters; }; var getFilteredRows = (0, _reselect.createSelector)([getFilters, getInputRows], function (filters) { var rows = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; if (!filters || (0, _isEmptyObject2['default'])(filters)) { return rows; } return filterRows(filters, rows); }); var getSortColumn = function getSortColumn(state) { return state.sortColumn; }; var getSortDirection = function getSortDirection(state) { return state.sortDirection; }; var getSortedRows = (0, _reselect.createSelector)([getFilteredRows, getSortColumn, getSortDirection], function (rows, sortColumn, sortDirection) { if (!sortDirection && !sortColumn) { return rows; } return sortRows(rows, sortColumn, sortDirection); }); var getGroupedColumns = function getGroupedColumns(state) { return state.groupBy; }; var getExpandedRows = function getExpandedRows(state) { return state.expandedRows; }; var getFlattenedGroupedRows = (0, _reselect.createSelector)([getSortedRows, getGroupedColumns, getExpandedRows], function (rows, groupedColumns) { var expandedRows = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; if (!groupedColumns || (0, _isEmptyObject2['default'])(groupedColumns) || (0, _isEmptyArray2['default'])(groupedColumns)) { return rows; } return groupRows(rows, groupedColumns, expandedRows); }); var getSelectedKeys = function getSelectedKeys(state) { return state.selectedKeys; }; var getRowKey = function getRowKey(state) { return state.rowKey; }; var getSelectedRowsByKey = (0, _reselect.createSelector)([getRowKey, getSelectedKeys, getInputRows], function (rowKey, selectedKeys) { var rows = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; return selectedKeys.map(function (k) { return rows.filter(function (r) { return r[rowKey] === k; })[0]; }); }); var Selectors = { getRows: getFlattenedGroupedRows, getSelectedRowsByKey: getSelectedRowsByKey }; module.exports = Selectors; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _Constants = __webpack_require__(56); var _reactDnd = __webpack_require__(12); var _HeaderCell = __webpack_require__(120); var _HeaderCell2 = _interopRequireDefault(_HeaderCell); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var DraggableHeaderCell = function (_Component) { _inherits(DraggableHeaderCell, _Component); function DraggableHeaderCell() { _classCallCheck(this, DraggableHeaderCell); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } DraggableHeaderCell.prototype.componentDidMount = function componentDidMount() { var connectDragPreview = this.props.connectDragPreview; var img = new Image(); img.src = './assets/images/drag_column_full.png'; img.onload = function () { connectDragPreview(img); }; }; DraggableHeaderCell.prototype.setScrollLeft = function setScrollLeft(scrollLeft) { var node = ReactDOM.findDOMNode(this); node.style.webkitTransform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; node.style.transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; }; DraggableHeaderCell.prototype.render = function render() { var _props = this.props, connectDragSource = _props.connectDragSource, isDragging = _props.isDragging; if (isDragging) { return null; } return connectDragSource(_react2['default'].createElement( 'div', { style: { cursor: 'move' } }, _react2['default'].createElement(_HeaderCell2['default'], this.props) )); }; return DraggableHeaderCell; }(_react.Component); DraggableHeaderCell.propTypes = { connectDragSource: _react.PropTypes.func.isRequired, connectDragPreview: _react.PropTypes.func.isRequired, isDragging: _react.PropTypes.bool.isRequired }; function collect(connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), connectDragPreview: connect.dragPreview() }; } var headerCellSource = { beginDrag: function beginDrag(props) { return props.column; }, endDrag: function endDrag(props) { return props.column; } }; exports['default'] = (0, _reactDnd.DragSource)(_Constants.DragItemTypes.Column, headerCellSource, collect)(DraggableHeaderCell); /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(1); var CheckboxEditor = React.createClass({ displayName: 'CheckboxEditor', propTypes: { value: React.PropTypes.bool, rowIdx: React.PropTypes.number, column: React.PropTypes.shape({ key: React.PropTypes.string, onCellChange: React.PropTypes.func }), dependentValues: React.PropTypes.object }, handleChange: function handleChange(e) { this.props.column.onCellChange(this.props.rowIdx, this.props.column.key, this.props.dependentValues, e); }, render: function render() { var checked = this.props.value != null ? this.props.value : false; var checkboxName = 'checkbox' + this.props.rowIdx; return React.createElement( 'div', { className: 'react-grid-checkbox-container', onClick: this.handleChange }, React.createElement('input', { className: 'react-grid-checkbox', type: 'checkbox', name: checkboxName, checked: checked }), React.createElement('label', { htmlFor: checkboxName, className: 'react-grid-checkbox-label' }) ); } }); module.exports = CheckboxEditor; /***/ }, /* 61 */ /***/ 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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var React = __webpack_require__(1); var ReactDOM = __webpack_require__(5); var ExcelColumn = __webpack_require__(13); var EditorBase = function (_React$Component) { _inherits(EditorBase, _React$Component); function EditorBase() { _classCallCheck(this, EditorBase); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } EditorBase.prototype.getStyle = function getStyle() { return { width: '100%' }; }; EditorBase.prototype.getValue = function getValue() { var updated = {}; updated[this.props.column.key] = this.getInputNode().value; return updated; }; EditorBase.prototype.getInputNode = function getInputNode() { var domNode = ReactDOM.findDOMNode(this); if (domNode.tagName === 'INPUT') { return domNode; } return domNode.querySelector('input:not([type=hidden])'); }; EditorBase.prototype.inheritContainerStyles = function inheritContainerStyles() { return true; }; return EditorBase; }(React.Component); EditorBase.propTypes = { onKeyDown: React.PropTypes.func.isRequired, value: React.PropTypes.any.isRequired, onBlur: React.PropTypes.func.isRequired, column: React.PropTypes.shape(ExcelColumn).isRequired, commit: React.PropTypes.func.isRequired }; module.exports = EditorBase; /***/ }, /* 62 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; var isEmptyArray = function isEmptyArray(obj) { return Array.isArray(obj) && obj.length === 0; }; exports["default"] = isEmptyArray; /***/ }, /* 63 */ /***/ function(module, exports) { 'use strict'; module.exports = function isColumnsImmutable(columns) { return typeof Immutable !== 'undefined' && columns instanceof Immutable.List; }; /***/ }, /* 64 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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 _typeof(obj) { return obj && obj.constructor === Symbol ? 'symbol' : typeof obj; } var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodashIsArray = __webpack_require__(3); var _lodashIsArray2 = _interopRequireDefault(_lodashIsArray); var _utilsGetNextUniqueId = __webpack_require__(170); var _utilsGetNextUniqueId2 = _interopRequireDefault(_utilsGetNextUniqueId); var _actionsRegistry = __webpack_require__(19); var _asap = __webpack_require__(114); var _asap2 = _interopRequireDefault(_asap); var HandlerRoles = { SOURCE: 'SOURCE', TARGET: 'TARGET' }; function validateSourceContract(source) { _invariant2['default'](typeof source.canDrag === 'function', 'Expected canDrag to be a function.'); _invariant2['default'](typeof source.beginDrag === 'function', 'Expected beginDrag to be a function.'); _invariant2['default'](typeof source.endDrag === 'function', 'Expected endDrag to be a function.'); } function validateTargetContract(target) { _invariant2['default'](typeof target.canDrop === 'function', 'Expected canDrop to be a function.'); _invariant2['default'](typeof target.hover === 'function', 'Expected hover to be a function.'); _invariant2['default'](typeof target.drop === 'function', 'Expected beginDrag to be a function.'); } function validateType(type, allowArray) { if (allowArray && _lodashIsArray2['default'](type)) { type.forEach(function (t) { return validateType(t, false); }); return; } _invariant2['default'](typeof type === 'string' || (typeof type === 'undefined' ? 'undefined' : _typeof(type)) === 'symbol', allowArray ? 'Type can only be a string, a symbol, or an array of either.' : 'Type can only be a string or a symbol.'); } function getNextHandlerId(role) { var id = _utilsGetNextUniqueId2['default']().toString(); switch (role) { case HandlerRoles.SOURCE: return 'S' + id; case HandlerRoles.TARGET: return 'T' + id; default: _invariant2['default'](false, 'Unknown role: ' + role); } } function parseRoleFromHandlerId(handlerId) { switch (handlerId[0]) { case 'S': return HandlerRoles.SOURCE; case 'T': return HandlerRoles.TARGET; default: _invariant2['default'](false, 'Cannot parse handler ID: ' + handlerId); } } var HandlerRegistry = (function () { function HandlerRegistry(store) { _classCallCheck(this, HandlerRegistry); this.store = store; this.types = {}; this.handlers = {}; this.pinnedSourceId = null; this.pinnedSource = null; } HandlerRegistry.prototype.addSource = function addSource(type, source) { validateType(type); validateSourceContract(source); var sourceId = this.addHandler(HandlerRoles.SOURCE, type, source); this.store.dispatch(_actionsRegistry.addSource(sourceId)); return sourceId; }; HandlerRegistry.prototype.addTarget = function addTarget(type, target) { validateType(type, true); validateTargetContract(target); var targetId = this.addHandler(HandlerRoles.TARGET, type, target); this.store.dispatch(_actionsRegistry.addTarget(targetId)); return targetId; }; HandlerRegistry.prototype.addHandler = function addHandler(role, type, handler) { var id = getNextHandlerId(role); this.types[id] = type; this.handlers[id] = handler; return id; }; HandlerRegistry.prototype.containsHandler = function containsHandler(handler) { var _this = this; return Object.keys(this.handlers).some(function (key) { return _this.handlers[key] === handler; }); }; HandlerRegistry.prototype.getSource = function getSource(sourceId, includePinned) { _invariant2['default'](this.isSourceId(sourceId), 'Expected a valid source ID.'); var isPinned = includePinned && sourceId === this.pinnedSourceId; var source = isPinned ? this.pinnedSource : this.handlers[sourceId]; return source; }; HandlerRegistry.prototype.getTarget = function getTarget(targetId) { _invariant2['default'](this.isTargetId(targetId), 'Expected a valid target ID.'); return this.handlers[targetId]; }; HandlerRegistry.prototype.getSourceType = function getSourceType(sourceId) { _invariant2['default'](this.isSourceId(sourceId), 'Expected a valid source ID.'); return this.types[sourceId]; }; HandlerRegistry.prototype.getTargetType = function getTargetType(targetId) { _invariant2['default'](this.isTargetId(targetId), 'Expected a valid target ID.'); return this.types[targetId]; }; HandlerRegistry.prototype.isSourceId = function isSourceId(handlerId) { var role = parseRoleFromHandlerId(handlerId); return role === HandlerRoles.SOURCE; }; HandlerRegistry.prototype.isTargetId = function isTargetId(handlerId) { var role = parseRoleFromHandlerId(handlerId); return role === HandlerRoles.TARGET; }; HandlerRegistry.prototype.removeSource = function removeSource(sourceId) { var _this2 = this; _invariant2['default'](this.getSource(sourceId), 'Expected an existing source.'); this.store.dispatch(_actionsRegistry.removeSource(sourceId)); _asap2['default'](function () { delete _this2.handlers[sourceId]; delete _this2.types[sourceId]; }); }; HandlerRegistry.prototype.removeTarget = function removeTarget(targetId) { var _this3 = this; _invariant2['default'](this.getTarget(targetId), 'Expected an existing target.'); this.store.dispatch(_actionsRegistry.removeTarget(targetId)); _asap2['default'](function () { delete _this3.handlers[targetId]; delete _this3.types[targetId]; }); }; HandlerRegistry.prototype.pinSource = function pinSource(sourceId) { var source = this.getSource(sourceId); _invariant2['default'](source, 'Expected an existing source.'); this.pinnedSourceId = sourceId; this.pinnedSource = source; }; HandlerRegistry.prototype.unpinSource = function unpinSource() { _invariant2['default'](this.pinnedSource, 'No source is pinned at the time.'); this.pinnedSourceId = null; this.pinnedSource = null; }; return HandlerRegistry; })(); exports['default'] = HandlerRegistry; module.exports = exports['default']; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = dirtyHandlerIds; exports.areDirty = areDirty; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashXor = __webpack_require__(288); var _lodashXor2 = _interopRequireDefault(_lodashXor); var _lodashIntersection = __webpack_require__(282); var _lodashIntersection2 = _interopRequireDefault(_lodashIntersection); var _actionsDragDrop = __webpack_require__(18); var _actionsRegistry = __webpack_require__(19); var NONE = []; var ALL = []; function dirtyHandlerIds(state, action, dragOperation) { if (state === undefined) state = NONE; switch (action.type) { case _actionsDragDrop.HOVER: break; case _actionsRegistry.ADD_SOURCE: case _actionsRegistry.ADD_TARGET: case _actionsRegistry.REMOVE_TARGET: case _actionsRegistry.REMOVE_SOURCE: return NONE; case _actionsDragDrop.BEGIN_DRAG: case _actionsDragDrop.PUBLISH_DRAG_SOURCE: case _actionsDragDrop.END_DRAG: case _actionsDragDrop.DROP: default: return ALL; } var targetIds = action.targetIds; var prevTargetIds = dragOperation.targetIds; var dirtyHandlerIds = _lodashXor2['default'](targetIds, prevTargetIds); var didChange = false; if (dirtyHandlerIds.length === 0) { for (var i = 0; i < targetIds.length; i++) { if (targetIds[i] !== prevTargetIds[i]) { didChange = true; break; } } } else { didChange = true; } if (!didChange) { return NONE; } var prevInnermostTargetId = prevTargetIds[prevTargetIds.length - 1]; var innermostTargetId = targetIds[targetIds.length - 1]; if (prevInnermostTargetId !== innermostTargetId) { if (prevInnermostTargetId) { dirtyHandlerIds.push(prevInnermostTargetId); } if (innermostTargetId) { dirtyHandlerIds.push(innermostTargetId); } } return dirtyHandlerIds; } function areDirty(state, handlerIds) { if (state === NONE) { return false; } if (state === ALL || typeof handlerIds === 'undefined') { return true; } return _lodashIntersection2['default'](handlerIds, state).length > 0; } /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports['default'] = dragOffset; exports.getSourceClientOffset = getSourceClientOffset; exports.getDifferenceFromInitialOffset = getDifferenceFromInitialOffset; var _actionsDragDrop = __webpack_require__(18); var initialState = { initialSourceClientOffset: null, initialClientOffset: null, clientOffset: null }; function areOffsetsEqual(offsetA, offsetB) { if (offsetA === offsetB) { return true; } return offsetA && offsetB && offsetA.x === offsetB.x && offsetA.y === offsetB.y; } function dragOffset(state, action) { if (state === undefined) state = initialState; switch (action.type) { case _actionsDragDrop.BEGIN_DRAG: return { initialSourceClientOffset: action.sourceClientOffset, initialClientOffset: action.clientOffset, clientOffset: action.clientOffset }; case _actionsDragDrop.HOVER: if (areOffsetsEqual(state.clientOffset, action.clientOffset)) { return state; } return _extends({}, state, { clientOffset: action.clientOffset }); case _actionsDragDrop.END_DRAG: case _actionsDragDrop.DROP: return initialState; default: return state; } } function getSourceClientOffset(state) { var clientOffset = state.clientOffset; var initialClientOffset = state.initialClientOffset; var initialSourceClientOffset = state.initialSourceClientOffset; if (!clientOffset || !initialClientOffset || !initialSourceClientOffset) { return null; } return { x: clientOffset.x + initialSourceClientOffset.x - initialClientOffset.x, y: clientOffset.y + initialSourceClientOffset.y - initialClientOffset.y }; } function getDifferenceFromInitialOffset(state) { var clientOffset = state.clientOffset; var initialClientOffset = state.initialClientOffset; if (!clientOffset || !initialClientOffset) { return null; } return { x: clientOffset.x - initialClientOffset.x, y: clientOffset.y - initialClientOffset.y }; } /***/ }, /* 67 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = matchesType; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashIsArray = __webpack_require__(3); var _lodashIsArray2 = _interopRequireDefault(_lodashIsArray); function matchesType(targetType, draggedItemType) { if (_lodashIsArray2['default'](targetType)) { return targetType.some(function (t) { return t === draggedItemType; }); } else { return targetType === draggedItemType; } } module.exports = exports['default']; /***/ }, /* 68 */ /***/ function(module, exports) { 'use strict'; module.exports = function hasClass(element, className) { if (element.classList) return !!className && element.classList.contains(className);else return (' ' + element.className + ' ').indexOf(' ' + className + ' ') !== -1; }; /***/ }, /* 69 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;(function (root, factory) { if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [exports], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof exports === "object") { factory(exports); } else { factory(root.babelHelpers = {}); } })(this, function (global) { var babelHelpers = global; babelHelpers.interopRequireDefault = function (obj) { return obj && obj.__esModule ? obj : { "default": obj }; }; babelHelpers._extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; }) /***/ }, /* 70 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2014-2015, Facebook, Inc. * All rights reserved. * https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/camelizeStyleName.js */ 'use strict'; var camelize = __webpack_require__(182); var msPattern = /^-ms-/; module.exports = function camelizeStyleName(string) { return camelize(string.replace(msPattern, 'ms-')); }; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright (c) 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. */ (function (global, factory) { true ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Immutable = factory()); }(this, function () { 'use strict';var SLICE$0 = Array.prototype.slice; function createClass(ctor, superClass) { if (superClass) { ctor.prototype = Object.create(superClass.prototype); } ctor.prototype.constructor = ctor; } function Iterable(value) { return isIterable(value) ? value : Seq(value); } createClass(KeyedIterable, Iterable); function KeyedIterable(value) { return isKeyed(value) ? value : KeyedSeq(value); } createClass(IndexedIterable, Iterable); function IndexedIterable(value) { return isIndexed(value) ? value : IndexedSeq(value); } createClass(SetIterable, Iterable); function SetIterable(value) { return isIterable(value) && !isAssociative(value) ? value : SetSeq(value); } function isIterable(maybeIterable) { return !!(maybeIterable && maybeIterable[IS_ITERABLE_SENTINEL]); } function isKeyed(maybeKeyed) { return !!(maybeKeyed && maybeKeyed[IS_KEYED_SENTINEL]); } function isIndexed(maybeIndexed) { return !!(maybeIndexed && maybeIndexed[IS_INDEXED_SENTINEL]); } function isAssociative(maybeAssociative) { return isKeyed(maybeAssociative) || isIndexed(maybeAssociative); } function isOrdered(maybeOrdered) { return !!(maybeOrdered && maybeOrdered[IS_ORDERED_SENTINEL]); } Iterable.isIterable = isIterable; Iterable.isKeyed = isKeyed; Iterable.isIndexed = isIndexed; Iterable.isAssociative = isAssociative; Iterable.isOrdered = isOrdered; Iterable.Keyed = KeyedIterable; Iterable.Indexed = IndexedIterable; Iterable.Set = SetIterable; var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; // Used for setting prototype methods that IE8 chokes on. var DELETE = 'delete'; // Constants describing the size of trie nodes. var SHIFT = 5; // Resulted in best performance after ______? var SIZE = 1 << SHIFT; var MASK = SIZE - 1; // A consistent shared value representing "not set" which equals nothing other // than itself, and nothing that could be provided externally. var NOT_SET = {}; // Boolean references, Rough equivalent of `bool &`. var CHANGE_LENGTH = { value: false }; var DID_ALTER = { value: false }; function MakeRef(ref) { ref.value = false; return ref; } function SetRef(ref) { ref && (ref.value = true); } // A function which returns a value representing an "owner" for transient writes // to tries. The return value will only ever equal itself, and will not equal // the return of any subsequent call of this function. function OwnerID() {} // http://jsperf.com/copy-array-inline function arrCopy(arr, offset) { offset = offset || 0; var len = Math.max(0, arr.length - offset); var newArr = new Array(len); for (var ii = 0; ii < len; ii++) { newArr[ii] = arr[ii + offset]; } return newArr; } function ensureSize(iter) { if (iter.size === undefined) { iter.size = iter.__iterate(returnTrue); } return iter.size; } function wrapIndex(iter, index) { // This implements "is array index" which the ECMAString spec defines as: // // A String property name P is an array index if and only if // ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal // to 2^32−1. // // http://www.ecma-international.org/ecma-262/6.0/#sec-array-exotic-objects if (typeof index !== 'number') { var uint32Index = index >>> 0; // N >>> 0 is shorthand for ToUint32 if ('' + uint32Index !== index || uint32Index === 4294967295) { return NaN; } index = uint32Index; } return index < 0 ? ensureSize(iter) + index : index; } function returnTrue() { return true; } function wholeSlice(begin, end, size) { return (begin === 0 || (size !== undefined && begin <= -size)) && (end === undefined || (size !== undefined && end >= size)); } function resolveBegin(begin, size) { return resolveIndex(begin, size, 0); } function resolveEnd(end, size) { return resolveIndex(end, size, size); } function resolveIndex(index, size, defaultIndex) { return index === undefined ? defaultIndex : index < 0 ? Math.max(0, size + index) : size === undefined ? index : Math.min(size, index); } /* global Symbol */ var ITERATE_KEYS = 0; var ITERATE_VALUES = 1; var ITERATE_ENTRIES = 2; var REAL_ITERATOR_SYMBOL = typeof Symbol === 'function' && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = '@@iterator'; var ITERATOR_SYMBOL = REAL_ITERATOR_SYMBOL || FAUX_ITERATOR_SYMBOL; function Iterator(next) { this.next = next; } Iterator.prototype.toString = function() { return '[Iterator]'; }; Iterator.KEYS = ITERATE_KEYS; Iterator.VALUES = ITERATE_VALUES; Iterator.ENTRIES = ITERATE_ENTRIES; Iterator.prototype.inspect = Iterator.prototype.toSource = function () { return this.toString(); } Iterator.prototype[ITERATOR_SYMBOL] = function () { return this; }; function iteratorValue(type, k, v, iteratorResult) { var value = type === 0 ? k : type === 1 ? v : [k, v]; iteratorResult ? (iteratorResult.value = value) : (iteratorResult = { value: value, done: false }); return iteratorResult; } function iteratorDone() { return { value: undefined, done: true }; } function hasIterator(maybeIterable) { return !!getIteratorFn(maybeIterable); } function isIterator(maybeIterator) { return maybeIterator && typeof maybeIterator.next === 'function'; } function getIterator(iterable) { var iteratorFn = getIteratorFn(iterable); return iteratorFn && iteratorFn.call(iterable); } function getIteratorFn(iterable) { var iteratorFn = iterable && ( (REAL_ITERATOR_SYMBOL && iterable[REAL_ITERATOR_SYMBOL]) || iterable[FAUX_ITERATOR_SYMBOL] ); if (typeof iteratorFn === 'function') { return iteratorFn; } } function isArrayLike(value) { return value && typeof value.length === 'number'; } createClass(Seq, Iterable); function Seq(value) { return value === null || value === undefined ? emptySequence() : isIterable(value) ? value.toSeq() : seqFromValue(value); } Seq.of = function(/*...values*/) { return Seq(arguments); }; Seq.prototype.toSeq = function() { return this; }; Seq.prototype.toString = function() { return this.__toString('Seq {', '}'); }; Seq.prototype.cacheResult = function() { if (!this._cache && this.__iterateUncached) { this._cache = this.entrySeq().toArray(); this.size = this._cache.length; } return this; }; // abstract __iterateUncached(fn, reverse) Seq.prototype.__iterate = function(fn, reverse) { return seqIterate(this, fn, reverse, true); }; // abstract __iteratorUncached(type, reverse) Seq.prototype.__iterator = function(type, reverse) { return seqIterator(this, type, reverse, true); }; createClass(KeyedSeq, Seq); function KeyedSeq(value) { return value === null || value === undefined ? emptySequence().toKeyedSeq() : isIterable(value) ? (isKeyed(value) ? value.toSeq() : value.fromEntrySeq()) : keyedSeqFromValue(value); } KeyedSeq.prototype.toKeyedSeq = function() { return this; }; createClass(IndexedSeq, Seq); function IndexedSeq(value) { return value === null || value === undefined ? emptySequence() : !isIterable(value) ? indexedSeqFromValue(value) : isKeyed(value) ? value.entrySeq() : value.toIndexedSeq(); } IndexedSeq.of = function(/*...values*/) { return IndexedSeq(arguments); }; IndexedSeq.prototype.toIndexedSeq = function() { return this; }; IndexedSeq.prototype.toString = function() { return this.__toString('Seq [', ']'); }; IndexedSeq.prototype.__iterate = function(fn, reverse) { return seqIterate(this, fn, reverse, false); }; IndexedSeq.prototype.__iterator = function(type, reverse) { return seqIterator(this, type, reverse, false); }; createClass(SetSeq, Seq); function SetSeq(value) { return ( value === null || value === undefined ? emptySequence() : !isIterable(value) ? indexedSeqFromValue(value) : isKeyed(value) ? value.entrySeq() : value ).toSetSeq(); } SetSeq.of = function(/*...values*/) { return SetSeq(arguments); }; SetSeq.prototype.toSetSeq = function() { return this; }; Seq.isSeq = isSeq; Seq.Keyed = KeyedSeq; Seq.Set = SetSeq; Seq.Indexed = IndexedSeq; var IS_SEQ_SENTINEL = '@@__IMMUTABLE_SEQ__@@'; Seq.prototype[IS_SEQ_SENTINEL] = true; createClass(ArraySeq, IndexedSeq); function ArraySeq(array) { this._array = array; this.size = array.length; } ArraySeq.prototype.get = function(index, notSetValue) { return this.has(index) ? this._array[wrapIndex(this, index)] : notSetValue; }; ArraySeq.prototype.__iterate = function(fn, reverse) { var array = this._array; var maxIndex = array.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { if (fn(array[reverse ? maxIndex - ii : ii], ii, this) === false) { return ii + 1; } } return ii; }; ArraySeq.prototype.__iterator = function(type, reverse) { var array = this._array; var maxIndex = array.length - 1; var ii = 0; return new Iterator(function() {return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii, array[reverse ? maxIndex - ii++ : ii++])} ); }; createClass(ObjectSeq, KeyedSeq); function ObjectSeq(object) { var keys = Object.keys(object); this._object = object; this._keys = keys; this.size = keys.length; } ObjectSeq.prototype.get = function(key, notSetValue) { if (notSetValue !== undefined && !this.has(key)) { return notSetValue; } return this._object[key]; }; ObjectSeq.prototype.has = function(key) { return this._object.hasOwnProperty(key); }; ObjectSeq.prototype.__iterate = function(fn, reverse) { var object = this._object; var keys = this._keys; var maxIndex = keys.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { var key = keys[reverse ? maxIndex - ii : ii]; if (fn(object[key], key, this) === false) { return ii + 1; } } return ii; }; ObjectSeq.prototype.__iterator = function(type, reverse) { var object = this._object; var keys = this._keys; var maxIndex = keys.length - 1; var ii = 0; return new Iterator(function() { var key = keys[reverse ? maxIndex - ii : ii]; return ii++ > maxIndex ? iteratorDone() : iteratorValue(type, key, object[key]); }); }; ObjectSeq.prototype[IS_ORDERED_SENTINEL] = true; createClass(IterableSeq, IndexedSeq); function IterableSeq(iterable) { this._iterable = iterable; this.size = iterable.length || iterable.size; } IterableSeq.prototype.__iterateUncached = function(fn, reverse) { if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterable = this._iterable; var iterator = getIterator(iterable); var iterations = 0; if (isIterator(iterator)) { var step; while (!(step = iterator.next()).done) { if (fn(step.value, iterations++, this) === false) { break; } } } return iterations; }; IterableSeq.prototype.__iteratorUncached = function(type, reverse) { if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterable = this._iterable; var iterator = getIterator(iterable); if (!isIterator(iterator)) { return new Iterator(iteratorDone); } var iterations = 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, iterations++, step.value); }); }; createClass(IteratorSeq, IndexedSeq); function IteratorSeq(iterator) { this._iterator = iterator; this._iteratorCache = []; } IteratorSeq.prototype.__iterateUncached = function(fn, reverse) { if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterator = this._iterator; var cache = this._iteratorCache; var iterations = 0; while (iterations < cache.length) { if (fn(cache[iterations], iterations++, this) === false) { return iterations; } } var step; while (!(step = iterator.next()).done) { var val = step.value; cache[iterations] = val; if (fn(val, iterations++, this) === false) { break; } } return iterations; }; IteratorSeq.prototype.__iteratorUncached = function(type, reverse) { if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = this._iterator; var cache = this._iteratorCache; var iterations = 0; return new Iterator(function() { if (iterations >= cache.length) { var step = iterator.next(); if (step.done) { return step; } cache[iterations] = step.value; } return iteratorValue(type, iterations, cache[iterations++]); }); }; // # pragma Helper functions function isSeq(maybeSeq) { return !!(maybeSeq && maybeSeq[IS_SEQ_SENTINEL]); } var EMPTY_SEQ; function emptySequence() { return EMPTY_SEQ || (EMPTY_SEQ = new ArraySeq([])); } function keyedSeqFromValue(value) { var seq = Array.isArray(value) ? new ArraySeq(value).fromEntrySeq() : isIterator(value) ? new IteratorSeq(value).fromEntrySeq() : hasIterator(value) ? new IterableSeq(value).fromEntrySeq() : typeof value === 'object' ? new ObjectSeq(value) : undefined; if (!seq) { throw new TypeError( 'Expected Array or iterable object of [k, v] entries, '+ 'or keyed object: ' + value ); } return seq; } function indexedSeqFromValue(value) { var seq = maybeIndexedSeqFromValue(value); if (!seq) { throw new TypeError( 'Expected Array or iterable object of values: ' + value ); } return seq; } function seqFromValue(value) { var seq = maybeIndexedSeqFromValue(value) || (typeof value === 'object' && new ObjectSeq(value)); if (!seq) { throw new TypeError( 'Expected Array or iterable object of values, or keyed object: ' + value ); } return seq; } function maybeIndexedSeqFromValue(value) { return ( isArrayLike(value) ? new ArraySeq(value) : isIterator(value) ? new IteratorSeq(value) : hasIterator(value) ? new IterableSeq(value) : undefined ); } function seqIterate(seq, fn, reverse, useKeys) { var cache = seq._cache; if (cache) { var maxIndex = cache.length - 1; for (var ii = 0; ii <= maxIndex; ii++) { var entry = cache[reverse ? maxIndex - ii : ii]; if (fn(entry[1], useKeys ? entry[0] : ii, seq) === false) { return ii + 1; } } return ii; } return seq.__iterateUncached(fn, reverse); } function seqIterator(seq, type, reverse, useKeys) { var cache = seq._cache; if (cache) { var maxIndex = cache.length - 1; var ii = 0; return new Iterator(function() { var entry = cache[reverse ? maxIndex - ii : ii]; return ii++ > maxIndex ? iteratorDone() : iteratorValue(type, useKeys ? entry[0] : ii - 1, entry[1]); }); } return seq.__iteratorUncached(type, reverse); } function fromJS(json, converter) { return converter ? fromJSWith(converter, json, '', {'': json}) : fromJSDefault(json); } function fromJSWith(converter, json, key, parentJSON) { if (Array.isArray(json)) { return converter.call(parentJSON, key, IndexedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); } if (isPlainObj(json)) { return converter.call(parentJSON, key, KeyedSeq(json).map(function(v, k) {return fromJSWith(converter, v, k, json)})); } return json; } function fromJSDefault(json) { if (Array.isArray(json)) { return IndexedSeq(json).map(fromJSDefault).toList(); } if (isPlainObj(json)) { return KeyedSeq(json).map(fromJSDefault).toMap(); } return json; } function isPlainObj(value) { return value && (value.constructor === Object || value.constructor === undefined); } /** * An extension of the "same-value" algorithm as [described for use by ES6 Map * and Set](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Key_equality) * * NaN is considered the same as NaN, however -0 and 0 are considered the same * value, which is different from the algorithm described by * [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). * * This is extended further to allow Objects to describe the values they * represent, by way of `valueOf` or `equals` (and `hashCode`). * * Note: because of this extension, the key equality of Immutable.Map and the * value equality of Immutable.Set will differ from ES6 Map and Set. * * ### Defining custom values * * The easiest way to describe the value an object represents is by implementing * `valueOf`. For example, `Date` represents a value by returning a unix * timestamp for `valueOf`: * * var date1 = new Date(1234567890000); // Fri Feb 13 2009 ... * var date2 = new Date(1234567890000); * date1.valueOf(); // 1234567890000 * assert( date1 !== date2 ); * assert( Immutable.is( date1, date2 ) ); * * Note: overriding `valueOf` may have other implications if you use this object * where JavaScript expects a primitive, such as implicit string coercion. * * For more complex types, especially collections, implementing `valueOf` may * not be performant. An alternative is to implement `equals` and `hashCode`. * * `equals` takes another object, presumably of similar type, and returns true * if the it is equal. Equality is symmetrical, so the same result should be * returned if this and the argument are flipped. * * assert( a.equals(b) === b.equals(a) ); * * `hashCode` returns a 32bit integer number representing the object which will * be used to determine how to store the value object in a Map or Set. You must * provide both or neither methods, one must not exist without the other. * * Also, an important relationship between these methods must be upheld: if two * values are equal, they *must* return the same hashCode. If the values are not * equal, they might have the same hashCode; this is called a hash collision, * and while undesirable for performance reasons, it is acceptable. * * if (a.equals(b)) { * assert( a.hashCode() === b.hashCode() ); * } * * All Immutable collections implement `equals` and `hashCode`. * */ function is(valueA, valueB) { if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { return true; } if (!valueA || !valueB) { return false; } if (typeof valueA.valueOf === 'function' && typeof valueB.valueOf === 'function') { valueA = valueA.valueOf(); valueB = valueB.valueOf(); if (valueA === valueB || (valueA !== valueA && valueB !== valueB)) { return true; } if (!valueA || !valueB) { return false; } } if (typeof valueA.equals === 'function' && typeof valueB.equals === 'function' && valueA.equals(valueB)) { return true; } return false; } function deepEqual(a, b) { if (a === b) { return true; } if ( !isIterable(b) || a.size !== undefined && b.size !== undefined && a.size !== b.size || a.__hash !== undefined && b.__hash !== undefined && a.__hash !== b.__hash || isKeyed(a) !== isKeyed(b) || isIndexed(a) !== isIndexed(b) || isOrdered(a) !== isOrdered(b) ) { return false; } if (a.size === 0 && b.size === 0) { return true; } var notAssociative = !isAssociative(a); if (isOrdered(a)) { var entries = a.entries(); return b.every(function(v, k) { var entry = entries.next().value; return entry && is(entry[1], v) && (notAssociative || is(entry[0], k)); }) && entries.next().done; } var flipped = false; if (a.size === undefined) { if (b.size === undefined) { if (typeof a.cacheResult === 'function') { a.cacheResult(); } } else { flipped = true; var _ = a; a = b; b = _; } } var allEqual = true; var bSize = b.__iterate(function(v, k) { if (notAssociative ? !a.has(v) : flipped ? !is(v, a.get(k, NOT_SET)) : !is(a.get(k, NOT_SET), v)) { allEqual = false; return false; } }); return allEqual && a.size === bSize; } createClass(Repeat, IndexedSeq); function Repeat(value, times) { if (!(this instanceof Repeat)) { return new Repeat(value, times); } this._value = value; this.size = times === undefined ? Infinity : Math.max(0, times); if (this.size === 0) { if (EMPTY_REPEAT) { return EMPTY_REPEAT; } EMPTY_REPEAT = this; } } Repeat.prototype.toString = function() { if (this.size === 0) { return 'Repeat []'; } return 'Repeat [ ' + this._value + ' ' + this.size + ' times ]'; }; Repeat.prototype.get = function(index, notSetValue) { return this.has(index) ? this._value : notSetValue; }; Repeat.prototype.includes = function(searchValue) { return is(this._value, searchValue); }; Repeat.prototype.slice = function(begin, end) { var size = this.size; return wholeSlice(begin, end, size) ? this : new Repeat(this._value, resolveEnd(end, size) - resolveBegin(begin, size)); }; Repeat.prototype.reverse = function() { return this; }; Repeat.prototype.indexOf = function(searchValue) { if (is(this._value, searchValue)) { return 0; } return -1; }; Repeat.prototype.lastIndexOf = function(searchValue) { if (is(this._value, searchValue)) { return this.size; } return -1; }; Repeat.prototype.__iterate = function(fn, reverse) { for (var ii = 0; ii < this.size; ii++) { if (fn(this._value, ii, this) === false) { return ii + 1; } } return ii; }; Repeat.prototype.__iterator = function(type, reverse) {var this$0 = this; var ii = 0; return new Iterator(function() {return ii < this$0.size ? iteratorValue(type, ii++, this$0._value) : iteratorDone()} ); }; Repeat.prototype.equals = function(other) { return other instanceof Repeat ? is(this._value, other._value) : deepEqual(other); }; var EMPTY_REPEAT; function invariant(condition, error) { if (!condition) throw new Error(error); } createClass(Range, IndexedSeq); function Range(start, end, step) { if (!(this instanceof Range)) { return new Range(start, end, step); } invariant(step !== 0, 'Cannot step a Range by 0'); start = start || 0; if (end === undefined) { end = Infinity; } step = step === undefined ? 1 : Math.abs(step); if (end < start) { step = -step; } this._start = start; this._end = end; this._step = step; this.size = Math.max(0, Math.ceil((end - start) / step - 1) + 1); if (this.size === 0) { if (EMPTY_RANGE) { return EMPTY_RANGE; } EMPTY_RANGE = this; } } Range.prototype.toString = function() { if (this.size === 0) { return 'Range []'; } return 'Range [ ' + this._start + '...' + this._end + (this._step !== 1 ? ' by ' + this._step : '') + ' ]'; }; Range.prototype.get = function(index, notSetValue) { return this.has(index) ? this._start + wrapIndex(this, index) * this._step : notSetValue; }; Range.prototype.includes = function(searchValue) { var possibleIndex = (searchValue - this._start) / this._step; return possibleIndex >= 0 && possibleIndex < this.size && possibleIndex === Math.floor(possibleIndex); }; Range.prototype.slice = function(begin, end) { if (wholeSlice(begin, end, this.size)) { return this; } begin = resolveBegin(begin, this.size); end = resolveEnd(end, this.size); if (end <= begin) { return new Range(0, 0); } return new Range(this.get(begin, this._end), this.get(end, this._end), this._step); }; Range.prototype.indexOf = function(searchValue) { var offsetValue = searchValue - this._start; if (offsetValue % this._step === 0) { var index = offsetValue / this._step; if (index >= 0 && index < this.size) { return index } } return -1; }; Range.prototype.lastIndexOf = function(searchValue) { return this.indexOf(searchValue); }; Range.prototype.__iterate = function(fn, reverse) { var maxIndex = this.size - 1; var step = this._step; var value = reverse ? this._start + maxIndex * step : this._start; for (var ii = 0; ii <= maxIndex; ii++) { if (fn(value, ii, this) === false) { return ii + 1; } value += reverse ? -step : step; } return ii; }; Range.prototype.__iterator = function(type, reverse) { var maxIndex = this.size - 1; var step = this._step; var value = reverse ? this._start + maxIndex * step : this._start; var ii = 0; return new Iterator(function() { var v = value; value += reverse ? -step : step; return ii > maxIndex ? iteratorDone() : iteratorValue(type, ii++, v); }); }; Range.prototype.equals = function(other) { return other instanceof Range ? this._start === other._start && this._end === other._end && this._step === other._step : deepEqual(this, other); }; var EMPTY_RANGE; createClass(Collection, Iterable); function Collection() { throw TypeError('Abstract'); } createClass(KeyedCollection, Collection);function KeyedCollection() {} createClass(IndexedCollection, Collection);function IndexedCollection() {} createClass(SetCollection, Collection);function SetCollection() {} Collection.Keyed = KeyedCollection; Collection.Indexed = IndexedCollection; Collection.Set = SetCollection; var imul = typeof Math.imul === 'function' && Math.imul(0xffffffff, 2) === -2 ? Math.imul : function imul(a, b) { a = a | 0; // int b = b | 0; // int var c = a & 0xffff; var d = b & 0xffff; // Shift by 0 fixes the sign on the high part. return (c * d) + ((((a >>> 16) * d + c * (b >>> 16)) << 16) >>> 0) | 0; // int }; // v8 has an optimization for storing 31-bit signed numbers. // Values which have either 00 or 11 as the high order bits qualify. // This function drops the highest order bit in a signed number, maintaining // the sign bit. function smi(i32) { return ((i32 >>> 1) & 0x40000000) | (i32 & 0xBFFFFFFF); } function hash(o) { if (o === false || o === null || o === undefined) { return 0; } if (typeof o.valueOf === 'function') { o = o.valueOf(); if (o === false || o === null || o === undefined) { return 0; } } if (o === true) { return 1; } var type = typeof o; if (type === 'number') { if (o !== o || o === Infinity) { return 0; } var h = o | 0; if (h !== o) { h ^= o * 0xFFFFFFFF; } while (o > 0xFFFFFFFF) { o /= 0xFFFFFFFF; h ^= o; } return smi(h); } if (type === 'string') { return o.length > STRING_HASH_CACHE_MIN_STRLEN ? cachedHashString(o) : hashString(o); } if (typeof o.hashCode === 'function') { return o.hashCode(); } if (type === 'object') { return hashJSObj(o); } if (typeof o.toString === 'function') { return hashString(o.toString()); } throw new Error('Value type ' + type + ' cannot be hashed.'); } function cachedHashString(string) { var hash = stringHashCache[string]; if (hash === undefined) { hash = hashString(string); if (STRING_HASH_CACHE_SIZE === STRING_HASH_CACHE_MAX_SIZE) { STRING_HASH_CACHE_SIZE = 0; stringHashCache = {}; } STRING_HASH_CACHE_SIZE++; stringHashCache[string] = hash; } return hash; } // http://jsperf.com/hashing-strings function hashString(string) { // This is the hash from JVM // The hash code for a string is computed as // s[0] * 31 ^ (n - 1) + s[1] * 31 ^ (n - 2) + ... + s[n - 1], // where s[i] is the ith character of the string and n is the length of // the string. We "mod" the result to make it between 0 (inclusive) and 2^31 // (exclusive) by dropping high bits. var hash = 0; for (var ii = 0; ii < string.length; ii++) { hash = 31 * hash + string.charCodeAt(ii) | 0; } return smi(hash); } function hashJSObj(obj) { var hash; if (usingWeakMap) { hash = weakMap.get(obj); if (hash !== undefined) { return hash; } } hash = obj[UID_HASH_KEY]; if (hash !== undefined) { return hash; } if (!canDefineProperty) { hash = obj.propertyIsEnumerable && obj.propertyIsEnumerable[UID_HASH_KEY]; if (hash !== undefined) { return hash; } hash = getIENodeHash(obj); if (hash !== undefined) { return hash; } } hash = ++objHashUID; if (objHashUID & 0x40000000) { objHashUID = 0; } if (usingWeakMap) { weakMap.set(obj, hash); } else if (isExtensible !== undefined && isExtensible(obj) === false) { throw new Error('Non-extensible objects are not allowed as keys.'); } else if (canDefineProperty) { Object.defineProperty(obj, UID_HASH_KEY, { 'enumerable': false, 'configurable': false, 'writable': false, 'value': hash }); } else if (obj.propertyIsEnumerable !== undefined && obj.propertyIsEnumerable === obj.constructor.prototype.propertyIsEnumerable) { // Since we can't define a non-enumerable property on the object // we'll hijack one of the less-used non-enumerable properties to // save our hash on it. Since this is a function it will not show up in // `JSON.stringify` which is what we want. obj.propertyIsEnumerable = function() { return this.constructor.prototype.propertyIsEnumerable.apply(this, arguments); }; obj.propertyIsEnumerable[UID_HASH_KEY] = hash; } else if (obj.nodeType !== undefined) { // At this point we couldn't get the IE `uniqueID` to use as a hash // and we couldn't use a non-enumerable property to exploit the // dontEnum bug so we simply add the `UID_HASH_KEY` on the node // itself. obj[UID_HASH_KEY] = hash; } else { throw new Error('Unable to set a non-enumerable property on object.'); } return hash; } // Get references to ES5 object methods. var isExtensible = Object.isExtensible; // True if Object.defineProperty works as expected. IE8 fails this test. var canDefineProperty = (function() { try { Object.defineProperty({}, '@', {}); return true; } catch (e) { return false; } }()); // IE has a `uniqueID` property on DOM nodes. We can construct the hash from it // and avoid memory leaks from the IE cloneNode bug. function getIENodeHash(node) { if (node && node.nodeType > 0) { switch (node.nodeType) { case 1: // Element return node.uniqueID; case 9: // Document return node.documentElement && node.documentElement.uniqueID; } } } // If possible, use a WeakMap. var usingWeakMap = typeof WeakMap === 'function'; var weakMap; if (usingWeakMap) { weakMap = new WeakMap(); } var objHashUID = 0; var UID_HASH_KEY = '__immutablehash__'; if (typeof Symbol === 'function') { UID_HASH_KEY = Symbol(UID_HASH_KEY); } var STRING_HASH_CACHE_MIN_STRLEN = 16; var STRING_HASH_CACHE_MAX_SIZE = 255; var STRING_HASH_CACHE_SIZE = 0; var stringHashCache = {}; function assertNotInfinite(size) { invariant( size !== Infinity, 'Cannot perform this action with an infinite size.' ); } createClass(Map, KeyedCollection); // @pragma Construction function Map(value) { return value === null || value === undefined ? emptyMap() : isMap(value) && !isOrdered(value) ? value : emptyMap().withMutations(function(map ) { var iter = KeyedIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v, k) {return map.set(k, v)}); }); } Map.of = function() {var keyValues = SLICE$0.call(arguments, 0); return emptyMap().withMutations(function(map ) { for (var i = 0; i < keyValues.length; i += 2) { if (i + 1 >= keyValues.length) { throw new Error('Missing value for key: ' + keyValues[i]); } map.set(keyValues[i], keyValues[i + 1]); } }); }; Map.prototype.toString = function() { return this.__toString('Map {', '}'); }; // @pragma Access Map.prototype.get = function(k, notSetValue) { return this._root ? this._root.get(0, undefined, k, notSetValue) : notSetValue; }; // @pragma Modification Map.prototype.set = function(k, v) { return updateMap(this, k, v); }; Map.prototype.setIn = function(keyPath, v) { return this.updateIn(keyPath, NOT_SET, function() {return v}); }; Map.prototype.remove = function(k) { return updateMap(this, k, NOT_SET); }; Map.prototype.deleteIn = function(keyPath) { return this.updateIn(keyPath, function() {return NOT_SET}); }; Map.prototype.update = function(k, notSetValue, updater) { return arguments.length === 1 ? k(this) : this.updateIn([k], notSetValue, updater); }; Map.prototype.updateIn = function(keyPath, notSetValue, updater) { if (!updater) { updater = notSetValue; notSetValue = undefined; } var updatedValue = updateInDeepMap( this, forceIterator(keyPath), notSetValue, updater ); return updatedValue === NOT_SET ? undefined : updatedValue; }; Map.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._root = null; this.__hash = undefined; this.__altered = true; return this; } return emptyMap(); }; // @pragma Composition Map.prototype.merge = function(/*...iters*/) { return mergeIntoMapWith(this, undefined, arguments); }; Map.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoMapWith(this, merger, iters); }; Map.prototype.mergeIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); return this.updateIn( keyPath, emptyMap(), function(m ) {return typeof m.merge === 'function' ? m.merge.apply(m, iters) : iters[iters.length - 1]} ); }; Map.prototype.mergeDeep = function(/*...iters*/) { return mergeIntoMapWith(this, deepMerger, arguments); }; Map.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoMapWith(this, deepMergerWith(merger), iters); }; Map.prototype.mergeDeepIn = function(keyPath) {var iters = SLICE$0.call(arguments, 1); return this.updateIn( keyPath, emptyMap(), function(m ) {return typeof m.mergeDeep === 'function' ? m.mergeDeep.apply(m, iters) : iters[iters.length - 1]} ); }; Map.prototype.sort = function(comparator) { // Late binding return OrderedMap(sortFactory(this, comparator)); }; Map.prototype.sortBy = function(mapper, comparator) { // Late binding return OrderedMap(sortFactory(this, comparator, mapper)); }; // @pragma Mutability Map.prototype.withMutations = function(fn) { var mutable = this.asMutable(); fn(mutable); return mutable.wasAltered() ? mutable.__ensureOwner(this.__ownerID) : this; }; Map.prototype.asMutable = function() { return this.__ownerID ? this : this.__ensureOwner(new OwnerID()); }; Map.prototype.asImmutable = function() { return this.__ensureOwner(); }; Map.prototype.wasAltered = function() { return this.__altered; }; Map.prototype.__iterator = function(type, reverse) { return new MapIterator(this, type, reverse); }; Map.prototype.__iterate = function(fn, reverse) {var this$0 = this; var iterations = 0; this._root && this._root.iterate(function(entry ) { iterations++; return fn(entry[1], entry[0], this$0); }, reverse); return iterations; }; Map.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; this.__altered = false; return this; } return makeMap(this.size, this._root, ownerID, this.__hash); }; function isMap(maybeMap) { return !!(maybeMap && maybeMap[IS_MAP_SENTINEL]); } Map.isMap = isMap; var IS_MAP_SENTINEL = '@@__IMMUTABLE_MAP__@@'; var MapPrototype = Map.prototype; MapPrototype[IS_MAP_SENTINEL] = true; MapPrototype[DELETE] = MapPrototype.remove; MapPrototype.removeIn = MapPrototype.deleteIn; // #pragma Trie Nodes function ArrayMapNode(ownerID, entries) { this.ownerID = ownerID; this.entries = entries; } ArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { var entries = this.entries; for (var ii = 0, len = entries.length; ii < len; ii++) { if (is(key, entries[ii][0])) { return entries[ii][1]; } } return notSetValue; }; ArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { var removed = value === NOT_SET; var entries = this.entries; var idx = 0; for (var len = entries.length; idx < len; idx++) { if (is(key, entries[idx][0])) { break; } } var exists = idx < len; if (exists ? entries[idx][1] === value : removed) { return this; } SetRef(didAlter); (removed || !exists) && SetRef(didChangeSize); if (removed && entries.length === 1) { return; // undefined } if (!exists && !removed && entries.length >= MAX_ARRAY_MAP_SIZE) { return createNodes(ownerID, entries, key, value); } var isEditable = ownerID && ownerID === this.ownerID; var newEntries = isEditable ? entries : arrCopy(entries); if (exists) { if (removed) { idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); } else { newEntries[idx] = [key, value]; } } else { newEntries.push([key, value]); } if (isEditable) { this.entries = newEntries; return this; } return new ArrayMapNode(ownerID, newEntries); }; function BitmapIndexedNode(ownerID, bitmap, nodes) { this.ownerID = ownerID; this.bitmap = bitmap; this.nodes = nodes; } BitmapIndexedNode.prototype.get = function(shift, keyHash, key, notSetValue) { if (keyHash === undefined) { keyHash = hash(key); } var bit = (1 << ((shift === 0 ? keyHash : keyHash >>> shift) & MASK)); var bitmap = this.bitmap; return (bitmap & bit) === 0 ? notSetValue : this.nodes[popCount(bitmap & (bit - 1))].get(shift + SHIFT, keyHash, key, notSetValue); }; BitmapIndexedNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var keyHashFrag = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var bit = 1 << keyHashFrag; var bitmap = this.bitmap; var exists = (bitmap & bit) !== 0; if (!exists && value === NOT_SET) { return this; } var idx = popCount(bitmap & (bit - 1)); var nodes = this.nodes; var node = exists ? nodes[idx] : undefined; var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); if (newNode === node) { return this; } if (!exists && newNode && nodes.length >= MAX_BITMAP_INDEXED_SIZE) { return expandNodes(ownerID, nodes, bitmap, keyHashFrag, newNode); } if (exists && !newNode && nodes.length === 2 && isLeafNode(nodes[idx ^ 1])) { return nodes[idx ^ 1]; } if (exists && newNode && nodes.length === 1 && isLeafNode(newNode)) { return newNode; } var isEditable = ownerID && ownerID === this.ownerID; var newBitmap = exists ? newNode ? bitmap : bitmap ^ bit : bitmap | bit; var newNodes = exists ? newNode ? setIn(nodes, idx, newNode, isEditable) : spliceOut(nodes, idx, isEditable) : spliceIn(nodes, idx, newNode, isEditable); if (isEditable) { this.bitmap = newBitmap; this.nodes = newNodes; return this; } return new BitmapIndexedNode(ownerID, newBitmap, newNodes); }; function HashArrayMapNode(ownerID, count, nodes) { this.ownerID = ownerID; this.count = count; this.nodes = nodes; } HashArrayMapNode.prototype.get = function(shift, keyHash, key, notSetValue) { if (keyHash === undefined) { keyHash = hash(key); } var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var node = this.nodes[idx]; return node ? node.get(shift + SHIFT, keyHash, key, notSetValue) : notSetValue; }; HashArrayMapNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var idx = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var removed = value === NOT_SET; var nodes = this.nodes; var node = nodes[idx]; if (removed && !node) { return this; } var newNode = updateNode(node, ownerID, shift + SHIFT, keyHash, key, value, didChangeSize, didAlter); if (newNode === node) { return this; } var newCount = this.count; if (!node) { newCount++; } else if (!newNode) { newCount--; if (newCount < MIN_HASH_ARRAY_MAP_SIZE) { return packNodes(ownerID, nodes, newCount, idx); } } var isEditable = ownerID && ownerID === this.ownerID; var newNodes = setIn(nodes, idx, newNode, isEditable); if (isEditable) { this.count = newCount; this.nodes = newNodes; return this; } return new HashArrayMapNode(ownerID, newCount, newNodes); }; function HashCollisionNode(ownerID, keyHash, entries) { this.ownerID = ownerID; this.keyHash = keyHash; this.entries = entries; } HashCollisionNode.prototype.get = function(shift, keyHash, key, notSetValue) { var entries = this.entries; for (var ii = 0, len = entries.length; ii < len; ii++) { if (is(key, entries[ii][0])) { return entries[ii][1]; } } return notSetValue; }; HashCollisionNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (keyHash === undefined) { keyHash = hash(key); } var removed = value === NOT_SET; if (keyHash !== this.keyHash) { if (removed) { return this; } SetRef(didAlter); SetRef(didChangeSize); return mergeIntoNode(this, ownerID, shift, keyHash, [key, value]); } var entries = this.entries; var idx = 0; for (var len = entries.length; idx < len; idx++) { if (is(key, entries[idx][0])) { break; } } var exists = idx < len; if (exists ? entries[idx][1] === value : removed) { return this; } SetRef(didAlter); (removed || !exists) && SetRef(didChangeSize); if (removed && len === 2) { return new ValueNode(ownerID, this.keyHash, entries[idx ^ 1]); } var isEditable = ownerID && ownerID === this.ownerID; var newEntries = isEditable ? entries : arrCopy(entries); if (exists) { if (removed) { idx === len - 1 ? newEntries.pop() : (newEntries[idx] = newEntries.pop()); } else { newEntries[idx] = [key, value]; } } else { newEntries.push([key, value]); } if (isEditable) { this.entries = newEntries; return this; } return new HashCollisionNode(ownerID, this.keyHash, newEntries); }; function ValueNode(ownerID, keyHash, entry) { this.ownerID = ownerID; this.keyHash = keyHash; this.entry = entry; } ValueNode.prototype.get = function(shift, keyHash, key, notSetValue) { return is(key, this.entry[0]) ? this.entry[1] : notSetValue; }; ValueNode.prototype.update = function(ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { var removed = value === NOT_SET; var keyMatch = is(key, this.entry[0]); if (keyMatch ? value === this.entry[1] : removed) { return this; } SetRef(didAlter); if (removed) { SetRef(didChangeSize); return; // undefined } if (keyMatch) { if (ownerID && ownerID === this.ownerID) { this.entry[1] = value; return this; } return new ValueNode(ownerID, this.keyHash, [key, value]); } SetRef(didChangeSize); return mergeIntoNode(this, ownerID, shift, hash(key), [key, value]); }; // #pragma Iterators ArrayMapNode.prototype.iterate = HashCollisionNode.prototype.iterate = function (fn, reverse) { var entries = this.entries; for (var ii = 0, maxIndex = entries.length - 1; ii <= maxIndex; ii++) { if (fn(entries[reverse ? maxIndex - ii : ii]) === false) { return false; } } } BitmapIndexedNode.prototype.iterate = HashArrayMapNode.prototype.iterate = function (fn, reverse) { var nodes = this.nodes; for (var ii = 0, maxIndex = nodes.length - 1; ii <= maxIndex; ii++) { var node = nodes[reverse ? maxIndex - ii : ii]; if (node && node.iterate(fn, reverse) === false) { return false; } } } ValueNode.prototype.iterate = function (fn, reverse) { return fn(this.entry); } createClass(MapIterator, Iterator); function MapIterator(map, type, reverse) { this._type = type; this._reverse = reverse; this._stack = map._root && mapIteratorFrame(map._root); } MapIterator.prototype.next = function() { var type = this._type; var stack = this._stack; while (stack) { var node = stack.node; var index = stack.index++; var maxIndex; if (node.entry) { if (index === 0) { return mapIteratorValue(type, node.entry); } } else if (node.entries) { maxIndex = node.entries.length - 1; if (index <= maxIndex) { return mapIteratorValue(type, node.entries[this._reverse ? maxIndex - index : index]); } } else { maxIndex = node.nodes.length - 1; if (index <= maxIndex) { var subNode = node.nodes[this._reverse ? maxIndex - index : index]; if (subNode) { if (subNode.entry) { return mapIteratorValue(type, subNode.entry); } stack = this._stack = mapIteratorFrame(subNode, stack); } continue; } } stack = this._stack = this._stack.__prev; } return iteratorDone(); }; function mapIteratorValue(type, entry) { return iteratorValue(type, entry[0], entry[1]); } function mapIteratorFrame(node, prev) { return { node: node, index: 0, __prev: prev }; } function makeMap(size, root, ownerID, hash) { var map = Object.create(MapPrototype); map.size = size; map._root = root; map.__ownerID = ownerID; map.__hash = hash; map.__altered = false; return map; } var EMPTY_MAP; function emptyMap() { return EMPTY_MAP || (EMPTY_MAP = makeMap(0)); } function updateMap(map, k, v) { var newRoot; var newSize; if (!map._root) { if (v === NOT_SET) { return map; } newSize = 1; newRoot = new ArrayMapNode(map.__ownerID, [[k, v]]); } else { var didChangeSize = MakeRef(CHANGE_LENGTH); var didAlter = MakeRef(DID_ALTER); newRoot = updateNode(map._root, map.__ownerID, 0, undefined, k, v, didChangeSize, didAlter); if (!didAlter.value) { return map; } newSize = map.size + (didChangeSize.value ? v === NOT_SET ? -1 : 1 : 0); } if (map.__ownerID) { map.size = newSize; map._root = newRoot; map.__hash = undefined; map.__altered = true; return map; } return newRoot ? makeMap(newSize, newRoot) : emptyMap(); } function updateNode(node, ownerID, shift, keyHash, key, value, didChangeSize, didAlter) { if (!node) { if (value === NOT_SET) { return node; } SetRef(didAlter); SetRef(didChangeSize); return new ValueNode(ownerID, keyHash, [key, value]); } return node.update(ownerID, shift, keyHash, key, value, didChangeSize, didAlter); } function isLeafNode(node) { return node.constructor === ValueNode || node.constructor === HashCollisionNode; } function mergeIntoNode(node, ownerID, shift, keyHash, entry) { if (node.keyHash === keyHash) { return new HashCollisionNode(ownerID, keyHash, [node.entry, entry]); } var idx1 = (shift === 0 ? node.keyHash : node.keyHash >>> shift) & MASK; var idx2 = (shift === 0 ? keyHash : keyHash >>> shift) & MASK; var newNode; var nodes = idx1 === idx2 ? [mergeIntoNode(node, ownerID, shift + SHIFT, keyHash, entry)] : ((newNode = new ValueNode(ownerID, keyHash, entry)), idx1 < idx2 ? [node, newNode] : [newNode, node]); return new BitmapIndexedNode(ownerID, (1 << idx1) | (1 << idx2), nodes); } function createNodes(ownerID, entries, key, value) { if (!ownerID) { ownerID = new OwnerID(); } var node = new ValueNode(ownerID, hash(key), [key, value]); for (var ii = 0; ii < entries.length; ii++) { var entry = entries[ii]; node = node.update(ownerID, 0, undefined, entry[0], entry[1]); } return node; } function packNodes(ownerID, nodes, count, excluding) { var bitmap = 0; var packedII = 0; var packedNodes = new Array(count); for (var ii = 0, bit = 1, len = nodes.length; ii < len; ii++, bit <<= 1) { var node = nodes[ii]; if (node !== undefined && ii !== excluding) { bitmap |= bit; packedNodes[packedII++] = node; } } return new BitmapIndexedNode(ownerID, bitmap, packedNodes); } function expandNodes(ownerID, nodes, bitmap, including, node) { var count = 0; var expandedNodes = new Array(SIZE); for (var ii = 0; bitmap !== 0; ii++, bitmap >>>= 1) { expandedNodes[ii] = bitmap & 1 ? nodes[count++] : undefined; } expandedNodes[including] = node; return new HashArrayMapNode(ownerID, count + 1, expandedNodes); } function mergeIntoMapWith(map, merger, iterables) { var iters = []; for (var ii = 0; ii < iterables.length; ii++) { var value = iterables[ii]; var iter = KeyedIterable(value); if (!isIterable(value)) { iter = iter.map(function(v ) {return fromJS(v)}); } iters.push(iter); } return mergeIntoCollectionWith(map, merger, iters); } function deepMerger(existing, value, key) { return existing && existing.mergeDeep && isIterable(value) ? existing.mergeDeep(value) : is(existing, value) ? existing : value; } function deepMergerWith(merger) { return function(existing, value, key) { if (existing && existing.mergeDeepWith && isIterable(value)) { return existing.mergeDeepWith(merger, value); } var nextValue = merger(existing, value, key); return is(existing, nextValue) ? existing : nextValue; }; } function mergeIntoCollectionWith(collection, merger, iters) { iters = iters.filter(function(x ) {return x.size !== 0}); if (iters.length === 0) { return collection; } if (collection.size === 0 && !collection.__ownerID && iters.length === 1) { return collection.constructor(iters[0]); } return collection.withMutations(function(collection ) { var mergeIntoMap = merger ? function(value, key) { collection.update(key, NOT_SET, function(existing ) {return existing === NOT_SET ? value : merger(existing, value, key)} ); } : function(value, key) { collection.set(key, value); } for (var ii = 0; ii < iters.length; ii++) { iters[ii].forEach(mergeIntoMap); } }); } function updateInDeepMap(existing, keyPathIter, notSetValue, updater) { var isNotSet = existing === NOT_SET; var step = keyPathIter.next(); if (step.done) { var existingValue = isNotSet ? notSetValue : existing; var newValue = updater(existingValue); return newValue === existingValue ? existing : newValue; } invariant( isNotSet || (existing && existing.set), 'invalid keyPath' ); var key = step.value; var nextExisting = isNotSet ? NOT_SET : existing.get(key, NOT_SET); var nextUpdated = updateInDeepMap( nextExisting, keyPathIter, notSetValue, updater ); return nextUpdated === nextExisting ? existing : nextUpdated === NOT_SET ? existing.remove(key) : (isNotSet ? emptyMap() : existing).set(key, nextUpdated); } function popCount(x) { x = x - ((x >> 1) & 0x55555555); x = (x & 0x33333333) + ((x >> 2) & 0x33333333); x = (x + (x >> 4)) & 0x0f0f0f0f; x = x + (x >> 8); x = x + (x >> 16); return x & 0x7f; } function setIn(array, idx, val, canEdit) { var newArray = canEdit ? array : arrCopy(array); newArray[idx] = val; return newArray; } function spliceIn(array, idx, val, canEdit) { var newLen = array.length + 1; if (canEdit && idx + 1 === newLen) { array[idx] = val; return array; } var newArray = new Array(newLen); var after = 0; for (var ii = 0; ii < newLen; ii++) { if (ii === idx) { newArray[ii] = val; after = -1; } else { newArray[ii] = array[ii + after]; } } return newArray; } function spliceOut(array, idx, canEdit) { var newLen = array.length - 1; if (canEdit && idx === newLen) { array.pop(); return array; } var newArray = new Array(newLen); var after = 0; for (var ii = 0; ii < newLen; ii++) { if (ii === idx) { after = 1; } newArray[ii] = array[ii + after]; } return newArray; } var MAX_ARRAY_MAP_SIZE = SIZE / 4; var MAX_BITMAP_INDEXED_SIZE = SIZE / 2; var MIN_HASH_ARRAY_MAP_SIZE = SIZE / 4; createClass(List, IndexedCollection); // @pragma Construction function List(value) { var empty = emptyList(); if (value === null || value === undefined) { return empty; } if (isList(value)) { return value; } var iter = IndexedIterable(value); var size = iter.size; if (size === 0) { return empty; } assertNotInfinite(size); if (size > 0 && size < SIZE) { return makeList(0, size, SHIFT, null, new VNode(iter.toArray())); } return empty.withMutations(function(list ) { list.setSize(size); iter.forEach(function(v, i) {return list.set(i, v)}); }); } List.of = function(/*...values*/) { return this(arguments); }; List.prototype.toString = function() { return this.__toString('List [', ']'); }; // @pragma Access List.prototype.get = function(index, notSetValue) { index = wrapIndex(this, index); if (index >= 0 && index < this.size) { index += this._origin; var node = listNodeFor(this, index); return node && node.array[index & MASK]; } return notSetValue; }; // @pragma Modification List.prototype.set = function(index, value) { return updateList(this, index, value); }; List.prototype.remove = function(index) { return !this.has(index) ? this : index === 0 ? this.shift() : index === this.size - 1 ? this.pop() : this.splice(index, 1); }; List.prototype.insert = function(index, value) { return this.splice(index, 0, value); }; List.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = this._origin = this._capacity = 0; this._level = SHIFT; this._root = this._tail = null; this.__hash = undefined; this.__altered = true; return this; } return emptyList(); }; List.prototype.push = function(/*...values*/) { var values = arguments; var oldSize = this.size; return this.withMutations(function(list ) { setListBounds(list, 0, oldSize + values.length); for (var ii = 0; ii < values.length; ii++) { list.set(oldSize + ii, values[ii]); } }); }; List.prototype.pop = function() { return setListBounds(this, 0, -1); }; List.prototype.unshift = function(/*...values*/) { var values = arguments; return this.withMutations(function(list ) { setListBounds(list, -values.length); for (var ii = 0; ii < values.length; ii++) { list.set(ii, values[ii]); } }); }; List.prototype.shift = function() { return setListBounds(this, 1); }; // @pragma Composition List.prototype.merge = function(/*...iters*/) { return mergeIntoListWith(this, undefined, arguments); }; List.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoListWith(this, merger, iters); }; List.prototype.mergeDeep = function(/*...iters*/) { return mergeIntoListWith(this, deepMerger, arguments); }; List.prototype.mergeDeepWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return mergeIntoListWith(this, deepMergerWith(merger), iters); }; List.prototype.setSize = function(size) { return setListBounds(this, 0, size); }; // @pragma Iteration List.prototype.slice = function(begin, end) { var size = this.size; if (wholeSlice(begin, end, size)) { return this; } return setListBounds( this, resolveBegin(begin, size), resolveEnd(end, size) ); }; List.prototype.__iterator = function(type, reverse) { var index = 0; var values = iterateList(this, reverse); return new Iterator(function() { var value = values(); return value === DONE ? iteratorDone() : iteratorValue(type, index++, value); }); }; List.prototype.__iterate = function(fn, reverse) { var index = 0; var values = iterateList(this, reverse); var value; while ((value = values()) !== DONE) { if (fn(value, index++, this) === false) { break; } } return index; }; List.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; return this; } return makeList(this._origin, this._capacity, this._level, this._root, this._tail, ownerID, this.__hash); }; function isList(maybeList) { return !!(maybeList && maybeList[IS_LIST_SENTINEL]); } List.isList = isList; var IS_LIST_SENTINEL = '@@__IMMUTABLE_LIST__@@'; var ListPrototype = List.prototype; ListPrototype[IS_LIST_SENTINEL] = true; ListPrototype[DELETE] = ListPrototype.remove; ListPrototype.setIn = MapPrototype.setIn; ListPrototype.deleteIn = ListPrototype.removeIn = MapPrototype.removeIn; ListPrototype.update = MapPrototype.update; ListPrototype.updateIn = MapPrototype.updateIn; ListPrototype.mergeIn = MapPrototype.mergeIn; ListPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; ListPrototype.withMutations = MapPrototype.withMutations; ListPrototype.asMutable = MapPrototype.asMutable; ListPrototype.asImmutable = MapPrototype.asImmutable; ListPrototype.wasAltered = MapPrototype.wasAltered; function VNode(array, ownerID) { this.array = array; this.ownerID = ownerID; } // TODO: seems like these methods are very similar VNode.prototype.removeBefore = function(ownerID, level, index) { if (index === level ? 1 << level : 0 || this.array.length === 0) { return this; } var originIndex = (index >>> level) & MASK; if (originIndex >= this.array.length) { return new VNode([], ownerID); } var removingFirst = originIndex === 0; var newChild; if (level > 0) { var oldChild = this.array[originIndex]; newChild = oldChild && oldChild.removeBefore(ownerID, level - SHIFT, index); if (newChild === oldChild && removingFirst) { return this; } } if (removingFirst && !newChild) { return this; } var editable = editableVNode(this, ownerID); if (!removingFirst) { for (var ii = 0; ii < originIndex; ii++) { editable.array[ii] = undefined; } } if (newChild) { editable.array[originIndex] = newChild; } return editable; }; VNode.prototype.removeAfter = function(ownerID, level, index) { if (index === (level ? 1 << level : 0) || this.array.length === 0) { return this; } var sizeIndex = ((index - 1) >>> level) & MASK; if (sizeIndex >= this.array.length) { return this; } var newChild; if (level > 0) { var oldChild = this.array[sizeIndex]; newChild = oldChild && oldChild.removeAfter(ownerID, level - SHIFT, index); if (newChild === oldChild && sizeIndex === this.array.length - 1) { return this; } } var editable = editableVNode(this, ownerID); editable.array.splice(sizeIndex + 1); if (newChild) { editable.array[sizeIndex] = newChild; } return editable; }; var DONE = {}; function iterateList(list, reverse) { var left = list._origin; var right = list._capacity; var tailPos = getTailOffset(right); var tail = list._tail; return iterateNodeOrLeaf(list._root, list._level, 0); function iterateNodeOrLeaf(node, level, offset) { return level === 0 ? iterateLeaf(node, offset) : iterateNode(node, level, offset); } function iterateLeaf(node, offset) { var array = offset === tailPos ? tail && tail.array : node && node.array; var from = offset > left ? 0 : left - offset; var to = right - offset; if (to > SIZE) { to = SIZE; } return function() { if (from === to) { return DONE; } var idx = reverse ? --to : from++; return array && array[idx]; }; } function iterateNode(node, level, offset) { var values; var array = node && node.array; var from = offset > left ? 0 : (left - offset) >> level; var to = ((right - offset) >> level) + 1; if (to > SIZE) { to = SIZE; } return function() { do { if (values) { var value = values(); if (value !== DONE) { return value; } values = null; } if (from === to) { return DONE; } var idx = reverse ? --to : from++; values = iterateNodeOrLeaf( array && array[idx], level - SHIFT, offset + (idx << level) ); } while (true); }; } } function makeList(origin, capacity, level, root, tail, ownerID, hash) { var list = Object.create(ListPrototype); list.size = capacity - origin; list._origin = origin; list._capacity = capacity; list._level = level; list._root = root; list._tail = tail; list.__ownerID = ownerID; list.__hash = hash; list.__altered = false; return list; } var EMPTY_LIST; function emptyList() { return EMPTY_LIST || (EMPTY_LIST = makeList(0, 0, SHIFT)); } function updateList(list, index, value) { index = wrapIndex(list, index); if (index !== index) { return list; } if (index >= list.size || index < 0) { return list.withMutations(function(list ) { index < 0 ? setListBounds(list, index).set(0, value) : setListBounds(list, 0, index + 1).set(index, value) }); } index += list._origin; var newTail = list._tail; var newRoot = list._root; var didAlter = MakeRef(DID_ALTER); if (index >= getTailOffset(list._capacity)) { newTail = updateVNode(newTail, list.__ownerID, 0, index, value, didAlter); } else { newRoot = updateVNode(newRoot, list.__ownerID, list._level, index, value, didAlter); } if (!didAlter.value) { return list; } if (list.__ownerID) { list._root = newRoot; list._tail = newTail; list.__hash = undefined; list.__altered = true; return list; } return makeList(list._origin, list._capacity, list._level, newRoot, newTail); } function updateVNode(node, ownerID, level, index, value, didAlter) { var idx = (index >>> level) & MASK; var nodeHas = node && idx < node.array.length; if (!nodeHas && value === undefined) { return node; } var newNode; if (level > 0) { var lowerNode = node && node.array[idx]; var newLowerNode = updateVNode(lowerNode, ownerID, level - SHIFT, index, value, didAlter); if (newLowerNode === lowerNode) { return node; } newNode = editableVNode(node, ownerID); newNode.array[idx] = newLowerNode; return newNode; } if (nodeHas && node.array[idx] === value) { return node; } SetRef(didAlter); newNode = editableVNode(node, ownerID); if (value === undefined && idx === newNode.array.length - 1) { newNode.array.pop(); } else { newNode.array[idx] = value; } return newNode; } function editableVNode(node, ownerID) { if (ownerID && node && ownerID === node.ownerID) { return node; } return new VNode(node ? node.array.slice() : [], ownerID); } function listNodeFor(list, rawIndex) { if (rawIndex >= getTailOffset(list._capacity)) { return list._tail; } if (rawIndex < 1 << (list._level + SHIFT)) { var node = list._root; var level = list._level; while (node && level > 0) { node = node.array[(rawIndex >>> level) & MASK]; level -= SHIFT; } return node; } } function setListBounds(list, begin, end) { // Sanitize begin & end using this shorthand for ToInt32(argument) // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 if (begin !== undefined) { begin = begin | 0; } if (end !== undefined) { end = end | 0; } var owner = list.__ownerID || new OwnerID(); var oldOrigin = list._origin; var oldCapacity = list._capacity; var newOrigin = oldOrigin + begin; var newCapacity = end === undefined ? oldCapacity : end < 0 ? oldCapacity + end : oldOrigin + end; if (newOrigin === oldOrigin && newCapacity === oldCapacity) { return list; } // If it's going to end after it starts, it's empty. if (newOrigin >= newCapacity) { return list.clear(); } var newLevel = list._level; var newRoot = list._root; // New origin might need creating a higher root. var offsetShift = 0; while (newOrigin + offsetShift < 0) { newRoot = new VNode(newRoot && newRoot.array.length ? [undefined, newRoot] : [], owner); newLevel += SHIFT; offsetShift += 1 << newLevel; } if (offsetShift) { newOrigin += offsetShift; oldOrigin += offsetShift; newCapacity += offsetShift; oldCapacity += offsetShift; } var oldTailOffset = getTailOffset(oldCapacity); var newTailOffset = getTailOffset(newCapacity); // New size might need creating a higher root. while (newTailOffset >= 1 << (newLevel + SHIFT)) { newRoot = new VNode(newRoot && newRoot.array.length ? [newRoot] : [], owner); newLevel += SHIFT; } // Locate or create the new tail. var oldTail = list._tail; var newTail = newTailOffset < oldTailOffset ? listNodeFor(list, newCapacity - 1) : newTailOffset > oldTailOffset ? new VNode([], owner) : oldTail; // Merge Tail into tree. if (oldTail && newTailOffset > oldTailOffset && newOrigin < oldCapacity && oldTail.array.length) { newRoot = editableVNode(newRoot, owner); var node = newRoot; for (var level = newLevel; level > SHIFT; level -= SHIFT) { var idx = (oldTailOffset >>> level) & MASK; node = node.array[idx] = editableVNode(node.array[idx], owner); } node.array[(oldTailOffset >>> SHIFT) & MASK] = oldTail; } // If the size has been reduced, there's a chance the tail needs to be trimmed. if (newCapacity < oldCapacity) { newTail = newTail && newTail.removeAfter(owner, 0, newCapacity); } // If the new origin is within the tail, then we do not need a root. if (newOrigin >= newTailOffset) { newOrigin -= newTailOffset; newCapacity -= newTailOffset; newLevel = SHIFT; newRoot = null; newTail = newTail && newTail.removeBefore(owner, 0, newOrigin); // Otherwise, if the root has been trimmed, garbage collect. } else if (newOrigin > oldOrigin || newTailOffset < oldTailOffset) { offsetShift = 0; // Identify the new top root node of the subtree of the old root. while (newRoot) { var beginIndex = (newOrigin >>> newLevel) & MASK; if (beginIndex !== (newTailOffset >>> newLevel) & MASK) { break; } if (beginIndex) { offsetShift += (1 << newLevel) * beginIndex; } newLevel -= SHIFT; newRoot = newRoot.array[beginIndex]; } // Trim the new sides of the new root. if (newRoot && newOrigin > oldOrigin) { newRoot = newRoot.removeBefore(owner, newLevel, newOrigin - offsetShift); } if (newRoot && newTailOffset < oldTailOffset) { newRoot = newRoot.removeAfter(owner, newLevel, newTailOffset - offsetShift); } if (offsetShift) { newOrigin -= offsetShift; newCapacity -= offsetShift; } } if (list.__ownerID) { list.size = newCapacity - newOrigin; list._origin = newOrigin; list._capacity = newCapacity; list._level = newLevel; list._root = newRoot; list._tail = newTail; list.__hash = undefined; list.__altered = true; return list; } return makeList(newOrigin, newCapacity, newLevel, newRoot, newTail); } function mergeIntoListWith(list, merger, iterables) { var iters = []; var maxSize = 0; for (var ii = 0; ii < iterables.length; ii++) { var value = iterables[ii]; var iter = IndexedIterable(value); if (iter.size > maxSize) { maxSize = iter.size; } if (!isIterable(value)) { iter = iter.map(function(v ) {return fromJS(v)}); } iters.push(iter); } if (maxSize > list.size) { list = list.setSize(maxSize); } return mergeIntoCollectionWith(list, merger, iters); } function getTailOffset(size) { return size < SIZE ? 0 : (((size - 1) >>> SHIFT) << SHIFT); } createClass(OrderedMap, Map); // @pragma Construction function OrderedMap(value) { return value === null || value === undefined ? emptyOrderedMap() : isOrderedMap(value) ? value : emptyOrderedMap().withMutations(function(map ) { var iter = KeyedIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v, k) {return map.set(k, v)}); }); } OrderedMap.of = function(/*...values*/) { return this(arguments); }; OrderedMap.prototype.toString = function() { return this.__toString('OrderedMap {', '}'); }; // @pragma Access OrderedMap.prototype.get = function(k, notSetValue) { var index = this._map.get(k); return index !== undefined ? this._list.get(index)[1] : notSetValue; }; // @pragma Modification OrderedMap.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._map.clear(); this._list.clear(); return this; } return emptyOrderedMap(); }; OrderedMap.prototype.set = function(k, v) { return updateOrderedMap(this, k, v); }; OrderedMap.prototype.remove = function(k) { return updateOrderedMap(this, k, NOT_SET); }; OrderedMap.prototype.wasAltered = function() { return this._map.wasAltered() || this._list.wasAltered(); }; OrderedMap.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._list.__iterate( function(entry ) {return entry && fn(entry[1], entry[0], this$0)}, reverse ); }; OrderedMap.prototype.__iterator = function(type, reverse) { return this._list.fromEntrySeq().__iterator(type, reverse); }; OrderedMap.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map.__ensureOwner(ownerID); var newList = this._list.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; this._list = newList; return this; } return makeOrderedMap(newMap, newList, ownerID, this.__hash); }; function isOrderedMap(maybeOrderedMap) { return isMap(maybeOrderedMap) && isOrdered(maybeOrderedMap); } OrderedMap.isOrderedMap = isOrderedMap; OrderedMap.prototype[IS_ORDERED_SENTINEL] = true; OrderedMap.prototype[DELETE] = OrderedMap.prototype.remove; function makeOrderedMap(map, list, ownerID, hash) { var omap = Object.create(OrderedMap.prototype); omap.size = map ? map.size : 0; omap._map = map; omap._list = list; omap.__ownerID = ownerID; omap.__hash = hash; return omap; } var EMPTY_ORDERED_MAP; function emptyOrderedMap() { return EMPTY_ORDERED_MAP || (EMPTY_ORDERED_MAP = makeOrderedMap(emptyMap(), emptyList())); } function updateOrderedMap(omap, k, v) { var map = omap._map; var list = omap._list; var i = map.get(k); var has = i !== undefined; var newMap; var newList; if (v === NOT_SET) { // removed if (!has) { return omap; } if (list.size >= SIZE && list.size >= map.size * 2) { newList = list.filter(function(entry, idx) {return entry !== undefined && i !== idx}); newMap = newList.toKeyedSeq().map(function(entry ) {return entry[0]}).flip().toMap(); if (omap.__ownerID) { newMap.__ownerID = newList.__ownerID = omap.__ownerID; } } else { newMap = map.remove(k); newList = i === list.size - 1 ? list.pop() : list.set(i, undefined); } } else { if (has) { if (v === list.get(i)[1]) { return omap; } newMap = map; newList = list.set(i, [k, v]); } else { newMap = map.set(k, list.size); newList = list.set(list.size, [k, v]); } } if (omap.__ownerID) { omap.size = newMap.size; omap._map = newMap; omap._list = newList; omap.__hash = undefined; return omap; } return makeOrderedMap(newMap, newList); } createClass(ToKeyedSequence, KeyedSeq); function ToKeyedSequence(indexed, useKeys) { this._iter = indexed; this._useKeys = useKeys; this.size = indexed.size; } ToKeyedSequence.prototype.get = function(key, notSetValue) { return this._iter.get(key, notSetValue); }; ToKeyedSequence.prototype.has = function(key) { return this._iter.has(key); }; ToKeyedSequence.prototype.valueSeq = function() { return this._iter.valueSeq(); }; ToKeyedSequence.prototype.reverse = function() {var this$0 = this; var reversedSequence = reverseFactory(this, true); if (!this._useKeys) { reversedSequence.valueSeq = function() {return this$0._iter.toSeq().reverse()}; } return reversedSequence; }; ToKeyedSequence.prototype.map = function(mapper, context) {var this$0 = this; var mappedSequence = mapFactory(this, mapper, context); if (!this._useKeys) { mappedSequence.valueSeq = function() {return this$0._iter.toSeq().map(mapper, context)}; } return mappedSequence; }; ToKeyedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; var ii; return this._iter.__iterate( this._useKeys ? function(v, k) {return fn(v, k, this$0)} : ((ii = reverse ? resolveSize(this) : 0), function(v ) {return fn(v, reverse ? --ii : ii++, this$0)}), reverse ); }; ToKeyedSequence.prototype.__iterator = function(type, reverse) { if (this._useKeys) { return this._iter.__iterator(type, reverse); } var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); var ii = reverse ? resolveSize(this) : 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, reverse ? --ii : ii++, step.value, step); }); }; ToKeyedSequence.prototype[IS_ORDERED_SENTINEL] = true; createClass(ToIndexedSequence, IndexedSeq); function ToIndexedSequence(iter) { this._iter = iter; this.size = iter.size; } ToIndexedSequence.prototype.includes = function(value) { return this._iter.includes(value); }; ToIndexedSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; var iterations = 0; return this._iter.__iterate(function(v ) {return fn(v, iterations++, this$0)}, reverse); }; ToIndexedSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); var iterations = 0; return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, iterations++, step.value, step) }); }; createClass(ToSetSequence, SetSeq); function ToSetSequence(iter) { this._iter = iter; this.size = iter.size; } ToSetSequence.prototype.has = function(key) { return this._iter.includes(key); }; ToSetSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._iter.__iterate(function(v ) {return fn(v, v, this$0)}, reverse); }; ToSetSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); return new Iterator(function() { var step = iterator.next(); return step.done ? step : iteratorValue(type, step.value, step.value, step); }); }; createClass(FromEntriesSequence, KeyedSeq); function FromEntriesSequence(entries) { this._iter = entries; this.size = entries.size; } FromEntriesSequence.prototype.entrySeq = function() { return this._iter.toSeq(); }; FromEntriesSequence.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._iter.__iterate(function(entry ) { // Check if entry exists first so array access doesn't throw for holes // in the parent iteration. if (entry) { validateEntry(entry); var indexedIterable = isIterable(entry); return fn( indexedIterable ? entry.get(1) : entry[1], indexedIterable ? entry.get(0) : entry[0], this$0 ); } }, reverse); }; FromEntriesSequence.prototype.__iterator = function(type, reverse) { var iterator = this._iter.__iterator(ITERATE_VALUES, reverse); return new Iterator(function() { while (true) { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; // Check if entry exists first so array access doesn't throw for holes // in the parent iteration. if (entry) { validateEntry(entry); var indexedIterable = isIterable(entry); return iteratorValue( type, indexedIterable ? entry.get(0) : entry[0], indexedIterable ? entry.get(1) : entry[1], step ); } } }); }; ToIndexedSequence.prototype.cacheResult = ToKeyedSequence.prototype.cacheResult = ToSetSequence.prototype.cacheResult = FromEntriesSequence.prototype.cacheResult = cacheResultThrough; function flipFactory(iterable) { var flipSequence = makeSequence(iterable); flipSequence._iter = iterable; flipSequence.size = iterable.size; flipSequence.flip = function() {return iterable}; flipSequence.reverse = function () { var reversedSequence = iterable.reverse.apply(this); // super.reverse() reversedSequence.flip = function() {return iterable.reverse()}; return reversedSequence; }; flipSequence.has = function(key ) {return iterable.includes(key)}; flipSequence.includes = function(key ) {return iterable.has(key)}; flipSequence.cacheResult = cacheResultThrough; flipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; return iterable.__iterate(function(v, k) {return fn(k, v, this$0) !== false}, reverse); } flipSequence.__iteratorUncached = function(type, reverse) { if (type === ITERATE_ENTRIES) { var iterator = iterable.__iterator(type, reverse); return new Iterator(function() { var step = iterator.next(); if (!step.done) { var k = step.value[0]; step.value[0] = step.value[1]; step.value[1] = k; } return step; }); } return iterable.__iterator( type === ITERATE_VALUES ? ITERATE_KEYS : ITERATE_VALUES, reverse ); } return flipSequence; } function mapFactory(iterable, mapper, context) { var mappedSequence = makeSequence(iterable); mappedSequence.size = iterable.size; mappedSequence.has = function(key ) {return iterable.has(key)}; mappedSequence.get = function(key, notSetValue) { var v = iterable.get(key, NOT_SET); return v === NOT_SET ? notSetValue : mapper.call(context, v, key, iterable); }; mappedSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; return iterable.__iterate( function(v, k, c) {return fn(mapper.call(context, v, k, c), k, this$0) !== false}, reverse ); } mappedSequence.__iteratorUncached = function (type, reverse) { var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); return new Iterator(function() { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var key = entry[0]; return iteratorValue( type, key, mapper.call(context, entry[1], key, iterable), step ); }); } return mappedSequence; } function reverseFactory(iterable, useKeys) { var reversedSequence = makeSequence(iterable); reversedSequence._iter = iterable; reversedSequence.size = iterable.size; reversedSequence.reverse = function() {return iterable}; if (iterable.flip) { reversedSequence.flip = function () { var flipSequence = flipFactory(iterable); flipSequence.reverse = function() {return iterable.flip()}; return flipSequence; }; } reversedSequence.get = function(key, notSetValue) {return iterable.get(useKeys ? key : -1 - key, notSetValue)}; reversedSequence.has = function(key ) {return iterable.has(useKeys ? key : -1 - key)}; reversedSequence.includes = function(value ) {return iterable.includes(value)}; reversedSequence.cacheResult = cacheResultThrough; reversedSequence.__iterate = function (fn, reverse) {var this$0 = this; return iterable.__iterate(function(v, k) {return fn(v, k, this$0)}, !reverse); }; reversedSequence.__iterator = function(type, reverse) {return iterable.__iterator(type, !reverse)}; return reversedSequence; } function filterFactory(iterable, predicate, context, useKeys) { var filterSequence = makeSequence(iterable); if (useKeys) { filterSequence.has = function(key ) { var v = iterable.get(key, NOT_SET); return v !== NOT_SET && !!predicate.call(context, v, key, iterable); }; filterSequence.get = function(key, notSetValue) { var v = iterable.get(key, NOT_SET); return v !== NOT_SET && predicate.call(context, v, key, iterable) ? v : notSetValue; }; } filterSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; var iterations = 0; iterable.__iterate(function(v, k, c) { if (predicate.call(context, v, k, c)) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0); } }, reverse); return iterations; }; filterSequence.__iteratorUncached = function (type, reverse) { var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var iterations = 0; return new Iterator(function() { while (true) { var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var key = entry[0]; var value = entry[1]; if (predicate.call(context, value, key, iterable)) { return iteratorValue(type, useKeys ? key : iterations++, value, step); } } }); } return filterSequence; } function countByFactory(iterable, grouper, context) { var groups = Map().asMutable(); iterable.__iterate(function(v, k) { groups.update( grouper.call(context, v, k, iterable), 0, function(a ) {return a + 1} ); }); return groups.asImmutable(); } function groupByFactory(iterable, grouper, context) { var isKeyedIter = isKeyed(iterable); var groups = (isOrdered(iterable) ? OrderedMap() : Map()).asMutable(); iterable.__iterate(function(v, k) { groups.update( grouper.call(context, v, k, iterable), function(a ) {return (a = a || [], a.push(isKeyedIter ? [k, v] : v), a)} ); }); var coerce = iterableClass(iterable); return groups.map(function(arr ) {return reify(iterable, coerce(arr))}); } function sliceFactory(iterable, begin, end, useKeys) { var originalSize = iterable.size; // Sanitize begin & end using this shorthand for ToInt32(argument) // http://www.ecma-international.org/ecma-262/6.0/#sec-toint32 if (begin !== undefined) { begin = begin | 0; } if (end !== undefined) { if (end === Infinity) { end = originalSize; } else { end = end | 0; } } if (wholeSlice(begin, end, originalSize)) { return iterable; } var resolvedBegin = resolveBegin(begin, originalSize); var resolvedEnd = resolveEnd(end, originalSize); // begin or end will be NaN if they were provided as negative numbers and // this iterable's size is unknown. In that case, cache first so there is // a known size and these do not resolve to NaN. if (resolvedBegin !== resolvedBegin || resolvedEnd !== resolvedEnd) { return sliceFactory(iterable.toSeq().cacheResult(), begin, end, useKeys); } // Note: resolvedEnd is undefined when the original sequence's length is // unknown and this slice did not supply an end and should contain all // elements after resolvedBegin. // In that case, resolvedSize will be NaN and sliceSize will remain undefined. var resolvedSize = resolvedEnd - resolvedBegin; var sliceSize; if (resolvedSize === resolvedSize) { sliceSize = resolvedSize < 0 ? 0 : resolvedSize; } var sliceSeq = makeSequence(iterable); // If iterable.size is undefined, the size of the realized sliceSeq is // unknown at this point unless the number of items to slice is 0 sliceSeq.size = sliceSize === 0 ? sliceSize : iterable.size && sliceSize || undefined; if (!useKeys && isSeq(iterable) && sliceSize >= 0) { sliceSeq.get = function (index, notSetValue) { index = wrapIndex(this, index); return index >= 0 && index < sliceSize ? iterable.get(index + resolvedBegin, notSetValue) : notSetValue; } } sliceSeq.__iterateUncached = function(fn, reverse) {var this$0 = this; if (sliceSize === 0) { return 0; } if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var skipped = 0; var isSkipping = true; var iterations = 0; iterable.__iterate(function(v, k) { if (!(isSkipping && (isSkipping = skipped++ < resolvedBegin))) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0) !== false && iterations !== sliceSize; } }); return iterations; }; sliceSeq.__iteratorUncached = function(type, reverse) { if (sliceSize !== 0 && reverse) { return this.cacheResult().__iterator(type, reverse); } // Don't bother instantiating parent iterator if taking 0. var iterator = sliceSize !== 0 && iterable.__iterator(type, reverse); var skipped = 0; var iterations = 0; return new Iterator(function() { while (skipped++ < resolvedBegin) { iterator.next(); } if (++iterations > sliceSize) { return iteratorDone(); } var step = iterator.next(); if (useKeys || type === ITERATE_VALUES) { return step; } else if (type === ITERATE_KEYS) { return iteratorValue(type, iterations - 1, undefined, step); } else { return iteratorValue(type, iterations - 1, step.value[1], step); } }); } return sliceSeq; } function takeWhileFactory(iterable, predicate, context) { var takeSequence = makeSequence(iterable); takeSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var iterations = 0; iterable.__iterate(function(v, k, c) {return predicate.call(context, v, k, c) && ++iterations && fn(v, k, this$0)} ); return iterations; }; takeSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var iterating = true; return new Iterator(function() { if (!iterating) { return iteratorDone(); } var step = iterator.next(); if (step.done) { return step; } var entry = step.value; var k = entry[0]; var v = entry[1]; if (!predicate.call(context, v, k, this$0)) { iterating = false; return iteratorDone(); } return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); }); }; return takeSequence; } function skipWhileFactory(iterable, predicate, context, useKeys) { var skipSequence = makeSequence(iterable); skipSequence.__iterateUncached = function (fn, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterate(fn, reverse); } var isSkipping = true; var iterations = 0; iterable.__iterate(function(v, k, c) { if (!(isSkipping && (isSkipping = predicate.call(context, v, k, c)))) { iterations++; return fn(v, useKeys ? k : iterations - 1, this$0); } }); return iterations; }; skipSequence.__iteratorUncached = function(type, reverse) {var this$0 = this; if (reverse) { return this.cacheResult().__iterator(type, reverse); } var iterator = iterable.__iterator(ITERATE_ENTRIES, reverse); var skipping = true; var iterations = 0; return new Iterator(function() { var step, k, v; do { step = iterator.next(); if (step.done) { if (useKeys || type === ITERATE_VALUES) { return step; } else if (type === ITERATE_KEYS) { return iteratorValue(type, iterations++, undefined, step); } else { return iteratorValue(type, iterations++, step.value[1], step); } } var entry = step.value; k = entry[0]; v = entry[1]; skipping && (skipping = predicate.call(context, v, k, this$0)); } while (skipping); return type === ITERATE_ENTRIES ? step : iteratorValue(type, k, v, step); }); }; return skipSequence; } function concatFactory(iterable, values) { var isKeyedIterable = isKeyed(iterable); var iters = [iterable].concat(values).map(function(v ) { if (!isIterable(v)) { v = isKeyedIterable ? keyedSeqFromValue(v) : indexedSeqFromValue(Array.isArray(v) ? v : [v]); } else if (isKeyedIterable) { v = KeyedIterable(v); } return v; }).filter(function(v ) {return v.size !== 0}); if (iters.length === 0) { return iterable; } if (iters.length === 1) { var singleton = iters[0]; if (singleton === iterable || isKeyedIterable && isKeyed(singleton) || isIndexed(iterable) && isIndexed(singleton)) { return singleton; } } var concatSeq = new ArraySeq(iters); if (isKeyedIterable) { concatSeq = concatSeq.toKeyedSeq(); } else if (!isIndexed(iterable)) { concatSeq = concatSeq.toSetSeq(); } concatSeq = concatSeq.flatten(true); concatSeq.size = iters.reduce( function(sum, seq) { if (sum !== undefined) { var size = seq.size; if (size !== undefined) { return sum + size; } } }, 0 ); return concatSeq; } function flattenFactory(iterable, depth, useKeys) { var flatSequence = makeSequence(iterable); flatSequence.__iterateUncached = function(fn, reverse) { var iterations = 0; var stopped = false; function flatDeep(iter, currentDepth) {var this$0 = this; iter.__iterate(function(v, k) { if ((!depth || currentDepth < depth) && isIterable(v)) { flatDeep(v, currentDepth + 1); } else if (fn(v, useKeys ? k : iterations++, this$0) === false) { stopped = true; } return !stopped; }, reverse); } flatDeep(iterable, 0); return iterations; } flatSequence.__iteratorUncached = function(type, reverse) { var iterator = iterable.__iterator(type, reverse); var stack = []; var iterations = 0; return new Iterator(function() { while (iterator) { var step = iterator.next(); if (step.done !== false) { iterator = stack.pop(); continue; } var v = step.value; if (type === ITERATE_ENTRIES) { v = v[1]; } if ((!depth || stack.length < depth) && isIterable(v)) { stack.push(iterator); iterator = v.__iterator(type, reverse); } else { return useKeys ? step : iteratorValue(type, iterations++, v, step); } } return iteratorDone(); }); } return flatSequence; } function flatMapFactory(iterable, mapper, context) { var coerce = iterableClass(iterable); return iterable.toSeq().map( function(v, k) {return coerce(mapper.call(context, v, k, iterable))} ).flatten(true); } function interposeFactory(iterable, separator) { var interposedSequence = makeSequence(iterable); interposedSequence.size = iterable.size && iterable.size * 2 -1; interposedSequence.__iterateUncached = function(fn, reverse) {var this$0 = this; var iterations = 0; iterable.__iterate(function(v, k) {return (!iterations || fn(separator, iterations++, this$0) !== false) && fn(v, iterations++, this$0) !== false}, reverse ); return iterations; }; interposedSequence.__iteratorUncached = function(type, reverse) { var iterator = iterable.__iterator(ITERATE_VALUES, reverse); var iterations = 0; var step; return new Iterator(function() { if (!step || iterations % 2) { step = iterator.next(); if (step.done) { return step; } } return iterations % 2 ? iteratorValue(type, iterations++, separator) : iteratorValue(type, iterations++, step.value, step); }); }; return interposedSequence; } function sortFactory(iterable, comparator, mapper) { if (!comparator) { comparator = defaultComparator; } var isKeyedIterable = isKeyed(iterable); var index = 0; var entries = iterable.toSeq().map( function(v, k) {return [k, v, index++, mapper ? mapper(v, k, iterable) : v]} ).toArray(); entries.sort(function(a, b) {return comparator(a[3], b[3]) || a[2] - b[2]}).forEach( isKeyedIterable ? function(v, i) { entries[i].length = 2; } : function(v, i) { entries[i] = v[1]; } ); return isKeyedIterable ? KeyedSeq(entries) : isIndexed(iterable) ? IndexedSeq(entries) : SetSeq(entries); } function maxFactory(iterable, comparator, mapper) { if (!comparator) { comparator = defaultComparator; } if (mapper) { var entry = iterable.toSeq() .map(function(v, k) {return [v, mapper(v, k, iterable)]}) .reduce(function(a, b) {return maxCompare(comparator, a[1], b[1]) ? b : a}); return entry && entry[0]; } else { return iterable.reduce(function(a, b) {return maxCompare(comparator, a, b) ? b : a}); } } function maxCompare(comparator, a, b) { var comp = comparator(b, a); // b is considered the new max if the comparator declares them equal, but // they are not equal and b is in fact a nullish value. return (comp === 0 && b !== a && (b === undefined || b === null || b !== b)) || comp > 0; } function zipWithFactory(keyIter, zipper, iters) { var zipSequence = makeSequence(keyIter); zipSequence.size = new ArraySeq(iters).map(function(i ) {return i.size}).min(); // Note: this a generic base implementation of __iterate in terms of // __iterator which may be more generically useful in the future. zipSequence.__iterate = function(fn, reverse) { /* generic: var iterator = this.__iterator(ITERATE_ENTRIES, reverse); var step; var iterations = 0; while (!(step = iterator.next()).done) { iterations++; if (fn(step.value[1], step.value[0], this) === false) { break; } } return iterations; */ // indexed: var iterator = this.__iterator(ITERATE_VALUES, reverse); var step; var iterations = 0; while (!(step = iterator.next()).done) { if (fn(step.value, iterations++, this) === false) { break; } } return iterations; }; zipSequence.__iteratorUncached = function(type, reverse) { var iterators = iters.map(function(i ) {return (i = Iterable(i), getIterator(reverse ? i.reverse() : i))} ); var iterations = 0; var isDone = false; return new Iterator(function() { var steps; if (!isDone) { steps = iterators.map(function(i ) {return i.next()}); isDone = steps.some(function(s ) {return s.done}); } if (isDone) { return iteratorDone(); } return iteratorValue( type, iterations++, zipper.apply(null, steps.map(function(s ) {return s.value})) ); }); }; return zipSequence } // #pragma Helper Functions function reify(iter, seq) { return isSeq(iter) ? seq : iter.constructor(seq); } function validateEntry(entry) { if (entry !== Object(entry)) { throw new TypeError('Expected [K, V] tuple: ' + entry); } } function resolveSize(iter) { assertNotInfinite(iter.size); return ensureSize(iter); } function iterableClass(iterable) { return isKeyed(iterable) ? KeyedIterable : isIndexed(iterable) ? IndexedIterable : SetIterable; } function makeSequence(iterable) { return Object.create( ( isKeyed(iterable) ? KeyedSeq : isIndexed(iterable) ? IndexedSeq : SetSeq ).prototype ); } function cacheResultThrough() { if (this._iter.cacheResult) { this._iter.cacheResult(); this.size = this._iter.size; return this; } else { return Seq.prototype.cacheResult.call(this); } } function defaultComparator(a, b) { return a > b ? 1 : a < b ? -1 : 0; } function forceIterator(keyPath) { var iter = getIterator(keyPath); if (!iter) { // Array might not be iterable in this environment, so we need a fallback // to our wrapped type. if (!isArrayLike(keyPath)) { throw new TypeError('Expected iterable or array-like: ' + keyPath); } iter = getIterator(Iterable(keyPath)); } return iter; } createClass(Record, KeyedCollection); function Record(defaultValues, name) { var hasInitialized; var RecordType = function Record(values) { if (values instanceof RecordType) { return values; } if (!(this instanceof RecordType)) { return new RecordType(values); } if (!hasInitialized) { hasInitialized = true; var keys = Object.keys(defaultValues); setProps(RecordTypePrototype, keys); RecordTypePrototype.size = keys.length; RecordTypePrototype._name = name; RecordTypePrototype._keys = keys; RecordTypePrototype._defaultValues = defaultValues; } this._map = Map(values); }; var RecordTypePrototype = RecordType.prototype = Object.create(RecordPrototype); RecordTypePrototype.constructor = RecordType; return RecordType; } Record.prototype.toString = function() { return this.__toString(recordName(this) + ' {', '}'); }; // @pragma Access Record.prototype.has = function(k) { return this._defaultValues.hasOwnProperty(k); }; Record.prototype.get = function(k, notSetValue) { if (!this.has(k)) { return notSetValue; } var defaultVal = this._defaultValues[k]; return this._map ? this._map.get(k, defaultVal) : defaultVal; }; // @pragma Modification Record.prototype.clear = function() { if (this.__ownerID) { this._map && this._map.clear(); return this; } var RecordType = this.constructor; return RecordType._empty || (RecordType._empty = makeRecord(this, emptyMap())); }; Record.prototype.set = function(k, v) { if (!this.has(k)) { throw new Error('Cannot set unknown key "' + k + '" on ' + recordName(this)); } if (this._map && !this._map.has(k)) { var defaultVal = this._defaultValues[k]; if (v === defaultVal) { return this; } } var newMap = this._map && this._map.set(k, v); if (this.__ownerID || newMap === this._map) { return this; } return makeRecord(this, newMap); }; Record.prototype.remove = function(k) { if (!this.has(k)) { return this; } var newMap = this._map && this._map.remove(k); if (this.__ownerID || newMap === this._map) { return this; } return makeRecord(this, newMap); }; Record.prototype.wasAltered = function() { return this._map.wasAltered(); }; Record.prototype.__iterator = function(type, reverse) {var this$0 = this; return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterator(type, reverse); }; Record.prototype.__iterate = function(fn, reverse) {var this$0 = this; return KeyedIterable(this._defaultValues).map(function(_, k) {return this$0.get(k)}).__iterate(fn, reverse); }; Record.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map && this._map.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; return this; } return makeRecord(this, newMap, ownerID); }; var RecordPrototype = Record.prototype; RecordPrototype[DELETE] = RecordPrototype.remove; RecordPrototype.deleteIn = RecordPrototype.removeIn = MapPrototype.removeIn; RecordPrototype.merge = MapPrototype.merge; RecordPrototype.mergeWith = MapPrototype.mergeWith; RecordPrototype.mergeIn = MapPrototype.mergeIn; RecordPrototype.mergeDeep = MapPrototype.mergeDeep; RecordPrototype.mergeDeepWith = MapPrototype.mergeDeepWith; RecordPrototype.mergeDeepIn = MapPrototype.mergeDeepIn; RecordPrototype.setIn = MapPrototype.setIn; RecordPrototype.update = MapPrototype.update; RecordPrototype.updateIn = MapPrototype.updateIn; RecordPrototype.withMutations = MapPrototype.withMutations; RecordPrototype.asMutable = MapPrototype.asMutable; RecordPrototype.asImmutable = MapPrototype.asImmutable; function makeRecord(likeRecord, map, ownerID) { var record = Object.create(Object.getPrototypeOf(likeRecord)); record._map = map; record.__ownerID = ownerID; return record; } function recordName(record) { return record._name || record.constructor.name || 'Record'; } function setProps(prototype, names) { try { names.forEach(setProp.bind(undefined, prototype)); } catch (error) { // Object.defineProperty failed. Probably IE8. } } function setProp(prototype, name) { Object.defineProperty(prototype, name, { get: function() { return this.get(name); }, set: function(value) { invariant(this.__ownerID, 'Cannot set on an immutable record.'); this.set(name, value); } }); } createClass(Set, SetCollection); // @pragma Construction function Set(value) { return value === null || value === undefined ? emptySet() : isSet(value) && !isOrdered(value) ? value : emptySet().withMutations(function(set ) { var iter = SetIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v ) {return set.add(v)}); }); } Set.of = function(/*...values*/) { return this(arguments); }; Set.fromKeys = function(value) { return this(KeyedIterable(value).keySeq()); }; Set.prototype.toString = function() { return this.__toString('Set {', '}'); }; // @pragma Access Set.prototype.has = function(value) { return this._map.has(value); }; // @pragma Modification Set.prototype.add = function(value) { return updateSet(this, this._map.set(value, true)); }; Set.prototype.remove = function(value) { return updateSet(this, this._map.remove(value)); }; Set.prototype.clear = function() { return updateSet(this, this._map.clear()); }; // @pragma Composition Set.prototype.union = function() {var iters = SLICE$0.call(arguments, 0); iters = iters.filter(function(x ) {return x.size !== 0}); if (iters.length === 0) { return this; } if (this.size === 0 && !this.__ownerID && iters.length === 1) { return this.constructor(iters[0]); } return this.withMutations(function(set ) { for (var ii = 0; ii < iters.length; ii++) { SetIterable(iters[ii]).forEach(function(value ) {return set.add(value)}); } }); }; Set.prototype.intersect = function() {var iters = SLICE$0.call(arguments, 0); if (iters.length === 0) { return this; } iters = iters.map(function(iter ) {return SetIterable(iter)}); var originalSet = this; return this.withMutations(function(set ) { originalSet.forEach(function(value ) { if (!iters.every(function(iter ) {return iter.includes(value)})) { set.remove(value); } }); }); }; Set.prototype.subtract = function() {var iters = SLICE$0.call(arguments, 0); if (iters.length === 0) { return this; } iters = iters.map(function(iter ) {return SetIterable(iter)}); var originalSet = this; return this.withMutations(function(set ) { originalSet.forEach(function(value ) { if (iters.some(function(iter ) {return iter.includes(value)})) { set.remove(value); } }); }); }; Set.prototype.merge = function() { return this.union.apply(this, arguments); }; Set.prototype.mergeWith = function(merger) {var iters = SLICE$0.call(arguments, 1); return this.union.apply(this, iters); }; Set.prototype.sort = function(comparator) { // Late binding return OrderedSet(sortFactory(this, comparator)); }; Set.prototype.sortBy = function(mapper, comparator) { // Late binding return OrderedSet(sortFactory(this, comparator, mapper)); }; Set.prototype.wasAltered = function() { return this._map.wasAltered(); }; Set.prototype.__iterate = function(fn, reverse) {var this$0 = this; return this._map.__iterate(function(_, k) {return fn(k, k, this$0)}, reverse); }; Set.prototype.__iterator = function(type, reverse) { return this._map.map(function(_, k) {return k}).__iterator(type, reverse); }; Set.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } var newMap = this._map.__ensureOwner(ownerID); if (!ownerID) { this.__ownerID = ownerID; this._map = newMap; return this; } return this.__make(newMap, ownerID); }; function isSet(maybeSet) { return !!(maybeSet && maybeSet[IS_SET_SENTINEL]); } Set.isSet = isSet; var IS_SET_SENTINEL = '@@__IMMUTABLE_SET__@@'; var SetPrototype = Set.prototype; SetPrototype[IS_SET_SENTINEL] = true; SetPrototype[DELETE] = SetPrototype.remove; SetPrototype.mergeDeep = SetPrototype.merge; SetPrototype.mergeDeepWith = SetPrototype.mergeWith; SetPrototype.withMutations = MapPrototype.withMutations; SetPrototype.asMutable = MapPrototype.asMutable; SetPrototype.asImmutable = MapPrototype.asImmutable; SetPrototype.__empty = emptySet; SetPrototype.__make = makeSet; function updateSet(set, newMap) { if (set.__ownerID) { set.size = newMap.size; set._map = newMap; return set; } return newMap === set._map ? set : newMap.size === 0 ? set.__empty() : set.__make(newMap); } function makeSet(map, ownerID) { var set = Object.create(SetPrototype); set.size = map ? map.size : 0; set._map = map; set.__ownerID = ownerID; return set; } var EMPTY_SET; function emptySet() { return EMPTY_SET || (EMPTY_SET = makeSet(emptyMap())); } createClass(OrderedSet, Set); // @pragma Construction function OrderedSet(value) { return value === null || value === undefined ? emptyOrderedSet() : isOrderedSet(value) ? value : emptyOrderedSet().withMutations(function(set ) { var iter = SetIterable(value); assertNotInfinite(iter.size); iter.forEach(function(v ) {return set.add(v)}); }); } OrderedSet.of = function(/*...values*/) { return this(arguments); }; OrderedSet.fromKeys = function(value) { return this(KeyedIterable(value).keySeq()); }; OrderedSet.prototype.toString = function() { return this.__toString('OrderedSet {', '}'); }; function isOrderedSet(maybeOrderedSet) { return isSet(maybeOrderedSet) && isOrdered(maybeOrderedSet); } OrderedSet.isOrderedSet = isOrderedSet; var OrderedSetPrototype = OrderedSet.prototype; OrderedSetPrototype[IS_ORDERED_SENTINEL] = true; OrderedSetPrototype.__empty = emptyOrderedSet; OrderedSetPrototype.__make = makeOrderedSet; function makeOrderedSet(map, ownerID) { var set = Object.create(OrderedSetPrototype); set.size = map ? map.size : 0; set._map = map; set.__ownerID = ownerID; return set; } var EMPTY_ORDERED_SET; function emptyOrderedSet() { return EMPTY_ORDERED_SET || (EMPTY_ORDERED_SET = makeOrderedSet(emptyOrderedMap())); } createClass(Stack, IndexedCollection); // @pragma Construction function Stack(value) { return value === null || value === undefined ? emptyStack() : isStack(value) ? value : emptyStack().unshiftAll(value); } Stack.of = function(/*...values*/) { return this(arguments); }; Stack.prototype.toString = function() { return this.__toString('Stack [', ']'); }; // @pragma Access Stack.prototype.get = function(index, notSetValue) { var head = this._head; index = wrapIndex(this, index); while (head && index--) { head = head.next; } return head ? head.value : notSetValue; }; Stack.prototype.peek = function() { return this._head && this._head.value; }; // @pragma Modification Stack.prototype.push = function(/*...values*/) { if (arguments.length === 0) { return this; } var newSize = this.size + arguments.length; var head = this._head; for (var ii = arguments.length - 1; ii >= 0; ii--) { head = { value: arguments[ii], next: head }; } if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; Stack.prototype.pushAll = function(iter) { iter = IndexedIterable(iter); if (iter.size === 0) { return this; } assertNotInfinite(iter.size); var newSize = this.size; var head = this._head; iter.reverse().forEach(function(value ) { newSize++; head = { value: value, next: head }; }); if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; Stack.prototype.pop = function() { return this.slice(1); }; Stack.prototype.unshift = function(/*...values*/) { return this.push.apply(this, arguments); }; Stack.prototype.unshiftAll = function(iter) { return this.pushAll(iter); }; Stack.prototype.shift = function() { return this.pop.apply(this, arguments); }; Stack.prototype.clear = function() { if (this.size === 0) { return this; } if (this.__ownerID) { this.size = 0; this._head = undefined; this.__hash = undefined; this.__altered = true; return this; } return emptyStack(); }; Stack.prototype.slice = function(begin, end) { if (wholeSlice(begin, end, this.size)) { return this; } var resolvedBegin = resolveBegin(begin, this.size); var resolvedEnd = resolveEnd(end, this.size); if (resolvedEnd !== this.size) { // super.slice(begin, end); return IndexedCollection.prototype.slice.call(this, begin, end); } var newSize = this.size - resolvedBegin; var head = this._head; while (resolvedBegin--) { head = head.next; } if (this.__ownerID) { this.size = newSize; this._head = head; this.__hash = undefined; this.__altered = true; return this; } return makeStack(newSize, head); }; // @pragma Mutability Stack.prototype.__ensureOwner = function(ownerID) { if (ownerID === this.__ownerID) { return this; } if (!ownerID) { this.__ownerID = ownerID; this.__altered = false; return this; } return makeStack(this.size, this._head, ownerID, this.__hash); }; // @pragma Iteration Stack.prototype.__iterate = function(fn, reverse) { if (reverse) { return this.reverse().__iterate(fn); } var iterations = 0; var node = this._head; while (node) { if (fn(node.value, iterations++, this) === false) { break; } node = node.next; } return iterations; }; Stack.prototype.__iterator = function(type, reverse) { if (reverse) { return this.reverse().__iterator(type); } var iterations = 0; var node = this._head; return new Iterator(function() { if (node) { var value = node.value; node = node.next; return iteratorValue(type, iterations++, value); } return iteratorDone(); }); }; function isStack(maybeStack) { return !!(maybeStack && maybeStack[IS_STACK_SENTINEL]); } Stack.isStack = isStack; var IS_STACK_SENTINEL = '@@__IMMUTABLE_STACK__@@'; var StackPrototype = Stack.prototype; StackPrototype[IS_STACK_SENTINEL] = true; StackPrototype.withMutations = MapPrototype.withMutations; StackPrototype.asMutable = MapPrototype.asMutable; StackPrototype.asImmutable = MapPrototype.asImmutable; StackPrototype.wasAltered = MapPrototype.wasAltered; function makeStack(size, head, ownerID, hash) { var map = Object.create(StackPrototype); map.size = size; map._head = head; map.__ownerID = ownerID; map.__hash = hash; map.__altered = false; return map; } var EMPTY_STACK; function emptyStack() { return EMPTY_STACK || (EMPTY_STACK = makeStack(0)); } /** * Contributes additional methods to a constructor */ function mixin(ctor, methods) { var keyCopier = function(key ) { ctor.prototype[key] = methods[key]; }; Object.keys(methods).forEach(keyCopier); Object.getOwnPropertySymbols && Object.getOwnPropertySymbols(methods).forEach(keyCopier); return ctor; } Iterable.Iterator = Iterator; mixin(Iterable, { // ### Conversion to other types toArray: function() { assertNotInfinite(this.size); var array = new Array(this.size || 0); this.valueSeq().__iterate(function(v, i) { array[i] = v; }); return array; }, toIndexedSeq: function() { return new ToIndexedSequence(this); }, toJS: function() { return this.toSeq().map( function(value ) {return value && typeof value.toJS === 'function' ? value.toJS() : value} ).__toJS(); }, toJSON: function() { return this.toSeq().map( function(value ) {return value && typeof value.toJSON === 'function' ? value.toJSON() : value} ).__toJS(); }, toKeyedSeq: function() { return new ToKeyedSequence(this, true); }, toMap: function() { // Use Late Binding here to solve the circular dependency. return Map(this.toKeyedSeq()); }, toObject: function() { assertNotInfinite(this.size); var object = {}; this.__iterate(function(v, k) { object[k] = v; }); return object; }, toOrderedMap: function() { // Use Late Binding here to solve the circular dependency. return OrderedMap(this.toKeyedSeq()); }, toOrderedSet: function() { // Use Late Binding here to solve the circular dependency. return OrderedSet(isKeyed(this) ? this.valueSeq() : this); }, toSet: function() { // Use Late Binding here to solve the circular dependency. return Set(isKeyed(this) ? this.valueSeq() : this); }, toSetSeq: function() { return new ToSetSequence(this); }, toSeq: function() { return isIndexed(this) ? this.toIndexedSeq() : isKeyed(this) ? this.toKeyedSeq() : this.toSetSeq(); }, toStack: function() { // Use Late Binding here to solve the circular dependency. return Stack(isKeyed(this) ? this.valueSeq() : this); }, toList: function() { // Use Late Binding here to solve the circular dependency. return List(isKeyed(this) ? this.valueSeq() : this); }, // ### Common JavaScript methods and properties toString: function() { return '[Iterable]'; }, __toString: function(head, tail) { if (this.size === 0) { return head + tail; } return head + ' ' + this.toSeq().map(this.__toStringMapper).join(', ') + ' ' + tail; }, // ### ES6 Collection methods (ES6 Array and Map) concat: function() {var values = SLICE$0.call(arguments, 0); return reify(this, concatFactory(this, values)); }, includes: function(searchValue) { return this.some(function(value ) {return is(value, searchValue)}); }, entries: function() { return this.__iterator(ITERATE_ENTRIES); }, every: function(predicate, context) { assertNotInfinite(this.size); var returnValue = true; this.__iterate(function(v, k, c) { if (!predicate.call(context, v, k, c)) { returnValue = false; return false; } }); return returnValue; }, filter: function(predicate, context) { return reify(this, filterFactory(this, predicate, context, true)); }, find: function(predicate, context, notSetValue) { var entry = this.findEntry(predicate, context); return entry ? entry[1] : notSetValue; }, forEach: function(sideEffect, context) { assertNotInfinite(this.size); return this.__iterate(context ? sideEffect.bind(context) : sideEffect); }, join: function(separator) { assertNotInfinite(this.size); separator = separator !== undefined ? '' + separator : ','; var joined = ''; var isFirst = true; this.__iterate(function(v ) { isFirst ? (isFirst = false) : (joined += separator); joined += v !== null && v !== undefined ? v.toString() : ''; }); return joined; }, keys: function() { return this.__iterator(ITERATE_KEYS); }, map: function(mapper, context) { return reify(this, mapFactory(this, mapper, context)); }, reduce: function(reducer, initialReduction, context) { assertNotInfinite(this.size); var reduction; var useFirst; if (arguments.length < 2) { useFirst = true; } else { reduction = initialReduction; } this.__iterate(function(v, k, c) { if (useFirst) { useFirst = false; reduction = v; } else { reduction = reducer.call(context, reduction, v, k, c); } }); return reduction; }, reduceRight: function(reducer, initialReduction, context) { var reversed = this.toKeyedSeq().reverse(); return reversed.reduce.apply(reversed, arguments); }, reverse: function() { return reify(this, reverseFactory(this, true)); }, slice: function(begin, end) { return reify(this, sliceFactory(this, begin, end, true)); }, some: function(predicate, context) { return !this.every(not(predicate), context); }, sort: function(comparator) { return reify(this, sortFactory(this, comparator)); }, values: function() { return this.__iterator(ITERATE_VALUES); }, // ### More sequential methods butLast: function() { return this.slice(0, -1); }, isEmpty: function() { return this.size !== undefined ? this.size === 0 : !this.some(function() {return true}); }, count: function(predicate, context) { return ensureSize( predicate ? this.toSeq().filter(predicate, context) : this ); }, countBy: function(grouper, context) { return countByFactory(this, grouper, context); }, equals: function(other) { return deepEqual(this, other); }, entrySeq: function() { var iterable = this; if (iterable._cache) { // We cache as an entries array, so we can just return the cache! return new ArraySeq(iterable._cache); } var entriesSequence = iterable.toSeq().map(entryMapper).toIndexedSeq(); entriesSequence.fromEntrySeq = function() {return iterable.toSeq()}; return entriesSequence; }, filterNot: function(predicate, context) { return this.filter(not(predicate), context); }, findEntry: function(predicate, context, notSetValue) { var found = notSetValue; this.__iterate(function(v, k, c) { if (predicate.call(context, v, k, c)) { found = [k, v]; return false; } }); return found; }, findKey: function(predicate, context) { var entry = this.findEntry(predicate, context); return entry && entry[0]; }, findLast: function(predicate, context, notSetValue) { return this.toKeyedSeq().reverse().find(predicate, context, notSetValue); }, findLastEntry: function(predicate, context, notSetValue) { return this.toKeyedSeq().reverse().findEntry(predicate, context, notSetValue); }, findLastKey: function(predicate, context) { return this.toKeyedSeq().reverse().findKey(predicate, context); }, first: function() { return this.find(returnTrue); }, flatMap: function(mapper, context) { return reify(this, flatMapFactory(this, mapper, context)); }, flatten: function(depth) { return reify(this, flattenFactory(this, depth, true)); }, fromEntrySeq: function() { return new FromEntriesSequence(this); }, get: function(searchKey, notSetValue) { return this.find(function(_, key) {return is(key, searchKey)}, undefined, notSetValue); }, getIn: function(searchKeyPath, notSetValue) { var nested = this; // Note: in an ES6 environment, we would prefer: // for (var key of searchKeyPath) { var iter = forceIterator(searchKeyPath); var step; while (!(step = iter.next()).done) { var key = step.value; nested = nested && nested.get ? nested.get(key, NOT_SET) : NOT_SET; if (nested === NOT_SET) { return notSetValue; } } return nested; }, groupBy: function(grouper, context) { return groupByFactory(this, grouper, context); }, has: function(searchKey) { return this.get(searchKey, NOT_SET) !== NOT_SET; }, hasIn: function(searchKeyPath) { return this.getIn(searchKeyPath, NOT_SET) !== NOT_SET; }, isSubset: function(iter) { iter = typeof iter.includes === 'function' ? iter : Iterable(iter); return this.every(function(value ) {return iter.includes(value)}); }, isSuperset: function(iter) { iter = typeof iter.isSubset === 'function' ? iter : Iterable(iter); return iter.isSubset(this); }, keyOf: function(searchValue) { return this.findKey(function(value ) {return is(value, searchValue)}); }, keySeq: function() { return this.toSeq().map(keyMapper).toIndexedSeq(); }, last: function() { return this.toSeq().reverse().first(); }, lastKeyOf: function(searchValue) { return this.toKeyedSeq().reverse().keyOf(searchValue); }, max: function(comparator) { return maxFactory(this, comparator); }, maxBy: function(mapper, comparator) { return maxFactory(this, comparator, mapper); }, min: function(comparator) { return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator); }, minBy: function(mapper, comparator) { return maxFactory(this, comparator ? neg(comparator) : defaultNegComparator, mapper); }, rest: function() { return this.slice(1); }, skip: function(amount) { return this.slice(Math.max(0, amount)); }, skipLast: function(amount) { return reify(this, this.toSeq().reverse().skip(amount).reverse()); }, skipWhile: function(predicate, context) { return reify(this, skipWhileFactory(this, predicate, context, true)); }, skipUntil: function(predicate, context) { return this.skipWhile(not(predicate), context); }, sortBy: function(mapper, comparator) { return reify(this, sortFactory(this, comparator, mapper)); }, take: function(amount) { return this.slice(0, Math.max(0, amount)); }, takeLast: function(amount) { return reify(this, this.toSeq().reverse().take(amount).reverse()); }, takeWhile: function(predicate, context) { return reify(this, takeWhileFactory(this, predicate, context)); }, takeUntil: function(predicate, context) { return this.takeWhile(not(predicate), context); }, valueSeq: function() { return this.toIndexedSeq(); }, // ### Hashable Object hashCode: function() { return this.__hash || (this.__hash = hashIterable(this)); } // ### Internal // abstract __iterate(fn, reverse) // abstract __iterator(type, reverse) }); // var IS_ITERABLE_SENTINEL = '@@__IMMUTABLE_ITERABLE__@@'; // var IS_KEYED_SENTINEL = '@@__IMMUTABLE_KEYED__@@'; // var IS_INDEXED_SENTINEL = '@@__IMMUTABLE_INDEXED__@@'; // var IS_ORDERED_SENTINEL = '@@__IMMUTABLE_ORDERED__@@'; var IterablePrototype = Iterable.prototype; IterablePrototype[IS_ITERABLE_SENTINEL] = true; IterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.values; IterablePrototype.__toJS = IterablePrototype.toArray; IterablePrototype.__toStringMapper = quoteString; IterablePrototype.inspect = IterablePrototype.toSource = function() { return this.toString(); }; IterablePrototype.chain = IterablePrototype.flatMap; IterablePrototype.contains = IterablePrototype.includes; mixin(KeyedIterable, { // ### More sequential methods flip: function() { return reify(this, flipFactory(this)); }, mapEntries: function(mapper, context) {var this$0 = this; var iterations = 0; return reify(this, this.toSeq().map( function(v, k) {return mapper.call(context, [k, v], iterations++, this$0)} ).fromEntrySeq() ); }, mapKeys: function(mapper, context) {var this$0 = this; return reify(this, this.toSeq().flip().map( function(k, v) {return mapper.call(context, k, v, this$0)} ).flip() ); } }); var KeyedIterablePrototype = KeyedIterable.prototype; KeyedIterablePrototype[IS_KEYED_SENTINEL] = true; KeyedIterablePrototype[ITERATOR_SYMBOL] = IterablePrototype.entries; KeyedIterablePrototype.__toJS = IterablePrototype.toObject; KeyedIterablePrototype.__toStringMapper = function(v, k) {return JSON.stringify(k) + ': ' + quoteString(v)}; mixin(IndexedIterable, { // ### Conversion to other types toKeyedSeq: function() { return new ToKeyedSequence(this, false); }, // ### ES6 Collection methods (ES6 Array and Map) filter: function(predicate, context) { return reify(this, filterFactory(this, predicate, context, false)); }, findIndex: function(predicate, context) { var entry = this.findEntry(predicate, context); return entry ? entry[0] : -1; }, indexOf: function(searchValue) { var key = this.keyOf(searchValue); return key === undefined ? -1 : key; }, lastIndexOf: function(searchValue) { var key = this.lastKeyOf(searchValue); return key === undefined ? -1 : key; }, reverse: function() { return reify(this, reverseFactory(this, false)); }, slice: function(begin, end) { return reify(this, sliceFactory(this, begin, end, false)); }, splice: function(index, removeNum /*, ...values*/) { var numArgs = arguments.length; removeNum = Math.max(removeNum | 0, 0); if (numArgs === 0 || (numArgs === 2 && !removeNum)) { return this; } // If index is negative, it should resolve relative to the size of the // collection. However size may be expensive to compute if not cached, so // only call count() if the number is in fact negative. index = resolveBegin(index, index < 0 ? this.count() : this.size); var spliced = this.slice(0, index); return reify( this, numArgs === 1 ? spliced : spliced.concat(arrCopy(arguments, 2), this.slice(index + removeNum)) ); }, // ### More collection methods findLastIndex: function(predicate, context) { var entry = this.findLastEntry(predicate, context); return entry ? entry[0] : -1; }, first: function() { return this.get(0); }, flatten: function(depth) { return reify(this, flattenFactory(this, depth, false)); }, get: function(index, notSetValue) { index = wrapIndex(this, index); return (index < 0 || (this.size === Infinity || (this.size !== undefined && index > this.size))) ? notSetValue : this.find(function(_, key) {return key === index}, undefined, notSetValue); }, has: function(index) { index = wrapIndex(this, index); return index >= 0 && (this.size !== undefined ? this.size === Infinity || index < this.size : this.indexOf(index) !== -1 ); }, interpose: function(separator) { return reify(this, interposeFactory(this, separator)); }, interleave: function(/*...iterables*/) { var iterables = [this].concat(arrCopy(arguments)); var zipped = zipWithFactory(this.toSeq(), IndexedSeq.of, iterables); var interleaved = zipped.flatten(true); if (zipped.size) { interleaved.size = zipped.size * iterables.length; } return reify(this, interleaved); }, keySeq: function() { return Range(0, this.size); }, last: function() { return this.get(-1); }, skipWhile: function(predicate, context) { return reify(this, skipWhileFactory(this, predicate, context, false)); }, zip: function(/*, ...iterables */) { var iterables = [this].concat(arrCopy(arguments)); return reify(this, zipWithFactory(this, defaultZipper, iterables)); }, zipWith: function(zipper/*, ...iterables */) { var iterables = arrCopy(arguments); iterables[0] = this; return reify(this, zipWithFactory(this, zipper, iterables)); } }); IndexedIterable.prototype[IS_INDEXED_SENTINEL] = true; IndexedIterable.prototype[IS_ORDERED_SENTINEL] = true; mixin(SetIterable, { // ### ES6 Collection methods (ES6 Array and Map) get: function(value, notSetValue) { return this.has(value) ? value : notSetValue; }, includes: function(value) { return this.has(value); }, // ### More sequential methods keySeq: function() { return this.valueSeq(); } }); SetIterable.prototype.has = IterablePrototype.includes; SetIterable.prototype.contains = SetIterable.prototype.includes; // Mixin subclasses mixin(KeyedSeq, KeyedIterable.prototype); mixin(IndexedSeq, IndexedIterable.prototype); mixin(SetSeq, SetIterable.prototype); mixin(KeyedCollection, KeyedIterable.prototype); mixin(IndexedCollection, IndexedIterable.prototype); mixin(SetCollection, SetIterable.prototype); // #pragma Helper functions function keyMapper(v, k) { return k; } function entryMapper(v, k) { return [k, v]; } function not(predicate) { return function() { return !predicate.apply(this, arguments); } } function neg(predicate) { return function() { return -predicate.apply(this, arguments); } } function quoteString(value) { return typeof value === 'string' ? JSON.stringify(value) : String(value); } function defaultZipper() { return arrCopy(arguments); } function defaultNegComparator(a, b) { return a < b ? 1 : a > b ? -1 : 0; } function hashIterable(iterable) { if (iterable.size === Infinity) { return 0; } var ordered = isOrdered(iterable); var keyed = isKeyed(iterable); var h = ordered ? 1 : 0; var size = iterable.__iterate( keyed ? ordered ? function(v, k) { h = 31 * h + hashMerge(hash(v), hash(k)) | 0; } : function(v, k) { h = h + hashMerge(hash(v), hash(k)) | 0; } : ordered ? function(v ) { h = 31 * h + hash(v) | 0; } : function(v ) { h = h + hash(v) | 0; } ); return murmurHashOfSize(size, h); } function murmurHashOfSize(size, h) { h = imul(h, 0xCC9E2D51); h = imul(h << 15 | h >>> -15, 0x1B873593); h = imul(h << 13 | h >>> -13, 5); h = (h + 0xE6546B64 | 0) ^ size; h = imul(h ^ h >>> 16, 0x85EBCA6B); h = imul(h ^ h >>> 13, 0xC2B2AE35); h = smi(h ^ h >>> 16); return h; } function hashMerge(a, b) { return a ^ b + 0x9E3779B9 + (a << 6) + (a >> 2) | 0; // int } var Immutable = { Iterable: Iterable, Seq: Seq, Collection: Collection, Map: Map, OrderedMap: OrderedMap, List: List, Stack: Stack, Set: Set, OrderedSet: OrderedSet, Record: Record, Range: Range, Repeat: Repeat, is: is, fromJS: fromJS }; return Immutable; })); /***/ }, /* 72 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(7), root = __webpack_require__(4); /* Built-in method references that are verified to be native. */ var Set = getNative(root, 'Set'); module.exports = Set; /***/ }, /* 73 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(20), stackClear = __webpack_require__(269), stackDelete = __webpack_require__(270), stackGet = __webpack_require__(271), stackHas = __webpack_require__(272), stackSet = __webpack_require__(273); /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; module.exports = Stack; /***/ }, /* 74 */ /***/ function(module, exports) { /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } module.exports = apply; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { var baseTimes = __webpack_require__(220), isArguments = __webpack_require__(47), isArray = __webpack_require__(3), isBuffer = __webpack_require__(90), isIndex = __webpack_require__(43), isTypedArray = __webpack_require__(92); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } module.exports = arrayLikeKeys; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(21), arrayIncludes = __webpack_require__(39), arrayIncludesWith = __webpack_require__(40), arrayMap = __webpack_require__(22), baseUnary = __webpack_require__(42), cacheHas = __webpack_require__(24); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of methods like `_.difference` without support * for excluding multiple arrays or iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Array} values The values to exclude. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of filtered values. */ function baseDifference(array, values, iteratee, comparator) { var index = -1, includes = arrayIncludes, isCommon = true, length = array.length, result = [], valuesLength = values.length; if (!length) { return result; } if (iteratee) { values = arrayMap(values, baseUnary(iteratee)); } if (comparator) { includes = arrayIncludesWith; isCommon = false; } else if (values.length >= LARGE_ARRAY_SIZE) { includes = cacheHas; isCommon = false; values = new SetCache(values); } outer: while (++index < length) { var value = array[index], computed = iteratee == null ? value : iteratee(value); value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var valuesIndex = valuesLength; while (valuesIndex--) { if (values[valuesIndex] === computed) { continue outer; } } result.push(value); } else if (!includes(values, computed, comparator)) { result.push(value); } } return result; } module.exports = baseDifference; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(194), isFlattenable = __webpack_require__(244); /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } module.exports = baseFlatten; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(81), toKey = __webpack_require__(27); /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } module.exports = baseGet; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqualDeep = __webpack_require__(207), isObject = __webpack_require__(8), isObjectLike = __webpack_require__(9); /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObject(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } module.exports = baseIsEqual; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(21), arrayIncludes = __webpack_require__(39), arrayIncludesWith = __webpack_require__(40), cacheHas = __webpack_require__(24), createSet = __webpack_require__(230), setToArray = __webpack_require__(45); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * The base implementation of `_.uniqBy` without support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new duplicate free array. */ function baseUniq(array, iteratee, comparator) { var index = -1, includes = arrayIncludes, length = array.length, isCommon = true, result = [], seen = result; if (comparator) { isCommon = false; includes = arrayIncludesWith; } else if (length >= LARGE_ARRAY_SIZE) { var set = iteratee ? null : createSet(array); if (set) { return setToArray(set); } isCommon = false; includes = cacheHas; seen = new SetCache; } else { seen = iteratee ? [] : result; } outer: while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (isCommon && computed === computed) { var seenIndex = seen.length; while (seenIndex--) { if (seen[seenIndex] === computed) { continue outer; } } if (iteratee) { seen.push(computed); } result.push(value); } else if (!includes(seen, computed, comparator)) { if (seen !== result) { seen.push(computed); } result.push(value); } } return result; } module.exports = baseUniq; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(3), isKey = __webpack_require__(44), stringToPath = __webpack_require__(275), toString = __webpack_require__(286); /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } module.exports = castPath; /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(7); var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); module.exports = defineProperty; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(21), arraySome = __webpack_require__(195), cacheHas = __webpack_require__(24); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } module.exports = equalArrays; /***/ }, /* 84 */ /***/ function(module, exports, __webpack_require__) { /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof (window) == 'object' && (window) && (window).Object === Object && (window); module.exports = freeGlobal; /***/ }, /* 85 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } module.exports = isPrototype; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(8); /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } module.exports = isStrictComparable; /***/ }, /* 87 */ /***/ function(module, exports) { /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } module.exports = matchesStrictComparable; /***/ }, /* 88 */ /***/ function(module, exports) { /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 89 */ /***/ function(module, exports) { /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } module.exports = toSource; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(4), stubFalse = __webpack_require__(285); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; module.exports = isBuffer; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55)(module))) /***/ }, /* 91 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(10), isObject = __webpack_require__(8); /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } module.exports = isFunction; /***/ }, /* 92 */ /***/ function(module, exports, __webpack_require__) { var baseIsTypedArray = __webpack_require__(211), baseUnary = __webpack_require__(42), nodeUtil = __webpack_require__(262); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; module.exports = isTypedArray; /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(38); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; module.exports = memoize; /***/ }, /* 94 */ /***/ function(module, exports) { /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } module.exports = noop; /***/ }, /* 95 */ /***/ function(module, exports, __webpack_require__) { var baseDifference = __webpack_require__(76), baseRest = __webpack_require__(11), isArrayLikeObject = __webpack_require__(28); /** * Creates an array excluding all given values using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to inspect. * @param {...*} [values] The values to exclude. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.xor * @example * * _.without([2, 1, 2, 3], 1, 2); * // => [3] */ var without = baseRest(function(array, values) { return isArrayLikeObject(array) ? baseDifference(array, values) : []; }); module.exports = without; /***/ }, /* 96 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _contextMenu = __webpack_require__(290); Object.defineProperty(exports, "ContextMenu", { enumerable: true, get: function get() { return _interopRequireDefault(_contextMenu).default; } }); var _contextmenuLayer = __webpack_require__(292); Object.defineProperty(exports, "ContextMenuLayer", { enumerable: true, get: function get() { return _interopRequireDefault(_contextmenuLayer).default; } }); var _menuItem = __webpack_require__(293); Object.defineProperty(exports, "MenuItem", { enumerable: true, get: function get() { return _interopRequireDefault(_menuItem).default; } }); var _monitor = __webpack_require__(51); Object.defineProperty(exports, "monitor", { enumerable: true, get: function get() { return _interopRequireDefault(_monitor).default; } }); var _submenu = __webpack_require__(295); Object.defineProperty(exports, "SubMenu", { enumerable: true, get: function get() { return _interopRequireDefault(_submenu).default; } }); var _connect = __webpack_require__(289); Object.defineProperty(exports, "connect", { enumerable: true, get: function get() { return _interopRequireDefault(_connect).default; } }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }, /* 97 */ 32, /* 98 */ /***/ 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; }; /***/ }, /* 99 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashMemoize = __webpack_require__(93); var _lodashMemoize2 = _interopRequireDefault(_lodashMemoize); var isFirefox = _lodashMemoize2['default'](function () { return (/firefox/i.test(navigator.userAgent) ); }); exports.isFirefox = isFirefox; var isSafari = _lodashMemoize2['default'](function () { return Boolean(window.safari); }); exports.isSafari = isSafari; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = areOptionsEqual; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsShallowEqual = __webpack_require__(53); var _utilsShallowEqual2 = _interopRequireDefault(_utilsShallowEqual); function areOptionsEqual(nextOptions, currentOptions) { if (currentOptions === nextOptions) { return true; } return currentOptions !== null && nextOptions !== null && _utilsShallowEqual2['default'](currentOptions, nextOptions); } module.exports = exports['default']; /***/ }, /* 101 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); exports['default'] = decorateHandler; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _disposables = __webpack_require__(159); var _utilsShallowEqual = __webpack_require__(53); var _utilsShallowEqual2 = _interopRequireDefault(_utilsShallowEqual); var _utilsShallowEqualScalar = __webpack_require__(103); var _utilsShallowEqualScalar2 = _interopRequireDefault(_utilsShallowEqualScalar); var _lodashIsPlainObject = __webpack_require__(6); var _lodashIsPlainObject2 = _interopRequireDefault(_lodashIsPlainObject); var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); function decorateHandler(_ref) { var DecoratedComponent = _ref.DecoratedComponent; var createHandler = _ref.createHandler; var createMonitor = _ref.createMonitor; var createConnector = _ref.createConnector; var registerHandler = _ref.registerHandler; var containerDisplayName = _ref.containerDisplayName; var getType = _ref.getType; var collect = _ref.collect; var options = _ref.options; var _options$arePropsEqual = options.arePropsEqual; var arePropsEqual = _options$arePropsEqual === undefined ? _utilsShallowEqualScalar2['default'] : _options$arePropsEqual; var displayName = DecoratedComponent.displayName || DecoratedComponent.name || 'Component'; return (function (_Component) { _inherits(DragDropContainer, _Component); DragDropContainer.prototype.getHandlerId = function getHandlerId() { return this.handlerId; }; DragDropContainer.prototype.getDecoratedComponentInstance = function getDecoratedComponentInstance() { return this.decoratedComponentInstance; }; DragDropContainer.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) { return !arePropsEqual(nextProps, this.props) || !_utilsShallowEqual2['default'](nextState, this.state); }; _createClass(DragDropContainer, null, [{ key: 'DecoratedComponent', value: DecoratedComponent, enumerable: true }, { key: 'displayName', value: containerDisplayName + '(' + displayName + ')', enumerable: true }, { key: 'contextTypes', value: { dragDropManager: _react.PropTypes.object.isRequired }, enumerable: true }]); function DragDropContainer(props, context) { _classCallCheck(this, DragDropContainer); _Component.call(this, props, context); this.handleChange = this.handleChange.bind(this); this.handleChildRef = this.handleChildRef.bind(this); _invariant2['default'](typeof this.context.dragDropManager === 'object', 'Could not find the drag and drop manager in the context of %s. ' + 'Make sure to wrap the top-level component of your app with DragDropContext. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-troubleshooting.html#could-not-find-the-drag-and-drop-manager-in-the-context', displayName, displayName); this.manager = this.context.dragDropManager; this.handlerMonitor = createMonitor(this.manager); this.handlerConnector = createConnector(this.manager.getBackend()); this.handler = createHandler(this.handlerMonitor); this.disposable = new _disposables.SerialDisposable(); this.receiveProps(props); this.state = this.getCurrentState(); this.dispose(); } DragDropContainer.prototype.componentDidMount = function componentDidMount() { this.isCurrentlyMounted = true; this.disposable = new _disposables.SerialDisposable(); this.currentType = null; this.receiveProps(this.props); this.handleChange(); }; DragDropContainer.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) { if (!arePropsEqual(nextProps, this.props)) { this.receiveProps(nextProps); this.handleChange(); } }; DragDropContainer.prototype.componentWillUnmount = function componentWillUnmount() { this.dispose(); this.isCurrentlyMounted = false; }; DragDropContainer.prototype.receiveProps = function receiveProps(props) { this.handler.receiveProps(props); this.receiveType(getType(props)); }; DragDropContainer.prototype.receiveType = function receiveType(type) { if (type === this.currentType) { return; } this.currentType = type; var _registerHandler = registerHandler(type, this.handler, this.manager); var handlerId = _registerHandler.handlerId; var unregister = _registerHandler.unregister; this.handlerId = handlerId; this.handlerMonitor.receiveHandlerId(handlerId); this.handlerConnector.receiveHandlerId(handlerId); var globalMonitor = this.manager.getMonitor(); var unsubscribe = globalMonitor.subscribeToStateChange(this.handleChange, { handlerIds: [handlerId] }); this.disposable.setDisposable(new _disposables.CompositeDisposable(new _disposables.Disposable(unsubscribe), new _disposables.Disposable(unregister))); }; DragDropContainer.prototype.handleChange = function handleChange() { if (!this.isCurrentlyMounted) { return; } var nextState = this.getCurrentState(); if (!_utilsShallowEqual2['default'](nextState, this.state)) { this.setState(nextState); } }; DragDropContainer.prototype.dispose = function dispose() { this.disposable.dispose(); this.handlerConnector.receiveHandlerId(null); }; DragDropContainer.prototype.handleChildRef = function handleChildRef(component) { this.decoratedComponentInstance = component; this.handler.receiveComponent(component); }; DragDropContainer.prototype.getCurrentState = function getCurrentState() { var nextState = collect(this.handlerConnector.hooks, this.handlerMonitor); if (false) { _invariant2['default'](_lodashIsPlainObject2['default'](nextState), 'Expected `collect` specified as the second argument to ' + '%s for %s to return a plain object of props to inject. ' + 'Instead, received %s.', containerDisplayName, displayName, nextState); } return nextState; }; DragDropContainer.prototype.render = function render() { return _react2['default'].createElement(DecoratedComponent, _extends({}, this.props, this.state, { ref: this.handleChildRef })); }; return DragDropContainer; })(_react.Component); } module.exports = exports['default']; /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = isValidType; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashIsArray = __webpack_require__(3); var _lodashIsArray2 = _interopRequireDefault(_lodashIsArray); function isValidType(type, allowArray) { return typeof type === 'string' || typeof type === 'symbol' || allowArray && _lodashIsArray2['default'](type) && type.every(function (t) { return isValidType(t, false); }); } module.exports = exports['default']; /***/ }, /* 103 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = shallowEqualScalar; function shallowEqualScalar(objA, objB) { if (objA === objB) { return true; } if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) { return false; } var keysA = Object.keys(objA); var keysB = Object.keys(objB); if (keysA.length !== keysB.length) { return false; } // Test for A's keys different from B. var hasOwn = Object.prototype.hasOwnProperty; for (var i = 0; i < keysA.length; i++) { if (!hasOwn.call(objB, keysA[i])) { return false; } var valA = objA[keysA[i]]; var valB = objB[keysA[i]]; if (valA !== valB || typeof valA === 'object' || typeof valB === 'object') { return false; } } return true; } module.exports = exports['default']; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = wrapConnectorHooks; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsCloneWithRef = __webpack_require__(317); var _utilsCloneWithRef2 = _interopRequireDefault(_utilsCloneWithRef); var _react = __webpack_require__(1); function throwIfCompositeComponentElement(element) { // Custom components can no longer be wrapped directly in React DnD 2.0 // so that we don't need to depend on findDOMNode() from react-dom. if (typeof element.type === 'string') { return; } var displayName = element.type.displayName || element.type.name || 'the component'; throw new Error('Only native element nodes can now be passed to React DnD connectors. ' + ('You can either wrap ' + displayName + ' into a <div>, or turn it into a ') + 'drag source or a drop target itself.'); } function wrapHookToRecognizeElement(hook) { return function () { var elementOrNode = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0]; var options = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1]; // When passed a node, call the hook straight away. if (!_react.isValidElement(elementOrNode)) { var node = elementOrNode; hook(node, options); return; } // If passed a ReactElement, clone it and attach this function as a ref. // This helps us achieve a neat API where user doesn't even know that refs // are being used under the hood. var element = elementOrNode; throwIfCompositeComponentElement(element); // When no options are passed, use the hook directly var ref = options ? function (node) { return hook(node, options); } : hook; return _utilsCloneWithRef2['default'](element, ref); }; } function wrapConnectorHooks(hooks) { var wrappedHooks = {}; Object.keys(hooks).forEach(function (key) { var hook = hooks[key]; var wrappedHook = wrapHookToRecognizeElement(hook); wrappedHooks[key] = function () { return wrappedHook; }; }); return wrappedHooks; } module.exports = exports['default']; /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = getContainer; var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function getContainer(container, defaultContainer) { container = typeof container === 'function' ? container() : container; return _reactDom2.default.findDOMNode(container) || defaultContainer; } module.exports = exports['default']; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (componentOrElement) { return (0, _ownerDocument2.default)(_reactDom2.default.findDOMNode(componentOrElement)); }; var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); var _ownerDocument = __webpack_require__(36); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = exports['default']; /***/ }, /* 107 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _createChainableTypeChecker = __webpack_require__(108); var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function validate(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue); if (_react2.default.isValidElement(propValue)) { return new Error('Invalid ' + location + ' `' + propFullName + '` of type ReactElement ' + ('supplied to `' + componentName + '`, expected a ReactComponent or a ') + 'DOMElement. You can usually obtain a ReactComponent or DOMElement ' + 'from a ReactElement by attaching a ref to it.'); } if ((propType !== 'object' || typeof propValue.render !== 'function') && propValue.nodeType !== 1) { return new Error('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected a ReactComponent or a ') + 'DOMElement.'); } return null; } exports.default = (0, _createChainableTypeChecker2.default)(validate); /***/ }, /* 108 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports.default = createChainableTypeChecker; /** * 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. */ // Mostly taken from ReactPropTypes. function createChainableTypeChecker(validate) { function checkType(isRequired, props, propName, componentName, location, propFullName) { var componentNameSafe = componentName || '<<anonymous>>'; var propFullNameSafe = propFullName || propName; if (props[propName] == null) { if (isRequired) { return new Error('Required ' + location + ' `' + propFullNameSafe + '` was not specified ' + ('in `' + componentNameSafe + '`.')); } return null; } for (var _len = arguments.length, args = Array(_len > 6 ? _len - 6 : 0), _key = 6; _key < _len; _key++) { args[_key - 6] = arguments[_key]; } return validate.apply(undefined, [props, propName, componentNameSafe, location, propFullNameSafe].concat(args)); } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _stripDiacritics = __webpack_require__(111); var _stripDiacritics2 = _interopRequireDefault(_stripDiacritics); function filterOptions(options, filterValue, excludeOptions, props) { var _this = this; if (props.ignoreAccents) { filterValue = (0, _stripDiacritics2['default'])(filterValue); } if (props.ignoreCase) { filterValue = filterValue.toLowerCase(); } if (excludeOptions) excludeOptions = excludeOptions.map(function (i) { return i[props.valueKey]; }); return options.filter(function (option) { if (excludeOptions && excludeOptions.indexOf(option[props.valueKey]) > -1) return false; if (props.filterOption) return props.filterOption.call(_this, option, filterValue); if (!filterValue) return true; var valueTest = String(option[props.valueKey]); var labelTest = String(option[props.labelKey]); if (props.ignoreAccents) { if (props.matchProp !== 'label') valueTest = (0, _stripDiacritics2['default'])(valueTest); if (props.matchProp !== 'value') labelTest = (0, _stripDiacritics2['default'])(labelTest); } if (props.ignoreCase) { if (props.matchProp !== 'label') valueTest = valueTest.toLowerCase(); if (props.matchProp !== 'value') labelTest = labelTest.toLowerCase(); } return props.matchPos === 'start' ? props.matchProp !== 'label' && valueTest.substr(0, filterValue.length) === filterValue || props.matchProp !== 'value' && labelTest.substr(0, filterValue.length) === filterValue : props.matchProp !== 'label' && valueTest.indexOf(filterValue) >= 0 || props.matchProp !== 'value' && labelTest.indexOf(filterValue) >= 0; }); } module.exports = filterOptions; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _classnames = __webpack_require__(32); var _classnames2 = _interopRequireDefault(_classnames); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); function menuRenderer(_ref) { var focusedOption = _ref.focusedOption; var instancePrefix = _ref.instancePrefix; var labelKey = _ref.labelKey; var onFocus = _ref.onFocus; var onSelect = _ref.onSelect; var optionClassName = _ref.optionClassName; var optionComponent = _ref.optionComponent; var optionRenderer = _ref.optionRenderer; var options = _ref.options; var valueArray = _ref.valueArray; var valueKey = _ref.valueKey; var onOptionRef = _ref.onOptionRef; var Option = optionComponent; return options.map(function (option, i) { var isSelected = valueArray && valueArray.indexOf(option) > -1; var isFocused = option === focusedOption; var optionClass = (0, _classnames2['default'])(optionClassName, { 'Select-option': true, 'is-selected': isSelected, 'is-focused': isFocused, 'is-disabled': option.disabled }); return _react2['default'].createElement( Option, { className: optionClass, instancePrefix: instancePrefix, isDisabled: option.disabled, isFocused: isFocused, isSelected: isSelected, key: 'option-' + i + '-' + option[valueKey], onFocus: onFocus, onSelect: onSelect, option: option, optionIndex: i, ref: function (ref) { onOptionRef(ref, isFocused); } }, optionRenderer(option, i) ); }); } module.exports = menuRenderer; /***/ }, /* 111 */ /***/ function(module, exports) { 'use strict'; var map = [{ 'base': 'A', 'letters': /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g }, { 'base': 'AA', 'letters': /[\uA732]/g }, { 'base': 'AE', 'letters': /[\u00C6\u01FC\u01E2]/g }, { 'base': 'AO', 'letters': /[\uA734]/g }, { 'base': 'AU', 'letters': /[\uA736]/g }, { 'base': 'AV', 'letters': /[\uA738\uA73A]/g }, { 'base': 'AY', 'letters': /[\uA73C]/g }, { 'base': 'B', 'letters': /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g }, { 'base': 'C', 'letters': /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g }, { 'base': 'D', 'letters': /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g }, { 'base': 'DZ', 'letters': /[\u01F1\u01C4]/g }, { 'base': 'Dz', 'letters': /[\u01F2\u01C5]/g }, { 'base': 'E', 'letters': /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g }, { 'base': 'F', 'letters': /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g }, { 'base': 'G', 'letters': /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g }, { 'base': 'H', 'letters': /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g }, { 'base': 'I', 'letters': /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g }, { 'base': 'J', 'letters': /[\u004A\u24BF\uFF2A\u0134\u0248]/g }, { 'base': 'K', 'letters': /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g }, { 'base': 'L', 'letters': /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g }, { 'base': 'LJ', 'letters': /[\u01C7]/g }, { 'base': 'Lj', 'letters': /[\u01C8]/g }, { 'base': 'M', 'letters': /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g }, { 'base': 'N', 'letters': /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g }, { 'base': 'NJ', 'letters': /[\u01CA]/g }, { 'base': 'Nj', 'letters': /[\u01CB]/g }, { 'base': 'O', 'letters': /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g }, { 'base': 'OI', 'letters': /[\u01A2]/g }, { 'base': 'OO', 'letters': /[\uA74E]/g }, { 'base': 'OU', 'letters': /[\u0222]/g }, { 'base': 'P', 'letters': /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g }, { 'base': 'Q', 'letters': /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g }, { 'base': 'R', 'letters': /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g }, { 'base': 'S', 'letters': /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g }, { 'base': 'T', 'letters': /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g }, { 'base': 'TZ', 'letters': /[\uA728]/g }, { 'base': 'U', 'letters': /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g }, { 'base': 'V', 'letters': /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g }, { 'base': 'VY', 'letters': /[\uA760]/g }, { 'base': 'W', 'letters': /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g }, { 'base': 'X', 'letters': /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g }, { 'base': 'Y', 'letters': /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g }, { 'base': 'Z', 'letters': /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g }, { 'base': 'a', 'letters': /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g }, { 'base': 'aa', 'letters': /[\uA733]/g }, { 'base': 'ae', 'letters': /[\u00E6\u01FD\u01E3]/g }, { 'base': 'ao', 'letters': /[\uA735]/g }, { 'base': 'au', 'letters': /[\uA737]/g }, { 'base': 'av', 'letters': /[\uA739\uA73B]/g }, { 'base': 'ay', 'letters': /[\uA73D]/g }, { 'base': 'b', 'letters': /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g }, { 'base': 'c', 'letters': /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g }, { 'base': 'd', 'letters': /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g }, { 'base': 'dz', 'letters': /[\u01F3\u01C6]/g }, { 'base': 'e', 'letters': /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g }, { 'base': 'f', 'letters': /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g }, { 'base': 'g', 'letters': /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g }, { 'base': 'h', 'letters': /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g }, { 'base': 'hv', 'letters': /[\u0195]/g }, { 'base': 'i', 'letters': /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g }, { 'base': 'j', 'letters': /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g }, { 'base': 'k', 'letters': /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g }, { 'base': 'l', 'letters': /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g }, { 'base': 'lj', 'letters': /[\u01C9]/g }, { 'base': 'm', 'letters': /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g }, { 'base': 'n', 'letters': /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g }, { 'base': 'nj', 'letters': /[\u01CC]/g }, { 'base': 'o', 'letters': /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g }, { 'base': 'oi', 'letters': /[\u01A3]/g }, { 'base': 'ou', 'letters': /[\u0223]/g }, { 'base': 'oo', 'letters': /[\uA74F]/g }, { 'base': 'p', 'letters': /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g }, { 'base': 'q', 'letters': /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g }, { 'base': 'r', 'letters': /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g }, { 'base': 's', 'letters': /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g }, { 'base': 't', 'letters': /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g }, { 'base': 'tz', 'letters': /[\uA729]/g }, { 'base': 'u', 'letters': /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g }, { 'base': 'v', 'letters': /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g }, { 'base': 'vy', 'letters': /[\uA761]/g }, { 'base': 'w', 'letters': /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g }, { 'base': 'x', 'letters': /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g }, { 'base': 'y', 'letters': /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g }, { 'base': 'z', 'letters': /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g }]; module.exports = function stripDiacritics(str) { for (var i = 0; i < map.length; i++) { str = str.replace(map[i].letters, map[i].base); } return str; }; /***/ }, /* 112 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = compose; /** * Composes single-argument functions from right to left. The rightmost * function can take multiple arguments as it provides the signature for * the resulting composite function. * * @param {...Function} funcs The functions to compose. * @returns {Function} A function obtained by composing the argument functions * from right to left. For example, compose(f, g, h) is identical to doing * (...args) => f(g(h(...args))). */ function compose() { for (var _len = arguments.length, funcs = Array(_len), _key = 0; _key < _len; _key++) { funcs[_key] = arguments[_key]; } if (funcs.length === 0) { return function (arg) { return arg; }; } if (funcs.length === 1) { return funcs[0]; } var last = funcs[funcs.length - 1]; var rest = funcs.slice(0, -1); return function () { return rest.reduceRight(function (composed, f) { return f(composed); }, last.apply(undefined, arguments)); }; } /***/ }, /* 113 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = warning; /** * Prints a warning in the console if it exists. * * @param {String} message The warning message. * @returns {void} */ function warning(message) { /* eslint-disable no-console */ if (typeof console !== 'undefined' && typeof console.error === 'function') { console.error(message); } /* eslint-enable no-console */ try { // This error was thrown as a convenience so that if you enable // "break on all exceptions" in your console, // it would pause the execution at this line. throw new Error(message); /* eslint-disable no-empty */ } catch (e) {} /* eslint-enable no-empty */ } /***/ }, /* 114 */ /***/ function(module, exports, __webpack_require__) { "use strict"; // rawAsap provides everything we need except exception management. var rawAsap = __webpack_require__(115); // RawTasks are recycled to reduce GC churn. var freeTasks = []; // We queue errors to ensure they are thrown in right order (FIFO). // Array-as-queue is good enough here, since we are just dealing with exceptions. var pendingErrors = []; var requestErrorThrow = rawAsap.makeRequestCallFromTimer(throwFirstError); function throwFirstError() { if (pendingErrors.length) { throw pendingErrors.shift(); } } /** * Calls a task as soon as possible after returning, in its own event, with priority * over other events like animation, reflow, and repaint. An error thrown from an * event will not interrupt, nor even substantially slow down the processing of * other events, but will be rather postponed to a lower priority event. * @param {{call}} task A callable object, typically a function that takes no * arguments. */ module.exports = asap; function asap(task) { var rawTask; if (freeTasks.length) { rawTask = freeTasks.pop(); } else { rawTask = new RawTask(); } rawTask.task = task; rawAsap(rawTask); } // We wrap tasks with recyclable task objects. A task object implements // `call`, just like a function. function RawTask() { this.task = null; } // The sole purpose of wrapping the task is to catch the exception and recycle // the task object after its single use. RawTask.prototype.call = function () { try { this.task.call(); } catch (error) { if (asap.onerror) { // This hook exists purely for testing purposes. // Its name will be periodically randomized to break any code that // depends on its existence. asap.onerror(error); } else { // In a web browser, exceptions are not fatal. However, to avoid // slowing down the queue of pending tasks, we rethrow the error in a // lower priority turn. pendingErrors.push(error); requestErrorThrow(); } } finally { this.task = null; freeTasks[freeTasks.length] = this; } }; /***/ }, /* 115 */ /***/ function(module, exports, __webpack_require__) { "use strict"; // Use the fastest means possible to execute a task in its own turn, with // priority over other events including IO, animation, reflow, and redraw // events in browsers. // // An exception thrown by a task will permanently interrupt the processing of // subsequent tasks. The higher level `asap` function ensures that if an // exception is thrown by a task, that the task queue will continue flushing as // soon as possible, but if you use `rawAsap` directly, you are responsible to // either ensure that no exceptions are thrown from your task, or to manually // call `rawAsap.requestFlush` if an exception is thrown. module.exports = rawAsap; function rawAsap(task) { if (!queue.length) { requestFlush(); flushing = true; } // Equivalent to push, but avoids a function call. queue[queue.length] = task; } var queue = []; // Once a flush has been requested, no further calls to `requestFlush` are // necessary until the next `flush` completes. var flushing = false; // `requestFlush` is an implementation-specific method that attempts to kick // off a `flush` event as quickly as possible. `flush` will attempt to exhaust // the event queue before yielding to the browser's own event loop. var requestFlush; // The position of the next task to execute in the task queue. This is // preserved between calls to `flush` so that it can be resumed if // a task throws an exception. var index = 0; // If a task schedules additional tasks recursively, the task queue can grow // unbounded. To prevent memory exhaustion, the task queue will periodically // truncate already-completed tasks. var capacity = 1024; // The flush function processes all tasks that have been scheduled with // `rawAsap` unless and until one of those tasks throws an exception. // If a task throws an exception, `flush` ensures that its state will remain // consistent and will resume where it left off when called again. // However, `flush` does not make any arrangements to be called again if an // exception is thrown. function flush() { while (index < queue.length) { var currentIndex = index; // Advance the index before calling the task. This ensures that we will // begin flushing on the next task the task throws an error. index = index + 1; queue[currentIndex].call(); // Prevent leaking memory for long chains of recursive calls to `asap`. // If we call `asap` within tasks scheduled by `asap`, the queue will // grow, but to avoid an O(n) walk for every task we execute, we don't // shift tasks off the queue after they have been executed. // Instead, we periodically shift 1024 tasks off the queue. if (index > capacity) { // Manually shift all values starting at the index back to the // beginning of the queue. for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) { queue[scan] = queue[scan + index]; } queue.length -= index; index = 0; } } queue.length = 0; index = 0; flushing = false; } // `requestFlush` is implemented using a strategy based on data collected from // every available SauceLabs Selenium web driver worker at time of writing. // https://docs.google.com/spreadsheets/d/1mG-5UYGup5qxGdEMWkhP6BWCz053NUb2E1QoUTU16uA/edit#gid=783724593 // Safari 6 and 6.1 for desktop, iPad, and iPhone are the only browsers that // have WebKitMutationObserver but not un-prefixed MutationObserver. // Must use `global` or `self` instead of `window` to work in both frames and web // workers. `global` is a provision of Browserify, Mr, Mrs, or Mop. /* globals self */ var scope = typeof (window) !== "undefined" ? (window) : self; var BrowserMutationObserver = scope.MutationObserver || scope.WebKitMutationObserver; // MutationObservers are desirable because they have high priority and work // reliably everywhere they are implemented. // They are implemented in all modern browsers. // // - Android 4-4.3 // - Chrome 26-34 // - Firefox 14-29 // - Internet Explorer 11 // - iPad Safari 6-7.1 // - iPhone Safari 7-7.1 // - Safari 6-7 if (typeof BrowserMutationObserver === "function") { requestFlush = makeRequestCallFromMutationObserver(flush); // MessageChannels are desirable because they give direct access to the HTML // task queue, are implemented in Internet Explorer 10, Safari 5.0-1, and Opera // 11-12, and in web workers in many engines. // Although message channels yield to any queued rendering and IO tasks, they // would be better than imposing the 4ms delay of timers. // However, they do not work reliably in Internet Explorer or Safari. // Internet Explorer 10 is the only browser that has setImmediate but does // not have MutationObservers. // Although setImmediate yields to the browser's renderer, it would be // preferrable to falling back to setTimeout since it does not have // the minimum 4ms penalty. // Unfortunately there appears to be a bug in Internet Explorer 10 Mobile (and // Desktop to a lesser extent) that renders both setImmediate and // MessageChannel useless for the purposes of ASAP. // https://github.com/kriskowal/q/issues/396 // Timers are implemented universally. // We fall back to timers in workers in most engines, and in foreground // contexts in the following browsers. // However, note that even this simple case requires nuances to operate in a // broad spectrum of browsers. // // - Firefox 3-13 // - Internet Explorer 6-9 // - iPad Safari 4.3 // - Lynx 2.8.7 } else { requestFlush = makeRequestCallFromTimer(flush); } // `requestFlush` requests that the high priority event queue be flushed as // soon as possible. // This is useful to prevent an error thrown in a task from stalling the event // queue if the exception handled by Node.js’s // `process.on("uncaughtException")` or by a domain. rawAsap.requestFlush = requestFlush; // To request a high priority event, we induce a mutation observer by toggling // the text of a text node between "1" and "-1". function makeRequestCallFromMutationObserver(callback) { var toggle = 1; var observer = new BrowserMutationObserver(callback); var node = document.createTextNode(""); observer.observe(node, {characterData: true}); return function requestCall() { toggle = -toggle; node.data = toggle; }; } // The message channel technique was discovered by Malte Ubl and was the // original foundation for this library. // http://www.nonblocking.io/2011/06/windownexttick.html // Safari 6.0.5 (at least) intermittently fails to create message ports on a // page's first load. Thankfully, this version of Safari supports // MutationObservers, so we don't need to fall back in that case. // function makeRequestCallFromMessageChannel(callback) { // var channel = new MessageChannel(); // channel.port1.onmessage = callback; // return function requestCall() { // channel.port2.postMessage(0); // }; // } // For reasons explained above, we are also unable to use `setImmediate` // under any circumstances. // Even if we were, there is another bug in Internet Explorer 10. // It is not sufficient to assign `setImmediate` to `requestFlush` because // `setImmediate` must be called *by name* and therefore must be wrapped in a // closure. // Never forget. // function makeRequestCallFromSetImmediate(callback) { // return function requestCall() { // setImmediate(callback); // }; // } // Safari 6.0 has a problem where timers will get lost while the user is // scrolling. This problem does not impact ASAP because Safari 6.0 supports // mutation observers, so that implementation is used instead. // However, if we ever elect to use timers in Safari, the prevalent work-around // is to add a scroll event listener that calls for a flush. // `setTimeout` does not call the passed callback if the delay is less than // approximately 7 in web workers in Firefox 8 through 18, and sometimes not // even then. function makeRequestCallFromTimer(callback) { return function requestCall() { // We dispatch a timeout with a specified delay of 0 for engines that // can reliably accommodate that request. This will usually be snapped // to a 4 milisecond delay, but once we're flushing, there's no delay // between events. var timeoutHandle = setTimeout(handleTimer, 0); // However, since this timer gets frequently dropped in Firefox // workers, we enlist an interval handle that will try to fire // an event 20 times per second until it succeeds. var intervalHandle = setInterval(handleTimer, 50); function handleTimer() { // Whichever timer succeeds will cancel both timers and // execute the callback. clearTimeout(timeoutHandle); clearInterval(intervalHandle); callback(); } }; } // This is for `asap.js` only. // Its name will be periodically randomized to break any code that depends on // its existence. rawAsap.makeRequestCallFromTimer = makeRequestCallFromTimer; // ASAP was originally a nextTick shim included in Q. This was factored out // into this ASAP package. It was later adapted to RSVP which made further // amendments. These decisions, particularly to marginalize MessageChannel and // to capture the MutationObserver implementation in a closure, were integrated // back into ASAP proper. // https://github.com/tildeio/rsvp.js/blob/cddf7232546a9cf858524b75cde6f9edf72620a7/lib/rsvp/asap.js /***/ }, /* 116 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var isValidElement = __webpack_require__(1).isValidElement; module.exports = function sameColumn(a, b) { var k = void 0; for (k in a) { if (a.hasOwnProperty(k)) { if (typeof a[k] === 'function' && typeof b[k] === 'function' || isValidElement(a[k]) && isValidElement(b[k])) { continue; } if (!b.hasOwnProperty(k) || a[k] !== b[k]) { return false; } } } for (k in b) { if (b.hasOwnProperty(k) && !a.hasOwnProperty(k)) { return false; } } return true; }; /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var shallowCloneObject = __webpack_require__(154); var sameColumn = __webpack_require__(116); var ColumnUtils = __webpack_require__(118); var getScrollbarSize = __webpack_require__(153); var isColumnsImmutable = __webpack_require__(63); function setColumnWidths(columns, totalWidth) { return columns.map(function (column) { var colInfo = Object.assign({}, column); if (column.width) { if (/^([0-9]+)%$/.exec(column.width.toString())) { colInfo.width = Math.floor(column.width / 100 * totalWidth); } } return colInfo; }); } function setDefferedColumnWidths(columns, unallocatedWidth, minColumnWidth) { var defferedColumns = columns.filter(function (c) { return !c.width; }); return columns.map(function (column) { if (!column.width) { if (unallocatedWidth <= 0) { column.width = minColumnWidth; } else { column.width = Math.floor(unallocatedWidth / ColumnUtils.getSize(defferedColumns)); } } return column; }); } function setColumnOffsets(columns) { var left = 0; return columns.map(function (column) { column.left = left; left += column.width; return column; }); } /** * Update column metrics calculation. * * @param {ColumnMetricsType} metrics */ function recalculate(metrics) { // compute width for columns which specify width var columns = setColumnWidths(metrics.columns, metrics.totalWidth); var unallocatedWidth = columns.filter(function (c) { return c.width; }).reduce(function (w, column) { return w - column.width; }, metrics.totalWidth); unallocatedWidth -= getScrollbarSize(); var width = columns.filter(function (c) { return c.width; }).reduce(function (w, column) { return w + column.width; }, 0); // compute width for columns which doesn't specify width columns = setDefferedColumnWidths(columns, unallocatedWidth, metrics.minColumnWidth); // compute left offset columns = setColumnOffsets(columns); return { columns: columns, width: width, totalWidth: metrics.totalWidth, minColumnWidth: metrics.minColumnWidth }; } /** * Update column metrics calculation by resizing a column. * * @param {ColumnMetricsType} metrics * @param {Column} column * @param {number} width */ function resizeColumn(metrics, index, width) { var column = ColumnUtils.getColumn(metrics.columns, index); var metricsClone = shallowCloneObject(metrics); metricsClone.columns = metrics.columns.slice(0); var updatedColumn = shallowCloneObject(column); updatedColumn.width = Math.max(width, metricsClone.minColumnWidth); metricsClone = ColumnUtils.spliceColumn(metricsClone, index, updatedColumn); return recalculate(metricsClone); } function areColumnsImmutable(prevColumns, nextColumns) { return isColumnsImmutable(prevColumns) && isColumnsImmutable(nextColumns); } function compareEachColumn(prevColumns, nextColumns, isSameColumn) { var i = void 0; var len = void 0; var column = void 0; var prevColumnsByKey = {}; var nextColumnsByKey = {}; if (ColumnUtils.getSize(prevColumns) !== ColumnUtils.getSize(nextColumns)) { return false; } for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) { column = prevColumns[i]; prevColumnsByKey[column.key] = column; } for (i = 0, len = ColumnUtils.getSize(nextColumns); i < len; i++) { column = nextColumns[i]; nextColumnsByKey[column.key] = column; var prevColumn = prevColumnsByKey[column.key]; if (prevColumn === undefined || !isSameColumn(prevColumn, column)) { return false; } } for (i = 0, len = ColumnUtils.getSize(prevColumns); i < len; i++) { column = prevColumns[i]; var nextColumn = nextColumnsByKey[column.key]; if (nextColumn === undefined) { return false; } } return true; } function sameColumns(prevColumns, nextColumns, isSameColumn) { if (areColumnsImmutable(prevColumns, nextColumns)) { return prevColumns === nextColumns; } return compareEachColumn(prevColumns, nextColumns, isSameColumn); } module.exports = { recalculate: recalculate, resizeColumn: resizeColumn, sameColumn: sameColumn, sameColumns: sameColumns }; /***/ }, /* 118 */ /***/ function(module, exports) { 'use strict'; module.exports = { getColumn: function getColumn(columns, idx) { if (Array.isArray(columns)) { return columns[idx]; } else if (typeof Immutable !== 'undefined') { return columns.get(idx); } }, spliceColumn: function spliceColumn(metrics, idx, column) { if (Array.isArray(metrics.columns)) { metrics.columns.splice(idx, 1, column); } else if (typeof Immutable !== 'undefined') { metrics.columns = metrics.columns.splice(idx, 1, column); } return metrics; }, getSize: function getSize(columns) { if (Array.isArray(columns)) { return columns.length; } else if (typeof Immutable !== 'undefined') { return columns.size; } }, // Logic extented to allow for functions to be passed down in column.editable // this allows us to deicde whether we can be edting from a cell level canEdit: function canEdit(col, rowData, enableCellSelect) { if (col.editable != null && typeof col.editable === 'function') { return enableCellSelect === true && col.editable(rowData); } return enableCellSelect === true && (!!col.editor || !!col.editable); } }; /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(1); var PropTypes = React.PropTypes; var createObjectWithProperties = __webpack_require__(152); // The list of the propTypes that we want to include in the Draggable div var knownDivPropertyKeys = ['onDragStart', 'onDragEnd', 'onDrag', 'style']; var Draggable = React.createClass({ displayName: 'Draggable', propTypes: { onDragStart: PropTypes.func, onDragEnd: PropTypes.func, onDrag: PropTypes.func, component: PropTypes.oneOfType([PropTypes.func, PropTypes.constructor]), style: PropTypes.object }, getDefaultProps: function getDefaultProps() { return { onDragStart: function onDragStart() { return true; }, onDragEnd: function onDragEnd() {}, onDrag: function onDrag() {} }; }, getInitialState: function getInitialState() { return { drag: null }; }, componentWillUnmount: function componentWillUnmount() { this.cleanUp(); }, onMouseDown: function onMouseDown(e) { var drag = this.props.onDragStart(e); if (drag === null && e.button !== 0) { return; } window.addEventListener('mouseup', this.onMouseUp); window.addEventListener('mousemove', this.onMouseMove); window.addEventListener('touchend', this.onMouseUp); window.addEventListener('touchmove', this.onMouseMove); this.setState({ drag: drag }); }, onMouseMove: function onMouseMove(e) { if (this.state.drag === null) { return; } if (e.preventDefault) { e.preventDefault(); } this.props.onDrag(e); }, onMouseUp: function onMouseUp(e) { this.cleanUp(); this.props.onDragEnd(e, this.state.drag); this.setState({ drag: null }); }, cleanUp: function cleanUp() { window.removeEventListener('mouseup', this.onMouseUp); window.removeEventListener('mousemove', this.onMouseMove); window.removeEventListener('touchend', this.onMouseUp); window.removeEventListener('touchmove', this.onMouseMove); }, getKnownDivProps: function getKnownDivProps() { return createObjectWithProperties(this.props, knownDivPropertyKeys); }, render: function render() { return React.createElement('div', _extends({}, this.getKnownDivProps(), { onMouseDown: this.onMouseDown, onTouchStart: this.onMouseDown, className: 'react-grid-HeaderCell__draggable' })); } }); module.exports = Draggable; /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(1); var ReactDOM = __webpack_require__(5); var joinClasses = __webpack_require__(155); var ExcelColumn = __webpack_require__(13); var ResizeHandle = __webpack_require__(121); var PropTypes = React.PropTypes; function simpleCellRenderer(objArgs) { return React.createElement( 'div', { className: 'widget-HeaderCell__value' }, objArgs.column.name ); } var HeaderCell = React.createClass({ displayName: 'HeaderCell', propTypes: { renderer: PropTypes.oneOfType([PropTypes.func, PropTypes.element]).isRequired, column: PropTypes.shape(ExcelColumn).isRequired, onResize: PropTypes.func.isRequired, height: PropTypes.number.isRequired, onResizeEnd: PropTypes.func.isRequired, className: PropTypes.string }, getDefaultProps: function getDefaultProps() { return { renderer: simpleCellRenderer }; }, getInitialState: function getInitialState() { return { resizing: false }; }, onDragStart: function onDragStart(e) { this.setState({ resizing: true }); // need to set dummy data for FF if (e && e.dataTransfer && e.dataTransfer.setData) e.dataTransfer.setData('text/plain', 'dummy'); }, onDrag: function onDrag(e) { var resize = this.props.onResize || null; // for flows sake, doesnt recognise a null check direct if (resize) { var _width = this.getWidthFromMouseEvent(e); if (_width > 0) { resize(this.props.column, _width); } } }, onDragEnd: function onDragEnd(e) { var width = this.getWidthFromMouseEvent(e); this.props.onResizeEnd(this.props.column, width); this.setState({ resizing: false }); }, getWidthFromMouseEvent: function getWidthFromMouseEvent(e) { var right = e.pageX || e.touches && e.touches[0] && e.touches[0].pageX || e.changedTouches && e.changedTouches[e.changedTouches.length - 1].pageX; var left = ReactDOM.findDOMNode(this).getBoundingClientRect().left; return right - left; }, getCell: function getCell() { if (React.isValidElement(this.props.renderer)) { // if it is a string, it's an HTML element, and column is not a valid property, so only pass height if (typeof this.props.renderer.type === 'string') { return React.cloneElement(this.props.renderer, { height: this.props.height }); } return React.cloneElement(this.props.renderer, { column: this.props.column, height: this.props.height }); } return this.props.renderer({ column: this.props.column }); }, getStyle: function getStyle() { return { width: this.props.column.width, left: this.props.column.left, display: 'inline-block', position: 'absolute', height: this.props.height, margin: 0, textOverflow: 'ellipsis', whiteSpace: 'nowrap' }; }, setScrollLeft: function setScrollLeft(scrollLeft) { var node = ReactDOM.findDOMNode(this); node.style.webkitTransform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; node.style.transform = 'translate3d(' + scrollLeft + 'px, 0px, 0px)'; }, render: function render() { var resizeHandle = void 0; if (this.props.column.resizable) { resizeHandle = React.createElement(ResizeHandle, { onDrag: this.onDrag, onDragStart: this.onDragStart, onDragEnd: this.onDragEnd }); } var className = joinClasses({ 'react-grid-HeaderCell': true, 'react-grid-HeaderCell--resizing': this.state.resizing, 'react-grid-HeaderCell--locked': this.props.column.locked }); className = joinClasses(className, this.props.className, this.props.column.cellClass); var cell = this.getCell(); return React.createElement( 'div', { className: className, style: this.getStyle() }, cell, resizeHandle ); } }); module.exports = HeaderCell; /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(1); var Draggable = __webpack_require__(119); var ResizeHandle = React.createClass({ displayName: 'ResizeHandle', style: { position: 'absolute', top: 0, right: 0, width: 6, height: '100%' }, render: function render() { return React.createElement(Draggable, _extends({}, this.props, { className: 'react-grid-HeaderCell__resizeHandle', style: this.style })); } }); module.exports = ResizeHandle; /***/ }, /* 122 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _ExcelColumn = __webpack_require__(13); var _ExcelColumn2 = _interopRequireDefault(_ExcelColumn); var _reactSelect = __webpack_require__(31); var _reactSelect2 = _interopRequireDefault(_reactSelect); var _isEmptyArray = __webpack_require__(62); var _isEmptyArray2 = _interopRequireDefault(_isEmptyArray); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var AutoCompleteFilter = function (_React$Component) { _inherits(AutoCompleteFilter, _React$Component); function AutoCompleteFilter(props) { _classCallCheck(this, AutoCompleteFilter); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); _this.getOptions = _this.getOptions.bind(_this); _this.handleChange = _this.handleChange.bind(_this); _this.filterValues = _this.filterValues.bind(_this); _this.state = { options: _this.getOptions(), rawValue: '', placeholder: 'Search...' }; return _this; } AutoCompleteFilter.prototype.componentWillReceiveProps = function componentWillReceiveProps(newProps) { this.setState({ options: this.getOptions(newProps) }); }; AutoCompleteFilter.prototype.getOptions = function getOptions(newProps) { var props = newProps || this.props; var options = props.getValidFilterValues(props.column.key); options = options.map(function (o) { if (typeof o === 'string') { return { value: o, label: o }; } return o; }); return options; }; AutoCompleteFilter.prototype.columnValueContainsSearchTerms = function columnValueContainsSearchTerms(columnValue, filterTerms) { var columnValueContainsSearchTerms = false; for (var key in filterTerms) { if (!filterTerms.hasOwnProperty(key)) { continue; } var filterTermValue = filterTerms[key].value; var checkValueIndex = columnValue.trim().toLowerCase().indexOf(filterTermValue.trim().toLowerCase()); var columnMatchesSearch = checkValueIndex !== -1 && (checkValueIndex !== 0 || columnValue === filterTermValue); if (columnMatchesSearch) { columnValueContainsSearchTerms = true; break; } } return columnValueContainsSearchTerms; }; AutoCompleteFilter.prototype.filterValues = function filterValues(row, columnFilter, columnKey) { var include = true; if (columnFilter === null) { include = false; } else if (!(0, _isEmptyArray2['default'])(columnFilter.filterTerm)) { include = this.columnValueContainsSearchTerms(row[columnKey], columnFilter.filterTerm); } return include; }; AutoCompleteFilter.prototype.handleChange = function handleChange(value) { var filters = value; this.setState({ filters: filters }); this.props.onChange({ filterTerm: filters, column: this.props.column, rawValue: value, filterValues: this.filterValues }); }; AutoCompleteFilter.prototype.render = function render() { var filterName = 'filter-' + this.props.column.key; return _react2['default'].createElement( 'div', { style: { width: this.props.column.width * 0.9 } }, _react2['default'].createElement(_reactSelect2['default'], { name: filterName, options: this.state.options, placeholder: this.state.placeholder, onChange: this.handleChange, escapeClearsValue: true, multi: true, value: this.state.filters }) ); }; return AutoCompleteFilter; }(_react2['default'].Component); AutoCompleteFilter.propTypes = { onChange: _react.PropTypes.func.isRequired, column: _react2['default'].PropTypes.shape(_ExcelColumn2['default']), getValidFilterValues: _react.PropTypes.func }; exports['default'] = AutoCompleteFilter; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _ExcelColumn = __webpack_require__(13); var _ExcelColumn2 = _interopRequireDefault(_ExcelColumn); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var RuleType = { Number: 1, Range: 2, GreaterThen: 3, LessThen: 4 }; var NumericFilter = function (_React$Component) { _inherits(NumericFilter, _React$Component); function NumericFilter(props) { _classCallCheck(this, NumericFilter); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); _this.handleChange = _this.handleChange.bind(_this); _this.handleKeyPress = _this.handleKeyPress.bind(_this); _this.getRules = _this.getRules.bind(_this); return _this; } NumericFilter.prototype.filterValues = function filterValues(row, columnFilter, columnKey) { if (columnFilter.filterTerm == null) { return true; } var result = false; // implement default filter logic var value = parseInt(row[columnKey], 10); for (var ruleKey in columnFilter.filterTerm) { if (!columnFilter.filterTerm.hasOwnProperty(ruleKey)) { continue; } var rule = columnFilter.filterTerm[ruleKey]; switch (rule.type) { case RuleType.Number: if (rule.value === value) { result = true; } break; case RuleType.GreaterThen: if (rule.value <= value) { result = true; } break; case RuleType.LessThen: if (rule.value >= value) { result = true; } break; case RuleType.Range: if (rule.begin <= value && rule.end >= value) { result = true; } break; default: // do nothing break; } } return result; }; NumericFilter.prototype.getRules = function getRules(value) { var rules = []; if (value === '') { return rules; } // check comma var list = value.split(','); if (list.length > 0) { // handle each value with comma for (var key in list) { if (!list.hasOwnProperty(key)) { continue; } var obj = list[key]; if (obj.indexOf('-') > 0) { // handle dash var begin = parseInt(obj.split('-')[0], 10); var end = parseInt(obj.split('-')[1], 10); rules.push({ type: RuleType.Range, begin: begin, end: end }); } else if (obj.indexOf('>') > -1) { // handle greater then var _begin = parseInt(obj.split('>')[1], 10); rules.push({ type: RuleType.GreaterThen, value: _begin }); } else if (obj.indexOf('<') > -1) { // handle less then var _end = parseInt(obj.split('<')[1], 10); rules.push({ type: RuleType.LessThen, value: _end }); } else { // handle normal values var numericValue = parseInt(obj, 10); rules.push({ type: RuleType.Number, value: numericValue }); } } } return rules; }; NumericFilter.prototype.handleKeyPress = function handleKeyPress(e) { // Validate the input var regex = '>|<|-|,|([0-9])'; var result = RegExp(regex).test(e.key); if (result === false) { e.preventDefault(); } }; NumericFilter.prototype.handleChange = function handleChange(e) { var value = e.target.value; var filters = this.getRules(value); this.props.onChange({ filterTerm: filters.length > 0 ? filters : null, column: this.props.column, rawValue: value, filterValues: this.filterValues }); }; NumericFilter.prototype.render = function render() { var inputKey = 'header-filter-' + this.props.column.key; var columnStyle = { float: 'left', marginRight: 5, maxWidth: '80%' }; var badgeStyle = { cursor: 'help' }; var tooltipText = 'Input Methods: Range (x-y), Greater Then (>x), Less Then (<y)'; return _react2['default'].createElement( 'div', null, _react2['default'].createElement( 'div', { style: columnStyle }, _react2['default'].createElement('input', { key: inputKey, type: 'text', placeholder: 'e.g. 3,10-15,>20', className: 'form-control input-sm', onChange: this.handleChange, onKeyPress: this.handleKeyPress }) ), _react2['default'].createElement( 'div', { className: 'input-sm' }, _react2['default'].createElement( 'span', { className: 'badge', style: badgeStyle, title: tooltipText }, '?' ) ) ); }; return NumericFilter; }(_react2['default'].Component); NumericFilter.propTypes = { onChange: _react2['default'].PropTypes.func.isRequired, column: _react2['default'].PropTypes.shape(_ExcelColumn2['default']) }; module.exports = NumericFilter; /***/ }, /* 124 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _NumericFilter = __webpack_require__(123); var _NumericFilter2 = _interopRequireDefault(_NumericFilter); var _AutoCompleteFilter = __webpack_require__(122); var _AutoCompleteFilter2 = _interopRequireDefault(_AutoCompleteFilter); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var Filters = { NumericFilter: _NumericFilter2['default'], AutoCompleteFilter: _AutoCompleteFilter2['default'] }; module.exports = Filters; /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _mixedTypeValueRetriever = __webpack_require__(34); var _mixedTypeValueRetriever2 = _interopRequireDefault(_mixedTypeValueRetriever); var _isImmutableCollection = __webpack_require__(33); var _isImmutableCollection2 = _interopRequireDefault(_isImmutableCollection); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var filterRows = function filterRows(filters) { var rows = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var retriever = (0, _mixedTypeValueRetriever2['default'])((0, _isImmutableCollection2['default'])(rows)); return rows.filter(function (r) { var include = true; for (var columnKey in filters) { if (filters.hasOwnProperty(columnKey)) { var colFilter = filters[columnKey]; // check if custom filter function exists if (colFilter.filterValues && typeof colFilter.filterValues === 'function' && !colFilter.filterValues(r, colFilter, columnKey)) { include = false; } else if (typeof colFilter.filterTerm === 'string') { // default filter action var rowValue = retriever.getValue(r, columnKey); if (rowValue) { if (rowValue.toString().toLowerCase().indexOf(colFilter.filterTerm.toLowerCase()) === -1) { include = false; } } else { include = false; } } } } return include; }); }; module.exports = filterRows; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _isImmutableCollection = __webpack_require__(33); var _isImmutableCollection2 = _interopRequireDefault(_isImmutableCollection); var _RowGrouperResolver = __webpack_require__(127); var _RowGrouperResolver2 = _interopRequireDefault(_RowGrouperResolver); 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"); } } var RowGrouper = function () { function RowGrouper(columns, expandedRows) { var isImmutable = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; _classCallCheck(this, RowGrouper); this.columns = columns.slice(0); this.expandedRows = expandedRows; this.resolver = new _RowGrouperResolver2['default'](isImmutable); } RowGrouper.prototype.isRowExpanded = function isRowExpanded(columnName, name) { var isExpanded = true; var expandedRowGroup = this.expandedRows[columnName]; if (expandedRowGroup && expandedRowGroup[name]) { isExpanded = expandedRowGroup[name].isExpanded; } return isExpanded; }; RowGrouper.prototype.groupRowsByColumn = function groupRowsByColumn(rows) { var columnIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0; var nextColumnIndex = columnIndex; var columnName = this.columns[columnIndex]; var groupedRows = this.resolver.getGroupedRows(rows, columnName); var keys = this.resolver.getGroupKeys(groupedRows); var dataviewRows = this.resolver.initRowsCollection(); for (var i = 0; i < keys.length; i++) { var key = keys[i]; var isExpanded = this.isRowExpanded(columnName, key); var rowGroupHeader = { name: key, __metaData: { isGroup: true, treeDepth: columnIndex, isExpanded: isExpanded, columnGroupName: columnName } }; dataviewRows = this.resolver.addHeaderRow(rowGroupHeader, dataviewRows); if (isExpanded) { nextColumnIndex = columnIndex + 1; if (this.columns.length > nextColumnIndex) { dataviewRows = dataviewRows.concat(this.groupRowsByColumn(this.resolver.getRowObj(groupedRows, key), nextColumnIndex)); nextColumnIndex = columnIndex - 1; } else { dataviewRows = dataviewRows.concat(this.resolver.getRowObj(groupedRows, key)); } } } return dataviewRows; }; return RowGrouper; }(); var groupRows = function groupRows(rows, groupedColumns, expandedRows) { var rowGrouper = new RowGrouper(groupedColumns, expandedRows, (0, _isImmutableCollection2['default'])(rows)); return rowGrouper.groupRowsByColumn(rows, 0); }; module.exports = groupRows; /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _immutable = __webpack_require__(71); var _groupBy = __webpack_require__(280); var _groupBy2 = _interopRequireDefault(_groupBy); var _mixedTypeValueRetriever = __webpack_require__(34); var _mixedTypeValueRetriever2 = _interopRequireDefault(_mixedTypeValueRetriever); 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"); } } var RowGrouperResolver = function () { function RowGrouperResolver(isImmutable) { _classCallCheck(this, RowGrouperResolver); this.isImmutable = isImmutable; this.getRowObj = (0, _mixedTypeValueRetriever2['default'])(isImmutable).getValue; } RowGrouperResolver.prototype.initRowsCollection = function initRowsCollection() { return this.isImmutable ? new _immutable.List() : []; }; RowGrouperResolver.prototype.getGroupedRows = function getGroupedRows(rows, columnName) { return this.isImmutable ? rows.groupBy(function (x) { return x.get(columnName); }) : (0, _groupBy2['default'])(rows, columnName); }; RowGrouperResolver.prototype.getGroupKeys = function getGroupKeys(groupedRows) { var getKeys = Object.keys; if (this.isImmutable) { getKeys = function getKeys(col) { var keys = []; var iterator = col.keys(); var item = iterator.next(); while (!item.done) { keys.push(item.value); item = iterator.next(); } return keys; }; } return getKeys(groupedRows); }; RowGrouperResolver.prototype.addHeaderRow = function addHeaderRow(rowGroupHeader, dataviewRows) { var rows = dataviewRows; var dvRows = rows.push(rowGroupHeader); if (this.isImmutable) { return dvRows; } return rows; }; return RowGrouperResolver; }(); exports['default'] = RowGrouperResolver; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _mixedTypeValueRetriever = __webpack_require__(34); var _mixedTypeValueRetriever2 = _interopRequireDefault(_mixedTypeValueRetriever); var _isImmutableCollection = __webpack_require__(33); var _isImmutableCollection2 = _interopRequireDefault(_isImmutableCollection); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var comparer = function comparer(a, b) { if (a > b) { return 1; } else if (a < b) { return -1; } return 0; }; var sortRows = function sortRows(rows, sortColumn, sortDirection) { var retriever = (0, _mixedTypeValueRetriever2['default'])((0, _isImmutableCollection2['default'])(rows)); var sortDirectionSign = sortDirection === 'ASC' ? 1 : -1; var rowComparer = function rowComparer(a, b) { return sortDirectionSign * comparer(retriever.getValue(a, sortColumn), retriever.getValue(b, sortColumn)); }; if (sortDirection === 'NONE') { return rows; } return rows.sort(rowComparer); }; module.exports = sortRows; module.exports.comparer = comparer; /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = { Selectors: __webpack_require__(58) }; /***/ }, /* 130 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDndHtml5Backend = __webpack_require__(303); var _reactDndHtml5Backend2 = _interopRequireDefault(_reactDndHtml5Backend); var _reactDnd = __webpack_require__(12); var _DraggableHeaderCell = __webpack_require__(59); var _DraggableHeaderCell2 = _interopRequireDefault(_DraggableHeaderCell); var _RowDragLayer = __webpack_require__(133); var _RowDragLayer2 = _interopRequireDefault(_RowDragLayer); var _isColumnsImmutable = __webpack_require__(63); var _isColumnsImmutable2 = _interopRequireDefault(_isColumnsImmutable); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var DraggableContainer = function (_Component) { _inherits(DraggableContainer, _Component); function DraggableContainer() { _classCallCheck(this, DraggableContainer); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } DraggableContainer.prototype.getRows = function getRows(rowsCount, rowGetter) { var rows = []; for (var j = 0; j < rowsCount; j++) { rows.push(rowGetter(j)); } return rows; }; DraggableContainer.prototype.renderGrid = function renderGrid() { return _react2['default'].Children.map(this.props.children, function (child) { return _react2['default'].cloneElement(child, { draggableHeaderCell: _DraggableHeaderCell2['default'] }); })[0]; }; DraggableContainer.prototype.render = function render() { var grid = this.renderGrid(); var rowGetter = this.props.getDragPreviewRow || grid.props.rowGetter; var rowsCount = grid.props.rowsCount; var columns = grid.props.columns; var rows = this.getRows(rowsCount, rowGetter); return _react2['default'].createElement( 'div', null, grid, _react2['default'].createElement(_RowDragLayer2['default'], { rowSelection: grid.props.rowSelection, rows: rows, columns: (0, _isColumnsImmutable2['default'])(columns) ? columns.toArray() : columns }) ); }; return DraggableContainer; }(_react.Component); DraggableContainer.propTypes = { children: _react2['default'].PropTypes.element.isRequired, getDragPreviewRow: _react2['default'].PropTypes.func }; exports['default'] = (0, _reactDnd.DragDropContext)(_reactDndHtml5Backend2['default'])(DraggableContainer); /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); var _reactDnd = __webpack_require__(12); var _RowComparer = __webpack_require__(57); var _RowComparer2 = _interopRequireDefault(_RowComparer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var rowDropTarget = function rowDropTarget(Row) { return function (_React$Component) { _inherits(_class, _React$Component); function _class() { _classCallCheck(this, _class); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } _class.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps) { return (0, _RowComparer2['default'])(nextProps, this.props); }; _class.prototype.moveRow = function moveRow() { _reactDom2['default'].findDOMNode(this).classList.add('slideUp'); }; _class.prototype.render = function render() { var _props = this.props, connectDropTarget = _props.connectDropTarget, isOver = _props.isOver, canDrop = _props.canDrop; var overlayTop = this.props.idx * this.props.height; return connectDropTarget(_react2['default'].createElement( 'div', null, _react2['default'].createElement(Row, _extends({ ref: 'row' }, this.props)), isOver && canDrop && _react2['default'].createElement('div', { style: { position: 'absolute', top: overlayTop, left: 0, height: this.props.height, width: '100%', zIndex: 1, borderBottom: '1px solid black' } }) )); }; return _class; }(_react2['default'].Component); }; var target = { drop: function drop(props, monitor, component) { // Obtain the dragged item component.moveRow(); var rowSource = monitor.getItem(); var rowTarget = { idx: props.idx, data: props.row }; props.onRowDrop({ rowSource: rowSource, rowTarget: rowTarget }); } }; function collect(connect, monitor) { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver(), canDrop: monitor.canDrop(), draggedRow: monitor.getItem() }; } exports['default'] = function (Row) { return (0, _reactDnd.DropTarget)('Row', target, collect, { arePropsEqual: function arePropsEqual(nextProps, currentProps) { return !(0, _RowComparer2['default'])(nextProps, currentProps); } })(rowDropTarget(Row)); }; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDnd = __webpack_require__(12); var _CheckboxEditor = __webpack_require__(60); var _CheckboxEditor2 = _interopRequireDefault(_CheckboxEditor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var RowActionsCell = function (_React$Component) { _inherits(RowActionsCell, _React$Component); function RowActionsCell() { _classCallCheck(this, RowActionsCell); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } RowActionsCell.prototype.renderRowIndex = function renderRowIndex() { return _react2['default'].createElement( 'div', { className: 'rdg-row-index' }, this.props.rowIdx + 1 ); }; RowActionsCell.prototype.render = function render() { var _props = this.props, connectDragSource = _props.connectDragSource, rowSelection = _props.rowSelection; var rowHandleStyle = rowSelection != null ? { position: 'absolute', marginTop: '5px' } : {}; var isSelected = this.props.value; var editorClass = isSelected ? 'rdg-actions-checkbox selected' : 'rdg-actions-checkbox'; return connectDragSource(_react2['default'].createElement( 'div', null, _react2['default'].createElement('div', { className: 'rdg-drag-row-handle', style: rowHandleStyle }), !isSelected ? this.renderRowIndex() : null, rowSelection != null && _react2['default'].createElement( 'div', { className: editorClass }, _react2['default'].createElement(_CheckboxEditor2['default'], { column: this.props.column, rowIdx: this.props.rowIdx, dependentValues: this.props.dependentValues, value: this.props.value }) ) )); }; return RowActionsCell; }(_react2['default'].Component); RowActionsCell.propTypes = { rowIdx: _react.PropTypes.number.isRequired, connectDragSource: _react.PropTypes.func.isRequired, connectDragPreview: _react.PropTypes.func.isRequired, isDragging: _react.PropTypes.bool.isRequired, isRowHovered: _react.PropTypes.bool, column: _react.PropTypes.object, dependentValues: _react.PropTypes.object, value: _react.PropTypes.bool, rowSelection: _react.PropTypes.object.isRequired }; RowActionsCell.defaultProps = { rowIdx: 0 }; function collect(connect, monitor) { return { connectDragSource: connect.dragSource(), isDragging: monitor.isDragging(), connectDragPreview: connect.dragPreview() }; } var rowIndexSource = { beginDrag: function beginDrag(props) { return { idx: props.rowIdx, data: props.dependentValues }; }, endDrag: function endDrag(props) { return { idx: props.rowIdx, data: props.dependentValues }; } }; exports['default'] = (0, _reactDnd.DragSource)('Row', rowIndexSource, collect)(RowActionsCell); /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDnd = __webpack_require__(12); var _Selectors = __webpack_require__(58); var _Selectors2 = _interopRequireDefault(_Selectors); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var layerStyles = { cursor: '-webkit-grabbing', position: 'fixed', pointerEvents: 'none', zIndex: 100, left: 0, top: 0, width: '100%', height: '100%' }; function getItemStyles(props) { var currentOffset = props.currentOffset; if (!currentOffset) { return { display: 'none' }; } var x = currentOffset.x, y = currentOffset.y; var transform = 'translate(' + x + 'px, ' + y + 'px)'; return { transform: transform, WebkitTransform: transform }; } var CustomDragLayer = function (_Component) { _inherits(CustomDragLayer, _Component); function CustomDragLayer() { _classCallCheck(this, CustomDragLayer); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } CustomDragLayer.prototype.isDraggedRowSelected = function isDraggedRowSelected(selectedRows) { var _props = this.props, item = _props.item, rowSelection = _props.rowSelection; if (selectedRows && selectedRows.length > 0) { var _ret = function () { var key = rowSelection.selectBy.keys.rowKey; return { v: selectedRows.filter(function (r) { return r[key] === item.data[key]; }).length > 0 }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } return false; }; CustomDragLayer.prototype.getDraggedRows = function getDraggedRows() { var draggedRows = void 0; var rowSelection = this.props.rowSelection; if (rowSelection && rowSelection.selectBy.keys) { var rows = this.props.rows; var _rowSelection$selectB = rowSelection.selectBy.keys, rowKey = _rowSelection$selectB.rowKey, values = _rowSelection$selectB.values; var selectedRows = _Selectors2['default'].getSelectedRowsByKey({ rowKey: rowKey, selectedKeys: values, rows: rows }); draggedRows = this.isDraggedRowSelected(selectedRows) ? selectedRows : [this.props.rows[this.props.item.idx]]; } else { draggedRows = [this.props.rows[this.props.item.idx]]; } return draggedRows; }; CustomDragLayer.prototype.renderDraggedRows = function renderDraggedRows() { var _this2 = this; var columns = this.props.columns; return this.getDraggedRows().map(function (r, i) { return _react2['default'].createElement( 'tr', { key: 'dragged-row-' + i }, _this2.renderDraggedCells(r, i, columns) ); }); }; CustomDragLayer.prototype.renderDraggedCells = function renderDraggedCells(item, rowIdx, columns) { var cells = []; if (item != null) { columns.forEach(function (c) { if (item.hasOwnProperty(c.key)) { if (c.formatter) { var Formatter = c.formatter; cells.push(_react2['default'].createElement( 'td', { key: 'dragged-cell-' + rowIdx + '-' + c.key, className: 'react-grid-Cell', style: { padding: '5px' } }, _react2['default'].createElement(Formatter, { value: item[c.key] }) )); } else { cells.push(_react2['default'].createElement( 'td', { key: 'dragged-cell-' + rowIdx + '-' + c.key, className: 'react-grid-Cell', style: { padding: '5px' } }, item[c.key] )); } } }); } return cells; }; CustomDragLayer.prototype.render = function render() { var isDragging = this.props.isDragging; if (!isDragging) { return null; } var draggedRows = this.renderDraggedRows(); return _react2['default'].createElement( 'div', { style: layerStyles, className: 'rdg-dragging' }, _react2['default'].createElement( 'div', { style: getItemStyles(this.props), className: 'rdg-dragging' }, _react2['default'].createElement( 'table', null, _react2['default'].createElement( 'tbody', null, draggedRows ) ) ) ); }; return CustomDragLayer; }(_react.Component); CustomDragLayer.propTypes = { item: _react.PropTypes.object, itemType: _react.PropTypes.string, currentOffset: _react.PropTypes.shape({ x: _react.PropTypes.number.isRequired, y: _react.PropTypes.number.isRequired }), isDragging: _react.PropTypes.bool.isRequired, rowSelection: _react.PropTypes.object, rows: _react.PropTypes.array.isRequired, columns: _react.PropTypes.array.isRequired }; function collect(monitor) { return { item: monitor.getItem(), itemType: monitor.getItemType(), currentOffset: monitor.getSourceClientOffset(), isDragging: monitor.isDragging() }; } exports['default'] = (0, _reactDnd.DragLayer)(collect)(CustomDragLayer); /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _DragDropContainer = __webpack_require__(130); var _DragDropContainer2 = _interopRequireDefault(_DragDropContainer); var _DraggableHeaderCell = __webpack_require__(59); var _DraggableHeaderCell2 = _interopRequireDefault(_DraggableHeaderCell); var _RowActionsCell = __webpack_require__(132); var _RowActionsCell2 = _interopRequireDefault(_RowActionsCell); var _DropTargetRowContainer = __webpack_require__(131); var _DropTargetRowContainer2 = _interopRequireDefault(_DropTargetRowContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports['default'] = { Container: _DragDropContainer2['default'], DraggableHeaderCell: _DraggableHeaderCell2['default'], RowActionsCell: _RowActionsCell2['default'], DropTargetRowContainer: _DropTargetRowContainer2['default'] }; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(1); var ReactDOM = __webpack_require__(5); var ReactAutocomplete = __webpack_require__(338); var ExcelColumn = __webpack_require__(13); var optionPropType = React.PropTypes.shape({ id: React.PropTypes.required, title: React.PropTypes.string }); var AutoCompleteEditor = React.createClass({ displayName: 'AutoCompleteEditor', propTypes: { onCommit: React.PropTypes.func, options: React.PropTypes.arrayOf(optionPropType), label: React.PropTypes.any, value: React.PropTypes.any, height: React.PropTypes.number, valueParams: React.PropTypes.arrayOf(React.PropTypes.string), column: React.PropTypes.shape(ExcelColumn), resultIdentifier: React.PropTypes.string, search: React.PropTypes.string, onKeyDown: React.PropTypes.func, onFocus: React.PropTypes.func, editorDisplayValue: React.PropTypes.func }, getDefaultProps: function getDefaultProps() { return { resultIdentifier: 'id' }; }, handleChange: function handleChange() { this.props.onCommit(); }, getValue: function getValue() { var value = void 0; var updated = {}; if (this.hasResults() && this.isFocusedOnSuggestion()) { value = this.getLabel(this.refs.autoComplete.state.focusedValue); if (this.props.valueParams) { value = this.constuctValueFromParams(this.refs.autoComplete.state.focusedValue, this.props.valueParams); } } else { value = this.refs.autoComplete.state.searchTerm; } updated[this.props.column.key] = value; return updated; }, getEditorDisplayValue: function getEditorDisplayValue() { var displayValue = { title: '' }; var _props = this.props, column = _props.column, value = _props.value, editorDisplayValue = _props.editorDisplayValue; if (editorDisplayValue && typeof editorDisplayValue === 'function') { displayValue.title = editorDisplayValue(column, value); } else { displayValue.title = value; } return displayValue; }, getInputNode: function getInputNode() { return ReactDOM.findDOMNode(this).getElementsByTagName('input')[0]; }, getLabel: function getLabel(item) { var label = this.props.label != null ? this.props.label : 'title'; if (typeof label === 'function') { return label(item); } else if (typeof label === 'string') { return item[label]; } }, hasResults: function hasResults() { return this.refs.autoComplete.state.results.length > 0; }, isFocusedOnSuggestion: function isFocusedOnSuggestion() { var autoComplete = this.refs.autoComplete; return autoComplete.state.focusedValue != null; }, constuctValueFromParams: function constuctValueFromParams(obj, props) { if (!props) { return ''; } var ret = []; for (var i = 0, ii = props.length; i < ii; i++) { ret.push(obj[props[i]]); } return ret.join('|'); }, render: function render() { var label = this.props.label != null ? this.props.label : 'title'; return React.createElement( 'div', { height: this.props.height, onKeyDown: this.props.onKeyDown }, React.createElement(ReactAutocomplete, { search: this.props.search, ref: 'autoComplete', label: label, onChange: this.handleChange, onFocus: this.props.onFocus, resultIdentifier: this.props.resultIdentifier, options: this.props.options, value: this.getEditorDisplayValue() }) ); } }); module.exports = AutoCompleteEditor; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } // Wrapper HOC used when having an editor which is a redux container. // Required since react-data-grid requires access to getInputNode, getValue, // howvever when doing this.getEditor() in react-data-grid we get a react // componenet wrapped by the redux connect function and thus wont have access // to the required methods. module.exports = function (ContainerEditor) { return function (_Component) { _inherits(ContainerEditorWrapper, _Component); function ContainerEditorWrapper() { _classCallCheck(this, ContainerEditorWrapper); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } ContainerEditorWrapper.prototype.getInputNode = function getInputNode() { return this.editorRef.getInputNode(); }; ContainerEditorWrapper.prototype.getValue = function getValue() { return this.editorRef.getValue(); }; ContainerEditorWrapper.prototype.render = function render() { var _this2 = this; return _react2['default'].createElement(ContainerEditor, _extends({ refCallback: function refCallback(ref) { _this2.editorRef = ref; } }, this.props)); }; return ContainerEditorWrapper; }(_react.Component); }; /***/ }, /* 137 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var React = __webpack_require__(1); var EditorBase = __webpack_require__(61); var DropDownEditor = function (_EditorBase) { _inherits(DropDownEditor, _EditorBase); function DropDownEditor() { _classCallCheck(this, DropDownEditor); return _possibleConstructorReturn(this, _EditorBase.apply(this, arguments)); } DropDownEditor.prototype.getInputNode = function getInputNode() { return _reactDom2['default'].findDOMNode(this); }; DropDownEditor.prototype.onClick = function onClick() { this.getInputNode().focus(); }; DropDownEditor.prototype.onDoubleClick = function onDoubleClick() { this.getInputNode().focus(); }; DropDownEditor.prototype.render = function render() { return React.createElement( 'select', { style: this.getStyle(), defaultValue: this.props.value, onBlur: this.props.onBlur, onChange: this.onChange }, this.renderOptions() ); }; DropDownEditor.prototype.renderOptions = function renderOptions() { var options = []; this.props.options.forEach(function (name) { if (typeof name === 'string') { options.push(React.createElement( 'option', { key: name, value: name }, name )); } else { options.push(React.createElement( 'option', { key: name.id, value: name.value, title: name.title }, name.text || name.value )); } }, this); return options; }; return DropDownEditor; }(EditorBase); DropDownEditor.propTypes = { options: React.PropTypes.arrayOf(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.objectOf({ id: React.PropTypes.string, title: React.PropTypes.string, value: React.PropTypes.string, text: React.PropTypes.string })])).isRequired }; module.exports = DropDownEditor; /***/ }, /* 138 */ /***/ 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 _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var React = __webpack_require__(1); var EditorBase = __webpack_require__(61); var SimpleTextEditor = function (_EditorBase) { _inherits(SimpleTextEditor, _EditorBase); function SimpleTextEditor() { _classCallCheck(this, SimpleTextEditor); return _possibleConstructorReturn(this, _EditorBase.apply(this, arguments)); } SimpleTextEditor.prototype.render = function render() { return React.createElement('input', { ref: 'input', type: 'text', onBlur: this.props.onBlur, className: 'form-control', defaultValue: this.props.value }); }; return SimpleTextEditor; }(EditorBase); module.exports = SimpleTextEditor; /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Editors = { AutoComplete: __webpack_require__(135), DropDownEditor: __webpack_require__(137), SimpleTextEditor: __webpack_require__(138), CheckboxEditor: __webpack_require__(60), ContainerEditorWrapper: __webpack_require__(136) }; module.exports = Editors; /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // Used for displaying the value of a dropdown (using DropDownEditor) when not editing it. // Accepts the same parameters as the DropDownEditor. var React = __webpack_require__(1); var DropDownFormatter = React.createClass({ displayName: 'DropDownFormatter', propTypes: { options: React.PropTypes.arrayOf(React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.objectOf({ id: React.PropTypes.string, title: React.PropTypes.string, value: React.PropTypes.string, text: React.PropTypes.string })])).isRequired, value: React.PropTypes.string.isRequired }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return nextProps.value !== this.props.value; }, render: function render() { var value = this.props.value; var option = this.props.options.filter(function (v) { return v === value || v.value === value; })[0]; if (!option) { option = value; } var title = option.title || option.value || option; var text = option.text || option.value || option; return React.createElement( 'div', { title: title }, text ); } }); module.exports = DropDownFormatter; /***/ }, /* 141 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(1); var PendingPool = {}; var ReadyPool = {}; var ImageFormatter = React.createClass({ displayName: 'ImageFormatter', propTypes: { value: React.PropTypes.string.isRequired }, getInitialState: function getInitialState() { return { ready: false }; }, componentWillMount: function componentWillMount() { this._load(this.props.value); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.value !== this.props.value) { this.setState({ value: null }); this._load(nextProps.value); } }, _load: function _load(src) { var imageSrc = src; if (ReadyPool[imageSrc]) { this.setState({ value: imageSrc }); return; } if (PendingPool[imageSrc]) { PendingPool[imageSrc].push(this._onLoad); return; } PendingPool[imageSrc] = [this._onLoad]; var img = new Image(); img.onload = function () { PendingPool[imageSrc].forEach(function (callback) { callback(imageSrc); }); delete PendingPool[imageSrc]; img.onload = null; imageSrc = undefined; }; img.src = imageSrc; }, _onLoad: function _onLoad(src) { if (this.isMounted() && src === this.props.value) { this.setState({ value: src }); } }, render: function render() { var style = this.state.value ? { backgroundImage: 'url(' + this.state.value + ')' } : undefined; return React.createElement('div', { className: 'react-grid-image', style: style }); } }); module.exports = ImageFormatter; /***/ }, /* 142 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // not including this // it currently requires the whole of moment, which we dont want to take as a dependency var ImageFormatter = __webpack_require__(141); var DropDownFormatter = __webpack_require__(140); var Formatters = { ImageFormatter: ImageFormatter, DropDownFormatter: DropDownFormatter }; module.exports = Formatters; /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactContextmenu = __webpack_require__(96); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ReactDataGridContextMenu = function (_React$Component) { _inherits(ReactDataGridContextMenu, _React$Component); function ReactDataGridContextMenu() { _classCallCheck(this, ReactDataGridContextMenu); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ReactDataGridContextMenu.prototype.render = function render() { return _react2['default'].createElement( _reactContextmenu.ContextMenu, { identifier: 'reactDataGridContextMenu' }, this.props.children ); }; return ReactDataGridContextMenu; }(_react2['default'].Component); ReactDataGridContextMenu.propTypes = { children: _react.PropTypes.node }; exports['default'] = ReactDataGridContextMenu; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var MenuHeader = function (_React$Component) { _inherits(MenuHeader, _React$Component); function MenuHeader() { _classCallCheck(this, MenuHeader); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } MenuHeader.prototype.render = function render() { return _react2["default"].createElement( "div", { className: "react-context-menu-header" }, this.props.children ); }; return MenuHeader; }(_react2["default"].Component); MenuHeader.propTypes = { children: _react.PropTypes.any }; exports["default"] = MenuHeader; /***/ }, /* 145 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.ContextMenuLayer = exports.connect = exports.SubMenu = exports.monitor = exports.MenuItem = exports.MenuHeader = exports.ContextMenu = undefined; var _reactContextmenu = __webpack_require__(96); var _ContextMenu = __webpack_require__(143); var _ContextMenu2 = _interopRequireDefault(_ContextMenu); var _MenuHeader = __webpack_require__(144); var _MenuHeader2 = _interopRequireDefault(_MenuHeader); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports.ContextMenu = _ContextMenu2['default']; exports.MenuHeader = _MenuHeader2['default']; exports.MenuItem = _reactContextmenu.MenuItem; exports.monitor = _reactContextmenu.monitor; exports.SubMenu = _reactContextmenu.SubMenu; exports.connect = _reactContextmenu.connect; exports.ContextMenuLayer = _reactContextmenu.ContextMenuLayer; /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { "use strict"; exports.__esModule = true; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var propTypes = { children: _react.PropTypes.array }; var defaultProps = { enableAddRow: true }; var AdvancedToolbar = function (_Component) { _inherits(AdvancedToolbar, _Component); function AdvancedToolbar() { _classCallCheck(this, AdvancedToolbar); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } AdvancedToolbar.prototype.render = function render() { return _react2["default"].createElement( "div", { className: "react-grid-Toolbar" }, this.props.children, _react2["default"].createElement("div", { className: "tools" }) ); }; return AdvancedToolbar; }(_react.Component); AdvancedToolbar.defaultProps = defaultProps; AdvancedToolbar.propTypes = propTypes; exports["default"] = AdvancedToolbar; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var GroupedColumnButton = function (_Component) { _inherits(GroupedColumnButton, _Component); function GroupedColumnButton() { _classCallCheck(this, GroupedColumnButton); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } GroupedColumnButton.prototype.render = function render() { var style = { width: '80px', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }; return _react2['default'].createElement( 'button', { className: 'btn grouped-col-btn btn-sm' }, _react2['default'].createElement( 'span', { style: style }, this.props.name ), _react2['default'].createElement('span', { className: 'glyphicon glyphicon-trash', style: { float: 'right', paddingLeft: '5px' }, onClick: this.props.onColumnGroupDeleted.bind(null, this.props.name) }) ); }; return GroupedColumnButton; }(_react.Component); exports['default'] = GroupedColumnButton; GroupedColumnButton.propTypes = { name: _react.PropTypes.string.isRequired, onColumnGroupDeleted: _react.PropTypes.func }; /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDnd = __webpack_require__(12); var _Constants = __webpack_require__(56); var _GroupedColumnButton = __webpack_require__(147); var _GroupedColumnButton2 = _interopRequireDefault(_GroupedColumnButton); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var propTypes = { isOver: _react.PropTypes.bool.isRequired, connectDropTarget: _react.PropTypes.func, canDrop: _react.PropTypes.bool.isRequired, groupBy: _react.PropTypes.array, noColumnsSelectedMessage: _react.PropTypes.string, panelDescription: _react.PropTypes.string, onColumnGroupDeleted: _react.PropTypes.func }; var defaultProps = { noColumnsSelectedMessage: 'Drag a column header here to group by that column', panelDescription: 'Drag a column header here to group by that column' }; var GroupedColumnsPanel = function (_Component) { _inherits(GroupedColumnsPanel, _Component); function GroupedColumnsPanel() { _classCallCheck(this, GroupedColumnsPanel); return _possibleConstructorReturn(this, _Component.call(this)); } GroupedColumnsPanel.prototype.getPanelInstructionMessage = function getPanelInstructionMessage() { var groupBy = this.props.groupBy; return groupBy && groupBy.length > 0 ? this.props.panelDescription : this.props.noColumnsSelectedMessage; }; GroupedColumnsPanel.prototype.renderGroupedColumns = function renderGroupedColumns() { var _this2 = this; return this.props.groupBy.map(function (c) { return _react2['default'].createElement(_GroupedColumnButton2['default'], { key: c, name: c, onColumnGroupDeleted: _this2.props.onColumnGroupDeleted }); }); }; GroupedColumnsPanel.prototype.renderOverlay = function renderOverlay(color) { return _react2['default'].createElement('div', { style: { position: 'absolute', top: 0, left: 0, height: '100%', width: '100%', zIndex: 1, opacity: 0.5, backgroundColor: color } }); }; GroupedColumnsPanel.prototype.render = function render() { var _props = this.props, connectDropTarget = _props.connectDropTarget, isOver = _props.isOver, canDrop = _props.canDrop; return connectDropTarget(_react2['default'].createElement( 'div', { style: { padding: '2px', position: 'relative', margin: '-10px', display: 'inline-block', border: '1px solid #eee' } }, this.renderGroupedColumns(), ' ', _react2['default'].createElement( 'span', null, this.getPanelInstructionMessage() ), isOver && canDrop && this.renderOverlay('yellow'), !isOver && canDrop && this.renderOverlay('#DBECFA') )); }; return GroupedColumnsPanel; }(_react.Component); GroupedColumnsPanel.defaultProps = defaultProps; GroupedColumnsPanel.propTypes = propTypes; var columnTarget = { drop: function drop(props, monitor) { // Obtain the dragged item var item = monitor.getItem(); if (typeof props.onColumnGroupAdded === 'function') { props.onColumnGroupAdded(item.key); } } }; function collect(connect, monitor) { return { connectDropTarget: connect.dropTarget(), isOver: monitor.isOver(), canDrop: monitor.canDrop(), draggedolumn: monitor.getItem() }; } exports['default'] = (0, _reactDnd.DropTarget)(_Constants.DragItemTypes.Column, columnTarget, collect)(GroupedColumnsPanel); /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var React = __webpack_require__(1); var Toolbar = React.createClass({ displayName: 'Toolbar', propTypes: { onAddRow: React.PropTypes.func, onToggleFilter: React.PropTypes.func, enableFilter: React.PropTypes.bool, numberOfRows: React.PropTypes.number, addRowButtonText: React.PropTypes.string, filterRowsButtonText: React.PropTypes.string, children: React.PropTypes.any }, onAddRow: function onAddRow() { if (this.props.onAddRow !== null && this.props.onAddRow instanceof Function) { this.props.onAddRow({ newRowIndex: this.props.numberOfRows }); } }, getDefaultProps: function getDefaultProps() { return { enableAddRow: true, addRowButtonText: 'Add Row', filterRowsButtonText: 'Filter Rows' }; }, renderAddRowButton: function renderAddRowButton() { if (this.props.onAddRow) { return React.createElement( 'button', { type: 'button', className: 'btn', onClick: this.onAddRow }, this.props.addRowButtonText ); } }, renderToggleFilterButton: function renderToggleFilterButton() { if (this.props.enableFilter) { return React.createElement( 'button', { type: 'button', className: 'btn', onClick: this.props.onToggleFilter }, this.props.filterRowsButtonText ); } }, render: function render() { return React.createElement( 'div', { className: 'react-grid-Toolbar' }, React.createElement( 'div', { className: 'tools' }, this.renderAddRowButton(), this.renderToggleFilterButton(), this.props.children ) ); } }); module.exports = Toolbar; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.GroupedColumnsPanel = exports.AdvancedToolbar = undefined; var _AdvancedToolbar = __webpack_require__(146); var _AdvancedToolbar2 = _interopRequireDefault(_AdvancedToolbar); var _GroupedColumnsPanel = __webpack_require__(148); var _GroupedColumnsPanel2 = _interopRequireDefault(_GroupedColumnsPanel); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } exports.AdvancedToolbar = _AdvancedToolbar2['default']; exports.GroupedColumnsPanel = _GroupedColumnsPanel2['default']; /***/ }, /* 151 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; function isEmpty(obj) { return Object.keys(obj).length === 0 && obj.constructor === Object; } exports["default"] = isEmpty; /***/ }, /* 152 */ /***/ function(module, exports) { "use strict"; function createObjectWithProperties(originalObj, properties) { var result = {}; for (var _iterator = properties, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) { var _ref; if (_isArray) { if (_i >= _iterator.length) break; _ref = _iterator[_i++]; } else { _i = _iterator.next(); if (_i.done) break; _ref = _i.value; } var property = _ref; if (originalObj[property]) { result[property] = originalObj[property]; } } return result; } module.exports = createObjectWithProperties; /***/ }, /* 153 */ /***/ function(module, exports) { 'use strict'; var size = void 0; function getScrollbarSize() { if (size === undefined) { var outer = document.createElement('div'); outer.style.width = '50px'; outer.style.height = '50px'; outer.style.position = 'absolute'; outer.style.top = '-200px'; outer.style.left = '-200px'; var inner = document.createElement('div'); inner.style.height = '100px'; inner.style.width = '100%'; outer.appendChild(inner); document.body.appendChild(outer); var outerWidth = outer.clientWidth; outer.style.overflowY = 'scroll'; var innerWidth = inner.clientWidth; document.body.removeChild(outer); size = outerWidth - innerWidth; } return size; } module.exports = getScrollbarSize; /***/ }, /* 154 */ /***/ function(module, exports) { "use strict"; function shallowCloneObject(obj) { var result = {}; for (var k in obj) { if (obj.hasOwnProperty(k)) { result[k] = obj[k]; } } return result; } module.exports = shallowCloneObject; /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames() { var classes = ''; var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments[i]; if (!arg) { continue; } if ('string' === typeof arg || 'number' === typeof arg) { classes += ' ' + arg; } else if (Object.prototype.toString.call(arg) === '[object Array]') { classes += ' ' + classNames.apply(null, arg); } else if ('object' === typeof arg) { for (var key in arg) { if (!arg.hasOwnProperty(key) || !arg[key]) { continue; } classes += ' ' + key; } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } // safely export classNames for RequireJS if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; exports.__esModule = true; var _isDisposable = __webpack_require__(35); var _isDisposable2 = _interopRequireWildcard(_isDisposable); /** * Represents a group of disposable resources that are disposed together. */ var CompositeDisposable = (function () { function CompositeDisposable() { for (var _len = arguments.length, disposables = Array(_len), _key = 0; _key < _len; _key++) { disposables[_key] = arguments[_key]; } _classCallCheck(this, CompositeDisposable); if (Array.isArray(disposables[0]) && disposables.length === 1) { disposables = disposables[0]; } for (var i = 0; i < disposables.length; i++) { if (!_isDisposable2['default'](disposables[i])) { throw new Error('Expected a disposable'); } } this.disposables = disposables; this.isDisposed = false; } /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Disposable} item Disposable to add. */ CompositeDisposable.prototype.add = function add(item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Disposable} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposable.prototype.remove = function remove(item) { if (this.isDisposed) { return false; } var index = this.disposables.indexOf(item); if (index === -1) { return false; } this.disposables.splice(index, 1); item.dispose(); return true; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposable.prototype.dispose = function dispose() { if (this.isDisposed) { return; } var len = this.disposables.length; var currentDisposables = new Array(len); for (var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.isDisposed = true; this.disposables = []; this.length = 0; for (var i = 0; i < len; i++) { currentDisposables[i].dispose(); } }; return CompositeDisposable; })(); exports['default'] = CompositeDisposable; module.exports = exports['default']; /***/ }, /* 157 */ /***/ function(module, exports) { "use strict"; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); exports.__esModule = true; var noop = function noop() {}; /** * The basic disposable. */ var Disposable = (function () { function Disposable(action) { _classCallCheck(this, Disposable); this.isDisposed = false; this.action = action || noop; } Disposable.prototype.dispose = function dispose() { if (!this.isDisposed) { this.action.call(null); this.isDisposed = true; } }; _createClass(Disposable, null, [{ key: "empty", enumerable: true, value: { dispose: noop } }]); return Disposable; })(); exports["default"] = Disposable; module.exports = exports["default"]; /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; var _classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }; exports.__esModule = true; var _isDisposable = __webpack_require__(35); var _isDisposable2 = _interopRequireWildcard(_isDisposable); var SerialDisposable = (function () { function SerialDisposable() { _classCallCheck(this, SerialDisposable); this.isDisposed = false; this.current = null; } /** * Gets the underlying disposable. * @return The underlying disposable. */ SerialDisposable.prototype.getDisposable = function getDisposable() { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ SerialDisposable.prototype.setDisposable = function setDisposable() { var value = arguments[0] === undefined ? null : arguments[0]; if (value != null && !_isDisposable2['default'](value)) { throw new Error('Expected either an empty value or a valid disposable'); } var isDisposed = this.isDisposed; var previous = undefined; if (!isDisposed) { previous = this.current; this.current = value; } if (previous) { previous.dispose(); } if (isDisposed && value) { value.dispose(); } }; /** * Disposes the underlying disposable as well as all future replacements. */ SerialDisposable.prototype.dispose = function dispose() { if (this.isDisposed) { return; } this.isDisposed = true; var previous = this.current; this.current = null; if (previous) { previous.dispose(); } }; return SerialDisposable; })(); exports['default'] = SerialDisposable; module.exports = exports['default']; /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _interopRequireWildcard = function (obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }; exports.__esModule = true; var _isDisposable2 = __webpack_require__(35); var _isDisposable3 = _interopRequireWildcard(_isDisposable2); exports.isDisposable = _isDisposable3['default']; var _Disposable2 = __webpack_require__(157); var _Disposable3 = _interopRequireWildcard(_Disposable2); exports.Disposable = _Disposable3['default']; var _CompositeDisposable2 = __webpack_require__(156); var _CompositeDisposable3 = _interopRequireWildcard(_CompositeDisposable2); exports.CompositeDisposable = _CompositeDisposable3['default']; var _SerialDisposable2 = __webpack_require__(158); var _SerialDisposable3 = _interopRequireWildcard(_SerialDisposable2); exports.SerialDisposable = _SerialDisposable3['default']; /***/ }, /* 160 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _reduxLibCreateStore = __webpack_require__(54); var _reduxLibCreateStore2 = _interopRequireDefault(_reduxLibCreateStore); var _reducers = __webpack_require__(167); var _reducers2 = _interopRequireDefault(_reducers); var _actionsDragDrop = __webpack_require__(18); var dragDropActions = _interopRequireWildcard(_actionsDragDrop); var _DragDropMonitor = __webpack_require__(161); var _DragDropMonitor2 = _interopRequireDefault(_DragDropMonitor); var _HandlerRegistry = __webpack_require__(64); var _HandlerRegistry2 = _interopRequireDefault(_HandlerRegistry); var DragDropManager = (function () { function DragDropManager(createBackend) { _classCallCheck(this, DragDropManager); var store = _reduxLibCreateStore2['default'](_reducers2['default']); this.store = store; this.monitor = new _DragDropMonitor2['default'](store); this.registry = this.monitor.registry; this.backend = createBackend(this); store.subscribe(this.handleRefCountChange.bind(this)); } DragDropManager.prototype.handleRefCountChange = function handleRefCountChange() { var shouldSetUp = this.store.getState().refCount > 0; if (shouldSetUp && !this.isSetUp) { this.backend.setup(); this.isSetUp = true; } else if (!shouldSetUp && this.isSetUp) { this.backend.teardown(); this.isSetUp = false; } }; DragDropManager.prototype.getMonitor = function getMonitor() { return this.monitor; }; DragDropManager.prototype.getBackend = function getBackend() { return this.backend; }; DragDropManager.prototype.getRegistry = function getRegistry() { return this.registry; }; DragDropManager.prototype.getActions = function getActions() { var manager = this; var dispatch = this.store.dispatch; function bindActionCreator(actionCreator) { return function () { var action = actionCreator.apply(manager, arguments); if (typeof action !== 'undefined') { dispatch(action); } }; } return Object.keys(dragDropActions).filter(function (key) { return typeof dragDropActions[key] === 'function'; }).reduce(function (boundActions, key) { boundActions[key] = bindActionCreator(dragDropActions[key]); return boundActions; }, {}); }; return DragDropManager; })(); exports['default'] = DragDropManager; module.exports = exports['default']; /***/ }, /* 161 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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'); } } var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _utilsMatchesType = __webpack_require__(67); var _utilsMatchesType2 = _interopRequireDefault(_utilsMatchesType); var _lodashIsArray = __webpack_require__(3); var _lodashIsArray2 = _interopRequireDefault(_lodashIsArray); var _HandlerRegistry = __webpack_require__(64); var _HandlerRegistry2 = _interopRequireDefault(_HandlerRegistry); var _reducersDragOffset = __webpack_require__(66); var _reducersDirtyHandlerIds = __webpack_require__(65); var DragDropMonitor = (function () { function DragDropMonitor(store) { _classCallCheck(this, DragDropMonitor); this.store = store; this.registry = new _HandlerRegistry2['default'](store); } DragDropMonitor.prototype.subscribeToStateChange = function subscribeToStateChange(listener) { var _this = this; var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var handlerIds = _ref.handlerIds; _invariant2['default'](typeof listener === 'function', 'listener must be a function.'); _invariant2['default'](typeof handlerIds === 'undefined' || _lodashIsArray2['default'](handlerIds), 'handlerIds, when specified, must be an array of strings.'); var prevStateId = this.store.getState().stateId; var handleChange = function handleChange() { var state = _this.store.getState(); var currentStateId = state.stateId; try { var canSkipListener = currentStateId === prevStateId || currentStateId === prevStateId + 1 && !_reducersDirtyHandlerIds.areDirty(state.dirtyHandlerIds, handlerIds); if (!canSkipListener) { listener(); } } finally { prevStateId = currentStateId; } }; return this.store.subscribe(handleChange); }; DragDropMonitor.prototype.subscribeToOffsetChange = function subscribeToOffsetChange(listener) { var _this2 = this; _invariant2['default'](typeof listener === 'function', 'listener must be a function.'); var previousState = this.store.getState().dragOffset; var handleChange = function handleChange() { var nextState = _this2.store.getState().dragOffset; if (nextState === previousState) { return; } previousState = nextState; listener(); }; return this.store.subscribe(handleChange); }; DragDropMonitor.prototype.canDragSource = function canDragSource(sourceId) { var source = this.registry.getSource(sourceId); _invariant2['default'](source, 'Expected to find a valid source.'); if (this.isDragging()) { return false; } return source.canDrag(this, sourceId); }; DragDropMonitor.prototype.canDropOnTarget = function canDropOnTarget(targetId) { var target = this.registry.getTarget(targetId); _invariant2['default'](target, 'Expected to find a valid target.'); if (!this.isDragging() || this.didDrop()) { return false; } var targetType = this.registry.getTargetType(targetId); var draggedItemType = this.getItemType(); return _utilsMatchesType2['default'](targetType, draggedItemType) && target.canDrop(this, targetId); }; DragDropMonitor.prototype.isDragging = function isDragging() { return Boolean(this.getItemType()); }; DragDropMonitor.prototype.isDraggingSource = function isDraggingSource(sourceId) { var source = this.registry.getSource(sourceId, true); _invariant2['default'](source, 'Expected to find a valid source.'); if (!this.isDragging() || !this.isSourcePublic()) { return false; } var sourceType = this.registry.getSourceType(sourceId); var draggedItemType = this.getItemType(); if (sourceType !== draggedItemType) { return false; } return source.isDragging(this, sourceId); }; DragDropMonitor.prototype.isOverTarget = function isOverTarget(targetId) { var _ref2 = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var _ref2$shallow = _ref2.shallow; var shallow = _ref2$shallow === undefined ? false : _ref2$shallow; if (!this.isDragging()) { return false; } var targetType = this.registry.getTargetType(targetId); var draggedItemType = this.getItemType(); if (!_utilsMatchesType2['default'](targetType, draggedItemType)) { return false; } var targetIds = this.getTargetIds(); if (!targetIds.length) { return false; } var index = targetIds.indexOf(targetId); if (shallow) { return index === targetIds.length - 1; } else { return index > -1; } }; DragDropMonitor.prototype.getItemType = function getItemType() { return this.store.getState().dragOperation.itemType; }; DragDropMonitor.prototype.getItem = function getItem() { return this.store.getState().dragOperation.item; }; DragDropMonitor.prototype.getSourceId = function getSourceId() { return this.store.getState().dragOperation.sourceId; }; DragDropMonitor.prototype.getTargetIds = function getTargetIds() { return this.store.getState().dragOperation.targetIds; }; DragDropMonitor.prototype.getDropResult = function getDropResult() { return this.store.getState().dragOperation.dropResult; }; DragDropMonitor.prototype.didDrop = function didDrop() { return this.store.getState().dragOperation.didDrop; }; DragDropMonitor.prototype.isSourcePublic = function isSourcePublic() { return this.store.getState().dragOperation.isSourcePublic; }; DragDropMonitor.prototype.getInitialClientOffset = function getInitialClientOffset() { return this.store.getState().dragOffset.initialClientOffset; }; DragDropMonitor.prototype.getInitialSourceClientOffset = function getInitialSourceClientOffset() { return this.store.getState().dragOffset.initialSourceClientOffset; }; DragDropMonitor.prototype.getClientOffset = function getClientOffset() { return this.store.getState().dragOffset.clientOffset; }; DragDropMonitor.prototype.getSourceClientOffset = function getSourceClientOffset() { return _reducersDragOffset.getSourceClientOffset(this.store.getState().dragOffset); }; DragDropMonitor.prototype.getDifferenceFromInitialOffset = function getDifferenceFromInitialOffset() { return _reducersDragOffset.getDifferenceFromInitialOffset(this.store.getState().dragOffset); }; return DragDropMonitor; })(); exports['default'] = DragDropMonitor; module.exports = exports['default']; /***/ }, /* 162 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var DragSource = (function () { function DragSource() { _classCallCheck(this, DragSource); } DragSource.prototype.canDrag = function canDrag() { return true; }; DragSource.prototype.isDragging = function isDragging(monitor, handle) { return handle === monitor.getSourceId(); }; DragSource.prototype.endDrag = function endDrag() {}; return DragSource; })(); exports["default"] = DragSource; module.exports = exports["default"]; /***/ }, /* 163 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var DropTarget = (function () { function DropTarget() { _classCallCheck(this, DropTarget); } DropTarget.prototype.canDrop = function canDrop() { return true; }; DropTarget.prototype.hover = function hover() {}; DropTarget.prototype.drop = function drop() {}; return DropTarget; })(); exports["default"] = DropTarget; module.exports = exports["default"]; /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createBackend; 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'); } } var _lodashNoop = __webpack_require__(94); var _lodashNoop2 = _interopRequireDefault(_lodashNoop); var TestBackend = (function () { function TestBackend(manager) { _classCallCheck(this, TestBackend); this.actions = manager.getActions(); } TestBackend.prototype.setup = function setup() { this.didCallSetup = true; }; TestBackend.prototype.teardown = function teardown() { this.didCallTeardown = true; }; TestBackend.prototype.connectDragSource = function connectDragSource() { return _lodashNoop2['default']; }; TestBackend.prototype.connectDragPreview = function connectDragPreview() { return _lodashNoop2['default']; }; TestBackend.prototype.connectDropTarget = function connectDropTarget() { return _lodashNoop2['default']; }; TestBackend.prototype.simulateBeginDrag = function simulateBeginDrag(sourceIds, options) { this.actions.beginDrag(sourceIds, options); }; TestBackend.prototype.simulatePublishDragSource = function simulatePublishDragSource() { this.actions.publishDragSource(); }; TestBackend.prototype.simulateHover = function simulateHover(targetIds, options) { this.actions.hover(targetIds, options); }; TestBackend.prototype.simulateDrop = function simulateDrop() { this.actions.drop(); }; TestBackend.prototype.simulateEndDrag = function simulateEndDrag() { this.actions.endDrag(); }; return TestBackend; })(); function createBackend(manager) { return new TestBackend(manager); } module.exports = exports['default']; /***/ }, /* 165 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequire(obj) { return obj && obj.__esModule ? obj['default'] : obj; } var _DragDropManager = __webpack_require__(160); exports.DragDropManager = _interopRequire(_DragDropManager); var _DragSource = __webpack_require__(162); exports.DragSource = _interopRequire(_DragSource); var _DropTarget = __webpack_require__(163); exports.DropTarget = _interopRequire(_DropTarget); var _backendsCreateTestBackend = __webpack_require__(164); exports.createTestBackend = _interopRequire(_backendsCreateTestBackend); /***/ }, /* 166 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports['default'] = dragOperation; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _actionsDragDrop = __webpack_require__(18); var _actionsRegistry = __webpack_require__(19); var _lodashWithout = __webpack_require__(95); var _lodashWithout2 = _interopRequireDefault(_lodashWithout); var initialState = { itemType: null, item: null, sourceId: null, targetIds: [], dropResult: null, didDrop: false, isSourcePublic: null }; function dragOperation(state, action) { if (state === undefined) state = initialState; switch (action.type) { case _actionsDragDrop.BEGIN_DRAG: return _extends({}, state, { itemType: action.itemType, item: action.item, sourceId: action.sourceId, isSourcePublic: action.isSourcePublic, dropResult: null, didDrop: false }); case _actionsDragDrop.PUBLISH_DRAG_SOURCE: return _extends({}, state, { isSourcePublic: true }); case _actionsDragDrop.HOVER: return _extends({}, state, { targetIds: action.targetIds }); case _actionsRegistry.REMOVE_TARGET: if (state.targetIds.indexOf(action.targetId) === -1) { return state; } return _extends({}, state, { targetIds: _lodashWithout2['default'](state.targetIds, action.targetId) }); case _actionsDragDrop.DROP: return _extends({}, state, { dropResult: action.dropResult, didDrop: true, targetIds: [] }); case _actionsDragDrop.END_DRAG: return _extends({}, state, { itemType: null, item: null, sourceId: null, dropResult: null, didDrop: false, isSourcePublic: null, targetIds: [] }); default: return state; } } module.exports = exports['default']; /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _dragOffset = __webpack_require__(66); var _dragOffset2 = _interopRequireDefault(_dragOffset); var _dragOperation = __webpack_require__(166); var _dragOperation2 = _interopRequireDefault(_dragOperation); var _refCount = __webpack_require__(168); var _refCount2 = _interopRequireDefault(_refCount); var _dirtyHandlerIds = __webpack_require__(65); var _dirtyHandlerIds2 = _interopRequireDefault(_dirtyHandlerIds); var _stateId = __webpack_require__(169); var _stateId2 = _interopRequireDefault(_stateId); exports['default'] = function (state, action) { if (state === undefined) state = {}; return { dirtyHandlerIds: _dirtyHandlerIds2['default'](state.dirtyHandlerIds, action, state.dragOperation), dragOffset: _dragOffset2['default'](state.dragOffset, action), refCount: _refCount2['default'](state.refCount, action), dragOperation: _dragOperation2['default'](state.dragOperation, action), stateId: _stateId2['default'](state.stateId) }; }; module.exports = exports['default']; /***/ }, /* 168 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = refCount; var _actionsRegistry = __webpack_require__(19); function refCount(state, action) { if (state === undefined) state = 0; switch (action.type) { case _actionsRegistry.ADD_SOURCE: case _actionsRegistry.ADD_TARGET: return state + 1; case _actionsRegistry.REMOVE_SOURCE: case _actionsRegistry.REMOVE_TARGET: return state - 1; default: return state; } } module.exports = exports['default']; /***/ }, /* 169 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = stateId; function stateId() { var state = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0]; return state + 1; } module.exports = exports["default"]; /***/ }, /* 170 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = getNextUniqueId; var nextUniqueId = 0; function getNextUniqueId() { return nextUniqueId++; } module.exports = exports["default"]; /***/ }, /* 171 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var babelHelpers = __webpack_require__(69); exports.__esModule = true; /** * document.activeElement */ exports['default'] = activeElement; var _ownerDocument = __webpack_require__(36); var _ownerDocument2 = babelHelpers.interopRequireDefault(_ownerDocument); function activeElement() { var doc = arguments[0] === undefined ? document : arguments[0]; try { return doc.activeElement; } catch (e) {} } module.exports = exports['default']; /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var hasClass = __webpack_require__(68); module.exports = function addClass(element, className) { if (element.classList) element.classList.add(className);else if (!hasClass(element)) element.className = element.className + ' ' + className; }; /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; module.exports = { addClass: __webpack_require__(172), removeClass: __webpack_require__(174), hasClass: __webpack_require__(68) }; /***/ }, /* 174 */ /***/ function(module, exports) { 'use strict'; module.exports = function removeClass(element, className) { if (element.classList) element.classList.remove(className);else element.className = element.className.replace(new RegExp('(^|\\s)' + className + '(?:\\s|$)', 'g'), '$1').replace(/\s+/g, ' ').replace(/^\s*|\s*$/g, ''); }; /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(14); var off = function off() {}; if (canUseDOM) { off = (function () { if (document.addEventListener) return function (node, eventName, handler, capture) { return node.removeEventListener(eventName, handler, capture || false); };else if (document.attachEvent) return function (node, eventName, handler) { return node.detachEvent('on' + eventName, handler); }; })(); } module.exports = off; /***/ }, /* 176 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(14); var on = function on() {}; if (canUseDOM) { on = (function () { if (document.addEventListener) return function (node, eventName, handler, capture) { return node.addEventListener(eventName, handler, capture || false); };else if (document.attachEvent) return function (node, eventName, handler) { return node.attachEvent('on' + eventName, handler); }; })(); } module.exports = on; /***/ }, /* 177 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(14); var contains = (function () { var root = canUseDOM && document.documentElement; return root && root.contains ? function (context, node) { return context.contains(node); } : root && root.compareDocumentPosition ? function (context, node) { return context === node || !!(context.compareDocumentPosition(node) & 16); } : function (context, node) { if (node) do { if (node === context) return true; } while (node = node.parentNode); return false; }; })(); module.exports = contains; /***/ }, /* 178 */ /***/ function(module, exports) { 'use strict'; module.exports = function getWindow(node) { return node === node.window ? node : node.nodeType === 9 ? node.defaultView || node.parentWindow : false; }; /***/ }, /* 179 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var babelHelpers = __webpack_require__(69); var _utilCamelizeStyle = __webpack_require__(70); var _utilCamelizeStyle2 = babelHelpers.interopRequireDefault(_utilCamelizeStyle); var rposition = /^(top|right|bottom|left)$/; var rnumnonpx = /^([+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|))(?!px)[a-z%]+$/i; module.exports = function _getComputedStyle(node) { if (!node) throw new TypeError('No Element passed to `getComputedStyle()`'); var doc = node.ownerDocument; return 'defaultView' in doc ? doc.defaultView.opener ? node.ownerDocument.defaultView.getComputedStyle(node, null) : window.getComputedStyle(node, null) : { //ie 8 "magic" from: https://github.com/jquery/jquery/blob/1.11-stable/src/css/curCSS.js#L72 getPropertyValue: function getPropertyValue(prop) { var style = node.style; prop = (0, _utilCamelizeStyle2['default'])(prop); if (prop == 'float') prop = 'styleFloat'; var current = node.currentStyle[prop] || null; if (current == null && style && style[prop]) current = style[prop]; if (rnumnonpx.test(current) && !rposition.test(prop)) { // Remember the original values var left = style.left; var runStyle = node.runtimeStyle; var rsLeft = runStyle && runStyle.left; // Put in the new values to get a computed value out if (rsLeft) runStyle.left = node.currentStyle.left; style.left = prop === 'fontSize' ? '1em' : current; current = style.pixelLeft + 'px'; // Revert the changed values style.left = left; if (rsLeft) runStyle.left = rsLeft; } return current; } }; }; /***/ }, /* 180 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var camelize = __webpack_require__(70), hyphenate = __webpack_require__(184), _getComputedStyle = __webpack_require__(179), removeStyle = __webpack_require__(181); var has = Object.prototype.hasOwnProperty; module.exports = function style(node, property, value) { var css = '', props = property; if (typeof property === 'string') { if (value === undefined) return node.style[camelize(property)] || _getComputedStyle(node).getPropertyValue(hyphenate(property));else (props = {})[property] = value; } for (var key in props) if (has.call(props, key)) { !props[key] && props[key] !== 0 ? removeStyle(node, hyphenate(key)) : css += hyphenate(key) + ':' + props[key] + ';'; } node.style.cssText += ';' + css; }; /***/ }, /* 181 */ /***/ function(module, exports) { 'use strict'; module.exports = function removeStyle(node, key) { return 'removeProperty' in node.style ? node.style.removeProperty(key) : node.style.removeAttribute(key); }; /***/ }, /* 182 */ /***/ function(module, exports) { "use strict"; var rHyphen = /-(.)/g; module.exports = function camelize(string) { return string.replace(rHyphen, function (_, chr) { return chr.toUpperCase(); }); }; /***/ }, /* 183 */ /***/ function(module, exports) { 'use strict'; var rUpper = /([A-Z])/g; module.exports = function hyphenate(string) { return string.replace(rUpper, '-$1').toLowerCase(); }; /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { /** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * https://github.com/facebook/react/blob/2aeb8a2a6beb00617a4217f7f8284924fa2ad819/src/vendor/core/hyphenateStyleName.js */ "use strict"; var hyphenate = __webpack_require__(183); var msPattern = /^ms-/; module.exports = function hyphenateStyleName(string) { return hyphenate(string).replace(msPattern, "-ms-"); }; /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var canUseDOM = __webpack_require__(14); var size; module.exports = function (recalc) { if (!size || recalc) { if (canUseDOM) { var scrollDiv = document.createElement('div'); scrollDiv.style.position = 'absolute'; scrollDiv.style.top = '-9999px'; scrollDiv.style.width = '50px'; scrollDiv.style.height = '50px'; scrollDiv.style.overflow = 'scroll'; document.body.appendChild(scrollDiv); size = scrollDiv.offsetWidth - scrollDiv.clientWidth; document.body.removeChild(scrollDiv); } } return size; }; /***/ }, /* 186 */ /***/ function(module, exports) { /** * lodash 3.0.2 (Custom Build) <https://lodash.com/> * Build: `lodash modern modularize exports="npm" -o ./` * Copyright 2012-2015 The Dojo Foundation <http://dojofoundation.org/> * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE> * Copyright 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors * Available under MIT license <https://lodash.com/license> */ /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 187 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(7), root = __webpack_require__(4); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); module.exports = DataView; /***/ }, /* 188 */ /***/ function(module, exports, __webpack_require__) { var hashClear = __webpack_require__(239), hashDelete = __webpack_require__(240), hashGet = __webpack_require__(241), hashHas = __webpack_require__(242), hashSet = __webpack_require__(243); /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; module.exports = Hash; /***/ }, /* 189 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(7), root = __webpack_require__(4); /* Built-in method references that are verified to be native. */ var Promise = getNative(root, 'Promise'); module.exports = Promise; /***/ }, /* 190 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(4); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; /***/ }, /* 191 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(7), root = __webpack_require__(4); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; /***/ }, /* 192 */ /***/ function(module, exports) { /** * A specialized version of `baseAggregator` for arrays. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function arrayAggregator(array, setter, iteratee, accumulator) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { var value = array[index]; setter(accumulator, value, iteratee(value), array); } return accumulator; } module.exports = arrayAggregator; /***/ }, /* 193 */ /***/ function(module, exports) { /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } module.exports = arrayFilter; /***/ }, /* 194 */ /***/ function(module, exports) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }, /* 195 */ /***/ function(module, exports) { /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } module.exports = arraySome; /***/ }, /* 196 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(16); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used by `_.defaults` to customize its `_.assignIn` use. * * @private * @param {*} objValue The destination value. * @param {*} srcValue The source value. * @param {string} key The key of the property to assign. * @param {Object} object The parent object of `objValue`. * @returns {*} Returns the value to assign. */ function assignInDefaults(objValue, srcValue, key, object) { if (objValue === undefined || (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { return srcValue; } return objValue; } module.exports = assignInDefaults; /***/ }, /* 197 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(41), eq = __webpack_require__(16); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignValue; /***/ }, /* 198 */ /***/ function(module, exports, __webpack_require__) { var baseEach = __webpack_require__(199); /** * Aggregates elements of `collection` on `accumulator` with keys transformed * by `iteratee` and values set by `setter`. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} setter The function to set `accumulator` values. * @param {Function} iteratee The iteratee to transform keys. * @param {Object} accumulator The initial aggregated object. * @returns {Function} Returns `accumulator`. */ function baseAggregator(collection, setter, iteratee, accumulator) { baseEach(collection, function(value, key, collection) { setter(accumulator, value, iteratee(value), collection); }); return accumulator; } module.exports = baseAggregator; /***/ }, /* 199 */ /***/ function(module, exports, __webpack_require__) { var baseForOwn = __webpack_require__(202), createBaseEach = __webpack_require__(228); /** * The base implementation of `_.forEach` without support for iteratee shorthands. * * @private * @param {Array|Object} collection The collection to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array|Object} Returns `collection`. */ var baseEach = createBaseEach(baseForOwn); module.exports = baseEach; /***/ }, /* 200 */ /***/ function(module, exports) { /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } module.exports = baseFindIndex; /***/ }, /* 201 */ /***/ function(module, exports, __webpack_require__) { var createBaseFor = __webpack_require__(229); /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; /***/ }, /* 202 */ /***/ function(module, exports, __webpack_require__) { var baseFor = __webpack_require__(201), keys = __webpack_require__(50); /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } module.exports = baseForOwn; /***/ }, /* 203 */ /***/ function(module, exports) { /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } module.exports = baseHasIn; /***/ }, /* 204 */ /***/ function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(200), baseIsNaN = __webpack_require__(209), strictIndexOf = __webpack_require__(274); /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } module.exports = baseIndexOf; /***/ }, /* 205 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(21), arrayIncludes = __webpack_require__(39), arrayIncludesWith = __webpack_require__(40), arrayMap = __webpack_require__(22), baseUnary = __webpack_require__(42), cacheHas = __webpack_require__(24); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * The base implementation of methods like `_.intersection`, without support * for iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of shared values. */ function baseIntersection(arrays, iteratee, comparator) { var includes = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array(othLength), maxLength = Infinity, result = []; while (othIndex--) { var array = arrays[othIndex]; if (othIndex && iteratee) { array = arrayMap(array, baseUnary(iteratee)); } maxLength = nativeMin(array.length, maxLength); caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) ? new SetCache(othIndex && array) : undefined; } array = arrays[0]; var index = -1, seen = caches[0]; outer: while (++index < length && result.length < maxLength) { var value = array[index], computed = iteratee ? iteratee(value) : value; value = (comparator || value !== 0) ? value : 0; if (!(seen ? cacheHas(seen, computed) : includes(result, computed, comparator) )) { othIndex = othLength; while (--othIndex) { var cache = caches[othIndex]; if (!(cache ? cacheHas(cache, computed) : includes(arrays[othIndex], computed, comparator)) ) { continue outer; } } if (seen) { seen.push(computed); } result.push(value); } } return result; } module.exports = baseIntersection; /***/ }, /* 206 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(10), isObjectLike = __webpack_require__(9); /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } module.exports = baseIsArguments; /***/ }, /* 207 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(73), equalArrays = __webpack_require__(83), equalByTag = __webpack_require__(231), equalObjects = __webpack_require__(232), getTag = __webpack_require__(236), isArray = __webpack_require__(3), isBuffer = __webpack_require__(90), isTypedArray = __webpack_require__(92); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', objectTag = '[object Object]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = getTag(object); objTag = objTag == argsTag ? objectTag : objTag; } if (!othIsArr) { othTag = getTag(other); othTag = othTag == argsTag ? objectTag : othTag; } var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } module.exports = baseIsEqualDeep; /***/ }, /* 208 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(73), baseIsEqual = __webpack_require__(79); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } module.exports = baseIsMatch; /***/ }, /* 209 */ /***/ function(module, exports) { /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } module.exports = baseIsNaN; /***/ }, /* 210 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(91), isMasked = __webpack_require__(247), isObject = __webpack_require__(8), toSource = __webpack_require__(89); /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } module.exports = baseIsNative; /***/ }, /* 211 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(10), isLength = __webpack_require__(48), isObjectLike = __webpack_require__(9); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } module.exports = baseIsTypedArray; /***/ }, /* 212 */ /***/ function(module, exports, __webpack_require__) { var baseMatches = __webpack_require__(215), baseMatchesProperty = __webpack_require__(216), identity = __webpack_require__(46), isArray = __webpack_require__(3), property = __webpack_require__(284); /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } module.exports = baseIteratee; /***/ }, /* 213 */ /***/ function(module, exports, __webpack_require__) { var isPrototype = __webpack_require__(85), nativeKeys = __webpack_require__(260); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } module.exports = baseKeys; /***/ }, /* 214 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(8), isPrototype = __webpack_require__(85), nativeKeysIn = __webpack_require__(261); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = baseKeysIn; /***/ }, /* 215 */ /***/ function(module, exports, __webpack_require__) { var baseIsMatch = __webpack_require__(208), getMatchData = __webpack_require__(233), matchesStrictComparable = __webpack_require__(87); /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } module.exports = baseMatches; /***/ }, /* 216 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(79), get = __webpack_require__(279), hasIn = __webpack_require__(281), isKey = __webpack_require__(44), isStrictComparable = __webpack_require__(86), matchesStrictComparable = __webpack_require__(87), toKey = __webpack_require__(27); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } module.exports = baseMatchesProperty; /***/ }, /* 217 */ /***/ function(module, exports) { /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } module.exports = baseProperty; /***/ }, /* 218 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(78); /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } module.exports = basePropertyDeep; /***/ }, /* 219 */ /***/ function(module, exports, __webpack_require__) { var constant = __webpack_require__(277), defineProperty = __webpack_require__(82), identity = __webpack_require__(46); /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; module.exports = baseSetToString; /***/ }, /* 220 */ /***/ function(module, exports) { /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } module.exports = baseTimes; /***/ }, /* 221 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), arrayMap = __webpack_require__(22), isArray = __webpack_require__(3), isSymbol = __webpack_require__(49); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = baseToString; /***/ }, /* 222 */ /***/ function(module, exports, __webpack_require__) { var baseDifference = __webpack_require__(76), baseFlatten = __webpack_require__(77), baseUniq = __webpack_require__(80); /** * The base implementation of methods like `_.xor`, without support for * iteratee shorthands, that accepts an array of arrays to inspect. * * @private * @param {Array} arrays The arrays to inspect. * @param {Function} [iteratee] The iteratee invoked per element. * @param {Function} [comparator] The comparator invoked per element. * @returns {Array} Returns the new array of values. */ function baseXor(arrays, iteratee, comparator) { var length = arrays.length; if (length < 2) { return length ? baseUniq(arrays[0]) : []; } var index = -1, result = Array(length); while (++index < length) { var array = arrays[index], othIndex = -1; while (++othIndex < length) { if (othIndex != index) { result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); } } } return baseUniq(baseFlatten(result, 1), iteratee, comparator); } module.exports = baseXor; /***/ }, /* 223 */ /***/ function(module, exports, __webpack_require__) { var isArrayLikeObject = __webpack_require__(28); /** * Casts `value` to an empty array if it's not an array like object. * * @private * @param {*} value The value to inspect. * @returns {Array|Object} Returns the cast array-like object. */ function castArrayLikeObject(value) { return isArrayLikeObject(value) ? value : []; } module.exports = castArrayLikeObject; /***/ }, /* 224 */ /***/ function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(197), baseAssignValue = __webpack_require__(41); /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } module.exports = copyObject; /***/ }, /* 225 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(4); /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; module.exports = coreJsData; /***/ }, /* 226 */ /***/ function(module, exports, __webpack_require__) { var arrayAggregator = __webpack_require__(192), baseAggregator = __webpack_require__(198), baseIteratee = __webpack_require__(212), isArray = __webpack_require__(3); /** * Creates a function like `_.groupBy`. * * @private * @param {Function} setter The function to set accumulator values. * @param {Function} [initializer] The accumulator object initializer. * @returns {Function} Returns the new aggregator function. */ function createAggregator(setter, initializer) { return function(collection, iteratee) { var func = isArray(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; return func(collection, setter, baseIteratee(iteratee, 2), accumulator); }; } module.exports = createAggregator; /***/ }, /* 227 */ /***/ function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(11), isIterateeCall = __webpack_require__(245); /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } module.exports = createAssigner; /***/ }, /* 228 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(17); /** * Creates a `baseEach` or `baseEachRight` function. * * @private * @param {Function} eachFunc The function to iterate over a collection. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { if (collection == null) { return collection; } if (!isArrayLike(collection)) { return eachFunc(collection, iteratee); } var length = collection.length, index = fromRight ? length : -1, iterable = Object(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } module.exports = createBaseEach; /***/ }, /* 229 */ /***/ function(module, exports) { /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; /***/ }, /* 230 */ /***/ function(module, exports, __webpack_require__) { var Set = __webpack_require__(72), noop = __webpack_require__(94), setToArray = __webpack_require__(45); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Creates a set object of `values`. * * @private * @param {Array} values The values to add to the set. * @returns {Object} Returns the new set. */ var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { return new Set(values); }; module.exports = createSet; /***/ }, /* 231 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), Uint8Array = __webpack_require__(190), eq = __webpack_require__(16), equalArrays = __webpack_require__(83), mapToArray = __webpack_require__(258), setToArray = __webpack_require__(45); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } module.exports = equalByTag; /***/ }, /* 232 */ /***/ function(module, exports, __webpack_require__) { var keys = __webpack_require__(50); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } module.exports = equalObjects; /***/ }, /* 233 */ /***/ function(module, exports, __webpack_require__) { var isStrictComparable = __webpack_require__(86), keys = __webpack_require__(50); /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } module.exports = getMatchData; /***/ }, /* 234 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(88); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }, /* 235 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; /***/ }, /* 236 */ /***/ function(module, exports, __webpack_require__) { var DataView = __webpack_require__(187), Map = __webpack_require__(37), Promise = __webpack_require__(189), Set = __webpack_require__(72), WeakMap = __webpack_require__(191), baseGetTag = __webpack_require__(10), toSource = __webpack_require__(89); /** `Object#toString` result references. */ var mapTag = '[object Map]', objectTag = '[object Object]', promiseTag = '[object Promise]', setTag = '[object Set]', weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } module.exports = getTag; /***/ }, /* 237 */ /***/ function(module, exports) { /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } module.exports = getValue; /***/ }, /* 238 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(81), isArguments = __webpack_require__(47), isArray = __webpack_require__(3), isIndex = __webpack_require__(43), isLength = __webpack_require__(48), toKey = __webpack_require__(27); /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } module.exports = hasPath; /***/ }, /* 239 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(26); /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } module.exports = hashClear; /***/ }, /* 240 */ /***/ function(module, exports) { /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } module.exports = hashDelete; /***/ }, /* 241 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(26); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } module.exports = hashGet; /***/ }, /* 242 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(26); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); } module.exports = hashHas; /***/ }, /* 243 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(26); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } module.exports = hashSet; /***/ }, /* 244 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(15), isArguments = __webpack_require__(47), isArray = __webpack_require__(3); /** Built-in value references. */ var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } module.exports = isFlattenable; /***/ }, /* 245 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(16), isArrayLike = __webpack_require__(17), isIndex = __webpack_require__(43), isObject = __webpack_require__(8); /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } module.exports = isIterateeCall; /***/ }, /* 246 */ /***/ function(module, exports) { /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } module.exports = isKeyable; /***/ }, /* 247 */ /***/ function(module, exports, __webpack_require__) { var coreJsData = __webpack_require__(225); /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } module.exports = isMasked; /***/ }, /* 248 */ /***/ function(module, exports) { /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } module.exports = listCacheClear; /***/ }, /* 249 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(23); /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } module.exports = listCacheDelete; /***/ }, /* 250 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(23); /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } module.exports = listCacheGet; /***/ }, /* 251 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(23); /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } module.exports = listCacheHas; /***/ }, /* 252 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(23); /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } module.exports = listCacheSet; /***/ }, /* 253 */ /***/ function(module, exports, __webpack_require__) { var Hash = __webpack_require__(188), ListCache = __webpack_require__(20), Map = __webpack_require__(37); /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } module.exports = mapCacheClear; /***/ }, /* 254 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(25); /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } module.exports = mapCacheDelete; /***/ }, /* 255 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(25); /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } module.exports = mapCacheGet; /***/ }, /* 256 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(25); /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } module.exports = mapCacheHas; /***/ }, /* 257 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(25); /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } module.exports = mapCacheSet; /***/ }, /* 258 */ /***/ function(module, exports) { /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } module.exports = mapToArray; /***/ }, /* 259 */ /***/ function(module, exports, __webpack_require__) { var memoize = __webpack_require__(93); /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } module.exports = memoizeCapped; /***/ }, /* 260 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(88); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; /***/ }, /* 261 */ /***/ function(module, exports) { /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } module.exports = nativeKeysIn; /***/ }, /* 262 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(84); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55)(module))) /***/ }, /* 263 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; /***/ }, /* 264 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(74); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } module.exports = overRest; /***/ }, /* 265 */ /***/ function(module, exports) { /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } module.exports = setCacheAdd; /***/ }, /* 266 */ /***/ function(module, exports) { /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } module.exports = setCacheHas; /***/ }, /* 267 */ /***/ function(module, exports, __webpack_require__) { var baseSetToString = __webpack_require__(219), shortOut = __webpack_require__(268); /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); module.exports = setToString; /***/ }, /* 268 */ /***/ function(module, exports) { /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } module.exports = shortOut; /***/ }, /* 269 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(20); /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } module.exports = stackClear; /***/ }, /* 270 */ /***/ function(module, exports) { /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } module.exports = stackDelete; /***/ }, /* 271 */ /***/ function(module, exports) { /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } module.exports = stackGet; /***/ }, /* 272 */ /***/ function(module, exports) { /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } module.exports = stackHas; /***/ }, /* 273 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(20), Map = __webpack_require__(37), MapCache = __webpack_require__(38); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } module.exports = stackSet; /***/ }, /* 274 */ /***/ function(module, exports) { /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } module.exports = strictIndexOf; /***/ }, /* 275 */ /***/ function(module, exports, __webpack_require__) { var memoizeCapped = __webpack_require__(259); /** Used to match property names within property paths. */ var reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); module.exports = stringToPath; /***/ }, /* 276 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(224), createAssigner = __webpack_require__(227), keysIn = __webpack_require__(283); /** * This method is like `_.assignIn` except that it accepts `customizer` * which is invoked to produce the assigned values. If `customizer` returns * `undefined`, assignment is handled by the method instead. The `customizer` * is invoked with five arguments: (objValue, srcValue, key, object, source). * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 4.0.0 * @alias extendWith * @category Object * @param {Object} object The destination object. * @param {...Object} sources The source objects. * @param {Function} [customizer] The function to customize assigned values. * @returns {Object} Returns `object`. * @see _.assignWith * @example * * function customizer(objValue, srcValue) { * return _.isUndefined(objValue) ? srcValue : objValue; * } * * var defaults = _.partialRight(_.assignInWith, customizer); * * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { copyObject(source, keysIn(source), object, customizer); }); module.exports = assignInWith; /***/ }, /* 277 */ /***/ function(module, exports) { /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } module.exports = constant; /***/ }, /* 278 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(74), assignInDefaults = __webpack_require__(196), assignInWith = __webpack_require__(276), baseRest = __webpack_require__(11); /** * Assigns own and inherited enumerable string keyed properties of source * objects to the destination object for all destination properties that * resolve to `undefined`. Source objects are applied from left to right. * Once a property is set, additional values of the same property are ignored. * * **Note:** This method mutates `object`. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @see _.defaultsDeep * @example * * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); * // => { 'a': 1, 'b': 2 } */ var defaults = baseRest(function(args) { args.push(undefined, assignInDefaults); return apply(assignInWith, undefined, args); }); module.exports = defaults; /***/ }, /* 279 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(78); /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } module.exports = get; /***/ }, /* 280 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(41), createAggregator = __webpack_require__(226); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an object composed of keys generated from the results of running * each element of `collection` thru `iteratee`. The order of grouped values * is determined by the order they occur in `collection`. The corresponding * value of each key is an array of elements responsible for generating the * key. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 0.1.0 * @category Collection * @param {Array|Object} collection The collection to iterate over. * @param {Function} [iteratee=_.identity] The iteratee to transform keys. * @returns {Object} Returns the composed aggregate object. * @example * * _.groupBy([6.1, 4.2, 6.3], Math.floor); * // => { '4': [4.2], '6': [6.1, 6.3] } * * // The `_.property` iteratee shorthand. * _.groupBy(['one', 'two', 'three'], 'length'); * // => { '3': ['one', 'two'], '5': ['three'] } */ var groupBy = createAggregator(function(result, value, key) { if (hasOwnProperty.call(result, key)) { result[key].push(value); } else { baseAssignValue(result, key, [value]); } }); module.exports = groupBy; /***/ }, /* 281 */ /***/ function(module, exports, __webpack_require__) { var baseHasIn = __webpack_require__(203), hasPath = __webpack_require__(238); /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } module.exports = hasIn; /***/ }, /* 282 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(22), baseIntersection = __webpack_require__(205), baseRest = __webpack_require__(11), castArrayLikeObject = __webpack_require__(223); /** * Creates an array of unique values that are included in all given arrays * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. The order and references of result values are * determined by the first array. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of intersecting values. * @example * * _.intersection([2, 1], [2, 3]); * // => [2] */ var intersection = baseRest(function(arrays) { var mapped = arrayMap(arrays, castArrayLikeObject); return (mapped.length && mapped[0] === arrays[0]) ? baseIntersection(mapped) : []; }); module.exports = intersection; /***/ }, /* 283 */ /***/ function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(75), baseKeysIn = __webpack_require__(214), isArrayLike = __webpack_require__(17); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } module.exports = keysIn; /***/ }, /* 284 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(217), basePropertyDeep = __webpack_require__(218), isKey = __webpack_require__(44), toKey = __webpack_require__(27); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } module.exports = property; /***/ }, /* 285 */ /***/ function(module, exports) { /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = stubFalse; /***/ }, /* 286 */ /***/ function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(221); /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } module.exports = toString; /***/ }, /* 287 */ /***/ function(module, exports, __webpack_require__) { var baseFlatten = __webpack_require__(77), baseRest = __webpack_require__(11), baseUniq = __webpack_require__(80), isArrayLikeObject = __webpack_require__(28); /** * Creates an array of unique values, in order, from all given arrays using * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of combined values. * @example * * _.union([2], [1, 2]); * // => [2, 1] */ var union = baseRest(function(arrays) { return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); }); module.exports = union; /***/ }, /* 288 */ /***/ function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(193), baseRest = __webpack_require__(11), baseXor = __webpack_require__(222), isArrayLikeObject = __webpack_require__(28); /** * Creates an array of unique values that is the * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) * of the given arrays. The order of result values is determined by the order * they occur in the arrays. * * @static * @memberOf _ * @since 2.4.0 * @category Array * @param {...Array} [arrays] The arrays to inspect. * @returns {Array} Returns the new array of filtered values. * @see _.difference, _.without * @example * * _.xor([2, 1], [2, 3]); * // => [1, 3] */ var xor = baseRest(function(arrays) { return baseXor(arrayFilter(arrays, isArrayLikeObject)); }); module.exports = xor; /***/ }, /* 289 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = function (Component) { var displayName = Component.displayName || Component.name || "Component"; return _react2.default.createClass({ displayName: "ContextMenuConnector(" + displayName + ")", getInitialState: function getInitialState() { return { item: _store2.default.getState().currentItem }; }, componentDidMount: function componentDidMount() { this.unsubscribe = _store2.default.subscribe(this.handleUpdate); }, componentWillUnmount: function componentWillUnmount() { this.unsubscribe(); }, handleUpdate: function handleUpdate() { this.setState(this.getInitialState()); }, render: function render() { return _react2.default.createElement(Component, _extends({}, this.props, { item: this.state.item })); } }); }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _store = __webpack_require__(29); var _store2 = _interopRequireDefault(_store); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }, /* 290 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _store = __webpack_require__(29); var _store2 = _interopRequireDefault(_store); var _wrapper = __webpack_require__(291); var _wrapper2 = _interopRequireDefault(_wrapper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var PropTypes = _react2.default.PropTypes; var ContextMenu = _react2.default.createClass({ displayName: "ContextMenu", propTypes: { identifier: PropTypes.string.isRequired }, getInitialState: function getInitialState() { return _store2.default.getState(); }, componentDidMount: function componentDidMount() { this.unsubscribe = _store2.default.subscribe(this.handleUpdate); }, componentWillUnmount: function componentWillUnmount() { if (this.unsubscribe) this.unsubscribe(); }, handleUpdate: function handleUpdate() { this.setState(this.getInitialState()); }, render: function render() { return _react2.default.createElement(_wrapper2.default, _extends({}, this.props, this.state)); } }); exports.default = ContextMenu; /***/ }, /* 291 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _monitor = __webpack_require__(51); var _monitor2 = _interopRequireDefault(_monitor); var _Modal = __webpack_require__(319); var _Modal2 = _interopRequireDefault(_Modal); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var modalStyle = { position: "fixed", zIndex: 1040, top: 0, bottom: 0, left: 0, right: 0 }, backdropStyle = _extends({}, modalStyle, { zIndex: "auto", backgroundColor: "transparent" }), menuStyles = { position: "fixed", zIndex: "auto" }; var ContextMenuWrapper = _react2.default.createClass({ displayName: "ContextMenuWrapper", getInitialState: function getInitialState() { return { left: 0, top: 0 }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var _this = this; if (nextProps.isVisible === nextProps.identifier) { var wrapper = window.requestAnimationFrame || setTimeout; wrapper(function () { _this.setState(_this.getMenuPosition(nextProps.x, nextProps.y)); _this.menu.parentNode.addEventListener("contextmenu", _this.hideMenu); }); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return this.props.isVisible !== nextProps.visible; }, hideMenu: function hideMenu(e) { e.preventDefault(); this.menu.parentNode.removeEventListener("contextmenu", this.hideMenu); _monitor2.default.hideMenu(); }, getMenuPosition: function getMenuPosition(x, y) { var scrollX = document.documentElement.scrollTop; var scrollY = document.documentElement.scrollLeft; var _window = window; var innerWidth = _window.innerWidth; var innerHeight = _window.innerHeight; var rect = this.menu.getBoundingClientRect(); var menuStyles = { top: y + scrollY, left: x + scrollX }; if (y + rect.height > innerHeight) { menuStyles.top -= rect.height; } if (x + rect.width > innerWidth) { menuStyles.left -= rect.width; } return menuStyles; }, render: function render() { var _this2 = this; var _props = this.props; var isVisible = _props.isVisible; var identifier = _props.identifier; var children = _props.children; var style = _extends({}, menuStyles, this.state); return _react2.default.createElement( _Modal2.default, { style: modalStyle, backdropStyle: backdropStyle, show: isVisible === identifier, onHide: function onHide() { return _monitor2.default.hideMenu(); } }, _react2.default.createElement( "nav", { ref: function ref(c) { return _this2.menu = c; }, style: style, className: "react-context-menu" }, children ) ); } }); exports.default = ContextMenuWrapper; /***/ }, /* 292 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; exports.default = function (identifier, configure) { return function (Component) { var displayName = Component.displayName || Component.name || "Component"; (0, _invariant2.default)(identifier && (typeof identifier === "string" || (typeof identifier === "undefined" ? "undefined" : _typeof(identifier)) === "symbol" || typeof identifier === "function"), "Expected identifier to be string, symbol or function. See %s", displayName); if (configure) { (0, _invariant2.default)(typeof configure === "function", "Expected configure to be a function. See %s", displayName); } return _react2.default.createClass({ displayName: displayName + "ContextMenuLayer", getDefaultProps: function getDefaultProps() { return { renderTag: "div", attributes: {} }; }, mouseDown: false, handleMouseDown: function handleMouseDown(event) { var _this = this; if (this.props.holdToDisplay >= 0 && event.button === 0) { event.persist(); this.mouseDown = true; setTimeout(function () { if (_this.mouseDown) _this.handleContextClick(event); }, this.props.holdToDisplay); } }, handleTouchstart: function handleTouchstart(event) { var _this2 = this; event.persist(); this.mouseDown = true; setTimeout(function () { if (_this2.mouseDown) _this2.handleContextClick(event); }, this.props.holdToDisplay); }, handleTouchEnd: function handleTouchEnd(event) { event.preventDefault(); this.mouseDown = false; }, handleMouseUp: function handleMouseUp(event) { if (event.button === 0) { this.mouseDown = false; } }, handleContextClick: function handleContextClick(event) { var currentItem = typeof configure === "function" ? configure(this.props) : {}; (0, _invariant2.default)((0, _lodash2.default)(currentItem), "Expected configure to return an object. See %s", displayName); event.preventDefault(); var xPos = event.clientX || event.touches && event.touches[0].pageX, yPos = event.clientY || event.touches && event.touches[0].pageY; _store2.default.dispatch({ type: "SET_PARAMS", data: { x: xPos, y: yPos, currentItem: currentItem, isVisible: typeof identifier === "function" ? identifier(this.props) : identifier } }); }, render: function render() { var _props = this.props; var _props$attributes = _props.attributes; var _props$attributes$cla = _props$attributes.className; var className = _props$attributes$cla === undefined ? "" : _props$attributes$cla; var attributes = _objectWithoutProperties(_props$attributes, ["className"]); var renderTag = _props.renderTag; var props = _objectWithoutProperties(_props, ["attributes", "renderTag"]); attributes.className = "react-context-menu-wrapper " + className; attributes.onContextMenu = this.handleContextClick; attributes.onMouseDown = this.handleMouseDown; attributes.onMouseUp = this.handleMouseUp; attributes.onTouchStart = this.handleTouchstart; attributes.onTouchEnd = this.handleTouchEnd; attributes.onMouseOut = this.handleMouseUp; return _react2.default.createElement(renderTag, attributes, _react2.default.createElement(Component, props)); } }); }; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodash = __webpack_require__(186); var _lodash2 = _interopRequireDefault(_lodash); var _store = __webpack_require__(29); var _store2 = _interopRequireDefault(_store); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } /***/ }, /* 293 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(97); var _classnames2 = _interopRequireDefault(_classnames); var _objectAssign = __webpack_require__(98); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _monitor = __webpack_require__(51); var _monitor2 = _interopRequireDefault(_monitor); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var PropTypes = _react2.default.PropTypes; var MenuItem = _react2.default.createClass({ displayName: "MenuItem", propTypes: { onClick: PropTypes.func.isRequired, data: PropTypes.object, disabled: PropTypes.bool, preventClose: PropTypes.bool }, getDefaultProps: function getDefaultProps() { return { disabled: false, data: {}, attributes: {} }; }, handleClick: function handleClick(event) { var _props = this.props; var disabled = _props.disabled; var onClick = _props.onClick; var data = _props.data; var preventClose = _props.preventClose; event.preventDefault(); if (disabled) return; (0, _objectAssign2.default)(data, _monitor2.default.getItem()); if (typeof onClick === "function") { onClick(event, data); } if (preventClose) return; _monitor2.default.hideMenu(); }, render: function render() { var _props2 = this.props; var disabled = _props2.disabled; var children = _props2.children; var _props2$attributes = _props2.attributes; var _props2$attributes$cl = _props2$attributes.className; var className = _props2$attributes$cl === undefined ? "" : _props2$attributes$cl; var props = _objectWithoutProperties(_props2$attributes, ["className"]); var menuItemClassNames = "react-context-menu-item " + className; var classes = (0, _classnames2.default)({ "react-context-menu-link": true, disabled: disabled }); return _react2.default.createElement( "div", _extends({ className: menuItemClassNames }, props), _react2.default.createElement( "a", { href: "#", className: classes, onClick: this.handleClick }, children ) ); } }); exports.default = MenuItem; /***/ }, /* 294 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function () { var state = arguments.length <= 0 || arguments[0] === undefined ? defaultState : arguments[0]; var action = arguments[1]; return action.type === "SET_PARAMS" ? (0, _objectAssign2.default)({}, state, action.data) : state; }; var _objectAssign = __webpack_require__(98); var _objectAssign2 = _interopRequireDefault(_objectAssign); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var defaultState = { x: 0, y: 0, isVisible: false, currentItem: {} }; /***/ }, /* 295 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(97); var _classnames2 = _interopRequireDefault(_classnames); var _wrapper = __webpack_require__(296); var _wrapper2 = _interopRequireDefault(_wrapper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var menuStyles = { position: "relative", zIndex: "auto" }; var SubMenu = _react2.default.createClass({ displayName: "SubMenu", propTypes: { title: _react2.default.PropTypes.string.isRequired, disabled: _react2.default.PropTypes.bool, hoverDelay: _react2.default.PropTypes.number }, getDefaultProps: function getDefaultProps() { return { hoverDelay: 500 }; }, getInitialState: function getInitialState() { return { visible: false }; }, shouldComponentUpdate: function shouldComponentUpdate(nextProps, nextState) { return this.state.isVisible !== nextState.visible; }, componentWillUnmount: function componentWillUnmount() { if (this.opentimer) clearTimeout(this.opentimer); if (this.closetimer) clearTimeout(this.closetimer); }, handleClick: function handleClick(e) { e.preventDefault(); }, handleMouseEnter: function handleMouseEnter() { var _this = this; if (this.closetimer) clearTimeout(this.closetimer); if (this.props.disabled || this.state.visible) return; this.opentimer = setTimeout(function () { return _this.setState({ visible: true }); }, this.props.hoverDelay); }, handleMouseLeave: function handleMouseLeave() { var _this2 = this; if (this.opentimer) clearTimeout(this.opentimer); if (!this.state.visible) return; this.closetimer = setTimeout(function () { return _this2.setState({ visible: false }); }, this.props.hoverDelay); }, render: function render() { var _this3 = this; var _props = this.props; var disabled = _props.disabled; var children = _props.children; var title = _props.title; var visible = this.state.visible; var classes = (0, _classnames2.default)({ "react-context-menu-link": true, disabled: disabled, active: visible }), menuClasses = "react-context-menu-item submenu"; return _react2.default.createElement( "div", { ref: function ref(c) { return _this3.item = c; }, className: menuClasses, style: menuStyles, onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave }, _react2.default.createElement( "a", { href: "#", className: classes, onClick: this.handleClick }, title ), _react2.default.createElement( _wrapper2.default, { visible: visible }, children ) ); } }); exports.default = SubMenu; /***/ }, /* 296 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var SubMenuWrapper = _react2.default.createClass({ displayName: "SubMenuWrapper", propTypes: { visible: _react2.default.PropTypes.bool }, getInitialState: function getInitialState() { return { position: { top: true, right: true } }; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { var _this = this; if (nextProps.visible) { var wrapper = window.requestAnimationFrame || setTimeout; wrapper(function () { _this.setState(_this.getMenuPosition()); _this.forceUpdate(); }); } else { this.setState(this.getInitialState()); } }, shouldComponentUpdate: function shouldComponentUpdate(nextProps) { return this.props.visible !== nextProps.visible; }, getMenuPosition: function getMenuPosition() { var _window = window; var innerWidth = _window.innerWidth; var innerHeight = _window.innerHeight; var rect = this.menu.getBoundingClientRect(); var position = {}; if (rect.bottom > innerHeight) { position.bottom = true; } else { position.top = true; } if (rect.right > innerWidth) { position.left = true; } else { position.right = true; } return { position: position }; }, getPositionStyles: function getPositionStyles() { var style = {}; var position = this.state.position; if (position.top) style.top = 0; if (position.bottom) style.bottom = 0; if (position.right) style.left = "100%"; if (position.left) style.right = "100%"; return style; }, render: function render() { var _this2 = this; var _props = this.props; var children = _props.children; var visible = _props.visible; var style = _extends({ display: visible ? "block" : "none", position: "absolute" }, this.getPositionStyles()); return _react2.default.createElement( "nav", { ref: function ref(c) { return _this2.menu = c; }, style: style, className: "react-context-menu" }, children ); } }); exports.default = SubMenuWrapper; /***/ }, /* 297 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; 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'); } } var _lodashUnion = __webpack_require__(287); var _lodashUnion2 = _interopRequireDefault(_lodashUnion); var _lodashWithout = __webpack_require__(95); var _lodashWithout2 = _interopRequireDefault(_lodashWithout); var EnterLeaveCounter = (function () { function EnterLeaveCounter() { _classCallCheck(this, EnterLeaveCounter); this.entered = []; } EnterLeaveCounter.prototype.enter = function enter(enteringNode) { var previousLength = this.entered.length; this.entered = _lodashUnion2['default'](this.entered.filter(function (node) { return document.documentElement.contains(node) && (!node.contains || node.contains(enteringNode)); }), [enteringNode]); return previousLength === 0 && this.entered.length > 0; }; EnterLeaveCounter.prototype.leave = function leave(leavingNode) { var previousLength = this.entered.length; this.entered = _lodashWithout2['default'](this.entered.filter(function (node) { return document.documentElement.contains(node); }), leavingNode); return previousLength > 0 && this.entered.length === 0; }; EnterLeaveCounter.prototype.reset = function reset() { this.entered = []; }; return EnterLeaveCounter; })(); exports['default'] = EnterLeaveCounter; module.exports = exports['default']; /***/ }, /* 298 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _lodashDefaults = __webpack_require__(278); var _lodashDefaults2 = _interopRequireDefault(_lodashDefaults); var _shallowEqual = __webpack_require__(304); var _shallowEqual2 = _interopRequireDefault(_shallowEqual); var _EnterLeaveCounter = __webpack_require__(297); var _EnterLeaveCounter2 = _interopRequireDefault(_EnterLeaveCounter); var _BrowserDetector = __webpack_require__(99); var _OffsetUtils = __webpack_require__(301); var _NativeDragSources = __webpack_require__(300); var _NativeTypes = __webpack_require__(52); var NativeTypes = _interopRequireWildcard(_NativeTypes); var HTML5Backend = (function () { function HTML5Backend(manager) { _classCallCheck(this, HTML5Backend); this.actions = manager.getActions(); this.monitor = manager.getMonitor(); this.registry = manager.getRegistry(); this.sourcePreviewNodes = {}; this.sourcePreviewNodeOptions = {}; this.sourceNodes = {}; this.sourceNodeOptions = {}; this.enterLeaveCounter = new _EnterLeaveCounter2['default'](); this.getSourceClientOffset = this.getSourceClientOffset.bind(this); this.handleTopDragStart = this.handleTopDragStart.bind(this); this.handleTopDragStartCapture = this.handleTopDragStartCapture.bind(this); this.handleTopDragEndCapture = this.handleTopDragEndCapture.bind(this); this.handleTopDragEnter = this.handleTopDragEnter.bind(this); this.handleTopDragEnterCapture = this.handleTopDragEnterCapture.bind(this); this.handleTopDragLeaveCapture = this.handleTopDragLeaveCapture.bind(this); this.handleTopDragOver = this.handleTopDragOver.bind(this); this.handleTopDragOverCapture = this.handleTopDragOverCapture.bind(this); this.handleTopDrop = this.handleTopDrop.bind(this); this.handleTopDropCapture = this.handleTopDropCapture.bind(this); this.handleSelectStart = this.handleSelectStart.bind(this); this.endDragIfSourceWasRemovedFromDOM = this.endDragIfSourceWasRemovedFromDOM.bind(this); this.endDragNativeItem = this.endDragNativeItem.bind(this); } HTML5Backend.prototype.setup = function setup() { if (typeof window === 'undefined') { return; } if (this.constructor.isSetUp) { throw new Error('Cannot have two HTML5 backends at the same time.'); } this.constructor.isSetUp = true; this.addEventListeners(window); }; HTML5Backend.prototype.teardown = function teardown() { if (typeof window === 'undefined') { return; } this.constructor.isSetUp = false; this.removeEventListeners(window); this.clearCurrentDragSourceNode(); }; HTML5Backend.prototype.addEventListeners = function addEventListeners(target) { target.addEventListener('dragstart', this.handleTopDragStart); target.addEventListener('dragstart', this.handleTopDragStartCapture, true); target.addEventListener('dragend', this.handleTopDragEndCapture, true); target.addEventListener('dragenter', this.handleTopDragEnter); target.addEventListener('dragenter', this.handleTopDragEnterCapture, true); target.addEventListener('dragleave', this.handleTopDragLeaveCapture, true); target.addEventListener('dragover', this.handleTopDragOver); target.addEventListener('dragover', this.handleTopDragOverCapture, true); target.addEventListener('drop', this.handleTopDrop); target.addEventListener('drop', this.handleTopDropCapture, true); }; HTML5Backend.prototype.removeEventListeners = function removeEventListeners(target) { target.removeEventListener('dragstart', this.handleTopDragStart); target.removeEventListener('dragstart', this.handleTopDragStartCapture, true); target.removeEventListener('dragend', this.handleTopDragEndCapture, true); target.removeEventListener('dragenter', this.handleTopDragEnter); target.removeEventListener('dragenter', this.handleTopDragEnterCapture, true); target.removeEventListener('dragleave', this.handleTopDragLeaveCapture, true); target.removeEventListener('dragover', this.handleTopDragOver); target.removeEventListener('dragover', this.handleTopDragOverCapture, true); target.removeEventListener('drop', this.handleTopDrop); target.removeEventListener('drop', this.handleTopDropCapture, true); }; HTML5Backend.prototype.connectDragPreview = function connectDragPreview(sourceId, node, options) { var _this = this; this.sourcePreviewNodeOptions[sourceId] = options; this.sourcePreviewNodes[sourceId] = node; return function () { delete _this.sourcePreviewNodes[sourceId]; delete _this.sourcePreviewNodeOptions[sourceId]; }; }; HTML5Backend.prototype.connectDragSource = function connectDragSource(sourceId, node, options) { var _this2 = this; this.sourceNodes[sourceId] = node; this.sourceNodeOptions[sourceId] = options; var handleDragStart = function handleDragStart(e) { return _this2.handleDragStart(e, sourceId); }; var handleSelectStart = function handleSelectStart(e) { return _this2.handleSelectStart(e, sourceId); }; node.setAttribute('draggable', true); node.addEventListener('dragstart', handleDragStart); node.addEventListener('selectstart', handleSelectStart); return function () { delete _this2.sourceNodes[sourceId]; delete _this2.sourceNodeOptions[sourceId]; node.removeEventListener('dragstart', handleDragStart); node.removeEventListener('selectstart', handleSelectStart); node.setAttribute('draggable', false); }; }; HTML5Backend.prototype.connectDropTarget = function connectDropTarget(targetId, node) { var _this3 = this; var handleDragEnter = function handleDragEnter(e) { return _this3.handleDragEnter(e, targetId); }; var handleDragOver = function handleDragOver(e) { return _this3.handleDragOver(e, targetId); }; var handleDrop = function handleDrop(e) { return _this3.handleDrop(e, targetId); }; node.addEventListener('dragenter', handleDragEnter); node.addEventListener('dragover', handleDragOver); node.addEventListener('drop', handleDrop); return function () { node.removeEventListener('dragenter', handleDragEnter); node.removeEventListener('dragover', handleDragOver); node.removeEventListener('drop', handleDrop); }; }; HTML5Backend.prototype.getCurrentSourceNodeOptions = function getCurrentSourceNodeOptions() { var sourceId = this.monitor.getSourceId(); var sourceNodeOptions = this.sourceNodeOptions[sourceId]; return _lodashDefaults2['default'](sourceNodeOptions || {}, { dropEffect: 'move' }); }; HTML5Backend.prototype.getCurrentDropEffect = function getCurrentDropEffect() { if (this.isDraggingNativeItem()) { // It makes more sense to default to 'copy' for native resources return 'copy'; } return this.getCurrentSourceNodeOptions().dropEffect; }; HTML5Backend.prototype.getCurrentSourcePreviewNodeOptions = function getCurrentSourcePreviewNodeOptions() { var sourceId = this.monitor.getSourceId(); var sourcePreviewNodeOptions = this.sourcePreviewNodeOptions[sourceId]; return _lodashDefaults2['default'](sourcePreviewNodeOptions || {}, { anchorX: 0.5, anchorY: 0.5, captureDraggingState: false }); }; HTML5Backend.prototype.getSourceClientOffset = function getSourceClientOffset(sourceId) { return _OffsetUtils.getNodeClientOffset(this.sourceNodes[sourceId]); }; HTML5Backend.prototype.isDraggingNativeItem = function isDraggingNativeItem() { var itemType = this.monitor.getItemType(); return Object.keys(NativeTypes).some(function (key) { return NativeTypes[key] === itemType; }); }; HTML5Backend.prototype.beginDragNativeItem = function beginDragNativeItem(type) { this.clearCurrentDragSourceNode(); var SourceType = _NativeDragSources.createNativeDragSource(type); this.currentNativeSource = new SourceType(); this.currentNativeHandle = this.registry.addSource(type, this.currentNativeSource); this.actions.beginDrag([this.currentNativeHandle]); // On Firefox, if mousemove fires, the drag is over but browser failed to tell us. // This is not true for other browsers. if (_BrowserDetector.isFirefox()) { window.addEventListener('mousemove', this.endDragNativeItem, true); } }; HTML5Backend.prototype.endDragNativeItem = function endDragNativeItem() { if (!this.isDraggingNativeItem()) { return; } if (_BrowserDetector.isFirefox()) { window.removeEventListener('mousemove', this.endDragNativeItem, true); } this.actions.endDrag(); this.registry.removeSource(this.currentNativeHandle); this.currentNativeHandle = null; this.currentNativeSource = null; }; HTML5Backend.prototype.endDragIfSourceWasRemovedFromDOM = function endDragIfSourceWasRemovedFromDOM() { var node = this.currentDragSourceNode; if (document.body.contains(node)) { return; } if (this.clearCurrentDragSourceNode()) { this.actions.endDrag(); } }; HTML5Backend.prototype.setCurrentDragSourceNode = function setCurrentDragSourceNode(node) { this.clearCurrentDragSourceNode(); this.currentDragSourceNode = node; this.currentDragSourceNodeOffset = _OffsetUtils.getNodeClientOffset(node); this.currentDragSourceNodeOffsetChanged = false; // Receiving a mouse event in the middle of a dragging operation // means it has ended and the drag source node disappeared from DOM, // so the browser didn't dispatch the dragend event. window.addEventListener('mousemove', this.endDragIfSourceWasRemovedFromDOM, true); }; HTML5Backend.prototype.clearCurrentDragSourceNode = function clearCurrentDragSourceNode() { if (this.currentDragSourceNode) { this.currentDragSourceNode = null; this.currentDragSourceNodeOffset = null; this.currentDragSourceNodeOffsetChanged = false; window.removeEventListener('mousemove', this.endDragIfSourceWasRemovedFromDOM, true); return true; } return false; }; HTML5Backend.prototype.checkIfCurrentDragSourceRectChanged = function checkIfCurrentDragSourceRectChanged() { var node = this.currentDragSourceNode; if (!node) { return false; } if (this.currentDragSourceNodeOffsetChanged) { return true; } this.currentDragSourceNodeOffsetChanged = !_shallowEqual2['default'](_OffsetUtils.getNodeClientOffset(node), this.currentDragSourceNodeOffset); return this.currentDragSourceNodeOffsetChanged; }; HTML5Backend.prototype.handleTopDragStartCapture = function handleTopDragStartCapture() { this.clearCurrentDragSourceNode(); this.dragStartSourceIds = []; }; HTML5Backend.prototype.handleDragStart = function handleDragStart(e, sourceId) { this.dragStartSourceIds.unshift(sourceId); }; HTML5Backend.prototype.handleTopDragStart = function handleTopDragStart(e) { var _this4 = this; var dragStartSourceIds = this.dragStartSourceIds; this.dragStartSourceIds = null; var clientOffset = _OffsetUtils.getEventClientOffset(e); // Don't publish the source just yet (see why below) this.actions.beginDrag(dragStartSourceIds, { publishSource: false, getSourceClientOffset: this.getSourceClientOffset, clientOffset: clientOffset }); var dataTransfer = e.dataTransfer; var nativeType = _NativeDragSources.matchNativeItemType(dataTransfer); if (this.monitor.isDragging()) { if (typeof dataTransfer.setDragImage === 'function') { // Use custom drag image if user specifies it. // If child drag source refuses drag but parent agrees, // use parent's node as drag image. Neither works in IE though. var sourceId = this.monitor.getSourceId(); var sourceNode = this.sourceNodes[sourceId]; var dragPreview = this.sourcePreviewNodes[sourceId] || sourceNode; var _getCurrentSourcePreviewNodeOptions = this.getCurrentSourcePreviewNodeOptions(); var anchorX = _getCurrentSourcePreviewNodeOptions.anchorX; var anchorY = _getCurrentSourcePreviewNodeOptions.anchorY; var anchorPoint = { anchorX: anchorX, anchorY: anchorY }; var dragPreviewOffset = _OffsetUtils.getDragPreviewOffset(sourceNode, dragPreview, clientOffset, anchorPoint); dataTransfer.setDragImage(dragPreview, dragPreviewOffset.x, dragPreviewOffset.y); } try { // Firefox won't drag without setting data dataTransfer.setData('application/json', {}); } catch (err) {} // IE doesn't support MIME types in setData // Store drag source node so we can check whether // it is removed from DOM and trigger endDrag manually. this.setCurrentDragSourceNode(e.target); // Now we are ready to publish the drag source.. or are we not? var _getCurrentSourcePreviewNodeOptions2 = this.getCurrentSourcePreviewNodeOptions(); var captureDraggingState = _getCurrentSourcePreviewNodeOptions2.captureDraggingState; if (!captureDraggingState) { // Usually we want to publish it in the next tick so that browser // is able to screenshot the current (not yet dragging) state. // // It also neatly avoids a situation where render() returns null // in the same tick for the source element, and browser freaks out. setTimeout(function () { return _this4.actions.publishDragSource(); }); } else { // In some cases the user may want to override this behavior, e.g. // to work around IE not supporting custom drag previews. // // When using a custom drag layer, the only way to prevent // the default drag preview from drawing in IE is to screenshot // the dragging state in which the node itself has zero opacity // and height. In this case, though, returning null from render() // will abruptly end the dragging, which is not obvious. // // This is the reason such behavior is strictly opt-in. this.actions.publishDragSource(); } } else if (nativeType) { // A native item (such as URL) dragged from inside the document this.beginDragNativeItem(nativeType); } else if (!dataTransfer.types && (!e.target.hasAttribute || !e.target.hasAttribute('draggable'))) { // Looks like a Safari bug: dataTransfer.types is null, but there was no draggable. // Just let it drag. It's a native type (URL or text) and will be picked up in dragenter handler. return; } else { // If by this time no drag source reacted, tell browser not to drag. e.preventDefault(); } }; HTML5Backend.prototype.handleTopDragEndCapture = function handleTopDragEndCapture() { if (this.clearCurrentDragSourceNode()) { // Firefox can dispatch this event in an infinite loop // if dragend handler does something like showing an alert. // Only proceed if we have not handled it already. this.actions.endDrag(); } }; HTML5Backend.prototype.handleTopDragEnterCapture = function handleTopDragEnterCapture(e) { this.dragEnterTargetIds = []; var isFirstEnter = this.enterLeaveCounter.enter(e.target); if (!isFirstEnter || this.monitor.isDragging()) { return; } var dataTransfer = e.dataTransfer; var nativeType = _NativeDragSources.matchNativeItemType(dataTransfer); if (nativeType) { // A native item (such as file or URL) dragged from outside the document this.beginDragNativeItem(nativeType); } }; HTML5Backend.prototype.handleDragEnter = function handleDragEnter(e, targetId) { this.dragEnterTargetIds.unshift(targetId); }; HTML5Backend.prototype.handleTopDragEnter = function handleTopDragEnter(e) { var _this5 = this; var dragEnterTargetIds = this.dragEnterTargetIds; this.dragEnterTargetIds = []; if (!this.monitor.isDragging()) { // This is probably a native item type we don't understand. return; } if (!_BrowserDetector.isFirefox()) { // Don't emit hover in `dragenter` on Firefox due to an edge case. // If the target changes position as the result of `dragenter`, Firefox // will still happily dispatch `dragover` despite target being no longer // there. The easy solution is to only fire `hover` in `dragover` on FF. this.actions.hover(dragEnterTargetIds, { clientOffset: _OffsetUtils.getEventClientOffset(e) }); } var canDrop = dragEnterTargetIds.some(function (targetId) { return _this5.monitor.canDropOnTarget(targetId); }); if (canDrop) { // IE requires this to fire dragover events e.preventDefault(); e.dataTransfer.dropEffect = this.getCurrentDropEffect(); } }; HTML5Backend.prototype.handleTopDragOverCapture = function handleTopDragOverCapture() { this.dragOverTargetIds = []; }; HTML5Backend.prototype.handleDragOver = function handleDragOver(e, targetId) { this.dragOverTargetIds.unshift(targetId); }; HTML5Backend.prototype.handleTopDragOver = function handleTopDragOver(e) { var _this6 = this; var dragOverTargetIds = this.dragOverTargetIds; this.dragOverTargetIds = []; if (!this.monitor.isDragging()) { // This is probably a native item type we don't understand. // Prevent default "drop and blow away the whole document" action. e.preventDefault(); e.dataTransfer.dropEffect = 'none'; return; } this.actions.hover(dragOverTargetIds, { clientOffset: _OffsetUtils.getEventClientOffset(e) }); var canDrop = dragOverTargetIds.some(function (targetId) { return _this6.monitor.canDropOnTarget(targetId); }); if (canDrop) { // Show user-specified drop effect. e.preventDefault(); e.dataTransfer.dropEffect = this.getCurrentDropEffect(); } else if (this.isDraggingNativeItem()) { // Don't show a nice cursor but still prevent default // "drop and blow away the whole document" action. e.preventDefault(); e.dataTransfer.dropEffect = 'none'; } else if (this.checkIfCurrentDragSourceRectChanged()) { // Prevent animating to incorrect position. // Drop effect must be other than 'none' to prevent animation. e.preventDefault(); e.dataTransfer.dropEffect = 'move'; } }; HTML5Backend.prototype.handleTopDragLeaveCapture = function handleTopDragLeaveCapture(e) { if (this.isDraggingNativeItem()) { e.preventDefault(); } var isLastLeave = this.enterLeaveCounter.leave(e.target); if (!isLastLeave) { return; } if (this.isDraggingNativeItem()) { this.endDragNativeItem(); } }; HTML5Backend.prototype.handleTopDropCapture = function handleTopDropCapture(e) { this.dropTargetIds = []; e.preventDefault(); if (this.isDraggingNativeItem()) { this.currentNativeSource.mutateItemByReadingDataTransfer(e.dataTransfer); } this.enterLeaveCounter.reset(); }; HTML5Backend.prototype.handleDrop = function handleDrop(e, targetId) { this.dropTargetIds.unshift(targetId); }; HTML5Backend.prototype.handleTopDrop = function handleTopDrop(e) { var dropTargetIds = this.dropTargetIds; this.dropTargetIds = []; this.actions.hover(dropTargetIds, { clientOffset: _OffsetUtils.getEventClientOffset(e) }); this.actions.drop(); if (this.isDraggingNativeItem()) { this.endDragNativeItem(); } else { this.endDragIfSourceWasRemovedFromDOM(); } }; HTML5Backend.prototype.handleSelectStart = function handleSelectStart(e) { var target = e.target; // Only IE requires us to explicitly say // we want drag drop operation to start if (typeof target.dragDrop !== 'function') { return; } // Inputs and textareas should be selectable if (target.tagName === 'INPUT' || target.tagName === 'SELECT' || target.tagName === 'TEXTAREA' || target.isContentEditable) { return; } // For other targets, ask IE // to enable drag and drop e.preventDefault(); target.dragDrop(); }; return HTML5Backend; })(); exports['default'] = HTML5Backend; module.exports = exports['default']; /***/ }, /* 299 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var MonotonicInterpolant = (function () { function MonotonicInterpolant(xs, ys) { _classCallCheck(this, MonotonicInterpolant); var length = xs.length; // Rearrange xs and ys so that xs is sorted var indexes = []; for (var i = 0; i < length; i++) { indexes.push(i); } indexes.sort(function (a, b) { return xs[a] < xs[b] ? -1 : 1; }); // Get consecutive differences and slopes var dys = []; var dxs = []; var ms = []; var dx = undefined; var dy = undefined; for (var i = 0; i < length - 1; i++) { dx = xs[i + 1] - xs[i]; dy = ys[i + 1] - ys[i]; dxs.push(dx); dys.push(dy); ms.push(dy / dx); } // Get degree-1 coefficients var c1s = [ms[0]]; for (var i = 0; i < dxs.length - 1; i++) { var _m = ms[i]; var mNext = ms[i + 1]; if (_m * mNext <= 0) { c1s.push(0); } else { dx = dxs[i]; var dxNext = dxs[i + 1]; var common = dx + dxNext; c1s.push(3 * common / ((common + dxNext) / _m + (common + dx) / mNext)); } } c1s.push(ms[ms.length - 1]); // Get degree-2 and degree-3 coefficients var c2s = []; var c3s = []; var m = undefined; for (var i = 0; i < c1s.length - 1; i++) { m = ms[i]; var c1 = c1s[i]; var invDx = 1 / dxs[i]; var common = c1 + c1s[i + 1] - m - m; c2s.push((m - c1 - common) * invDx); c3s.push(common * invDx * invDx); } this.xs = xs; this.ys = ys; this.c1s = c1s; this.c2s = c2s; this.c3s = c3s; } MonotonicInterpolant.prototype.interpolate = function interpolate(x) { var xs = this.xs; var ys = this.ys; var c1s = this.c1s; var c2s = this.c2s; var c3s = this.c3s; // The rightmost point in the dataset should give an exact result var i = xs.length - 1; if (x === xs[i]) { return ys[i]; } // Search for the interval x is in, returning the corresponding y if x is one of the original xs var low = 0; var high = c3s.length - 1; var mid = undefined; while (low <= high) { mid = Math.floor(0.5 * (low + high)); var xHere = xs[mid]; if (xHere < x) { low = mid + 1; } else if (xHere > x) { high = mid - 1; } else { return ys[mid]; } } i = Math.max(0, high); // Interpolate var diff = x - xs[i]; var diffSq = diff * diff; return ys[i] + c1s[i] * diff + c2s[i] * diffSq + c3s[i] * diff * diffSq; }; return MonotonicInterpolant; })(); exports["default"] = MonotonicInterpolant; module.exports = exports["default"]; /***/ }, /* 300 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _nativeTypesConfig; exports.createNativeDragSource = createNativeDragSource; exports.matchNativeItemType = matchNativeItemType; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var _NativeTypes = __webpack_require__(52); var NativeTypes = _interopRequireWildcard(_NativeTypes); function getDataFromDataTransfer(dataTransfer, typesToTry, defaultValue) { var result = typesToTry.reduce(function (resultSoFar, typeToTry) { return resultSoFar || dataTransfer.getData(typeToTry); }, null); return result != null ? // eslint-disable-line eqeqeq result : defaultValue; } var nativeTypesConfig = (_nativeTypesConfig = {}, _defineProperty(_nativeTypesConfig, NativeTypes.FILE, { exposeProperty: 'files', matchesTypes: ['Files'], getData: function getData(dataTransfer) { return Array.prototype.slice.call(dataTransfer.files); } }), _defineProperty(_nativeTypesConfig, NativeTypes.URL, { exposeProperty: 'urls', matchesTypes: ['Url', 'text/uri-list'], getData: function getData(dataTransfer, matchesTypes) { return getDataFromDataTransfer(dataTransfer, matchesTypes, '').split('\n'); } }), _defineProperty(_nativeTypesConfig, NativeTypes.TEXT, { exposeProperty: 'text', matchesTypes: ['Text', 'text/plain'], getData: function getData(dataTransfer, matchesTypes) { return getDataFromDataTransfer(dataTransfer, matchesTypes, ''); } }), _nativeTypesConfig); function createNativeDragSource(type) { var _nativeTypesConfig$type = nativeTypesConfig[type]; var exposeProperty = _nativeTypesConfig$type.exposeProperty; var matchesTypes = _nativeTypesConfig$type.matchesTypes; var getData = _nativeTypesConfig$type.getData; return (function () { function NativeDragSource() { _classCallCheck(this, NativeDragSource); this.item = Object.defineProperties({}, _defineProperty({}, exposeProperty, { get: function get() { console.warn( // eslint-disable-line no-console 'Browser doesn\'t allow reading "' + exposeProperty + '" until the drop event.'); return null; }, configurable: true, enumerable: true })); } NativeDragSource.prototype.mutateItemByReadingDataTransfer = function mutateItemByReadingDataTransfer(dataTransfer) { delete this.item[exposeProperty]; this.item[exposeProperty] = getData(dataTransfer, matchesTypes); }; NativeDragSource.prototype.canDrag = function canDrag() { return true; }; NativeDragSource.prototype.beginDrag = function beginDrag() { return this.item; }; NativeDragSource.prototype.isDragging = function isDragging(monitor, handle) { return handle === monitor.getSourceId(); }; NativeDragSource.prototype.endDrag = function endDrag() {}; return NativeDragSource; })(); } function matchNativeItemType(dataTransfer) { var dataTransferTypes = Array.prototype.slice.call(dataTransfer.types || []); return Object.keys(nativeTypesConfig).filter(function (nativeItemType) { var matchesTypes = nativeTypesConfig[nativeItemType].matchesTypes; return matchesTypes.some(function (t) { return dataTransferTypes.indexOf(t) > -1; }); })[0] || null; } /***/ }, /* 301 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.getNodeClientOffset = getNodeClientOffset; exports.getEventClientOffset = getEventClientOffset; exports.getDragPreviewOffset = getDragPreviewOffset; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _BrowserDetector = __webpack_require__(99); var _MonotonicInterpolant = __webpack_require__(299); var _MonotonicInterpolant2 = _interopRequireDefault(_MonotonicInterpolant); var ELEMENT_NODE = 1; function getNodeClientOffset(node) { var el = node.nodeType === ELEMENT_NODE ? node : node.parentElement; if (!el) { return null; } var _el$getBoundingClientRect = el.getBoundingClientRect(); var top = _el$getBoundingClientRect.top; var left = _el$getBoundingClientRect.left; return { x: left, y: top }; } function getEventClientOffset(e) { return { x: e.clientX, y: e.clientY }; } function getDragPreviewOffset(sourceNode, dragPreview, clientOffset, anchorPoint) { // The browsers will use the image intrinsic size under different conditions. // Firefox only cares if it's an image, but WebKit also wants it to be detached. var isImage = dragPreview.nodeName === 'IMG' && (_BrowserDetector.isFirefox() || !document.documentElement.contains(dragPreview)); var dragPreviewNode = isImage ? sourceNode : dragPreview; var dragPreviewNodeOffsetFromClient = getNodeClientOffset(dragPreviewNode); var offsetFromDragPreview = { x: clientOffset.x - dragPreviewNodeOffsetFromClient.x, y: clientOffset.y - dragPreviewNodeOffsetFromClient.y }; var sourceWidth = sourceNode.offsetWidth; var sourceHeight = sourceNode.offsetHeight; var anchorX = anchorPoint.anchorX; var anchorY = anchorPoint.anchorY; var dragPreviewWidth = isImage ? dragPreview.width : sourceWidth; var dragPreviewHeight = isImage ? dragPreview.height : sourceHeight; // Work around @2x coordinate discrepancies in browsers if (_BrowserDetector.isSafari() && isImage) { dragPreviewHeight /= window.devicePixelRatio; dragPreviewWidth /= window.devicePixelRatio; } else if (_BrowserDetector.isFirefox() && !isImage) { dragPreviewHeight *= window.devicePixelRatio; dragPreviewWidth *= window.devicePixelRatio; } // Interpolate coordinates depending on anchor point // If you know a simpler way to do this, let me know var interpolantX = new _MonotonicInterpolant2['default']([0, 0.5, 1], [ // Dock to the left offsetFromDragPreview.x, // Align at the center offsetFromDragPreview.x / sourceWidth * dragPreviewWidth, // Dock to the right offsetFromDragPreview.x + dragPreviewWidth - sourceWidth]); var interpolantY = new _MonotonicInterpolant2['default']([0, 0.5, 1], [ // Dock to the top offsetFromDragPreview.y, // Align at the center offsetFromDragPreview.y / sourceHeight * dragPreviewHeight, // Dock to the bottom offsetFromDragPreview.y + dragPreviewHeight - sourceHeight]); var x = interpolantX.interpolate(anchorX); var y = interpolantY.interpolate(anchorY); // Work around Safari 8 positioning bug if (_BrowserDetector.isSafari() && isImage) { // We'll have to wait for @3x to see if this is entirely correct y += (window.devicePixelRatio - 1) * dragPreviewHeight; } return { x: x, y: y }; } /***/ }, /* 302 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = getEmptyImage; var emptyImage = undefined; function getEmptyImage() { if (!emptyImage) { emptyImage = new Image(); emptyImage.src = 'data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=='; } return emptyImage; } module.exports = exports['default']; /***/ }, /* 303 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createHTML5Backend; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _HTML5Backend = __webpack_require__(298); var _HTML5Backend2 = _interopRequireDefault(_HTML5Backend); var _getEmptyImage = __webpack_require__(302); var _getEmptyImage2 = _interopRequireDefault(_getEmptyImage); var _NativeTypes = __webpack_require__(52); var NativeTypes = _interopRequireWildcard(_NativeTypes); exports.NativeTypes = NativeTypes; exports.getEmptyImage = _getEmptyImage2['default']; function createHTML5Backend(manager) { return new _HTML5Backend2['default'](manager); } /***/ }, /* 304 */ 53, /* 305 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _slice = Array.prototype.slice; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); exports['default'] = DragDropContext; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _dndCore = __webpack_require__(165); var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _utilsCheckDecoratorArguments = __webpack_require__(30); var _utilsCheckDecoratorArguments2 = _interopRequireDefault(_utilsCheckDecoratorArguments); function DragDropContext(backendOrModule) { _utilsCheckDecoratorArguments2['default'].apply(undefined, ['DragDropContext', 'backend'].concat(_slice.call(arguments))); // Auto-detect ES6 default export for people still using ES5 var backend = undefined; if (typeof backendOrModule === 'object' && typeof backendOrModule['default'] === 'function') { backend = backendOrModule['default']; } else { backend = backendOrModule; } _invariant2['default'](typeof backend === 'function', 'Expected the backend to be a function or an ES6 module exporting a default function. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-drop-context.html'); var childContext = { dragDropManager: new _dndCore.DragDropManager(backend) }; return function decorateContext(DecoratedComponent) { var displayName = DecoratedComponent.displayName || DecoratedComponent.name || 'Component'; return (function (_Component) { _inherits(DragDropContextContainer, _Component); function DragDropContextContainer() { _classCallCheck(this, DragDropContextContainer); _Component.apply(this, arguments); } DragDropContextContainer.prototype.getDecoratedComponentInstance = function getDecoratedComponentInstance() { return this.refs.child; }; DragDropContextContainer.prototype.getManager = function getManager() { return childContext.dragDropManager; }; DragDropContextContainer.prototype.getChildContext = function getChildContext() { return childContext; }; DragDropContextContainer.prototype.render = function render() { return _react2['default'].createElement(DecoratedComponent, _extends({}, this.props, { ref: 'child' })); }; _createClass(DragDropContextContainer, null, [{ key: 'DecoratedComponent', value: DecoratedComponent, enumerable: true }, { key: 'displayName', value: 'DragDropContext(' + displayName + ')', enumerable: true }, { key: 'childContextTypes', value: { dragDropManager: _react.PropTypes.object.isRequired }, enumerable: true }]); return DragDropContextContainer; })(_react.Component); }; } module.exports = exports['default']; /***/ }, /* 306 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _slice = Array.prototype.slice; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); exports['default'] = DragLayer; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _utilsShallowEqual = __webpack_require__(53); var _utilsShallowEqual2 = _interopRequireDefault(_utilsShallowEqual); var _utilsShallowEqualScalar = __webpack_require__(103); var _utilsShallowEqualScalar2 = _interopRequireDefault(_utilsShallowEqualScalar); var _lodashIsPlainObject = __webpack_require__(6); var _lodashIsPlainObject2 = _interopRequireDefault(_lodashIsPlainObject); var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _utilsCheckDecoratorArguments = __webpack_require__(30); var _utilsCheckDecoratorArguments2 = _interopRequireDefault(_utilsCheckDecoratorArguments); function DragLayer(collect) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _utilsCheckDecoratorArguments2['default'].apply(undefined, ['DragLayer', 'collect[, options]'].concat(_slice.call(arguments))); _invariant2['default'](typeof collect === 'function', 'Expected "collect" provided as the first argument to DragLayer ' + 'to be a function that collects props to inject into the component. ', 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-layer.html', collect); _invariant2['default'](_lodashIsPlainObject2['default'](options), 'Expected "options" provided as the second argument to DragLayer to be ' + 'a plain object when specified. ' + 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-layer.html', options); return function decorateLayer(DecoratedComponent) { var _options$arePropsEqual = options.arePropsEqual; var arePropsEqual = _options$arePropsEqual === undefined ? _utilsShallowEqualScalar2['default'] : _options$arePropsEqual; var displayName = DecoratedComponent.displayName || DecoratedComponent.name || 'Component'; return (function (_Component) { _inherits(DragLayerContainer, _Component); DragLayerContainer.prototype.getDecoratedComponentInstance = function getDecoratedComponentInstance() { return this.refs.child; }; DragLayerContainer.prototype.shouldComponentUpdate = function shouldComponentUpdate(nextProps, nextState) { return !arePropsEqual(nextProps, this.props) || !_utilsShallowEqual2['default'](nextState, this.state); }; _createClass(DragLayerContainer, null, [{ key: 'DecoratedComponent', value: DecoratedComponent, enumerable: true }, { key: 'displayName', value: 'DragLayer(' + displayName + ')', enumerable: true }, { key: 'contextTypes', value: { dragDropManager: _react.PropTypes.object.isRequired }, enumerable: true }]); function DragLayerContainer(props, context) { _classCallCheck(this, DragLayerContainer); _Component.call(this, props); this.handleChange = this.handleChange.bind(this); this.manager = context.dragDropManager; _invariant2['default'](typeof this.manager === 'object', 'Could not find the drag and drop manager in the context of %s. ' + 'Make sure to wrap the top-level component of your app with DragDropContext. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-troubleshooting.html#could-not-find-the-drag-and-drop-manager-in-the-context', displayName, displayName); this.state = this.getCurrentState(); } DragLayerContainer.prototype.componentDidMount = function componentDidMount() { this.isCurrentlyMounted = true; var monitor = this.manager.getMonitor(); this.unsubscribeFromOffsetChange = monitor.subscribeToOffsetChange(this.handleChange); this.unsubscribeFromStateChange = monitor.subscribeToStateChange(this.handleChange); this.handleChange(); }; DragLayerContainer.prototype.componentWillUnmount = function componentWillUnmount() { this.isCurrentlyMounted = false; this.unsubscribeFromOffsetChange(); this.unsubscribeFromStateChange(); }; DragLayerContainer.prototype.handleChange = function handleChange() { if (!this.isCurrentlyMounted) { return; } var nextState = this.getCurrentState(); if (!_utilsShallowEqual2['default'](nextState, this.state)) { this.setState(nextState); } }; DragLayerContainer.prototype.getCurrentState = function getCurrentState() { var monitor = this.manager.getMonitor(); return collect(monitor); }; DragLayerContainer.prototype.render = function render() { return _react2['default'].createElement(DecoratedComponent, _extends({}, this.props, this.state, { ref: 'child' })); }; return DragLayerContainer; })(_react.Component); }; } module.exports = exports['default']; /***/ }, /* 307 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _slice = Array.prototype.slice; exports['default'] = DragSource; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodashIsPlainObject = __webpack_require__(6); var _lodashIsPlainObject2 = _interopRequireDefault(_lodashIsPlainObject); var _utilsCheckDecoratorArguments = __webpack_require__(30); var _utilsCheckDecoratorArguments2 = _interopRequireDefault(_utilsCheckDecoratorArguments); var _decorateHandler = __webpack_require__(101); var _decorateHandler2 = _interopRequireDefault(_decorateHandler); var _registerSource = __webpack_require__(315); var _registerSource2 = _interopRequireDefault(_registerSource); var _createSourceFactory = __webpack_require__(310); var _createSourceFactory2 = _interopRequireDefault(_createSourceFactory); var _createSourceMonitor = __webpack_require__(311); var _createSourceMonitor2 = _interopRequireDefault(_createSourceMonitor); var _createSourceConnector = __webpack_require__(309); var _createSourceConnector2 = _interopRequireDefault(_createSourceConnector); var _utilsIsValidType = __webpack_require__(102); var _utilsIsValidType2 = _interopRequireDefault(_utilsIsValidType); function DragSource(type, spec, collect) { var options = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; _utilsCheckDecoratorArguments2['default'].apply(undefined, ['DragSource', 'type, spec, collect[, options]'].concat(_slice.call(arguments))); var getType = type; if (typeof type !== 'function') { _invariant2['default'](_utilsIsValidType2['default'](type), 'Expected "type" provided as the first argument to DragSource to be ' + 'a string, or a function that returns a string given the current props. ' + 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', type); getType = function () { return type; }; } _invariant2['default'](_lodashIsPlainObject2['default'](spec), 'Expected "spec" provided as the second argument to DragSource to be ' + 'a plain object. Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', spec); var createSource = _createSourceFactory2['default'](spec); _invariant2['default'](typeof collect === 'function', 'Expected "collect" provided as the third argument to DragSource to be ' + 'a function that returns a plain object of props to inject. ' + 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', collect); _invariant2['default'](_lodashIsPlainObject2['default'](options), 'Expected "options" provided as the fourth argument to DragSource to be ' + 'a plain object when specified. ' + 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', collect); return function decorateSource(DecoratedComponent) { return _decorateHandler2['default']({ connectBackend: function connectBackend(backend, sourceId) { return backend.connectDragSource(sourceId); }, containerDisplayName: 'DragSource', createHandler: createSource, registerHandler: _registerSource2['default'], createMonitor: _createSourceMonitor2['default'], createConnector: _createSourceConnector2['default'], DecoratedComponent: DecoratedComponent, getType: getType, collect: collect, options: options }); }; } module.exports = exports['default']; /***/ }, /* 308 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _slice = Array.prototype.slice; exports['default'] = DropTarget; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodashIsPlainObject = __webpack_require__(6); var _lodashIsPlainObject2 = _interopRequireDefault(_lodashIsPlainObject); var _utilsCheckDecoratorArguments = __webpack_require__(30); var _utilsCheckDecoratorArguments2 = _interopRequireDefault(_utilsCheckDecoratorArguments); var _decorateHandler = __webpack_require__(101); var _decorateHandler2 = _interopRequireDefault(_decorateHandler); var _registerTarget = __webpack_require__(316); var _registerTarget2 = _interopRequireDefault(_registerTarget); var _createTargetFactory = __webpack_require__(313); var _createTargetFactory2 = _interopRequireDefault(_createTargetFactory); var _createTargetMonitor = __webpack_require__(314); var _createTargetMonitor2 = _interopRequireDefault(_createTargetMonitor); var _createTargetConnector = __webpack_require__(312); var _createTargetConnector2 = _interopRequireDefault(_createTargetConnector); var _utilsIsValidType = __webpack_require__(102); var _utilsIsValidType2 = _interopRequireDefault(_utilsIsValidType); function DropTarget(type, spec, collect) { var options = arguments.length <= 3 || arguments[3] === undefined ? {} : arguments[3]; _utilsCheckDecoratorArguments2['default'].apply(undefined, ['DropTarget', 'type, spec, collect[, options]'].concat(_slice.call(arguments))); var getType = type; if (typeof type !== 'function') { _invariant2['default'](_utilsIsValidType2['default'](type, true), 'Expected "type" provided as the first argument to DropTarget to be ' + 'a string, an array of strings, or a function that returns either given ' + 'the current props. Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', type); getType = function () { return type; }; } _invariant2['default'](_lodashIsPlainObject2['default'](spec), 'Expected "spec" provided as the second argument to DropTarget to be ' + 'a plain object. Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', spec); var createTarget = _createTargetFactory2['default'](spec); _invariant2['default'](typeof collect === 'function', 'Expected "collect" provided as the third argument to DropTarget to be ' + 'a function that returns a plain object of props to inject. ' + 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', collect); _invariant2['default'](_lodashIsPlainObject2['default'](options), 'Expected "options" provided as the fourth argument to DropTarget to be ' + 'a plain object when specified. ' + 'Instead, received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', collect); return function decorateTarget(DecoratedComponent) { return _decorateHandler2['default']({ connectBackend: function connectBackend(backend, targetId) { return backend.connectDropTarget(targetId); }, containerDisplayName: 'DropTarget', createHandler: createTarget, registerHandler: _registerTarget2['default'], createMonitor: _createTargetMonitor2['default'], createConnector: _createTargetConnector2['default'], DecoratedComponent: DecoratedComponent, getType: getType, collect: collect, options: options }); }; } module.exports = exports['default']; /***/ }, /* 309 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createSourceConnector; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _wrapConnectorHooks = __webpack_require__(104); var _wrapConnectorHooks2 = _interopRequireDefault(_wrapConnectorHooks); var _areOptionsEqual = __webpack_require__(100); var _areOptionsEqual2 = _interopRequireDefault(_areOptionsEqual); function createSourceConnector(backend) { var currentHandlerId = undefined; var currentDragSourceNode = undefined; var currentDragSourceOptions = undefined; var disconnectCurrentDragSource = undefined; var currentDragPreviewNode = undefined; var currentDragPreviewOptions = undefined; var disconnectCurrentDragPreview = undefined; function reconnectDragSource() { if (disconnectCurrentDragSource) { disconnectCurrentDragSource(); disconnectCurrentDragSource = null; } if (currentHandlerId && currentDragSourceNode) { disconnectCurrentDragSource = backend.connectDragSource(currentHandlerId, currentDragSourceNode, currentDragSourceOptions); } } function reconnectDragPreview() { if (disconnectCurrentDragPreview) { disconnectCurrentDragPreview(); disconnectCurrentDragPreview = null; } if (currentHandlerId && currentDragPreviewNode) { disconnectCurrentDragPreview = backend.connectDragPreview(currentHandlerId, currentDragPreviewNode, currentDragPreviewOptions); } } function receiveHandlerId(handlerId) { if (handlerId === currentHandlerId) { return; } currentHandlerId = handlerId; reconnectDragSource(); reconnectDragPreview(); } var hooks = _wrapConnectorHooks2['default']({ dragSource: function connectDragSource(node, options) { if (node === currentDragSourceNode && _areOptionsEqual2['default'](options, currentDragSourceOptions)) { return; } currentDragSourceNode = node; currentDragSourceOptions = options; reconnectDragSource(); }, dragPreview: function connectDragPreview(node, options) { if (node === currentDragPreviewNode && _areOptionsEqual2['default'](options, currentDragPreviewOptions)) { return; } currentDragPreviewNode = node; currentDragPreviewOptions = options; reconnectDragPreview(); } }); return { receiveHandlerId: receiveHandlerId, hooks: hooks }; } module.exports = exports['default']; /***/ }, /* 310 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createSourceFactory; 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'); } } var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodashIsPlainObject = __webpack_require__(6); var _lodashIsPlainObject2 = _interopRequireDefault(_lodashIsPlainObject); var ALLOWED_SPEC_METHODS = ['canDrag', 'beginDrag', 'canDrag', 'isDragging', 'endDrag']; var REQUIRED_SPEC_METHODS = ['beginDrag']; function createSourceFactory(spec) { Object.keys(spec).forEach(function (key) { _invariant2['default'](ALLOWED_SPEC_METHODS.indexOf(key) > -1, 'Expected the drag source specification to only have ' + 'some of the following keys: %s. ' + 'Instead received a specification with an unexpected "%s" key. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', ALLOWED_SPEC_METHODS.join(', '), key); _invariant2['default'](typeof spec[key] === 'function', 'Expected %s in the drag source specification to be a function. ' + 'Instead received a specification with %s: %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', key, key, spec[key]); }); REQUIRED_SPEC_METHODS.forEach(function (key) { _invariant2['default'](typeof spec[key] === 'function', 'Expected %s in the drag source specification to be a function. ' + 'Instead received a specification with %s: %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', key, key, spec[key]); }); var Source = (function () { function Source(monitor) { _classCallCheck(this, Source); this.monitor = monitor; this.props = null; this.component = null; } Source.prototype.receiveProps = function receiveProps(props) { this.props = props; }; Source.prototype.receiveComponent = function receiveComponent(component) { this.component = component; }; Source.prototype.canDrag = function canDrag() { if (!spec.canDrag) { return true; } return spec.canDrag(this.props, this.monitor); }; Source.prototype.isDragging = function isDragging(globalMonitor, sourceId) { if (!spec.isDragging) { return sourceId === globalMonitor.getSourceId(); } return spec.isDragging(this.props, this.monitor); }; Source.prototype.beginDrag = function beginDrag() { var item = spec.beginDrag(this.props, this.monitor, this.component); if (false) { _invariant2['default'](_lodashIsPlainObject2['default'](item), 'beginDrag() must return a plain object that represents the dragged item. ' + 'Instead received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source.html', item); } return item; }; Source.prototype.endDrag = function endDrag() { if (!spec.endDrag) { return; } spec.endDrag(this.props, this.monitor, this.component); }; return Source; })(); return function createSource(monitor) { return new Source(monitor); }; } module.exports = exports['default']; /***/ }, /* 311 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createSourceMonitor; 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'); } } var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var isCallingCanDrag = false; var isCallingIsDragging = false; var SourceMonitor = (function () { function SourceMonitor(manager) { _classCallCheck(this, SourceMonitor); this.internalMonitor = manager.getMonitor(); } SourceMonitor.prototype.receiveHandlerId = function receiveHandlerId(sourceId) { this.sourceId = sourceId; }; SourceMonitor.prototype.canDrag = function canDrag() { _invariant2['default'](!isCallingCanDrag, 'You may not call monitor.canDrag() inside your canDrag() implementation. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source-monitor.html'); try { isCallingCanDrag = true; return this.internalMonitor.canDragSource(this.sourceId); } finally { isCallingCanDrag = false; } }; SourceMonitor.prototype.isDragging = function isDragging() { _invariant2['default'](!isCallingIsDragging, 'You may not call monitor.isDragging() inside your isDragging() implementation. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drag-source-monitor.html'); try { isCallingIsDragging = true; return this.internalMonitor.isDraggingSource(this.sourceId); } finally { isCallingIsDragging = false; } }; SourceMonitor.prototype.getItemType = function getItemType() { return this.internalMonitor.getItemType(); }; SourceMonitor.prototype.getItem = function getItem() { return this.internalMonitor.getItem(); }; SourceMonitor.prototype.getDropResult = function getDropResult() { return this.internalMonitor.getDropResult(); }; SourceMonitor.prototype.didDrop = function didDrop() { return this.internalMonitor.didDrop(); }; SourceMonitor.prototype.getInitialClientOffset = function getInitialClientOffset() { return this.internalMonitor.getInitialClientOffset(); }; SourceMonitor.prototype.getInitialSourceClientOffset = function getInitialSourceClientOffset() { return this.internalMonitor.getInitialSourceClientOffset(); }; SourceMonitor.prototype.getSourceClientOffset = function getSourceClientOffset() { return this.internalMonitor.getSourceClientOffset(); }; SourceMonitor.prototype.getClientOffset = function getClientOffset() { return this.internalMonitor.getClientOffset(); }; SourceMonitor.prototype.getDifferenceFromInitialOffset = function getDifferenceFromInitialOffset() { return this.internalMonitor.getDifferenceFromInitialOffset(); }; return SourceMonitor; })(); function createSourceMonitor(manager) { return new SourceMonitor(manager); } module.exports = exports['default']; /***/ }, /* 312 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createTargetConnector; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _wrapConnectorHooks = __webpack_require__(104); var _wrapConnectorHooks2 = _interopRequireDefault(_wrapConnectorHooks); var _areOptionsEqual = __webpack_require__(100); var _areOptionsEqual2 = _interopRequireDefault(_areOptionsEqual); function createTargetConnector(backend) { var currentHandlerId = undefined; var currentDropTargetNode = undefined; var currentDropTargetOptions = undefined; var disconnectCurrentDropTarget = undefined; function reconnectDropTarget() { if (disconnectCurrentDropTarget) { disconnectCurrentDropTarget(); disconnectCurrentDropTarget = null; } if (currentHandlerId && currentDropTargetNode) { disconnectCurrentDropTarget = backend.connectDropTarget(currentHandlerId, currentDropTargetNode, currentDropTargetOptions); } } function receiveHandlerId(handlerId) { if (handlerId === currentHandlerId) { return; } currentHandlerId = handlerId; reconnectDropTarget(); } var hooks = _wrapConnectorHooks2['default']({ dropTarget: function connectDropTarget(node, options) { if (node === currentDropTargetNode && _areOptionsEqual2['default'](options, currentDropTargetOptions)) { return; } currentDropTargetNode = node; currentDropTargetOptions = options; reconnectDropTarget(); } }); return { receiveHandlerId: receiveHandlerId, hooks: hooks }; } module.exports = exports['default']; /***/ }, /* 313 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createTargetFactory; 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'); } } var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _lodashIsPlainObject = __webpack_require__(6); var _lodashIsPlainObject2 = _interopRequireDefault(_lodashIsPlainObject); var ALLOWED_SPEC_METHODS = ['canDrop', 'hover', 'drop']; function createTargetFactory(spec) { Object.keys(spec).forEach(function (key) { _invariant2['default'](ALLOWED_SPEC_METHODS.indexOf(key) > -1, 'Expected the drop target specification to only have ' + 'some of the following keys: %s. ' + 'Instead received a specification with an unexpected "%s" key. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', ALLOWED_SPEC_METHODS.join(', '), key); _invariant2['default'](typeof spec[key] === 'function', 'Expected %s in the drop target specification to be a function. ' + 'Instead received a specification with %s: %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', key, key, spec[key]); }); var Target = (function () { function Target(monitor) { _classCallCheck(this, Target); this.monitor = monitor; this.props = null; this.component = null; } Target.prototype.receiveProps = function receiveProps(props) { this.props = props; }; Target.prototype.receiveMonitor = function receiveMonitor(monitor) { this.monitor = monitor; }; Target.prototype.receiveComponent = function receiveComponent(component) { this.component = component; }; Target.prototype.canDrop = function canDrop() { if (!spec.canDrop) { return true; } return spec.canDrop(this.props, this.monitor); }; Target.prototype.hover = function hover() { if (!spec.hover) { return; } spec.hover(this.props, this.monitor, this.component); }; Target.prototype.drop = function drop() { if (!spec.drop) { return; } var dropResult = spec.drop(this.props, this.monitor, this.component); if (false) { _invariant2['default'](typeof dropResult === 'undefined' || _lodashIsPlainObject2['default'](dropResult), 'drop() must either return undefined, or an object that represents the drop result. ' + 'Instead received %s. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target.html', dropResult); } return dropResult; }; return Target; })(); return function createTarget(monitor) { return new Target(monitor); }; } module.exports = exports['default']; /***/ }, /* 314 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = createTargetMonitor; 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'); } } var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var isCallingCanDrop = false; var TargetMonitor = (function () { function TargetMonitor(manager) { _classCallCheck(this, TargetMonitor); this.internalMonitor = manager.getMonitor(); } TargetMonitor.prototype.receiveHandlerId = function receiveHandlerId(targetId) { this.targetId = targetId; }; TargetMonitor.prototype.canDrop = function canDrop() { _invariant2['default'](!isCallingCanDrop, 'You may not call monitor.canDrop() inside your canDrop() implementation. ' + 'Read more: http://gaearon.github.io/react-dnd/docs-drop-target-monitor.html'); try { isCallingCanDrop = true; return this.internalMonitor.canDropOnTarget(this.targetId); } finally { isCallingCanDrop = false; } }; TargetMonitor.prototype.isOver = function isOver(options) { return this.internalMonitor.isOverTarget(this.targetId, options); }; TargetMonitor.prototype.getItemType = function getItemType() { return this.internalMonitor.getItemType(); }; TargetMonitor.prototype.getItem = function getItem() { return this.internalMonitor.getItem(); }; TargetMonitor.prototype.getDropResult = function getDropResult() { return this.internalMonitor.getDropResult(); }; TargetMonitor.prototype.didDrop = function didDrop() { return this.internalMonitor.didDrop(); }; TargetMonitor.prototype.getInitialClientOffset = function getInitialClientOffset() { return this.internalMonitor.getInitialClientOffset(); }; TargetMonitor.prototype.getInitialSourceClientOffset = function getInitialSourceClientOffset() { return this.internalMonitor.getInitialSourceClientOffset(); }; TargetMonitor.prototype.getSourceClientOffset = function getSourceClientOffset() { return this.internalMonitor.getSourceClientOffset(); }; TargetMonitor.prototype.getClientOffset = function getClientOffset() { return this.internalMonitor.getClientOffset(); }; TargetMonitor.prototype.getDifferenceFromInitialOffset = function getDifferenceFromInitialOffset() { return this.internalMonitor.getDifferenceFromInitialOffset(); }; return TargetMonitor; })(); function createTargetMonitor(manager) { return new TargetMonitor(manager); } module.exports = exports['default']; /***/ }, /* 315 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = registerSource; function registerSource(type, source, manager) { var registry = manager.getRegistry(); var sourceId = registry.addSource(type, source); function unregisterSource() { registry.removeSource(sourceId); } return { handlerId: sourceId, unregister: unregisterSource }; } module.exports = exports["default"]; /***/ }, /* 316 */ /***/ function(module, exports) { "use strict"; exports.__esModule = true; exports["default"] = registerTarget; function registerTarget(type, target, manager) { var registry = manager.getRegistry(); var targetId = registry.addTarget(type, target); function unregisterTarget() { registry.removeTarget(targetId); } return { handlerId: targetId, unregister: unregisterTarget }; } module.exports = exports["default"]; /***/ }, /* 317 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = cloneWithRef; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _invariant = __webpack_require__(2); var _invariant2 = _interopRequireDefault(_invariant); var _react = __webpack_require__(1); function cloneWithRef(element, newRef) { var previousRef = element.ref; _invariant2['default'](typeof previousRef !== 'string', 'Cannot connect React DnD to an element with an existing string ref. ' + 'Please convert it to use a callback ref instead, or wrap it into a <span> or <div>. ' + 'Read more: https://facebook.github.io/react/docs/more-about-refs.html#the-ref-callback-attribute'); if (!previousRef) { // When there is no ref on the element, use the new ref directly return _react.cloneElement(element, { ref: newRef }); } return _react.cloneElement(element, { ref: function ref(node) { newRef(node); if (previousRef) { previousRef(node); } } }); } module.exports = exports['default']; /***/ }, /* 318 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var React = __webpack_require__(1); var sizerStyle = { position: 'absolute', top: 0, left: 0, visibility: 'hidden', height: 0, overflow: 'scroll', whiteSpace: 'pre' }; var AutosizeInput = React.createClass({ displayName: 'AutosizeInput', propTypes: { className: React.PropTypes.string, // className for the outer element defaultValue: React.PropTypes.any, // default field value inputClassName: React.PropTypes.string, // className for the input element inputStyle: React.PropTypes.object, // css styles for the input element minWidth: React.PropTypes.oneOfType([// minimum width for input element React.PropTypes.number, React.PropTypes.string]), onChange: React.PropTypes.func, // onChange handler: function(newValue) {} placeholder: React.PropTypes.string, // placeholder text placeholderIsMinWidth: React.PropTypes.bool, // don't collapse size to less than the placeholder style: React.PropTypes.object, // css styles for the outer element value: React.PropTypes.any }, // field value getDefaultProps: function getDefaultProps() { return { minWidth: 1 }; }, getInitialState: function getInitialState() { return { inputWidth: this.props.minWidth }; }, componentDidMount: function componentDidMount() { this.copyInputStyles(); this.updateInputWidth(); }, componentDidUpdate: function componentDidUpdate() { this.updateInputWidth(); }, copyInputStyles: function copyInputStyles() { if (!this.isMounted() || !window.getComputedStyle) { return; } var inputStyle = window.getComputedStyle(this.refs.input); if (!inputStyle) { return; } var widthNode = this.refs.sizer; widthNode.style.fontSize = inputStyle.fontSize; widthNode.style.fontFamily = inputStyle.fontFamily; widthNode.style.fontWeight = inputStyle.fontWeight; widthNode.style.fontStyle = inputStyle.fontStyle; widthNode.style.letterSpacing = inputStyle.letterSpacing; if (this.props.placeholder) { var placeholderNode = this.refs.placeholderSizer; placeholderNode.style.fontSize = inputStyle.fontSize; placeholderNode.style.fontFamily = inputStyle.fontFamily; placeholderNode.style.fontWeight = inputStyle.fontWeight; placeholderNode.style.fontStyle = inputStyle.fontStyle; placeholderNode.style.letterSpacing = inputStyle.letterSpacing; } }, updateInputWidth: function updateInputWidth() { if (!this.isMounted() || typeof this.refs.sizer.scrollWidth === 'undefined') { return; } var newInputWidth = undefined; if (this.props.placeholder && (!this.props.value || this.props.value && this.props.placeholderIsMinWidth)) { newInputWidth = Math.max(this.refs.sizer.scrollWidth, this.refs.placeholderSizer.scrollWidth) + 2; } else { newInputWidth = this.refs.sizer.scrollWidth + 2; } if (newInputWidth < this.props.minWidth) { newInputWidth = this.props.minWidth; } if (newInputWidth !== this.state.inputWidth) { this.setState({ inputWidth: newInputWidth }); } }, getInput: function getInput() { return this.refs.input; }, focus: function focus() { this.refs.input.focus(); }, blur: function blur() { this.refs.input.blur(); }, select: function select() { this.refs.input.select(); }, render: function render() { var sizerValue = this.props.defaultValue || this.props.value || ''; var wrapperStyle = this.props.style || {}; if (!wrapperStyle.display) wrapperStyle.display = 'inline-block'; var inputStyle = _extends({}, this.props.inputStyle); inputStyle.width = this.state.inputWidth + 'px'; inputStyle.boxSizing = 'content-box'; var inputProps = _extends({}, this.props); inputProps.className = this.props.inputClassName; inputProps.style = inputStyle; // ensure props meant for `AutosizeInput` don't end up on the `input` delete inputProps.inputClassName; delete inputProps.inputStyle; delete inputProps.minWidth; delete inputProps.placeholderIsMinWidth; return React.createElement( 'div', { className: this.props.className, style: wrapperStyle }, React.createElement('input', _extends({}, inputProps, { ref: 'input' })), React.createElement( 'div', { ref: 'sizer', style: sizerStyle }, sizerValue ), this.props.placeholder ? React.createElement( 'div', { ref: 'placeholderSizer', style: sizerStyle }, this.props.placeholder ) : null ); } }); module.exports = AutosizeInput; /***/ }, /* 319 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; /*eslint-disable react/prop-types */ var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _warning = __webpack_require__(342); var _warning2 = _interopRequireDefault(_warning); var _componentOrElement = __webpack_require__(107); var _componentOrElement2 = _interopRequireDefault(_componentOrElement); var _elementType = __webpack_require__(326); var _elementType2 = _interopRequireDefault(_elementType); var _Portal = __webpack_require__(321); var _Portal2 = _interopRequireDefault(_Portal); var _ModalManager = __webpack_require__(320); var _ModalManager2 = _interopRequireDefault(_ModalManager); var _ownerDocument = __webpack_require__(106); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); var _addEventListener = __webpack_require__(322); var _addEventListener2 = _interopRequireDefault(_addEventListener); var _addFocusListener = __webpack_require__(323); var _addFocusListener2 = _interopRequireDefault(_addFocusListener); var _inDOM = __webpack_require__(14); var _inDOM2 = _interopRequireDefault(_inDOM); var _activeElement = __webpack_require__(171); var _activeElement2 = _interopRequireDefault(_activeElement); var _contains = __webpack_require__(177); var _contains2 = _interopRequireDefault(_contains); var _getContainer = __webpack_require__(105); var _getContainer2 = _interopRequireDefault(_getContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var modalManager = new _ModalManager2.default(); /** * Love them or hate them, `<Modal/>` provides a solid foundation for creating dialogs, lightboxes, or whatever else. * The Modal component renders its `children` node in front of a backdrop component. * * The Modal offers a few helpful features over using just a `<Portal/>` component and some styles: * * - Manages dialog stacking when one-at-a-time just isn't enough. * - Creates a backdrop, for disabling interaction below the modal. * - It properly manages focus; moving to the modal content, and keeping it there until the modal is closed. * - It disables scrolling of the page content while open. * - Adds the appropriate ARIA roles are automatically. * - Easily pluggable animations via a `<Transition/>` component. * * Note that, in the same way the backdrop element prevents users from clicking or interacting * with the page content underneath the Modal, Screen readers also need to be signaled to not to * interact with page content while the Modal is open. To do this, we use a common technique of applying * the `aria-hidden='true'` attribute to the non-Modal elements in the Modal `container`. This means that for * a Modal to be truly modal, it should have a `container` that is _outside_ your app's * React hierarchy (such as the default: document.body). */ var Modal = _react2.default.createClass({ displayName: 'Modal', propTypes: _extends({}, _Portal2.default.propTypes, { /** * Set the visibility of the Modal */ show: _react2.default.PropTypes.bool, /** * A Node, Component instance, or function that returns either. The Modal is appended to it's container element. * * For the sake of assistive technologies, the container should usually be the document body, so that the rest of the * page content can be placed behind a virtual backdrop as well as a visual one. */ container: _react2.default.PropTypes.oneOfType([_componentOrElement2.default, _react2.default.PropTypes.func]), /** * A callback fired when the Modal is opening. */ onShow: _react2.default.PropTypes.func, /** * A callback fired when either the backdrop is clicked, or the escape key is pressed. * * The `onHide` callback only signals intent from the Modal, * you must actually set the `show` prop to `false` for the Modal to close. */ onHide: _react2.default.PropTypes.func, /** * Include a backdrop component. */ backdrop: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.bool, _react2.default.PropTypes.oneOf(['static'])]), /** * A function that returns a backdrop component. Useful for custom * backdrop rendering. * * ```js * renderBackdrop={props => <MyBackdrop {...props} />} * ``` */ renderBackdrop: _react2.default.PropTypes.func, /** * A callback fired when the escape key, if specified in `keyboard`, is pressed. */ onEscapeKeyUp: _react2.default.PropTypes.func, /** * A callback fired when the backdrop, if specified, is clicked. */ onBackdropClick: _react2.default.PropTypes.func, /** * A style object for the backdrop component. */ backdropStyle: _react2.default.PropTypes.object, /** * A css class or classes for the backdrop component. */ backdropClassName: _react2.default.PropTypes.string, /** * A css class or set of classes applied to the modal container when the modal is open, * and removed when it is closed. */ containerClassName: _react2.default.PropTypes.string, /** * Close the modal when escape key is pressed */ keyboard: _react2.default.PropTypes.bool, /** * A `<Transition/>` component to use for the dialog and backdrop components. */ transition: _elementType2.default, /** * The `timeout` of the dialog transition if specified. This number is used to ensure that * transition callbacks are always fired, even if browser transition events are canceled. * * See the Transition `timeout` prop for more infomation. */ dialogTransitionTimeout: _react2.default.PropTypes.number, /** * The `timeout` of the backdrop transition if specified. This number is used to * ensure that transition callbacks are always fired, even if browser transition events are canceled. * * See the Transition `timeout` prop for more infomation. */ backdropTransitionTimeout: _react2.default.PropTypes.number, /** * When `true` The modal will automatically shift focus to itself when it opens, and * replace it to the last focused element when it closes. This also * works correctly with any Modal children that have the `autoFocus` prop. * * Generally this should never be set to `false` as it makes the Modal less * accessible to assistive technologies, like screen readers. */ autoFocus: _react2.default.PropTypes.bool, /** * When `true` The modal will prevent focus from leaving the Modal while open. * * Generally this should never be set to `false` as it makes the Modal less * accessible to assistive technologies, like screen readers. */ enforceFocus: _react2.default.PropTypes.bool, /** * Callback fired before the Modal transitions in */ onEnter: _react2.default.PropTypes.func, /** * Callback fired as the Modal begins to transition in */ onEntering: _react2.default.PropTypes.func, /** * Callback fired after the Modal finishes transitioning in */ onEntered: _react2.default.PropTypes.func, /** * Callback fired right before the Modal transitions out */ onExit: _react2.default.PropTypes.func, /** * Callback fired as the Modal begins to transition out */ onExiting: _react2.default.PropTypes.func, /** * Callback fired after the Modal finishes transitioning out */ onExited: _react2.default.PropTypes.func, /** * A ModalManager instance used to track and manage the state of open * Modals. Useful when customizing how modals interact within a container */ manager: _react2.default.PropTypes.object.isRequired }), getDefaultProps: function getDefaultProps() { var noop = function noop() {}; return { show: false, backdrop: true, keyboard: true, autoFocus: true, enforceFocus: true, onHide: noop, manager: modalManager, renderBackdrop: function renderBackdrop(props) { return _react2.default.createElement('div', props); } }; }, getInitialState: function getInitialState() { return { exited: !this.props.show }; }, render: function render() { var _props = this.props; var show = _props.show; var container = _props.container; var children = _props.children; var Transition = _props.transition; var backdrop = _props.backdrop; var dialogTransitionTimeout = _props.dialogTransitionTimeout; var className = _props.className; var style = _props.style; var onExit = _props.onExit; var onExiting = _props.onExiting; var onEnter = _props.onEnter; var onEntering = _props.onEntering; var onEntered = _props.onEntered; var dialog = _react2.default.Children.only(children); var mountModal = show || Transition && !this.state.exited; if (!mountModal) { return null; } var _dialog$props = dialog.props; var role = _dialog$props.role; var tabIndex = _dialog$props.tabIndex; if (role === undefined || tabIndex === undefined) { dialog = (0, _react.cloneElement)(dialog, { role: role === undefined ? 'document' : role, tabIndex: tabIndex == null ? '-1' : tabIndex }); } if (Transition) { dialog = _react2.default.createElement( Transition, { transitionAppear: true, unmountOnExit: true, 'in': show, timeout: dialogTransitionTimeout, onExit: onExit, onExiting: onExiting, onExited: this.handleHidden, onEnter: onEnter, onEntering: onEntering, onEntered: onEntered }, dialog ); } return _react2.default.createElement( _Portal2.default, { ref: this.setMountNode, container: container }, _react2.default.createElement( 'div', { ref: 'modal', role: role || 'dialog', style: style, className: className }, backdrop && this.renderBackdrop(), dialog ) ); }, renderBackdrop: function renderBackdrop() { var _this = this; var _props2 = this.props; var backdropStyle = _props2.backdropStyle; var backdropClassName = _props2.backdropClassName; var renderBackdrop = _props2.renderBackdrop; var Transition = _props2.transition; var backdropTransitionTimeout = _props2.backdropTransitionTimeout; var backdropRef = function backdropRef(ref) { return _this.backdrop = ref; }; var backdrop = _react2.default.createElement('div', { ref: backdropRef, style: this.props.backdropStyle, className: this.props.backdropClassName, onClick: this.handleBackdropClick }); if (Transition) { backdrop = _react2.default.createElement( Transition, { transitionAppear: true, 'in': this.props.show, timeout: backdropTransitionTimeout }, renderBackdrop({ ref: backdropRef, style: backdropStyle, className: backdropClassName, onClick: this.handleBackdropClick }) ); } return backdrop; }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (nextProps.show) { this.setState({ exited: false }); } else if (!nextProps.transition) { // Otherwise let handleHidden take care of marking exited. this.setState({ exited: true }); } }, componentWillUpdate: function componentWillUpdate(nextProps) { if (!this.props.show && nextProps.show) { this.checkForFocus(); } }, componentDidMount: function componentDidMount() { if (this.props.show) { this.onShow(); } }, componentDidUpdate: function componentDidUpdate(prevProps) { var transition = this.props.transition; if (prevProps.show && !this.props.show && !transition) { // Otherwise handleHidden will call this. this.onHide(); } else if (!prevProps.show && this.props.show) { this.onShow(); } }, componentWillUnmount: function componentWillUnmount() { var _props3 = this.props; var show = _props3.show; var transition = _props3.transition; if (show || transition && !this.state.exited) { this.onHide(); } }, onShow: function onShow() { var doc = (0, _ownerDocument2.default)(this); var container = (0, _getContainer2.default)(this.props.container, doc.body); this.props.manager.add(this, container, this.props.containerClassName); this._onDocumentKeyupListener = (0, _addEventListener2.default)(doc, 'keyup', this.handleDocumentKeyUp); this._onFocusinListener = (0, _addFocusListener2.default)(this.enforceFocus); this.focus(); if (this.props.onShow) { this.props.onShow(); } }, onHide: function onHide() { this.props.manager.remove(this); this._onDocumentKeyupListener.remove(); this._onFocusinListener.remove(); this.restoreLastFocus(); }, setMountNode: function setMountNode(ref) { this.mountNode = ref ? ref.getMountNode() : ref; }, handleHidden: function handleHidden() { this.setState({ exited: true }); this.onHide(); if (this.props.onExited) { var _props4; (_props4 = this.props).onExited.apply(_props4, arguments); } }, handleBackdropClick: function handleBackdropClick(e) { if (e.target !== e.currentTarget) { return; } if (this.props.onBackdropClick) { this.props.onBackdropClick(e); } if (this.props.backdrop === true) { this.props.onHide(); } }, handleDocumentKeyUp: function handleDocumentKeyUp(e) { if (this.props.keyboard && e.keyCode === 27 && this.isTopModal()) { if (this.props.onEscapeKeyUp) { this.props.onEscapeKeyUp(e); } this.props.onHide(); } }, checkForFocus: function checkForFocus() { if (_inDOM2.default) { this.lastFocus = (0, _activeElement2.default)(); } }, focus: function focus() { var autoFocus = this.props.autoFocus; var modalContent = this.getDialogElement(); var current = (0, _activeElement2.default)((0, _ownerDocument2.default)(this)); var focusInModal = current && (0, _contains2.default)(modalContent, current); if (modalContent && autoFocus && !focusInModal) { this.lastFocus = current; if (!modalContent.hasAttribute('tabIndex')) { modalContent.setAttribute('tabIndex', -1); (0, _warning2.default)(false, 'The modal content node does not accept focus. ' + 'For the benefit of assistive technologies, the tabIndex of the node is being set to "-1".'); } modalContent.focus(); } }, restoreLastFocus: function restoreLastFocus() { // Support: <=IE11 doesn't support `focus()` on svg elements (RB: #917) if (this.lastFocus && this.lastFocus.focus) { this.lastFocus.focus(); this.lastFocus = null; } }, enforceFocus: function enforceFocus() { var enforceFocus = this.props.enforceFocus; if (!enforceFocus || !this.isMounted() || !this.isTopModal()) { return; } var active = (0, _activeElement2.default)((0, _ownerDocument2.default)(this)); var modal = this.getDialogElement(); if (modal && modal !== active && !(0, _contains2.default)(modal, active)) { modal.focus(); } }, //instead of a ref, which might conflict with one the parent applied. getDialogElement: function getDialogElement() { var node = this.refs.modal; return node && node.lastChild; }, isTopModal: function isTopModal() { return this.props.manager.isTopModal(this); } }); Modal.Manager = _ModalManager2.default; exports.default = Modal; module.exports = exports['default']; /***/ }, /* 320 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _style = __webpack_require__(180); var _style2 = _interopRequireDefault(_style); var _class = __webpack_require__(173); var _class2 = _interopRequireDefault(_class); var _scrollbarSize = __webpack_require__(185); var _scrollbarSize2 = _interopRequireDefault(_scrollbarSize); var _isOverflowing = __webpack_require__(324); var _isOverflowing2 = _interopRequireDefault(_isOverflowing); var _manageAriaHidden = __webpack_require__(325); 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 findIndexOf(arr, cb) { var idx = -1; arr.some(function (d, i) { if (cb(d, i)) { idx = i; return true; } }); return idx; } function findContainer(data, modal) { return findIndexOf(data, function (d) { return d.modals.indexOf(modal) !== -1; }); } function setContainerStyle(state, container) { var style = { overflow: 'hidden' }; // we are only interested in the actual `style` here // becasue we will override it state.style = { overflow: container.style.overflow, paddingRight: container.style.paddingRight }; if (state.overflowing) { // use computed style, here to get the real padding // to add our scrollbar width style.paddingRight = parseInt((0, _style2.default)(container, 'paddingRight') || 0, 10) + (0, _scrollbarSize2.default)() + 'px'; } (0, _style2.default)(container, style); } function removeContainerStyle(_ref, container) { var style = _ref.style; Object.keys(style).forEach(function (key) { return container.style[key] = style[key]; }); } /** * Proper state managment for containers and the modals in those containers. * * @internal Used by the Modal to ensure proper styling of containers. */ var ModalManager = function () { function ModalManager() { var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var _ref2$hideSiblingNode = _ref2.hideSiblingNodes; var hideSiblingNodes = _ref2$hideSiblingNode === undefined ? true : _ref2$hideSiblingNode; var _ref2$handleContainer = _ref2.handleContainerOverflow; var handleContainerOverflow = _ref2$handleContainer === undefined ? true : _ref2$handleContainer; _classCallCheck(this, ModalManager); this.hideSiblingNodes = hideSiblingNodes; this.handleContainerOverflow = handleContainerOverflow; this.modals = []; this.containers = []; this.data = []; } _createClass(ModalManager, [{ key: 'add', value: function add(modal, container, className) { var modalIdx = this.modals.indexOf(modal); var containerIdx = this.containers.indexOf(container); if (modalIdx !== -1) { return modalIdx; } modalIdx = this.modals.length; this.modals.push(modal); if (this.hideSiblingNodes) { (0, _manageAriaHidden.hideSiblings)(container, modal.mountNode); } if (containerIdx !== -1) { this.data[containerIdx].modals.push(modal); return modalIdx; } var data = { modals: [modal], //right now only the first modal of a container will have its classes applied classes: className ? className.split(/\s+/) : [], overflowing: (0, _isOverflowing2.default)(container) }; if (this.handleContainerOverflow) { setContainerStyle(data, container); } data.classes.forEach(_class2.default.addClass.bind(null, container)); this.containers.push(container); this.data.push(data); return modalIdx; } }, { key: 'remove', value: function remove(modal) { var modalIdx = this.modals.indexOf(modal); if (modalIdx === -1) { return; } var containerIdx = findContainer(this.data, modal); var data = this.data[containerIdx]; var container = this.containers[containerIdx]; data.modals.splice(data.modals.indexOf(modal), 1); this.modals.splice(modalIdx, 1); // if that was the last modal in a container, // clean up the container if (data.modals.length === 0) { data.classes.forEach(_class2.default.removeClass.bind(null, container)); if (this.handleContainerOverflow) { removeContainerStyle(data, container); } if (this.hideSiblingNodes) { (0, _manageAriaHidden.showSiblings)(container, modal.mountNode); } this.containers.splice(containerIdx, 1); this.data.splice(containerIdx, 1); } else if (this.hideSiblingNodes) { //otherwise make sure the next top modal is visible to a SR (0, _manageAriaHidden.ariaHidden)(false, data.modals[data.modals.length - 1].mountNode); } } }, { key: 'isTopModal', value: function isTopModal(modal) { return !!this.modals.length && this.modals[this.modals.length - 1] === modal; } }]); return ModalManager; }(); exports.default = ModalManager; module.exports = exports['default']; /***/ }, /* 321 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _reactDom = __webpack_require__(5); var _reactDom2 = _interopRequireDefault(_reactDom); var _componentOrElement = __webpack_require__(107); var _componentOrElement2 = _interopRequireDefault(_componentOrElement); var _ownerDocument = __webpack_require__(106); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); var _getContainer = __webpack_require__(105); var _getContainer2 = _interopRequireDefault(_getContainer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy. * You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`. * The children of `<Portal/>` component will be appended to the `container` specified. */ var Portal = _react2.default.createClass({ displayName: 'Portal', propTypes: { /** * A Node, Component instance, or function that returns either. The `container` will have the Portal children * appended to it. */ container: _react2.default.PropTypes.oneOfType([_componentOrElement2.default, _react2.default.PropTypes.func]) }, componentDidMount: function componentDidMount() { this._renderOverlay(); }, componentDidUpdate: function componentDidUpdate() { this._renderOverlay(); }, componentWillReceiveProps: function componentWillReceiveProps(nextProps) { if (this._overlayTarget && nextProps.container !== this.props.container) { this._portalContainerNode.removeChild(this._overlayTarget); this._portalContainerNode = (0, _getContainer2.default)(nextProps.container, (0, _ownerDocument2.default)(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, componentWillUnmount: function componentWillUnmount() { this._unrenderOverlay(); this._unmountOverlayTarget(); }, _mountOverlayTarget: function _mountOverlayTarget() { if (!this._overlayTarget) { this._overlayTarget = document.createElement('div'); this._portalContainerNode = (0, _getContainer2.default)(this.props.container, (0, _ownerDocument2.default)(this).body); this._portalContainerNode.appendChild(this._overlayTarget); } }, _unmountOverlayTarget: function _unmountOverlayTarget() { if (this._overlayTarget) { this._portalContainerNode.removeChild(this._overlayTarget); this._overlayTarget = null; } this._portalContainerNode = null; }, _renderOverlay: function _renderOverlay() { var overlay = !this.props.children ? null : _react2.default.Children.only(this.props.children); // Save reference for future access. if (overlay !== null) { this._mountOverlayTarget(); this._overlayInstance = _reactDom2.default.unstable_renderSubtreeIntoContainer(this, overlay, this._overlayTarget); } else { // Unrender if the component is null for transitions to null this._unrenderOverlay(); this._unmountOverlayTarget(); } }, _unrenderOverlay: function _unrenderOverlay() { if (this._overlayTarget) { _reactDom2.default.unmountComponentAtNode(this._overlayTarget); this._overlayInstance = null; } }, render: function render() { return null; }, getMountNode: function getMountNode() { return this._overlayTarget; }, getOverlayDOMNode: function getOverlayDOMNode() { if (!this.isMounted()) { throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.'); } if (this._overlayInstance) { return _reactDom2.default.findDOMNode(this._overlayInstance); } return null; } }); exports.default = Portal; module.exports = exports['default']; /***/ }, /* 322 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (node, event, handler, capture) { (0, _on2.default)(node, event, handler, capture); return { remove: function remove() { (0, _off2.default)(node, event, handler, capture); } }; }; var _on = __webpack_require__(176); var _on2 = _interopRequireDefault(_on); var _off = __webpack_require__(175); var _off2 = _interopRequireDefault(_off); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = exports['default']; /***/ }, /* 323 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = addFocusListener; /** * Firefox doesn't have a focusin event so using capture is easiest way to get bubbling * IE8 can't do addEventListener, but does have onfocusin, so we use that in ie8 * * We only allow one Listener at a time to avoid stack overflows */ function addFocusListener(handler) { var useFocusin = !document.addEventListener; var remove = void 0; if (useFocusin) { document.attachEvent('onfocusin', handler); remove = function remove() { return document.detachEvent('onfocusin', handler); }; } else { document.addEventListener('focus', handler, true); remove = function remove() { return document.removeEventListener('focus', handler, true); }; } return { remove: remove }; } module.exports = exports['default']; /***/ }, /* 324 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = isOverflowing; var _isWindow = __webpack_require__(178); var _isWindow2 = _interopRequireDefault(_isWindow); var _ownerDocument = __webpack_require__(36); var _ownerDocument2 = _interopRequireDefault(_ownerDocument); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function isBody(node) { return node && node.tagName.toLowerCase() === 'body'; } function bodyIsOverflowing(node) { var doc = (0, _ownerDocument2.default)(node); var win = (0, _isWindow2.default)(doc); var fullWidth = win.innerWidth; // Support: ie8, no innerWidth if (!fullWidth) { var documentElementRect = doc.documentElement.getBoundingClientRect(); fullWidth = documentElementRect.right - Math.abs(documentElementRect.left); } return doc.body.clientWidth < fullWidth; } function isOverflowing(container) { var win = (0, _isWindow2.default)(container); return win || isBody(container) ? bodyIsOverflowing(container) : container.scrollHeight > container.clientHeight; } module.exports = exports['default']; /***/ }, /* 325 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ariaHidden = ariaHidden; exports.hideSiblings = hideSiblings; exports.showSiblings = showSiblings; var BLACKLIST = ['template', 'script', 'style']; var isHidable = function isHidable(_ref) { var nodeType = _ref.nodeType; var tagName = _ref.tagName; return nodeType === 1 && BLACKLIST.indexOf(tagName.toLowerCase()) === -1; }; var siblings = function siblings(container, mount, cb) { mount = [].concat(mount); [].forEach.call(container.children, function (node) { if (mount.indexOf(node) === -1 && isHidable(node)) { cb(node); } }); }; function ariaHidden(show, node) { if (!node) { return; } if (show) { node.setAttribute('aria-hidden', 'true'); } else { node.removeAttribute('aria-hidden'); } } function hideSiblings(container, mountNode) { siblings(container, mountNode, function (node) { return ariaHidden(true, node); }); } function showSiblings(container, mountNode) { siblings(container, mountNode, function (node) { return ariaHidden(false, node); }); } /***/ }, /* 326 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _createChainableTypeChecker = __webpack_require__(108); var _createChainableTypeChecker2 = _interopRequireDefault(_createChainableTypeChecker); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function elementType(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = typeof propValue === 'undefined' ? 'undefined' : _typeof(propValue); if (_react2.default.isValidElement(propValue)) { return new Error('Invalid ' + location + ' `' + propFullName + '` of type ReactElement ' + ('supplied to `' + componentName + '`, expected an element type (a string ') + 'or a ReactClass).'); } if (propType !== 'function' && propType !== 'string') { return new Error('Invalid ' + location + ' `' + propFullName + '` of value `' + propValue + '` ' + ('supplied to `' + componentName + '`, expected an element type (a string ') + 'or a ReactClass).'); } return null; } exports.default = (0, _createChainableTypeChecker2.default)(elementType); /***/ }, /* 327 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(31); var _Select2 = _interopRequireDefault(_Select); var _utilsStripDiacritics = __webpack_require__(111); var _utilsStripDiacritics2 = _interopRequireDefault(_utilsStripDiacritics); var propTypes = { autoload: _react2['default'].PropTypes.bool.isRequired, // automatically call the `loadOptions` prop on-mount; defaults to true cache: _react2['default'].PropTypes.any, // object to use to cache results; set to null/false to disable caching children: _react2['default'].PropTypes.func.isRequired, // Child function responsible for creating the inner Select component; (props: Object): PropTypes.element ignoreAccents: _react2['default'].PropTypes.bool, // strip diacritics when filtering; defaults to true ignoreCase: _react2['default'].PropTypes.bool, // perform case-insensitive filtering; defaults to true loadingPlaceholder: _react.PropTypes.string.isRequired, // replaces the placeholder while options are loading loadOptions: _react2['default'].PropTypes.func.isRequired, // callback to load options asynchronously; (inputValue: string, callback: Function): ?Promise options: _react.PropTypes.array.isRequired, // array of options placeholder: _react2['default'].PropTypes.oneOfType([// field placeholder, displayed when there's no value (shared with Select) _react2['default'].PropTypes.string, _react2['default'].PropTypes.node]), searchPromptText: _react2['default'].PropTypes.oneOfType([// label to prompt for search input _react2['default'].PropTypes.string, _react2['default'].PropTypes.node]) }; var defaultProps = { autoload: true, cache: {}, children: defaultChildren, ignoreAccents: true, ignoreCase: true, loadingPlaceholder: 'Loading...', options: [], searchPromptText: 'Type to search' }; var Async = (function (_Component) { _inherits(Async, _Component); function Async(props, context) { _classCallCheck(this, Async); _get(Object.getPrototypeOf(Async.prototype), 'constructor', this).call(this, props, context); this.state = { isLoading: false, options: props.options }; this._onInputChange = this._onInputChange.bind(this); } _createClass(Async, [{ key: 'componentDidMount', value: function componentDidMount() { var autoload = this.props.autoload; if (autoload) { this.loadOptions(''); } } }, { key: 'componentWillUpdate', value: function componentWillUpdate(nextProps, nextState) { var _this = this; var propertiesToSync = ['options']; propertiesToSync.forEach(function (prop) { if (_this.props[prop] !== nextProps[prop]) { _this.setState(_defineProperty({}, prop, nextProps[prop])); } }); } }, { key: 'loadOptions', value: function loadOptions(inputValue) { var _this2 = this; var _props = this.props; var cache = _props.cache; var loadOptions = _props.loadOptions; if (cache && cache.hasOwnProperty(inputValue)) { this.setState({ options: cache[inputValue] }); return; } var callback = function callback(error, data) { if (callback === _this2._callback) { _this2._callback = null; var options = data && data.options || []; if (cache) { cache[inputValue] = options; } _this2.setState({ isLoading: false, options: options }); } }; // Ignore all but the most recent request this._callback = callback; var promise = loadOptions(inputValue, callback); if (promise) { promise.then(function (data) { return callback(null, data); }, function (error) { return callback(error); }); } if (this._callback && !this.state.isLoading) { this.setState({ isLoading: true }); } return inputValue; } }, { key: '_onInputChange', value: function _onInputChange(inputValue) { var _props2 = this.props; var ignoreAccents = _props2.ignoreAccents; var ignoreCase = _props2.ignoreCase; if (ignoreAccents) { inputValue = (0, _utilsStripDiacritics2['default'])(inputValue); } if (ignoreCase) { inputValue = inputValue.toLowerCase(); } return this.loadOptions(inputValue); } }, { key: 'render', value: function render() { var _props3 = this.props; var children = _props3.children; var loadingPlaceholder = _props3.loadingPlaceholder; var placeholder = _props3.placeholder; var searchPromptText = _props3.searchPromptText; var _state = this.state; var isLoading = _state.isLoading; var options = _state.options; var props = { noResultsText: isLoading ? loadingPlaceholder : searchPromptText, placeholder: isLoading ? loadingPlaceholder : placeholder, options: isLoading ? [] : options }; return children(_extends({}, this.props, props, { isLoading: isLoading, onInputChange: this._onInputChange })); } }]); return Async; })(_react.Component); exports['default'] = Async; Async.propTypes = propTypes; Async.defaultProps = defaultProps; function defaultChildren(props) { return _react2['default'].createElement(_Select2['default'], props); }; module.exports = exports['default']; /***/ }, /* 328 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(31); var _Select2 = _interopRequireDefault(_Select); var AsyncCreatable = _react2['default'].createClass({ displayName: 'AsyncCreatableSelect', render: function render() { var _this = this; return _react2['default'].createElement( _Select2['default'].Async, this.props, function (asyncProps) { return _react2['default'].createElement( _Select2['default'].Creatable, _this.props, function (creatableProps) { return _react2['default'].createElement(_Select2['default'], _extends({}, asyncProps, creatableProps, { onInputChange: function (input) { creatableProps.onInputChange(input); return asyncProps.onInputChange(input); } })); } ); } ); } }); module.exports = AsyncCreatable; /***/ }, /* 329 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _Select = __webpack_require__(31); var _Select2 = _interopRequireDefault(_Select); var _utilsDefaultFilterOptions = __webpack_require__(109); var _utilsDefaultFilterOptions2 = _interopRequireDefault(_utilsDefaultFilterOptions); var _utilsDefaultMenuRenderer = __webpack_require__(110); var _utilsDefaultMenuRenderer2 = _interopRequireDefault(_utilsDefaultMenuRenderer); var Creatable = _react2['default'].createClass({ displayName: 'CreatableSelect', propTypes: { // Child function responsible for creating the inner Select component // This component can be used to compose HOCs (eg Creatable and Async) // (props: Object): PropTypes.element children: _react2['default'].PropTypes.func, // See Select.propTypes.filterOptions filterOptions: _react2['default'].PropTypes.any, // Searches for any matching option within the set of options. // This function prevents duplicate options from being created. // ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean isOptionUnique: _react2['default'].PropTypes.func, // Determines if the current input text represents a valid option. // ({ label: string }): boolean isValidNewOption: _react2['default'].PropTypes.func, // See Select.propTypes.menuRenderer menuRenderer: _react2['default'].PropTypes.any, // Factory to create new option. // ({ label: string, labelKey: string, valueKey: string }): Object newOptionCreator: _react2['default'].PropTypes.func, // See Select.propTypes.options options: _react2['default'].PropTypes.array, // Creates prompt/placeholder option text. // (filterText: string): string promptTextCreator: _react2['default'].PropTypes.func, // Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option. shouldKeyDownEventCreateNewOption: _react2['default'].PropTypes.func }, // Default prop methods statics: { isOptionUnique: isOptionUnique, isValidNewOption: isValidNewOption, newOptionCreator: newOptionCreator, promptTextCreator: promptTextCreator, shouldKeyDownEventCreateNewOption: shouldKeyDownEventCreateNewOption }, getDefaultProps: function getDefaultProps() { return { filterOptions: _utilsDefaultFilterOptions2['default'], isOptionUnique: isOptionUnique, isValidNewOption: isValidNewOption, menuRenderer: _utilsDefaultMenuRenderer2['default'], newOptionCreator: newOptionCreator, promptTextCreator: promptTextCreator, shouldKeyDownEventCreateNewOption: shouldKeyDownEventCreateNewOption }; }, createNewOption: function createNewOption() { var _props = this.props; var isValidNewOption = _props.isValidNewOption; var newOptionCreator = _props.newOptionCreator; var _props$options = _props.options; var options = _props$options === undefined ? [] : _props$options; var shouldKeyDownEventCreateNewOption = _props.shouldKeyDownEventCreateNewOption; if (isValidNewOption({ label: this.inputValue })) { var option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey }); var _isOptionUnique = this.isOptionUnique({ option: option }); // Don't add the same option twice. if (_isOptionUnique) { options.unshift(option); this.select.selectValue(option); } } }, filterOptions: function filterOptions() { var _props2 = this.props; var filterOptions = _props2.filterOptions; var isValidNewOption = _props2.isValidNewOption; var options = _props2.options; var promptTextCreator = _props2.promptTextCreator; // TRICKY Check currently selected options as well. // Don't display a create-prompt for a value that's selected. // This covers async edge-cases where a newly-created Option isn't yet in the async-loaded array. var excludeOptions = arguments[2] || []; var filteredOptions = filterOptions.apply(undefined, arguments) || []; if (isValidNewOption({ label: this.inputValue })) { var _newOptionCreator = this.props.newOptionCreator; var option = _newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey }); // TRICKY Compare to all options (not just filtered options) in case option has already been selected). // For multi-selects, this would remove it from the filtered list. var _isOptionUnique2 = this.isOptionUnique({ option: option, options: excludeOptions.concat(filteredOptions) }); if (_isOptionUnique2) { var _prompt = promptTextCreator(this.inputValue); this._createPlaceholderOption = _newOptionCreator({ label: _prompt, labelKey: this.labelKey, valueKey: this.valueKey }); filteredOptions.unshift(this._createPlaceholderOption); } } return filteredOptions; }, isOptionUnique: function isOptionUnique(_ref2) { var option = _ref2.option; var options = _ref2.options; var isOptionUnique = this.props.isOptionUnique; options = options || this.select.filterOptions(); return isOptionUnique({ labelKey: this.labelKey, option: option, options: options, valueKey: this.valueKey }); }, menuRenderer: function menuRenderer(params) { var menuRenderer = this.props.menuRenderer; return menuRenderer(_extends({}, params, { onSelect: this.onOptionSelect })); }, onInputChange: function onInputChange(input) { // This value may be needed in between Select mounts (when this.select is null) this.inputValue = input; }, onInputKeyDown: function onInputKeyDown(event) { var shouldKeyDownEventCreateNewOption = this.props.shouldKeyDownEventCreateNewOption; var focusedOption = this.select.getFocusedOption(); if (focusedOption && focusedOption === this._createPlaceholderOption && shouldKeyDownEventCreateNewOption({ keyCode: event.keyCode })) { this.createNewOption(); // Prevent decorated Select from doing anything additional with this keyDown event event.preventDefault(); } }, onOptionSelect: function onOptionSelect(option, event) { if (option === this._createPlaceholderOption) { this.createNewOption(); } else { this.select.selectValue(option); } }, render: function render() { var _this = this; var _props3 = this.props; var _props3$children = _props3.children; var children = _props3$children === undefined ? defaultChildren : _props3$children; var newOptionCreator = _props3.newOptionCreator; var shouldKeyDownEventCreateNewOption = _props3.shouldKeyDownEventCreateNewOption; var restProps = _objectWithoutProperties(_props3, ['children', 'newOptionCreator', 'shouldKeyDownEventCreateNewOption']); var props = _extends({}, restProps, { allowCreate: true, filterOptions: this.filterOptions, menuRenderer: this.menuRenderer, onInputChange: this.onInputChange, onInputKeyDown: this.onInputKeyDown, ref: function ref(_ref) { _this.select = _ref; // These values may be needed in between Select mounts (when this.select is null) if (_ref) { _this.labelKey = _ref.props.labelKey; _this.valueKey = _ref.props.valueKey; } } }); return children(props); } }); function defaultChildren(props) { return _react2['default'].createElement(_Select2['default'], props); }; function isOptionUnique(_ref3) { var option = _ref3.option; var options = _ref3.options; var labelKey = _ref3.labelKey; var valueKey = _ref3.valueKey; return options.filter(function (existingOption) { return existingOption[labelKey] === option[labelKey] || existingOption[valueKey] === option[valueKey]; }).length === 0; }; function isValidNewOption(_ref4) { var label = _ref4.label; return !!label; }; function newOptionCreator(_ref5) { var label = _ref5.label; var labelKey = _ref5.labelKey; var valueKey = _ref5.valueKey; var option = {}; option[valueKey] = label; option[labelKey] = label; option.className = 'Select-create-option-placeholder'; return option; }; function promptTextCreator(label) { return 'Create option "' + label + '"'; } function shouldKeyDownEventCreateNewOption(_ref6) { var keyCode = _ref6.keyCode; switch (keyCode) { case 9: // TAB case 13: // ENTER case 188: // COMMA return true; } return false; }; module.exports = Creatable; /***/ }, /* 330 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(32); var _classnames2 = _interopRequireDefault(_classnames); var Option = _react2['default'].createClass({ displayName: 'Option', propTypes: { children: _react2['default'].PropTypes.node, className: _react2['default'].PropTypes.string, // className (based on mouse position) instancePrefix: _react2['default'].PropTypes.string.isRequired, // unique prefix for the ids (used for aria) isDisabled: _react2['default'].PropTypes.bool, // the option is disabled isFocused: _react2['default'].PropTypes.bool, // the option is focused isSelected: _react2['default'].PropTypes.bool, // the option is selected onFocus: _react2['default'].PropTypes.func, // method to handle mouseEnter on option element onSelect: _react2['default'].PropTypes.func, // method to handle click on option element onUnfocus: _react2['default'].PropTypes.func, // method to handle mouseLeave on option element option: _react2['default'].PropTypes.object.isRequired, // object that is base for that option optionIndex: _react2['default'].PropTypes.number }, // index of the option, used to generate unique ids for aria blockEvent: function blockEvent(event) { event.preventDefault(); event.stopPropagation(); if (event.target.tagName !== 'A' || !('href' in event.target)) { return; } if (event.target.target) { window.open(event.target.href, event.target.target); } else { window.location.href = event.target.href; } }, handleMouseDown: function handleMouseDown(event) { event.preventDefault(); event.stopPropagation(); this.props.onSelect(this.props.option, event); }, handleMouseEnter: function handleMouseEnter(event) { this.onFocus(event); }, handleMouseMove: function handleMouseMove(event) { this.onFocus(event); }, handleTouchEnd: function handleTouchEnd(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; this.handleMouseDown(event); }, handleTouchMove: function handleTouchMove(event) { // Set a flag that the view is being dragged this.dragging = true; }, handleTouchStart: function handleTouchStart(event) { // Set a flag that the view is not being dragged this.dragging = false; }, onFocus: function onFocus(event) { if (!this.props.isFocused) { this.props.onFocus(this.props.option, event); } }, render: function render() { var _props = this.props; var option = _props.option; var instancePrefix = _props.instancePrefix; var optionIndex = _props.optionIndex; var className = (0, _classnames2['default'])(this.props.className, option.className); return option.disabled ? _react2['default'].createElement( 'div', { className: className, onMouseDown: this.blockEvent, onClick: this.blockEvent }, this.props.children ) : _react2['default'].createElement( 'div', { className: className, style: option.style, role: 'option', onMouseDown: this.handleMouseDown, onMouseEnter: this.handleMouseEnter, onMouseMove: this.handleMouseMove, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove, onTouchEnd: this.handleTouchEnd, id: instancePrefix + '-option-' + optionIndex, title: option.title }, this.props.children ); } }); module.exports = Option; /***/ }, /* 331 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); var _classnames = __webpack_require__(32); var _classnames2 = _interopRequireDefault(_classnames); var Value = _react2['default'].createClass({ displayName: 'Value', propTypes: { children: _react2['default'].PropTypes.node, disabled: _react2['default'].PropTypes.bool, // disabled prop passed to ReactSelect id: _react2['default'].PropTypes.string, // Unique id for the value - used for aria onClick: _react2['default'].PropTypes.func, // method to handle click on value label onRemove: _react2['default'].PropTypes.func, // method to handle removal of the value value: _react2['default'].PropTypes.object.isRequired }, // the option object for this value handleMouseDown: function handleMouseDown(event) { if (event.type === 'mousedown' && event.button !== 0) { return; } if (this.props.onClick) { event.stopPropagation(); this.props.onClick(this.props.value, event); return; } if (this.props.value.href) { event.stopPropagation(); } }, onRemove: function onRemove(event) { event.preventDefault(); event.stopPropagation(); this.props.onRemove(this.props.value); }, handleTouchEndRemove: function handleTouchEndRemove(event) { // Check if the view is being dragged, In this case // we don't want to fire the click event (because the user only wants to scroll) if (this.dragging) return; // Fire the mouse events this.onRemove(event); }, handleTouchMove: function handleTouchMove(event) { // Set a flag that the view is being dragged this.dragging = true; }, handleTouchStart: function handleTouchStart(event) { // Set a flag that the view is not being dragged this.dragging = false; }, renderRemoveIcon: function renderRemoveIcon() { if (this.props.disabled || !this.props.onRemove) return; return _react2['default'].createElement( 'span', { className: 'Select-value-icon', 'aria-hidden': 'true', onMouseDown: this.onRemove, onTouchEnd: this.handleTouchEndRemove, onTouchStart: this.handleTouchStart, onTouchMove: this.handleTouchMove }, '×' ); }, renderLabel: function renderLabel() { var className = 'Select-value-label'; return this.props.onClick || this.props.value.href ? _react2['default'].createElement( 'a', { className: className, href: this.props.value.href, target: this.props.value.target, onMouseDown: this.handleMouseDown, onTouchEnd: this.handleMouseDown }, this.props.children ) : _react2['default'].createElement( 'span', { className: className, role: 'option', 'aria-selected': 'true', id: this.props.id }, this.props.children ); }, render: function render() { return _react2['default'].createElement( 'div', { className: (0, _classnames2['default'])('Select-value', this.props.value.className), style: this.props.value.style, title: this.props.value.title }, this.renderRemoveIcon(), this.renderLabel() ); } }); module.exports = Value; /***/ }, /* 332 */ /***/ function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = arrowRenderer; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _react = __webpack_require__(1); var _react2 = _interopRequireDefault(_react); function arrowRenderer(_ref) { var onMouseDown = _ref.onMouseDown; return _react2["default"].createElement("span", { className: "Select-arrow", onMouseDown: onMouseDown }); } ; module.exports = exports["default"]; /***/ }, /* 333 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports['default'] = applyMiddleware; var _compose = __webpack_require__(112); var _compose2 = _interopRequireDefault(_compose); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /** * Creates a store enhancer that applies middleware to the dispatch method * of the Redux store. This is handy for a variety of tasks, such as expressing * asynchronous actions in a concise manner, or logging every action payload. * * See `redux-thunk` package as an example of the Redux middleware. * * Because middleware is potentially asynchronous, this should be the first * store enhancer in the composition chain. * * Note that each middleware will be given the `dispatch` and `getState` functions * as named arguments. * * @param {...Function} middlewares The middleware chain to be applied. * @returns {Function} A store enhancer applying the middleware. */ function applyMiddleware() { for (var _len = arguments.length, middlewares = Array(_len), _key = 0; _key < _len; _key++) { middlewares[_key] = arguments[_key]; } return function (createStore) { return function (reducer, preloadedState, enhancer) { var store = createStore(reducer, preloadedState, enhancer); var _dispatch = store.dispatch; var chain = []; var middlewareAPI = { getState: store.getState, dispatch: function dispatch(action) { return _dispatch(action); } }; chain = middlewares.map(function (middleware) { return middleware(middlewareAPI); }); _dispatch = _compose2['default'].apply(undefined, chain)(store.dispatch); return _extends({}, store, { dispatch: _dispatch }); }; }; } /***/ }, /* 334 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports['default'] = bindActionCreators; function bindActionCreator(actionCreator, dispatch) { return function () { return dispatch(actionCreator.apply(undefined, arguments)); }; } /** * Turns an object whose values are action creators, into an object with the * same keys, but with every function wrapped into a `dispatch` call so they * may be invoked directly. This is just a convenience method, as you can call * `store.dispatch(MyActionCreators.doSomething())` yourself just fine. * * For convenience, you can also pass a single function as the first argument, * and get a function in return. * * @param {Function|Object} actionCreators An object whose values are action * creator functions. One handy way to obtain it is to use ES6 `import * as` * syntax. You may also pass a single function. * * @param {Function} dispatch The `dispatch` function available on your Redux * store. * * @returns {Function|Object} The object mimicking the original object, but with * every action creator wrapped into the `dispatch` call. If you passed a * function as `actionCreators`, the return value will also be a single * function. */ function bindActionCreators(actionCreators, dispatch) { if (typeof actionCreators === 'function') { return bindActionCreator(actionCreators, dispatch); } if (typeof actionCreators !== 'object' || actionCreators === null) { throw new Error('bindActionCreators expected an object or a function, instead received ' + (actionCreators === null ? 'null' : typeof actionCreators) + '. ' + 'Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?'); } var keys = Object.keys(actionCreators); var boundActionCreators = {}; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var actionCreator = actionCreators[key]; if (typeof actionCreator === 'function') { boundActionCreators[key] = bindActionCreator(actionCreator, dispatch); } } return boundActionCreators; } /***/ }, /* 335 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports['default'] = combineReducers; var _createStore = __webpack_require__(54); var _isPlainObject = __webpack_require__(6); var _isPlainObject2 = _interopRequireDefault(_isPlainObject); var _warning = __webpack_require__(113); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function getUndefinedStateErrorMessage(key, action) { var actionType = action && action.type; var actionName = actionType && '"' + actionType.toString() + '"' || 'an action'; return 'Given action ' + actionName + ', reducer "' + key + '" returned undefined. ' + 'To ignore an action, you must explicitly return the previous state.'; } function getUnexpectedStateShapeWarningMessage(inputState, reducers, action, unexpectedKeyCache) { var reducerKeys = Object.keys(reducers); var argumentName = action && action.type === _createStore.ActionTypes.INIT ? 'preloadedState argument passed to createStore' : 'previous state received by the reducer'; if (reducerKeys.length === 0) { return 'Store does not have a valid reducer. Make sure the argument passed ' + 'to combineReducers is an object whose values are reducers.'; } if (!(0, _isPlainObject2['default'])(inputState)) { return 'The ' + argumentName + ' has unexpected type of "' + {}.toString.call(inputState).match(/\s([a-z|A-Z]+)/)[1] + '". Expected argument to be an object with the following ' + ('keys: "' + reducerKeys.join('", "') + '"'); } var unexpectedKeys = Object.keys(inputState).filter(function (key) { return !reducers.hasOwnProperty(key) && !unexpectedKeyCache[key]; }); unexpectedKeys.forEach(function (key) { unexpectedKeyCache[key] = true; }); if (unexpectedKeys.length > 0) { return 'Unexpected ' + (unexpectedKeys.length > 1 ? 'keys' : 'key') + ' ' + ('"' + unexpectedKeys.join('", "') + '" found in ' + argumentName + '. ') + 'Expected to find one of the known reducer keys instead: ' + ('"' + reducerKeys.join('", "') + '". Unexpected keys will be ignored.'); } } function assertReducerSanity(reducers) { Object.keys(reducers).forEach(function (key) { var reducer = reducers[key]; var initialState = reducer(undefined, { type: _createStore.ActionTypes.INIT }); if (typeof initialState === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined during initialization. ' + 'If the state passed to the reducer is undefined, you must ' + 'explicitly return the initial state. The initial state may ' + 'not be undefined.'); } var type = '@@redux/PROBE_UNKNOWN_ACTION_' + Math.random().toString(36).substring(7).split('').join('.'); if (typeof reducer(undefined, { type: type }) === 'undefined') { throw new Error('Reducer "' + key + '" returned undefined when probed with a random type. ' + ('Don\'t try to handle ' + _createStore.ActionTypes.INIT + ' or other actions in "redux/*" ') + 'namespace. They are considered private. Instead, you must return the ' + 'current state for any unknown actions, unless it is undefined, ' + 'in which case you must return the initial state, regardless of the ' + 'action type. The initial state may not be undefined.'); } }); } /** * Turns an object whose values are different reducer functions, into a single * reducer function. It will call every child reducer, and gather their results * into a single state object, whose keys correspond to the keys of the passed * reducer functions. * * @param {Object} reducers An object whose values correspond to different * reducer functions that need to be combined into one. One handy way to obtain * it is to use ES6 `import * as reducers` syntax. The reducers may never return * undefined for any action. Instead, they should return their initial state * if the state passed to them was undefined, and the current state for any * unrecognized action. * * @returns {Function} A reducer function that invokes every reducer inside the * passed object, and builds a state object with the same shape. */ function combineReducers(reducers) { var reducerKeys = Object.keys(reducers); var finalReducers = {}; for (var i = 0; i < reducerKeys.length; i++) { var key = reducerKeys[i]; if (false) { if (typeof reducers[key] === 'undefined') { (0, _warning2['default'])('No reducer provided for key "' + key + '"'); } } if (typeof reducers[key] === 'function') { finalReducers[key] = reducers[key]; } } var finalReducerKeys = Object.keys(finalReducers); if (false) { var unexpectedKeyCache = {}; } var sanityError; try { assertReducerSanity(finalReducers); } catch (e) { sanityError = e; } return function combination() { var state = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var action = arguments[1]; if (sanityError) { throw sanityError; } if (false) { var warningMessage = getUnexpectedStateShapeWarningMessage(state, finalReducers, action, unexpectedKeyCache); if (warningMessage) { (0, _warning2['default'])(warningMessage); } } var hasChanged = false; var nextState = {}; for (var i = 0; i < finalReducerKeys.length; i++) { var key = finalReducerKeys[i]; var reducer = finalReducers[key]; var previousStateForKey = state[key]; var nextStateForKey = reducer(previousStateForKey, action); if (typeof nextStateForKey === 'undefined') { var errorMessage = getUndefinedStateErrorMessage(key, action); throw new Error(errorMessage); } nextState[key] = nextStateForKey; hasChanged = hasChanged || nextStateForKey !== previousStateForKey; } return hasChanged ? nextState : state; }; } /***/ }, /* 336 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; exports.compose = exports.applyMiddleware = exports.bindActionCreators = exports.combineReducers = exports.createStore = undefined; var _createStore = __webpack_require__(54); var _createStore2 = _interopRequireDefault(_createStore); var _combineReducers = __webpack_require__(335); var _combineReducers2 = _interopRequireDefault(_combineReducers); var _bindActionCreators = __webpack_require__(334); var _bindActionCreators2 = _interopRequireDefault(_bindActionCreators); var _applyMiddleware = __webpack_require__(333); var _applyMiddleware2 = _interopRequireDefault(_applyMiddleware); var _compose = __webpack_require__(112); var _compose2 = _interopRequireDefault(_compose); var _warning = __webpack_require__(113); var _warning2 = _interopRequireDefault(_warning); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } /* * This is a dummy function to check if the function name has been altered by minification. * If the function has been minified and NODE_ENV !== 'production', warn the user. */ function isCrushed() {} if (false) { (0, _warning2['default'])('You are currently using minified code outside of NODE_ENV === \'production\'. ' + 'This means that you are running a slower development build of Redux. ' + 'You can use loose-envify (https://github.com/zertosh/loose-envify) for browserify ' + 'or DefinePlugin for webpack (http://stackoverflow.com/questions/30030031) ' + 'to ensure you have the correct code for your production build.'); } exports.createStore = _createStore2['default']; exports.combineReducers = _combineReducers2['default']; exports.bindActionCreators = _bindActionCreators2['default']; exports.applyMiddleware = _applyMiddleware2['default']; exports.compose = _compose2['default']; /***/ }, /* 337 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; exports.defaultMemoize = defaultMemoize; exports.createSelectorCreator = createSelectorCreator; exports.createStructuredSelector = createStructuredSelector; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function defaultEqualityCheck(a, b) { return a === b; } function defaultMemoize(func) { var equalityCheck = arguments.length <= 1 || arguments[1] === undefined ? defaultEqualityCheck : arguments[1]; var lastArgs = null; var lastResult = null; return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (lastArgs === null || lastArgs.length !== args.length || !args.every(function (value, index) { return equalityCheck(value, lastArgs[index]); })) { lastResult = func.apply(undefined, args); } lastArgs = args; return lastResult; }; } function getDependencies(funcs) { var dependencies = Array.isArray(funcs[0]) ? funcs[0] : funcs; if (!dependencies.every(function (dep) { return typeof dep === 'function'; })) { var dependencyTypes = dependencies.map(function (dep) { return typeof dep; }).join(', '); throw new Error('Selector creators expect all input-selectors to be functions, ' + ('instead received the following types: [' + dependencyTypes + ']')); } return dependencies; } function createSelectorCreator(memoize) { for (var _len2 = arguments.length, memoizeOptions = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { memoizeOptions[_key2 - 1] = arguments[_key2]; } return function () { for (var _len3 = arguments.length, funcs = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { funcs[_key3] = arguments[_key3]; } var recomputations = 0; var resultFunc = funcs.pop(); var dependencies = getDependencies(funcs); var memoizedResultFunc = memoize.apply(undefined, [function () { recomputations++; return resultFunc.apply(undefined, arguments); }].concat(memoizeOptions)); var selector = function selector(state, props) { for (var _len4 = arguments.length, args = Array(_len4 > 2 ? _len4 - 2 : 0), _key4 = 2; _key4 < _len4; _key4++) { args[_key4 - 2] = arguments[_key4]; } var params = dependencies.map(function (dependency) { return dependency.apply(undefined, [state, props].concat(args)); }); return memoizedResultFunc.apply(undefined, _toConsumableArray(params)); }; selector.resultFunc = resultFunc; selector.recomputations = function () { return recomputations; }; selector.resetRecomputations = function () { return recomputations = 0; }; return selector; }; } var createSelector = exports.createSelector = createSelectorCreator(defaultMemoize); function createStructuredSelector(selectors) { var selectorCreator = arguments.length <= 1 || arguments[1] === undefined ? createSelector : arguments[1]; if (typeof selectors !== 'object') { throw new Error('createStructuredSelector expects first argument to be an object ' + ('where each property is a selector, instead received a ' + typeof selectors)); } var objectKeys = Object.keys(selectors); return selectorCreator(objectKeys.map(function (key) { return selectors[key]; }), function () { for (var _len5 = arguments.length, values = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) { values[_key5] = arguments[_key5]; } return values.reduce(function (composition, value, index) { composition[objectKeys[index]] = value; return composition; }, {}); }); } /***/ }, /* 338 */ /***/ function(module, exports, __webpack_require__) { (function webpackUniversalModuleDefinition(root, factory) { if(true) module.exports = factory(__webpack_require__(1)); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["ReactAutocomplete"] = factory(require("react")); else root["ReactAutocomplete"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_1__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { "use strict"; var React = __webpack_require__(1); var joinClasses = __webpack_require__(2); var Autocomplete = React.createClass({ displayName: "Autocomplete", propTypes: { options: React.PropTypes.any, search: React.PropTypes.func, resultRenderer: React.PropTypes.oneOfType([React.PropTypes.component, React.PropTypes.func]), value: React.PropTypes.object, onChange: React.PropTypes.func, onError: React.PropTypes.func, onFocus: React.PropTypes.func }, getDefaultProps: function () { return { search: searchArray }; }, getInitialState: function () { var searchTerm = this.props.searchTerm ? this.props.searchTerm : this.props.value ? this.props.value.title : ""; return { results: [], showResults: false, showResultsInProgress: false, searchTerm: searchTerm, focusedValue: null }; }, getResultIdentifier: function (result) { if (this.props.resultIdentifier === undefined) { return result.id; } else { return result[this.props.resultIdentifier]; } }, render: function () { var className = joinClasses(this.props.className, "react-autocomplete-Autocomplete", this.state.showResults ? "react-autocomplete-Autocomplete--resultsShown" : undefined); var style = { position: "relative", outline: "none" }; return React.createElement("div", { tabIndex: "1", className: className, onFocus: this.onFocus, onBlur: this.onBlur, style: style }, React.createElement("input", { ref: "search", className: "react-autocomplete-Autocomplete__search", style: { width: "100%" }, onClick: this.showAllResults, onChange: this.onQueryChange, onFocus: this.onSearchInputFocus, onBlur: this.onQueryBlur, onKeyDown: this.onQueryKeyDown, value: this.state.searchTerm }), React.createElement(Results, { className: "react-autocomplete-Autocomplete__results", onSelect: this.onValueChange, onFocus: this.onValueFocus, results: this.state.results, focusedValue: this.state.focusedValue, show: this.state.showResults, renderer: this.props.resultRenderer, label: this.props.label, resultIdentifier: this.props.resultIdentifier })); }, componentWillReceiveProps: function (nextProps) { var searchTerm = nextProps.searchTerm ? nextProps.searchTerm : nextProps.value ? nextProps.value.title : ""; this.setState({ searchTerm: searchTerm }); }, componentWillMount: function () { this.blurTimer = null; }, /** * Show results for a search term value. * * This method doesn't update search term value itself. * * @param {Search} searchTerm */ showResults: function (searchTerm) { this.setState({ showResultsInProgress: true }); this.props.search(this.props.options, searchTerm.trim(), this.onSearchComplete); }, showAllResults: function () { if (!this.state.showResultsInProgress && !this.state.showResults) { this.showResults(""); } }, onValueChange: function (value) { var state = { value: value, showResults: false }; if (value) { state.searchTerm = value.title; } this.setState(state); if (this.props.onChange) { this.props.onChange(value); } }, onSearchComplete: function (err, results) { if (err) { if (this.props.onError) { this.props.onError(err); } else { throw err; } } this.setState({ showResultsInProgress: false, showResults: true, results: results }); }, onValueFocus: function (value) { this.setState({ focusedValue: value }); }, onQueryChange: function (e) { var searchTerm = e.target.value; this.setState({ searchTerm: searchTerm, focusedValue: null }); this.showResults(searchTerm); }, onFocus: function () { if (this.blurTimer) { clearTimeout(this.blurTimer); this.blurTimer = null; } this.refs.search.getDOMNode().focus(); }, onSearchInputFocus: function () { if (this.props.onFocus) { this.props.onFocus(); } this.showAllResults(); }, onBlur: function () { // wrap in setTimeout so we can catch a click on results this.blurTimer = setTimeout((function () { if (this.isMounted()) { this.setState({ showResults: false }); } }).bind(this), 100); }, onQueryKeyDown: function (e) { if (e.key === "Enter") { e.preventDefault(); if (this.state.focusedValue) { this.onValueChange(this.state.focusedValue); } } else if (e.key === "ArrowUp" && this.state.showResults) { e.preventDefault(); var prevIdx = Math.max(this.focusedValueIndex() - 1, 0); this.setState({ focusedValue: this.state.results[prevIdx] }); } else if (e.key === "ArrowDown") { e.preventDefault(); if (this.state.showResults) { var nextIdx = Math.min(this.focusedValueIndex() + (this.state.showResults ? 1 : 0), this.state.results.length - 1); this.setState({ showResults: true, focusedValue: this.state.results[nextIdx] }); } else { this.showAllResults(); } } }, focusedValueIndex: function () { if (!this.state.focusedValue) { return -1; } for (var i = 0, len = this.state.results.length; i < len; i++) { if (this.getResultIdentifier(this.state.results[i]) === this.getResultIdentifier(this.state.focusedValue)) { return i; } } return -1; } }); var Results = React.createClass({ displayName: "Results", getResultIdentifier: function (result) { if (this.props.resultIdentifier === undefined) { if (!result.id) { throw "id property not found on result. You must specify a resultIdentifier and pass as props to autocomplete component"; } return result.id; } else { return result[this.props.resultIdentifier]; } }, render: function () { var style = { display: this.props.show ? "block" : "none", position: "absolute", listStyleType: "none" }; var $__0 = this.props, className = $__0.className, props = (function (source, exclusion) { var rest = {};var hasOwn = Object.prototype.hasOwnProperty;if (source == null) { throw new TypeError(); }for (var key in source) { if (hasOwn.call(source, key) && !hasOwn.call(exclusion, key)) { rest[key] = source[key]; } }return rest; })($__0, { className: 1 }); return React.createElement("ul", React.__spread({}, props, { style: style, className: className + " react-autocomplete-Results" }), this.props.results.map(this.renderResult)); }, renderResult: function (result) { var focused = this.props.focusedValue && this.getResultIdentifier(this.props.focusedValue) === this.getResultIdentifier(result); var Renderer = this.props.renderer || Result; return React.createElement(Renderer, { ref: focused ? "focused" : undefined, key: this.getResultIdentifier(result), result: result, focused: focused, onMouseEnter: this.onMouseEnterResult, onClick: this.props.onSelect, label: this.props.label }); }, componentDidUpdate: function () { this.scrollToFocused(); }, componentDidMount: function () { this.scrollToFocused(); }, componentWillMount: function () { this.ignoreFocus = false; }, scrollToFocused: function () { var focused = this.refs && this.refs.focused; if (focused) { var containerNode = this.getDOMNode(); var scroll = containerNode.scrollTop; var height = containerNode.offsetHeight; var node = focused.getDOMNode(); var top = node.offsetTop; var bottom = top + node.offsetHeight; // we update ignoreFocus to true if we change the scroll position so // the mouseover event triggered because of that won't have an // effect if (top < scroll) { this.ignoreFocus = true; containerNode.scrollTop = top; } else if (bottom - scroll > height) { this.ignoreFocus = true; containerNode.scrollTop = bottom - height; } } }, onMouseEnterResult: function (e, result) { // check if we need to prevent the next onFocus event because it was // probably caused by a mouseover due to scroll position change if (this.ignoreFocus) { this.ignoreFocus = false; } else { // we need to make sure focused node is visible // for some reason mouse events fire on visible nodes due to // box-shadow var containerNode = this.getDOMNode(); var scroll = containerNode.scrollTop; var height = containerNode.offsetHeight; var node = e.target; var top = node.offsetTop; var bottom = top + node.offsetHeight; if (bottom > scroll && top < scroll + height) { this.props.onFocus(result); } } } }); var Result = React.createClass({ displayName: "Result", getDefaultProps: function () { return { label: function (result) { return result.title; } }; }, getLabel: function (result) { if (typeof this.props.label === "function") { return this.props.label(result); } else if (typeof this.props.label === "string") { return result[this.props.label]; } }, render: function () { var className = joinClasses({ "react-autocomplete-Result": true, "react-autocomplete-Result--active": this.props.focused }); return React.createElement("li", { style: { listStyleType: "none" }, className: className, onClick: this.onClick, onMouseEnter: this.onMouseEnter }, React.createElement("a", null, this.getLabel(this.props.result))); }, onClick: function () { this.props.onClick(this.props.result); }, onMouseEnter: function (e) { if (this.props.onMouseEnter) { this.props.onMouseEnter(e, this.props.result); } }, shouldComponentUpdate: function (nextProps) { return nextProps.result.id !== this.props.result.id || nextProps.focused !== this.props.focused; } }); /** * Search options using specified search term treating options as an array * of candidates. * * @param {Array.<Object>} options * @param {String} searchTerm * @param {Callback} cb */ function searchArray(options, searchTerm, cb) { if (!options) { return cb(null, []); } searchTerm = new RegExp(searchTerm, "i"); var results = []; for (var i = 0, len = options.length; i < len; i++) { if (searchTerm.exec(options[i].title)) { results.push(options[i]); } } cb(null, results); } module.exports = Autocomplete; /***/ }, /* 1 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_1__; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ function classNames() { var classes = ''; var arg; for (var i = 0; i < arguments.length; i++) { arg = arguments[i]; if (!arg) { continue; } if ('string' === typeof arg || 'number' === typeof arg) { classes += ' ' + arg; } else if (Object.prototype.toString.call(arg) === '[object Array]') { classes += ' ' + classNames.apply(null, arg); } else if ('object' === typeof arg) { for (var key in arg) { if (!arg.hasOwnProperty(key) || !arg[key]) { continue; } classes += ' ' + key; } } } return classes.substr(1); } // safely export classNames for node / browserify if (typeof module !== 'undefined' && module.exports) { module.exports = classNames; } // safely export classNames for RequireJS if (true) { !(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_RESULT__ = function() { return classNames; }.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } /***/ } /******/ ]) }); ; /***/ }, /* 339 */ /***/ function(module, exports, __webpack_require__) { module.exports = __webpack_require__(340); /***/ }, /* 340 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _ponyfill = __webpack_require__(341); var _ponyfill2 = _interopRequireDefault(_ponyfill); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var root; /* global window */ if (typeof self !== 'undefined') { root = self; } else if (typeof window !== 'undefined') { root = window; } else if (typeof (window) !== 'undefined') { root = (window); } else if (true) { root = module; } else { root = Function('return this')(); } var result = (0, _ponyfill2['default'])(root); exports['default'] = result; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(55)(module))) /***/ }, /* 341 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports['default'] = symbolObservablePonyfill; function symbolObservablePonyfill(root) { var result; var _Symbol = root.Symbol; if (typeof _Symbol === 'function') { if (_Symbol.observable) { result = _Symbol.observable; } else { result = _Symbol('observable'); _Symbol.observable = result; } } else { result = '@@observable'; } return result; }; /***/ }, /* 342 */ /***/ function(module, exports, __webpack_require__) { /** * 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'; /** * 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 = function() {}; if (false) { warning = function(condition, format, args) { var len = arguments.length; args = new Array(len > 2 ? len - 2 : 0); for (var 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.length < 10 || (/^[s\W]*$/).test(format)) { throw new Error( 'The warning format should be able to uniquely identify this ' + 'warning. Please, use a more descriptive format than: ' + format ); } if (!condition) { var argIndex = 0; var message = 'Warning: ' + format.replace(/%s/g, function() { return args[argIndex++]; }); if (typeof console !== 'undefined') { console.error(message); } try { // 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; /***/ } /******/ ]))) }); ;
web/src/js/components/disciplina/novo.js
helderfarias/ges
'use strict'; import React from 'react'; import { Link, History } from 'react-router'; import DisciplinaAction from '../../actions/disciplina_action'; import DisciplinaStore from '../../stores/disciplina_store'; import Growl from '../comuns/alert'; export default React.createClass({ mixins: [ History ], handleSubmit(e) { e.preventDefault(); let disciplina = { nome: this.refs.nome.value }; DisciplinaAction.salvar(disciplina); }, componentDidMount() { DisciplinaStore.addChangeListener(this.onChangeListener); }, componentWillUnmount() { DisciplinaStore.removeChangeListener(this.onChangeListener); }, onChangeListener() { if (DisciplinaStore.getErros().length === 0) { this.history.replaceState(null, '/disciplinas'); return; } Growl.notifyOnErrors(DisciplinaStore.getErros()); }, render() { return ( <div> <div className="row"> <div className="col-lg-12"> <h3 className="page-header">Disciplina - Novo</h3> </div> </div> <div className="row"> <div className="col-lg-12"> <div className="panel panel-default"> <div className="panel-heading"> Dados da disciplina </div> <div className="panel-body"> <div className="row"> <div className="col-lg-6"> <form className="form-horizontal" role="form" onSubmit={this.handleSubmit}> <div className="form-group"> <label className="control-label col-sm-2">Nome </label> <div className="col-sm-10"> <input type="text" className="form-control" ref="nome" id="nome" placeholder="Nome" autoFocus/> </div> </div> <div className="form-group"> <div className="col-sm-offset-2 col-sm-10"> <button type="submit" className="btn btn-success">Confirmar</button> <span>&nbsp;</span> <Link to="/disciplinas" className="btn btn-default">Cancelar</Link> </div> </div> </form> </div> </div> </div> </div> </div> </div> </div> ); } });
vendor/phpunit/php-code-coverage/PHP/CodeCoverage/Report/HTML/Renderer/Template/js/jquery.min.js
kaiocesar/getpocket
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
src/index.js
lujinming1/gallery-by-react
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.css'; window.onresize = function(){ window.location.reload(); window.location.href = ""; } ReactDOM.render( <App />, document.getElementById('root') );
pathfinder/vtables/csmoperations/src/common/LinkList.js
leanix/leanix-custom-reports
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Link from './Link'; class LinkList extends Component { constructor(props) { super(props); } render() { if (this.props.links.length < 1) { return null; } const delimiter = !this.props.delimiter ? '<br/>' : this.props.delimiter; return ( <span> {this.props.links.map((e, i) => { if (i === 0) { return ( <span key={i}> <Link link={e.link} target={e.target} text={e.text} /> </span> ); } return ( <span key={i}> <span dangerouslySetInnerHTML={{ __html: delimiter }} /> <Link link={e.link} target={e.target} text={e.text} /> </span> ); })} </span> ); } } LinkList.propTypes = { links: PropTypes.arrayOf( PropTypes.shape({ link: PropTypes.string.isRequired, target: PropTypes.string.isRequired, text: PropTypes.string.isRequired }).isRequired ).isRequired, delimiter: PropTypes.string }; export default LinkList;
src/components/layer-list-item.js
jjmulenex/sdk
/* * Copyright 2015-present Boundless Spatial Inc., http://boundlessgeo.com * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations * under the License. */ import React from 'react'; import PropTypes from 'prop-types'; import {DragSource, DropTarget} from 'react-dnd'; import {getLayerIndexById, isLayerVisible, getLayerTitle} from '../util'; import * as mapActions from '../actions/map'; export const layerListItemSource = { beginDrag(props) { return { index: props.index, layer: props.layer, }; } }; export const layerListItemTarget = { drop(props, monitor, component) { var sourceItem = monitor.getItem(); const dragIndex = sourceItem.index; const hoverIndex = props.index; // Don't replace items with themselves if (dragIndex === hoverIndex) { return; } // Time to actually perform the action const target = props.layers[hoverIndex]; if (target && sourceItem.layer && sourceItem.layer.id !== target.id) { props.dispatch(mapActions.orderLayer(sourceItem.layer.id, target.id)); } } }; export function collect(connect, monitor) { return { connectDragSource: connect.dragSource(), connectDragPreview: connect.dragPreview(), }; } export function collectDrop(connect, monitor) { return { isOver: monitor.isOver({shallow: true}), connectDropTarget: connect.dropTarget() }; } /** @module components/layer-list-item * * @desc Provides a layer list item, with a radio button or checkbox for visibility control. */ export default class SdkLayerListItem extends React.Component { moveLayer(layerId, targetId) { this.props.dispatch(mapActions.orderLayer(layerId, targetId)); } moveLayerUp() { const layer_id = this.props.layer.id; const index = getLayerIndexById(this.props.layers, layer_id); if (index < this.props.layers.length - 1) { this.moveLayer(layer_id, this.props.layers[index + 1].id); } } moveLayerDown() { const layer_id = this.props.layer.id; const index = getLayerIndexById(this.props.layers, layer_id); if (index > 0) { this.moveLayer(layer_id, this.props.layers[index - 1].id); } } removeLayer() { this.props.dispatch(mapActions.removeLayer(this.props.layer.id)); } toggleVisibility() { const shown = isLayerVisible(this.props.layer); if (this.props.exclusive) { this.props.dispatch(mapActions.setLayerInGroupVisible(this.props.layer.id, this.props.groupId)); } else { this.props.dispatch(mapActions.setLayerVisibility(this.props.layer.id, shown ? 'none' : 'visible')); } } getVisibilityControl() { const layer = this.props.layer; const is_checked = isLayerVisible(layer); if (this.props.exclusive) { return ( <input type="radio" name={this.props.groupId} onChange={() => { this.toggleVisibility(); }} checked={is_checked} /> ); } else { return ( <input type="checkbox" onChange={() => { this.toggleVisibility(); }} checked={is_checked} /> ); } } render() { const layer = this.props.layer; const checkbox = this.getVisibilityControl(); const error_class = this.props.error ? ' sdk-layer-error' : ''; const markup = ( <li className={`sdk-layer${error_class}`} key={layer.id}> <span className="sdk-checkbox">{checkbox}</span> <span className="sdk-name">{getLayerTitle(this.props.layer)}</span> </li> ); if (this.props.enableDD) { return this.props.connectDragSource(this.props.connectDropTarget(markup)); } else { return markup; } } } SdkLayerListItem.propTypes = { /** * Should we enable drag and drop? */ enableDD: PropTypes.bool, /** * Set of layers which belong to the same group */ groupLayers: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, })), /** * Set of all layers in the map. */ layers: PropTypes.arrayOf(PropTypes.shape({ id: PropTypes.string, })).isRequired, /** * Does this layer belong to an exclusive group? If so render as a radio button group. */ exclusive: PropTypes.bool, /** * Identifier of the group to which this layer belongs. */ groupId: PropTypes.string, /** * The layer to use for this item. */ layer: PropTypes.shape({ /** * Identifier of the layer. */ id: PropTypes.string, }).isRequired, /** * If the layer's source has an error, display * the layer as "errored". */ error: PropTypes.bool, }; SdkLayerListItem.defaultProps = { error: false, }; export const types = 'layerlistitem'; export const SdkLayerListItemDD = DropTarget(types, layerListItemTarget, collectDrop)(DragSource(types, layerListItemSource, collect)(SdkLayerListItem));
client/tests/components/messageList.spec.js
3m3kalionel/PostIt
import React from 'react'; import { mount } from 'enzyme'; import 'materialize-css/dist/js/materialize'; import { MessageList } from '../../components/dashboard/MessageList'; import { message, user } from '../__mocks__/__mockData__'; const props = { groupId: '', getMembers: jest.fn(), getMessages: jest.fn(), group: {} }; const enzymeWrapper = mount(<MessageList {...props} />); describe('Given the message list component is mounted', () => { it('should render self', () => { expect(enzymeWrapper.exists()).toBe(true); }); it('should show no messages by default', () => { expect(enzymeWrapper.find('#message-list').exists()).toBe(false); expect(enzymeWrapper.find('#no-messages').exists()).toBe(true); }); it('should show group messages when a group is selected', () => { enzymeWrapper.setProps({ group: { messages: [message], members: [{ ...user, id: 1 }] } }); expect(enzymeWrapper.find('#message-list').exists()).toBe(true); expect(enzymeWrapper.find('#no-messages').exists()).toBe(false); }); it('should get group members and messages when selected group changes', () => { enzymeWrapper.setProps({ groupId: '2' }); expect(props.getMembers.mock.calls.length).toBe(1); expect(props.getMessages.mock.calls.length).toBe(1); }); });
js/widgets/expense_donut/components.js
monetario/web
import React from 'react'; import Reflux from 'reflux'; import Donut from '../../components/donut'; import Store from './store'; import Actions from './actions'; const ExpenseDonutWidget = React.createClass({ mixins: [ Reflux.connectFilter(Store, "store", function(storeData) { return storeData.widgetData[this.props.name]; }) ], getInitialState() { var storeData = Store.getDefaultData(this.props.name); return { store: storeData.widgetData[this.props.name] }; }, componentDidMount() { Actions.load(this.props.name, this.props.url); }, renderChart() { if (this.state.store.data.length === 0) { return ''; } let data = this.state.store.data.map((item) => { let label = 'Transactions'; if (this.props.categories[item.category_id]) { label = this.props.categories[item.category_id].name; } return {label: label, value: item.amount} }); let colors = this.state.store.data.map((item) => { if (this.props.categories[item.category_id]) { return this.props.categories[item.category_id].colour } return '#444' }); return <Donut name={this.props.name} data={data} colors={colors} />; }, render() { return ( <section className="col-lg-6 connectedSortable ui-sortable"> <div className="box box-solid bg-green-gradient"> <div className="box-header"> <i className="fa fa-calendar"></i> <h3 className="box-title">{this.props.title}</h3> <div className="pull-right box-tools"> <div className="btn-group"> <button className="btn btn-success btn-sm dropdown-toggle" data-toggle="dropdown"> <i className="fa fa-bars"></i> </button> <ul className="dropdown-menu pull-right" role="menu"> <li><a href="#">Add new event</a></li> <li><a href="#">Clear events</a></li> <li className="divider"></li> <li><a href="#">View calendar</a></li> </ul> </div> <button className="btn btn-success btn-sm" data-widget="collapse"> <i className="fa fa-minus"></i> </button> <button className="btn btn-success btn-sm" data-widget="remove"> <i className="fa fa-times"></i> </button> </div> </div> <div className="box-body no-padding"> <div id="calendar"></div> </div> <div className="box-footer text-black"> <div className="row"> {this.renderChart()} </div> </div> </div> </section> ); } }); export default ExpenseDonutWidget;
src/containers/BooksPage.js
great-design-and-systems/cataloguing-app
import * as actions from '../actions/BookActions'; import * as alertActions from '../actions/NotificationActions'; import * as dialogActions from '../actions/DialogActions'; import * as googleActions from '../actions/GoogleBookActions'; import * as headerActions from '../actions/HeaderActions'; import { BookPreviewFooter, BooksPageBody } from '../components/books/'; import { CancelModalFooter, DeleteModalBody } from '../components/common'; import { Book } from '../api/books/'; import { ConnectedBookPreviewPage } from '../containers/BookPreviewPage'; import { LABEL_AN_ERROR_HAS_OCCURRED, LABEL_ADD_BOOK} from '../labels'; import PropTypes from 'prop-types'; import React from 'react'; import { bindActionCreators } from 'redux'; import { browserHistory } from 'react-router'; import { connect } from 'react-redux'; export class BooksPage extends React.Component { constructor(props) { super(props); this.createBook = this.createNewBook.bind(this); this.onRemove = this.onRemoveBook.bind(this); this.searchSubmit = this.onSearchSubmit.bind(this); this.searchInput = this.onSearchInput.bind(this); this.createGoogleBook = this.createBookFromGoogle.bind(this); this.onPreview = this.previewBook.bind(this); } componentWillMount() { this.props.actions.loadBooks(); this.props.googleActions.getNewestBookCarousel(); this.setHeaders(); } componentDidMount(){ this.setHeaders(); } setHeaders() { const headers = {}; headers[LABEL_ADD_BOOK] = { fontIcon: 'plus', onClick: this.createBook }; this.props.headerActions.setHeaderControls(headers); } createNewBook() { browserHistory.push('books/new'); } onRemoveBook(book) { return new Promise((resolve, reject) => { try { this.props.actions.openDialogConfirmBookCancel({ body: <DeleteModalBody itemName={book[Book.TITLE]}/>, footer: <CancelModalFooter reject={reject} resolve={resolve} confirmCancel={() => { this.props.actions.deleteBook(book[Book.BOOK_ID]); this.props.actions.closeDialog(); }} closeDialog={this.props.actions.closeDialog}/> }); } catch (err) { reject(err); } }); } onSearchSubmit(event) { event.preventDefault(); this.props.googleActions.searchSubmit(); } onSearchInput(event) { this.props.googleActions.searchInput(event.target.value); } createBookFromGoogle(bookId, selfLink) { this.props.googleActions.createNewBookFromGoogle(bookId, selfLink) .then(() => { browserHistory.push('/books/new?bookId=' + bookId); this.props.dialogActions.closeDialog(); }) .catch(err => { this.props.alertActions.alertDanger(err.message); }); } previewBook(book) { this.props.dialogActions.openDialog({ title: book[Book.TITLE], body: <ConnectedBookPreviewPage book={book}/>, footer: <BookPreviewFooter closeDialog={this.props.googleActions.closeDialog} readOnly={true}/> }) .catch(error => { this.props.alertActions.alertDanger(error ? error.message : LABEL_AN_ERROR_HAS_OCCURRED); }); } render() { return (<BooksPageBody books={this.props.books} onRemove={this.onRemove} onPreview={this.onPreview} searchBooks={this.props.actions.searchBooks} createBook={this.createBook} searchSubmit={this.searchSubmit} searchInput={this.searchInput} googleBooks={this.props.googleBooks} dialogActions={this.props.dialogActions} ajaxGlobal={this.props.ajaxGlobal} createGoogleBook={this.createGoogleBook}/>); } } BooksPage.defaultProps = { access: ['admin', 'librarian', 'student'] }; BooksPage.propTypes = { actions: PropTypes.object.isRequired, googleActions: PropTypes.object.isRequired, books: PropTypes.array.isRequired, ajaxGlobal: PropTypes.object.isRequired, googleBooks: PropTypes.object.isRequired, dialogActions: PropTypes.object.isRequired, alertActions: PropTypes.object.isRequired, headerActions: PropTypes.object.isRequired }; function mapStateToProps(state) { return { ajaxGlobal: state.ajaxGlobal, books: state.books, googleBooks: state.googleBooks }; } function mapDispatchToProps(dispatch) { return { actions: bindActionCreators(actions, dispatch), googleActions: bindActionCreators(googleActions, dispatch), dialogActions: bindActionCreators(dialogActions, dispatch), alertActions: bindActionCreators(alertActions, dispatch), headerActions: bindActionCreators(headerActions, dispatch) }; } export const ConnectBookPage = connect( mapStateToProps, mapDispatchToProps )(BooksPage);
options/TextConfigItem.js
SuperDOgePx/chrome-extension-react
import React from 'react'; import { autobind } from 'core-decorators'; import ConfigItem from './ConfigItem'; @autobind export default class TextConfigItem extends ConfigItem { changeHandler(e) { this.setValue(e.target.value); } renderConfig() { const { size = 30 } = this.props; return ( <label className="text-item"> {this.props.children} <input type="text" value={this.getValue()} onChange={this.changeHandler} size={size} /> </label> ); } }
src/chapters/01-definicije-verjetnosti/index.js
medja/ovs-prirocnik
import React from 'react'; import { createChapter } from 'components/chapter'; import KlasicnaVerjetnost from './01-klasicna-verjetnost'; import StatisticnaVerjetnost from './02-statisticna-verjetnost'; import GeometrijskaVerjetnost from './03-geometrijska-verjetnost'; const title = 'Definicije verjetnosti'; function Chapter() { return ( <div> <p> Verjetnost znamo definirati na tri različne načine. Vsak od njih je drugačen in ima svoje prednosti. A kljub njihovim razlikam so v resnici vsi trije med seboj ekvivalentni. </p> </div> ); } const subchapters = [ KlasicnaVerjetnost, StatisticnaVerjetnost, GeometrijskaVerjetnost ]; export default createChapter(title, Chapter, subchapters);
ajax/libs/rxjs/2.3.13/rx.lite.compat.js
jonobr1/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); // 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 = Rx.doneEnumerator = { done: true, value: undefined }; Rx.iterator = $iterator$; /** `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; }; } 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; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { result[i] = fun.call(thisp, self[i], i, object); } } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return {}.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function 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) { if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); } var s = state; var id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(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 SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, 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 localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (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 enumerableOf = Enumerable.of = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(arguments.length === 2 ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, arguments.length === 2 ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (err) { var self = this; this.queue.push(function () { self.observer.onError(err); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** * Creates 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(); } }); }); }; /** * 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; }); }; /** * 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); }; /** * 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 'throwError' for browsers <IE9. * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable.catchError = Observable['catch'] = function () { return enumerableOf(argsOrArray(arguments, 0)).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. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { return enumerableOf(argsOrArray(arguments, 0)).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.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 = []; function subscribe(xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support isPromise(xs) && (xs = observableFromPromise(xs)); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(subscription); if (q.length > 0) { subscribe(q.shift()); } else { activeCount--; isStopped && activeCount === 0 && observer.onCompleted(); } })); } group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; activeCount === 0 && observer.onCompleted(); })); return group; }); }; /** * 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 for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(innerSubscription); isStopped && group.length === 1 && observer.onCompleted(); })); }, observer.onError.bind(observer), function () { isStopped = true; group.length === 1 && observer.onCompleted(); })); return group; }); }; /** * 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 isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * 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 () { return new AnonymousObservable(this.subscribe.bind(this)); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * 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. * @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) { try { onError(err); } catch (e) { observer.onError(e); } } observer.onError(err); }, function () { if (onCompleted) { try { onCompleted(); } catch (e) { observer.onError(e); } } observer.onCompleted(); }); }); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(arguments.length === 2 ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, arguments.length === 2 ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, arguments.length === 2 ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @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) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { !hasValue && hasSeed && observer.onNext(seed); observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && observer.onNext(q.shift()); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableOf([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; 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 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 (e) { observer.onError(e); 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} prop The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (prop) { return this.map(function (x) { return x[prop]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i); 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 element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var source = this; return new AnonymousObservable(function (observer) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } running && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new RangeError(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining-- > 0) { observer.onNext(x); 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. * @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 (e) { observer.onError(e); return; } shouldRun && observer.onNext(value); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * 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); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = root.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation){ event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch(event.type){ case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; // Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs // for proper loading order! var marionette = !!root.Backbone && !!root.Backbone.Marionette; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { if (marionette) { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { if (!subject.isDisposed) { subject.onNext(value); subject.onCompleted(); } }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @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().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @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 && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, window, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, subject.subscribe.bind(subject)); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var count = 0, d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count++); self(d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); } 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); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * 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. * @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); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var 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.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { observer.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { observer.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; /** * 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)); /* * 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; }); }; 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 InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.exception = error; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); 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; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
ajax/libs/rxjs/2.2.26/rx.all.js
bgrins/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, identity = Rx.helpers.identity = function (x) { return x; }, 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' && p.then !== Rx.Observable.prototype.then; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }; // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFunction(/x/)) { isFunction = function(value) { return typeof value == 'function' && toString.call(value) == funcClass; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; /** @private */ var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; /** @private */ var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; // Collection polyfills function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Collections var IndexedItem = function (id, value) { this.id = id; this.value = value; }; IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); if (c === 0) { c = this.id - other.id; } return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { if (index === undefined) { index = 0; } if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Removes and disposes all disposables from the CompositeDisposable, but does not dispose the CompositeDisposable. */ CompositeDisposablePrototype.clear = function () { var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } }; /** * Determines whether the CompositeDisposable contains a specific disposable. * @param {Mixed} item Disposable to search for. * @returns {Boolean} true if the disposable was found; otherwise, false. */ CompositeDisposablePrototype.contains = function (item) { return this.disposables.indexOf(item) !== -1; }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var BooleanDisposable = (function () { function BooleanDisposable (isSingle) { this.isSingle = isSingle; this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { if (this.current && this.isSingle) { throw new Error('Disposable has already been assigned'); } var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; return BooleanDisposable; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } ScheduledDisposable.prototype.dispose = function () { var parent = this; this.scheduler.schedule(function () { if (!parent.isDisposed) { parent.isDisposed = true; parent.disposable.dispose(); } }); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { /** * @constructor * @private */ function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchException = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { action(); }); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt), t; if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return queue === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); var scheduleMethod, clearMethod = noop; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return setTimeout(action, 0); }; clearMethod = clearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = setTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { clearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** @private */ var CatchScheduler = (function (_super) { function localNow() { return this._scheduler.now(); } function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, _super); /** @private */ function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } /** @private */ CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; /** @private */ CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; /** @private */ CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; /** @private */ CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (notification.kind === 'N') { observer.onCompleted(); } }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableFor = Enumerable.forEach = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * * @param observer Observer object. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (_super) { inherits(AnonymousObserver, _super); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { _super.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (exception) { this._onError(exception); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (_super) { inherits(CheckedObserver, _super); function CheckedObserver(observer) { _super.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); try { this._observer.onNext(value); } catch (e) { throw e; } finally { this._state = 0; } }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); try { this._observer.onError(err); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); try { this._observer.onCompleted(); } catch (e) { throw e; } finally { this._state = 2; } }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (_super) { inherits(ScheduledObserver, _super); function ScheduledObserver(scheduler, observer) { _super.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (exception) { var self = this; this.queue.push(function () { self.observer.onError(exception); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { _super.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** @private */ var ObserveOnObserver = (function (_super) { inherits(ObserveOnObserver, _super); /** @private */ function ObserveOnObserver() { _super.apply(this, arguments); } /** @private */ ObserveOnObserver.prototype.next = function (value) { _super.prototype.next.call(this, value); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.error = function (e) { _super.prototype.error.call(this, e); this.ensureActive(); }; /** @private */ ObserveOnObserver.prototype.completed = function () { _super.prototype.completed.call(this); this.ensureActive(); }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber = typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted); return this._subscribe(subscriber); }; return Observable; })(); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); return function () { if (promise && promise.abort) { promise.abort(); } } }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new Error('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, function (err) { reject(err); }, function () { if (hasValue) { resolve(value); } }); }); }; /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0; return scheduler.scheduleRecursive(function (self) { if (count < array.length) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an iterable into an Observable sequence * * @example * var res = Rx.Observable.fromIterable(new Map()); * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. */ Observable.fromIterable = function (iterable, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var iterator; try { iterator = iterable[$iterator$](); } catch (e) { observer.onError(e); return; } return scheduler.scheduleRecursive(function (self) { var next; try { next = iterator.next(); } catch (err) { observer.onError(err); return; } if (next.done) { observer.onCompleted(); } else { observer.onNext(next.value); self(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == null) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throwException(new Error('Error')); * var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * * @example * var res = Rx.Observable.using(function () { return new AsyncSubject(); }, function (s) { return s; }); * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); if (resource) { disposable = resource; } source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = argsOrArray(arguments, 0); function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable['catch'] = function () { var items = argsOrArray(arguments, 0); return enumerableFor(items).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * * @example * 1 - res = Rx.Observable.concat(xs, ys, zs); * 2 - res = Rx.Observable.concat([xs, ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var sources = argsOrArray(arguments, 0); return enumerableFor(sources).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [], subscribe = function (xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support if (isPromise(xs)) { xs = observableFromPromise(xs); } subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { var s; group.remove(subscription); if (q.length > 0) { s = q.shift(); subscribe(s); } else { activeCount--; if (isStopped && activeCount === 0) { observer.onCompleted(); } } })); }; group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; if (activeCount === 0) { observer.onCompleted(); } })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll =function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } innerSubscription.setDisposable(innerSource.subscribe(function (x) { observer.onNext(x); }, observer.onError.bind(observer), function () { group.remove(innerSubscription); if (isStopped && group.length === 1) { observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; if (group.length === 1) { observer.onCompleted(); } })); return group; }); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), function () { self(); }, function () { self(); })); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe(function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable if (isPromise(innerSource)) { innerSource = observableFromPromise(innerSource); } d.setDisposable(innerSource.subscribe(function (x) { if (latest === id) { observer.onNext(x); } }, function (e) { if (latest === id) { observer.onError(e); } }, function () { if (latest === id) { hasLatest = false; if (isStopped) { observer.onCompleted(); } } })); }, observer.onError.bind(observer), function () { isStopped = true; if (!hasLatest) { observer.onCompleted(); } }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(observer); }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.doAction(observer); * var res = observable.doAction(onNext); * var res = observable.doAction(onNext, onError); * var res = observable.doAction(onNext, onError, onCompleted); * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(42); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * var res = source.takeLast(5); * var res = source.takeLast(5, Rx.Scheduler.timeout); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; if (count <= 0) { throw new Error(argumentOutOfRange); } if (arguments.length === 1) { skip = count; } if (skip <= 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = [], createWindow = function () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); }; createWindow(); m.setDisposable(source.subscribe(function (x) { var s; for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; if (c >= 0 && c % skip === 0) { s = q.shift(); s.onCompleted(); } n++; if (n % skip === 0) { createWindow(); } }, function (exception) { while (q.length > 0) { q.shift().onError(exception); } observer.onError(exception); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; function concatMap(selector) { return this.map(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).concatAll(); } function concatMapObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector) { if (resultSelector) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.map(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return concatMap.call(this, selector); } return concatMap.call(this, function () { return selector; }); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; if (defaultValue === undefined) { defaultValue = null; } return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, observer.onError.bind(observer), function () { if (!found) { observer.onNext(defaultValue); } observer.onCompleted(); }); }); }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (x) { return x.toString(); }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, keySerializer) { var source = this; keySelector || (keySelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var hashSet = {}; return source.subscribe(function (x) { var key, serializedKey, otherKey, hasMatch = false; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (exception) { observer.onError(exception); return; } for (otherKey in hashSet) { if (serializedKey === otherKey) { hasMatch = true; break; } } if (!hasMatch) { hashSet[serializedKey] = null; observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function. * * @example * var res = observable.groupBy(function (x) { return x.id; }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} [elementSelector] A function to map each source element to an element in an observable group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. */ observableProto.groupBy = function (keySelector, elementSelector, keySerializer) { return this.groupByUntil(keySelector, elementSelector, function () { return observableNever(); }, keySerializer); }; /** * Groups the elements of an observable sequence according to a specified key selector function. * A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same * key value as a reclaimed group occurs, the group will be reborn with a new lifetime request. * * @example * var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); }); * 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }); * 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); }); * @param {Function} keySelector A function to extract the key for each element. * @param {Function} durationSelector A function to signal the expiration of a group. * @param {Function} [keySerializer] Used to serialize the given object into a string for object comparison. * @returns {Observable} * A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value. * If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered. * */ observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, keySerializer) { var source = this; elementSelector || (elementSelector = identity); keySerializer || (keySerializer = defaultKeySerializer); return new AnonymousObservable(function (observer) { var map = {}, groupDisposable = new CompositeDisposable(), refCountDisposable = new RefCountDisposable(groupDisposable); groupDisposable.add(source.subscribe(function (x) { var duration, durationGroup, element, fireNewMapEntry, group, key, serializedKey, md, writer, w; try { key = keySelector(x); serializedKey = keySerializer(key); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } fireNewMapEntry = false; try { writer = map[serializedKey]; if (!writer) { writer = new Subject(); map[serializedKey] = writer; fireNewMapEntry = true; } } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } if (fireNewMapEntry) { group = new GroupedObservable(key, writer, refCountDisposable); durationGroup = new GroupedObservable(key, writer); try { duration = durationSelector(durationGroup); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } observer.onNext(group); md = new SingleAssignmentDisposable(); groupDisposable.add(md); var expire = function () { if (serializedKey in map) { delete map[serializedKey]; writer.onCompleted(); } groupDisposable.remove(md); }; md.setDisposable(duration.take(1).subscribe(noop, function (exn) { for (w in map) { map[w].onError(exn); } observer.onError(exn); }, function () { expire(); })); } try { element = elementSelector(x); } catch (e) { for (w in map) { map[w].onError(e); } observer.onError(e); return; } writer.onNext(element); }, function (ex) { for (var w in map) { map[w].onError(ex); } observer.onError(ex); }, function () { for (var w in map) { map[w].onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} property The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (property) { return this.select(function (x) { return x[property]; }); }; function selectMany(selector) { return this.select(function (x, i) { var result = selector(x, i); return isPromise(result) ? observableFromPromise(result) : result; }).mergeObservable(); } function selectManyObserver(onNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { observer.onNext(onNext(x, index++)); }, function (err) { observer.onNext(onError(err)); observer.completed(); }, function () { observer.onNext(onCompleted()); observer.onCompleted(); }); }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.select(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; function extremaBy(source, keySelector, comparer) { return new AnonymousObservable(function (observer) { var hasValue = false, lastKey = null, list = []; return source.subscribe(function (x) { var comparison, key; try { key = keySelector(x); } catch (ex) { observer.onError(ex); return; } comparison = 0; if (!hasValue) { hasValue = true; lastKey = key; } else { try { comparison = comparer(key, lastKey); } catch (ex1) { observer.onError(ex1); return; } } if (comparison > 0) { lastKey = key; list = []; } if (comparison >= 0) { list.push(x); } }, observer.onError.bind(observer), function () { observer.onNext(list); observer.onCompleted(); }); }); } function firstOnly(x) { if (x.length === 0) { throw new Error(sequenceContainsNoElements); } return x[0]; } /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.aggregate(function (acc, x) { return acc + x; }); * 2 - res = source.aggregate(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.aggregate = function () { var seed, hasSeed, accumulator; if (arguments.length === 2) { seed = arguments[0]; hasSeed = true; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value. * For aggregation behavior with incremental intermediate results, see Observable.scan. * @example * 1 - res = source.reduce(function (acc, x) { return acc + x; }); * 2 - res = source.reduce(function (acc, x) { return acc + x; }, 0); * @param {Function} accumulator An accumulator function to be invoked on each element. * @param {Any} [seed] The initial accumulator value. * @returns {Observable} An observable sequence containing a single element with the final accumulator value. */ observableProto.reduce = function (accumulator) { var seed, hasSeed; if (arguments.length === 2) { hasSeed = true; seed = arguments[1]; } return hasSeed ? this.scan(seed, accumulator).startWith(seed).finalValue() : this.scan(accumulator).finalValue(); }; /** * Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence. * @example * var result = source.any(); * var result = source.any(function (x) { return x > 3; }); * @param {Function} [predicate] A function to test each element for a condition. * @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence. */ observableProto.some = observableProto.any = function (predicate, thisArg) { var source = this; return predicate ? source.where(predicate, thisArg).any() : new AnonymousObservable(function (observer) { return source.subscribe(function () { observer.onNext(true); observer.onCompleted(); }, observer.onError.bind(observer), function () { observer.onNext(false); observer.onCompleted(); }); }); }; /** * Determines whether an observable sequence is empty. * * @memberOf Observable# * @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty. */ observableProto.isEmpty = function () { return this.any().select(function (b) { return !b; }); }; /** * Determines whether all elements of an observable sequence satisfy a condition. * * 1 - res = source.all(function (value) { return value.length > 3; }); * @memberOf Observable# * @param {Function} [predicate] A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate. */ observableProto.every = observableProto.all = function (predicate, thisArg) { return this.where(function (v) { return !predicate(v); }, thisArg).any().select(function (b) { return !b; }); }; /** * Determines whether an observable sequence contains a specified element with an optional equality comparer. * @example * 1 - res = source.contains(42); * 2 - res = source.contains({ value: 42 }, function (x, y) { return x.value === y.value; }); * @param value The value to locate in the source sequence. * @param {Function} [comparer] An equality comparer to compare elements. * @returns {Observable} An observable sequence containing a single element determining whether the source sequence contains an element that has the specified value. */ observableProto.contains = function (value, comparer) { comparer || (comparer = defaultComparer); return this.where(function (v) { return comparer(v, value); }).any(); }; /** * Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items. * @example * res = source.count(); * res = source.count(function (x) { return x > 3; }); * @param {Function} [predicate]A function to test each element for a condition. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence. */ observableProto.count = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).count() : this.aggregate(0, function (count) { return count + 1; }); }; /** * Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence. * @example * var res = source.sum(); * var res = source.sum(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence. */ observableProto.sum = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).sum() : this.aggregate(0, function (prev, curr) { return prev + curr; }); }; /** * Returns the elements in an observable sequence with the minimum key value according to the specified comparer. * @example * var res = source.minBy(function (x) { return x.value; }); * var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value. */ observableProto.minBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; }); }; /** * Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check. * @example * var res = source.min(); * var res = source.min(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence. */ observableProto.min = function (comparer) { return this.minBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Returns the elements in an observable sequence with the maximum key value according to the specified comparer. * @example * var res = source.maxBy(function (x) { return x.value; }); * var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; }); * @param {Function} keySelector Key selector function. * @param {Function} [comparer] Comparer used to compare key values. * @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value. */ observableProto.maxBy = function (keySelector, comparer) { comparer || (comparer = defaultSubComparer); return extremaBy(this, keySelector, comparer); }; /** * Returns the maximum value in an observable sequence according to the specified comparer. * @example * var res = source.max(); * var res = source.max(function (x, y) { return x.value - y.value; }); * @param {Function} [comparer] Comparer used to compare elements. * @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence. */ observableProto.max = function (comparer) { return this.maxBy(identity, comparer).select(function (x) { return firstOnly(x); }); }; /** * Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present. * @example * var res = res = source.average(); * var res = res = source.average(function (x) { return x.value; }); * @param {Function} [selector] A transform function to apply to each element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence containing a single element with the average of the sequence of values. */ observableProto.average = function (keySelector, thisArg) { return keySelector ? this.select(keySelector, thisArg).average() : this.scan({ sum: 0, count: 0 }, function (prev, cur) { return { sum: prev.sum + cur, count: prev.count + 1 }; }).finalValue().select(function (s) { if (s.count === 0) { throw new Error('The input sequence was empty'); } return s.sum / s.count; }); }; function sequenceEqualArray(first, second, comparer) { return new AnonymousObservable(function (observer) { var count = 0, len = second.length; return first.subscribe(function (value) { var equal = false; try { if (count < len) { equal = comparer(value, second[count++]); } } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } }, observer.onError.bind(observer), function () { observer.onNext(count === len); observer.onCompleted(); }); }); } /** * Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer. * * @example * var res = res = source.sequenceEqual([1,2,3]); * var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; }); * 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42)); * 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; }); * @param {Observable} second Second observable sequence or array to compare. * @param {Function} [comparer] Comparer used to compare elements of both sequences. * @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer. */ observableProto.sequenceEqual = function (second, comparer) { var first = this; comparer || (comparer = defaultComparer); if (Array.isArray(second)) { return sequenceEqualArray(first, second, comparer); } return new AnonymousObservable(function (observer) { var donel = false, doner = false, ql = [], qr = []; var subscription1 = first.subscribe(function (x) { var equal, v; if (qr.length > 0) { v = qr.shift(); try { equal = comparer(v, x); } catch (e) { observer.onError(e); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (doner) { observer.onNext(false); observer.onCompleted(); } else { ql.push(x); } }, observer.onError.bind(observer), function () { donel = true; if (ql.length === 0) { if (qr.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (doner) { observer.onNext(true); observer.onCompleted(); } } }); isPromise(second) && (second = observableFromPromise(second)); var subscription2 = second.subscribe(function (x) { var equal, v; if (ql.length > 0) { v = ql.shift(); try { equal = comparer(v, x); } catch (exception) { observer.onError(exception); return; } if (!equal) { observer.onNext(false); observer.onCompleted(); } } else if (donel) { observer.onNext(false); observer.onCompleted(); } else { qr.push(x); } }, observer.onError.bind(observer), function () { doner = true; if (qr.length === 0) { if (ql.length > 0) { observer.onNext(false); observer.onCompleted(); } else if (donel) { observer.onNext(true); observer.onCompleted(); } } }); return new CompositeDisposable(subscription1, subscription2); }); }; function elementAtOrDefault(source, index, hasDefault, defaultValue) { if (index < 0) { throw new Error(argumentOutOfRange); } return new AnonymousObservable(function (observer) { var i = index; return source.subscribe(function (x) { if (i === 0) { observer.onNext(x); observer.onCompleted(); } i--; }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(argumentOutOfRange)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the element at a specified index in a sequence. * @example * var res = source.elementAt(5); * @param {Number} index The zero-based index of the element to retrieve. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence. */ observableProto.elementAt = function (index) { return elementAtOrDefault(this, index, false); }; /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @example * var res = source.elementAtOrDefault(5); * var res = source.elementAtOrDefault(5, 0); * @param {Number} index The zero-based index of the element to retrieve. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence. */ observableProto.elementAtOrDefault = function (index, defaultValue) { return elementAtOrDefault(this, index, true, defaultValue); }; function singleOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { if (seenValue) { observer.onError(new Error('Sequence contains more than one element')); } else { value = x; seenValue = true; } }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence. * @example * var res = res = source.single(); * var res = res = source.single(function (x) { return x === 42; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate. */ observableProto.single = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).single() : singleOrDefaultAsync(this, false); }; /** * Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence. * @example * var res = res = source.singleOrDefault(); * var res = res = source.singleOrDefault(function (x) { return x === 42; }); * res = source.singleOrDefault(function (x) { return x === 42; }, 0); * res = source.singleOrDefault(null, 0); * @memberOf Observable# * @param {Function} predicate A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if the index is outside the bounds of the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) { return predicate? this.where(predicate, thisArg).singleOrDefault(null, defaultValue) : singleOrDefaultAsync(this, true, defaultValue) }; function firstOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { observer.onNext(x); observer.onCompleted(); }, observer.onError.bind(observer), function () { if (!hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(defaultValue); observer.onCompleted(); } }); }); } /** * Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence. * @example * var res = res = source.first(); * var res = res = source.first(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence. */ observableProto.first = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).first() : firstOrDefaultAsync(this, false); }; /** * Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = res = source.firstOrDefault(); * var res = res = source.firstOrDefault(function (x) { return x > 3; }); * var res = source.firstOrDefault(function (x) { return x > 3; }, 0); * var res = source.firstOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate).firstOrDefault(null, defaultValue) : firstOrDefaultAsync(this, true, defaultValue); }; function lastOrDefaultAsync(source, hasDefault, defaultValue) { return new AnonymousObservable(function (observer) { var value = defaultValue, seenValue = false; return source.subscribe(function (x) { value = x; seenValue = true; }, observer.onError.bind(observer), function () { if (!seenValue && !hasDefault) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); } /** * Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element. * @example * var res = source.last(); * var res = source.last(function (x) { return x > 3; }); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate. */ observableProto.last = function (predicate, thisArg) { return predicate ? this.where(predicate, thisArg).last() : lastOrDefaultAsync(this, false); }; /** * Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. * @example * var res = source.lastOrDefault(); * var res = source.lastOrDefault(function (x) { return x > 3; }); * var res = source.lastOrDefault(function (x) { return x > 3; }, 0); * var res = source.lastOrDefault(null, 0); * @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence. * @param [defaultValue] The default value if no such element exists. If not specified, defaults to null. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists. */ observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) { return predicate ? this.where(predicate, thisArg).lastOrDefault(null, defaultValue) : lastOrDefaultAsync(this, true, defaultValue); }; function findValue (source, predicate, thisArg, yieldIndex) { return new AnonymousObservable(function (observer) { var i = 0; return source.subscribe(function (x) { var shouldRun; try { shouldRun = predicate.call(thisArg, x, i, source); } catch(e) { observer.onError(e); return; } if (shouldRun) { observer.onNext(yieldIndex ? i : x); observer.onCompleted(); } else { i++; } }, observer.onError.bind(observer), function () { observer.onNext(yieldIndex ? -1 : undefined); observer.onCompleted(); }); }); } /** * Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined. */ observableProto.find = function (predicate, thisArg) { return findValue(this, predicate, thisArg, false); }; /** * Searches for an element that matches the conditions defined by the specified predicate, and returns * an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence. * @param {Function} predicate The predicate that defines the conditions of the element to search for. * @param {Any} [thisArg] Object to use as `this` when executing the predicate. * @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1. */ observableProto.findIndex = function (predicate, thisArg) { return findValue(this, predicate, thisArg, true); }; /** * Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence. * * @example * var res = Rx.Observable.start(function () { console.log('hello'); }); * var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout); * var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console); * * @param {Function} func Function to run asynchronously. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. * * Remarks * * The function is called immediately, not during the subscription of the resulting sequence. * * Multiple subscriptions to the resulting sequence can observe the function's result. */ Observable.start = function (func, scheduler, context) { return observableToAsync(func, scheduler, context)(); }; /** * Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler. * * @example * var res = Rx.Observable.toAsync(function (x, y) { return x + y; })(4, 3); * var res = Rx.Observable.toAsync(function (x, y) { return x + y; }, Rx.Scheduler.timeout)(4, 3); * var res = Rx.Observable.toAsync(function (x) { this.log(x); }, Rx.Scheduler.timeout, console)('hello'); * * @param {Function} function Function to convert to an asynchronous function. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @returns {Function} Asynchronous function. */ var observableToAsync = Observable.toAsync = function (func, scheduler, context) { scheduler || (scheduler = timeoutScheduler); return function () { var args = arguments, subject = new AsyncSubject(); scheduler.schedule(function () { var result; try { result = func.apply(context, args); } catch (e) { subject.onError(e); return; } subject.onNext(result); subject.onCompleted(); }); return subject.asObservable(); }; }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = immediateScheduler); return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } } else { if (results.length === 1) { results = results[0]; } } observer.onNext(results); observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = immediateScheduler); return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } } else { if (results.length === 1) { results = results[0]; } } observer.onNext(results); observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }); }; }; function createListener (element, name, handler) { // Node.js specific if (element.addListener) { element.addListener(name, handler); return disposableCreate(function () { element.removeListener(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 (typeof el.item === 'function' && typeof el.length === 'number') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.subject.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var n = 2, hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(n); function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, observer.onError.bind(observer), function () { isDone = true; observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer)) ); }); } var PausableBufferedObservable = (function (_super) { inherits(PausableBufferedObservable, _super); function subscribe(observer) { var q = [], previous = true; var subscription = combineLatestSource( this.source, this.subject.distinctUntilChanged(), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (results.shouldFire && previous) { observer.onNext(results.data); } if (results.shouldFire && !previous) { while (q.length > 0) { observer.onNext(q.shift()); } previous = true; } else if (!results.shouldFire && !previous) { q.push(results.data); } else if (!results.shouldFire && previous) { previous = false; } }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); this.subject.onNext(false); return subscription; } function PausableBufferedObservable(source, subject) { this.source = source; this.subject = subject || new Subject(); this.isPaused = true; _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { if (this.isPaused === true){ return; } this.isPaused = true; this.subject.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { if (this.isPaused === false){ return; } this.isPaused = false; this.subject.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return !selector ? this.multicast(new Subject()) : this.multicast(function () { return new Subject(); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); * * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish(null).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return !selector ? this.multicast(new AsyncSubject()) : this.multicast(function () { return new AsyncSubject(); }, selector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); * * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue). refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return !selector ? this.multicast(new ReplaySubject(bufferSize, window, scheduler)) : this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.replayWhileObserved(3); * var res = source.replayWhileObserved(3, 500); * var res = source.replayWhileObserved(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.replayWhileObserved = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, _super); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { _super.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (_super) { function RemovableDisposable (subject, observer) { this.subject = subject; this.observer = observer; }; RemovableDisposable.prototype.dispose = function () { this.observer.dispose(); if (!this.subject.isDisposed) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); } }; function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = new RemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, _super); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; _super.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /* @private */ _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { var observer; checkDisposed.call(this); if (!this.isStopped) { var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onNext(value); observer.ensureActive(); } } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; } }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { var observer; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); /** @private */ var ConnectableObservable = Rx.ConnectableObservable = (function (_super) { inherits(ConnectableObservable, _super); /** * @constructor * @private */ function ConnectableObservable(source, subject) { var state = { subject: subject, source: source.asObservable(), hasSubscription: false, subscription: null }; this.connect = function () { if (!state.hasSubscription) { state.hasSubscription = true; state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () { state.hasSubscription = false; })); } return state.subscription; }; function subscribe(observer) { return state.subject.subscribe(observer); } _super.call(this, subscribe); } /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.connect = function () { return this.connect(); }; /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.refCount = function () { var connectableSubscription = null, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect, subscription; count++; shouldConnect = count === 1; subscription = source.subscribe(observer); if (shouldConnect) { connectableSubscription = source.connect(); } return disposableCreate(function () { subscription.dispose(); count--; if (count === 0) { connectableSubscription.dispose(); } }); }); }; return ConnectableObservable; }(Observable)); // Real Dictionary var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647]; var noSuchkey = "no such key"; var duplicatekey = "duplicate key"; function isPrime(candidate) { if (candidate & 1 === 0) { return candidate === 2; } var num1 = Math.sqrt(candidate), num2 = 3; while (num2 <= num1) { if (candidate % num2 === 0) { return false; } num2 += 2; } return true; } function getPrime(min) { var index, num, candidate; for (index = 0; index < primes.length; ++index) { num = primes[index]; if (num >= min) { return num; } } candidate = min | 1; while (candidate < primes[primes.length - 1]) { if (isPrime(candidate)) { return candidate; } candidate += 2; } return min; } function stringHashFn(str) { var hash = 757602046; if (!str.length) { return hash; } for (var i = 0, len = str.length; i < len; i++) { var character = str.charCodeAt(i); hash = ((hash<<5)-hash)+character; hash = hash & hash; } return hash; } function numberHashFn(key) { var c2 = 0x27d4eb2d; key = (key ^ 61) ^ (key >>> 16); key = key + (key << 3); key = key ^ (key >>> 4); key = key * c2; key = key ^ (key >>> 15); return key; } var getHashCode = (function () { var uniqueIdCounter = 0; return function (obj) { if (obj == null) { throw new Error(noSuchkey); } // Check for built-ins before tacking on our own for any object if (typeof obj === 'string') { return stringHashFn(obj); } if (typeof obj === 'number') { return numberHashFn(obj); } if (typeof obj === 'boolean') { return obj === true ? 1 : 0; } if (obj instanceof Date) { return obj.getTime(); } if (obj.getHashCode) { return obj.getHashCode(); } var id = 17 * uniqueIdCounter++; obj.getHashCode = function () { return id; }; return id; }; } ()); function newEntry() { return { key: null, value: null, next: 0, hashCode: 0 }; } // Dictionary implementation var Dictionary = function (capacity, comparer) { if (capacity < 0) { throw new Error('out of range') } if (capacity > 0) { this._initialize(capacity); } this.comparer = comparer || defaultComparer; this.freeCount = 0; this.size = 0; this.freeList = -1; }; Dictionary.prototype._initialize = function (capacity) { var prime = getPrime(capacity), i; this.buckets = new Array(prime); this.entries = new Array(prime); for (i = 0; i < prime; i++) { this.buckets[i] = -1; this.entries[i] = newEntry(); } this.freeList = -1; }; Dictionary.prototype.count = function () { return this.size; }; Dictionary.prototype.add = function (key, value) { return this._insert(key, value, true); }; Dictionary.prototype._insert = function (key, value, add) { if (!this.buckets) { this._initialize(0); } var index3; var num = getHashCode(key) & 2147483647; var index1 = num % this.buckets.length; for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) { if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) { if (add) { throw new Error(duplicatekey); } this.entries[index2].value = value; return; } } if (this.freeCount > 0) { index3 = this.freeList; this.freeList = this.entries[index3].next; --this.freeCount; } else { if (this.size === this.entries.length) { this._resize(); index1 = num % this.buckets.length; } index3 = this.size; ++this.size; } this.entries[index3].hashCode = num; this.entries[index3].next = this.buckets[index1]; this.entries[index3].key = key; this.entries[index3].value = value; this.buckets[index1] = index3; }; Dictionary.prototype._resize = function () { var prime = getPrime(this.size * 2), numArray = new Array(prime); for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; } var entryArray = new Array(prime); for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; } for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); } for (var index1 = 0; index1 < this.size; ++index1) { var index2 = entryArray[index1].hashCode % prime; entryArray[index1].next = numArray[index2]; numArray[index2] = index1; } this.buckets = numArray; this.entries = entryArray; }; Dictionary.prototype.remove = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; var index1 = num % this.buckets.length; var index2 = -1; for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) { if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) { if (index2 < 0) { this.buckets[index1] = this.entries[index3].next; } else { this.entries[index2].next = this.entries[index3].next; } this.entries[index3].hashCode = -1; this.entries[index3].next = this.freeList; this.entries[index3].key = null; this.entries[index3].value = null; this.freeList = index3; ++this.freeCount; return true; } else { index2 = index3; } } } return false; }; Dictionary.prototype.clear = function () { var index, len; if (this.size <= 0) { return; } for (index = 0, len = this.buckets.length; index < len; ++index) { this.buckets[index] = -1; } for (index = 0; index < this.size; ++index) { this.entries[index] = newEntry(); } this.freeList = -1; this.size = 0; }; Dictionary.prototype._findEntry = function (key) { if (this.buckets) { var num = getHashCode(key) & 2147483647; for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) { if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) { return index; } } } return -1; }; Dictionary.prototype.count = function () { return this.size - this.freeCount; }; Dictionary.prototype.tryGetValue = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } return undefined; }; Dictionary.prototype.getValues = function () { var index = 0, results = []; if (this.entries) { for (var index1 = 0; index1 < this.size; index1++) { if (this.entries[index1].hashCode >= 0) { results[index++] = this.entries[index1].value; } } } return results; }; Dictionary.prototype.get = function (key) { var entry = this._findEntry(key); if (entry >= 0) { return this.entries[entry].value; } throw new Error(noSuchkey); }; Dictionary.prototype.set = function (key, value) { this._insert(key, value, false); }; Dictionary.prototype.containskey = function (key) { return this._findEntry(key) >= 0; }; /** * Correlates the elements of two sequences based on overlapping durations. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), leftDone = false, leftId = 0, leftMap = new Dictionary(), rightDone = false, rightId = 0, rightMap = new Dictionary(); group.add(left.subscribe(function (value) { var duration, expire, id = leftId++, md = new SingleAssignmentDisposable(), result, values; leftMap.add(id, value); group.add(md); expire = function () { if (leftMap.remove(id) && leftMap.count() === 0 && leftDone) { observer.onCompleted(); } return group.remove(md); }; try { duration = leftDurationSelector(value); } catch (e) { observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); values = rightMap.getValues(); for (var i = 0; i < values.length; i++) { try { result = resultSelector(value, values[i]); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); } }, observer.onError.bind(observer), function () { leftDone = true; if (rightDone || leftMap.count() === 0) { observer.onCompleted(); } })); group.add(right.subscribe(function (value) { var duration, expire, id = rightId++, md = new SingleAssignmentDisposable(), result, values; rightMap.add(id, value); group.add(md); expire = function () { if (rightMap.remove(id) && rightMap.count() === 0 && rightDone) { observer.onCompleted(); } return group.remove(md); }; try { duration = rightDurationSelector(value); } catch (exception) { observer.onError(exception); return; } md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), function () { expire(); })); values = leftMap.getValues(); for (var i = 0; i < values.length; i++) { try { result = resultSelector(values[i], value); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); } }, observer.onError.bind(observer), function () { rightDone = true; if (leftDone || rightMap.count() === 0) { observer.onCompleted(); } })); return group; }); }; /** * Correlates the elements of two sequences based on overlapping durations, and groups the results. * * @param {Observable} right The right observable sequence to join elements for. * @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap. * @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap. * @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element. * @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration. */ observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) { var left = this; return new AnonymousObservable(function (observer) { var nothing = function () {}; var group = new CompositeDisposable(); var r = new RefCountDisposable(group); var leftMap = new Dictionary(); var rightMap = new Dictionary(); var leftID = 0; var rightID = 0; group.add(left.subscribe( function (value) { var s = new Subject(); var id = leftID++; leftMap.add(id, s); var i, len, leftValues, rightValues; var result; try { result = resultSelector(value, addRef(s, r)); } catch (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); return; } observer.onNext(result); rightValues = rightMap.getValues(); for (i = 0, len = rightValues.length; i < len; i++) { s.onNext(rightValues[i]); } var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { if (leftMap.remove(id)) { s.onCompleted(); } group.remove(md); }; var duration; try { duration = leftDurationSelector(value); } catch (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftMap.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( nothing, function (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); }, expire) ); }, function (e) { var leftValues = leftMap.getValues(); for (var i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); }, observer.onCompleted.bind(observer))); group.add(right.subscribe( function (value) { var leftValues, i, len; var id = rightID++; rightMap.add(id, value); var md = new SingleAssignmentDisposable(); group.add(md); var expire = function () { rightMap.remove(id); group.remove(md); }; var duration; try { duration = rightDurationSelector(value); } catch (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftMap.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); return; } md.setDisposable(duration.take(1).subscribe( nothing, function (e) { leftValues = leftMap.getValues(); for (i = 0, len = leftMap.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); }, expire) ); leftValues = leftMap.getValues(); for (i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onNext(value); } }, function (e) { var leftValues = leftMap.getValues(); for (var i = 0, len = leftValues.length; i < len; i++) { leftValues[i].onError(e); } observer.onError(e); })); return r; }); }; /** * Projects each element of an observable sequence into zero or more buffers. * * @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) { return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into zero or more windows. * * @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows). * @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored. * @returns {Observable} An observable sequence of windows. */ observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) { if (arguments.length === 1 && typeof arguments[0] !== 'function') { return observableWindowWithBounaries.call(this, windowOpeningsOrClosingSelector); } return typeof windowOpeningsOrClosingSelector === 'function' ? observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) : observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector); }; function observableWindowWithOpenings(windowOpenings, windowClosingSelector) { return windowOpenings.groupJoin(this, windowClosingSelector, function () { return observableEmpty(); }, function (_, window) { return window; }); } function observableWindowWithBounaries(windowBoundaries) { var source = this; return new AnonymousObservable(function (observer) { var window = new Subject(), d = new CompositeDisposable(), r = new RefCountDisposable(d); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); d.add(windowBoundaries.subscribe(function (w) { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); }, function (err) { window.onError(err); observer.onError(err); }, function () { window.onCompleted(); observer.onCompleted(); })); return r; }); } function observableWindowWithClosingSelector(windowClosingSelector) { var source = this; return new AnonymousObservable(function (observer) { var createWindowClose, m = new SerialDisposable(), d = new CompositeDisposable(m), r = new RefCountDisposable(d), window = new Subject(); observer.onNext(addRef(window, r)); d.add(source.subscribe(function (x) { window.onNext(x); }, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); observer.onCompleted(); })); createWindowClose = function () { var m1, windowClose; try { windowClose = windowClosingSelector(); } catch (exception) { observer.onError(exception); return; } m1 = new SingleAssignmentDisposable(); m.setDisposable(m1); m1.setDisposable(windowClose.take(1).subscribe(noop, function (ex) { window.onError(ex); observer.onError(ex); }, function () { window.onCompleted(); window = new Subject(); observer.onNext(addRef(window, r)); createWindowClose(); })); }; createWindowClose(); return r; }); } /** * Returns a new observable that triggers on the second and subsequent triggerings of the input observable. * The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair. * The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs. * @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array. */ observableProto.pairwise = function () { var source = this; return new AnonymousObservable(function (observer) { var previous, hasPrevious = false; return source.subscribe( function (x) { if (hasPrevious) { observer.onNext([previous, x]); } else { hasPrevious = true; } previous = x; }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns two observables which partition the observations of the source by the given function. * The first will trigger observations for those values for which the predicate returns true. * The second will trigger observations for those values where the predicate returns false. * The predicate is executed once for each subscribed observer. * Both also propagate all error observations arising from the source and each completes * when the source completes. * @param {Function} predicate * The function to determine which output Observable will trigger a particular observation. * @returns {Array} * An array of observables. The first triggers when the predicate returns true, * and the second triggers when the predicate returns false. */ observableProto.partition = function(predicate, thisArg) { var published = this.publish().refCount(); return [ published.filter(predicate, thisArg), published.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); }) ]; }; function enumerableWhile(condition, source) { return new Enumerable(function () { return new Enumerator(function () { return condition() ? { done: false, value: source } : { done: true, value: undefined }; }); }); } /** * Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions. * This operator allows for a fluent style of writing queries that use the same sequence multiple times. * * @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.letBind = observableProto['let'] = function (func) { return func(this); }; /** * Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9 * * @example * 1 - res = Rx.Observable.if(condition, obs1); * 2 - res = Rx.Observable.if(condition, obs1, obs2); * 3 - res = Rx.Observable.if(condition, obs1, scheduler); * @param {Function} condition The condition which determines if the thenSource or elseSource will be run. * @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler. * @returns {Observable} An observable sequence which is either the thenSource or elseSource. */ Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) { return observableDefer(function () { elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty()); isPromise(thenSource) && (thenSource = observableFromPromise(thenSource)); isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler)); // Assume a scheduler for empty only typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler)); return condition() ? thenSource : elseSourceOrScheduler; }); }; /** * Concatenates the observable sequences obtained by running the specified result selector for each element in source. * There is an alias for this method called 'forIn' for browsers <IE9 * @param {Array} sources An array of values to turn into an observable sequence. * @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence. * @returns {Observable} An observable sequence from the concatenated observable sequences. */ Observable['for'] = Observable.forIn = function (sources, resultSelector) { return enumerableFor(sources, resultSelector).concat(); }; /** * Repeats source as long as condition holds emulating a while loop. * There is an alias for this method called 'whileDo' for browsers <IE9 * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) { isPromise(source) && (source = observableFromPromise(source)); return enumerableWhile(condition, source).concat(); }; /** * Repeats source as long as condition holds emulating a do while loop. * * @param {Function} condition The condition which determines if the source will be repeated. * @param {Observable} source The observable sequence that will be run if the condition function returns true. * @returns {Observable} An observable sequence which is repeated as long as the condition holds. */ observableProto.doWhile = function (condition) { return observableConcat([this, observableWhileDo(condition, this)]); }; /** * Uses selector to determine which source in sources to use. * There is an alias 'switchCase' for browsers <IE9. * * @example * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0); * 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler); * * @param {Function} selector The function which extracts the value for to test in a case statement. * @param {Array} sources A object which has keys which correspond to the case statement labels. * @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler. * * @returns {Observable} An observable sequence which is determined by a case statement. */ Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) { return observableDefer(function () { defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty()); typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler)); var result = sources[selector()]; isPromise(result) && (result = observableFromPromise(result)); return result || defaultSourceOrScheduler; }); }; /** * Expands an observable sequence by recursively invoking selector. * * @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again. * @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler. * @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion. */ observableProto.expand = function (selector, scheduler) { scheduler || (scheduler = immediateScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = [], m = new SerialDisposable(), d = new CompositeDisposable(m), activeCount = 0, isAcquired = false; var ensureActive = function () { var isOwner = false; if (q.length > 0) { isOwner = !isAcquired; isAcquired = true; } if (isOwner) { m.setDisposable(scheduler.scheduleRecursive(function (self) { var work; if (q.length > 0) { work = q.shift(); } else { isAcquired = false; return; } var m1 = new SingleAssignmentDisposable(); d.add(m1); m1.setDisposable(work.subscribe(function (x) { observer.onNext(x); var result = null; try { result = selector(x); } catch (e) { observer.onError(e); } q.push(result); activeCount++; ensureActive(); }, observer.onError.bind(observer), function () { d.remove(m1); activeCount--; if (activeCount === 0) { observer.onCompleted(); } })); self(); })); } }; q.push(source); activeCount++; ensureActive(); return d; }); }; /** * Runs all observable sequences in parallel and collect their last elements. * * @example * 1 - res = Rx.Observable.forkJoin([obs1, obs2]); * 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...); * @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences. */ Observable.forkJoin = function () { var allSources = argsOrArray(arguments, 0); return new AnonymousObservable(function (subscriber) { var count = allSources.length; if (count === 0) { subscriber.onCompleted(); return disposableEmpty; } var group = new CompositeDisposable(), finished = false, hasResults = new Array(count), hasCompleted = new Array(count), results = new Array(count); for (var idx = 0; idx < count; idx++) { (function (i) { var source = allSources[i]; isPromise(source) && (source = observableFromPromise(source)); group.add( source.subscribe( function (value) { if (!finished) { hasResults[i] = true; results[i] = value; } }, function (e) { finished = true; subscriber.onError(e); group.dispose(); }, function () { if (!finished) { if (!hasResults[i]) { subscriber.onCompleted(); return; } hasCompleted[i] = true; for (var ix = 0; ix < count; ix++) { if (!hasCompleted[ix]) { return; } } finished = true; subscriber.onNext(results); subscriber.onCompleted(); } })); })(idx); } return group; }); }; /** * Runs two observable sequences in parallel and combines their last elemenets. * * @param {Observable} second Second observable sequence. * @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences. * @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences. */ observableProto.forkJoin = function (second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var leftStopped = false, rightStopped = false, hasLeft = false, hasRight = false, lastLeft, lastRight, leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(second) && (second = observableFromPromise(second)); leftSubscription.setDisposable( first.subscribe(function (left) { hasLeft = true; lastLeft = left; }, function (err) { rightSubscription.dispose(); observer.onError(err); }, function () { leftStopped = true; if (rightStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); rightSubscription.setDisposable( second.subscribe(function (right) { hasRight = true; lastRight = right; }, function (err) { leftSubscription.dispose(); observer.onError(err); }, function () { rightStopped = true; if (leftStopped) { if (!hasLeft) { observer.onCompleted(); } else if (!hasRight) { observer.onCompleted(); } else { var result; try { result = resultSelector(lastLeft, lastRight); } catch (e) { observer.onError(e); return; } observer.onNext(result); observer.onCompleted(); } } }) ); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Comonadic bind operator. * @param {Function} selector A transform function to apply to each element. * @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler. * @returns {Observable} An observable sequence which results from the comonadic bind operation. */ observableProto.manySelect = function (selector, scheduler) { scheduler || (scheduler = immediateScheduler); var source = this; return observableDefer(function () { var chain; return source .select( function (x) { var curr = new ChainObservable(x); if (chain) { chain.onNext(x); } chain = curr; return curr; }) .doAction( noop, function (e) { if (chain) { chain.onError(e); } }, function () { if (chain) { chain.onCompleted(); } }) .observeOn(scheduler) .select(function (x, i, o) { return selector(x, i, o); }); }); }; var ChainObservable = (function (_super) { function subscribe (observer) { var self = this, g = new CompositeDisposable(); g.add(currentThreadScheduler.schedule(function () { observer.onNext(self.head); g.add(self.tail.mergeObservable().subscribe(observer)); })); return g; } inherits(ChainObservable, _super); function ChainObservable(head) { _super.call(this, subscribe); this.head = head; this.tail = new AsyncSubject(); } addProperties(ChainObservable.prototype, Observer, { onCompleted: function () { this.onNext(Observable.empty()); }, onError: function (e) { this.onNext(Observable.throwException(e)); }, onNext: function (v) { this.tail.onNext(v); this.tail.onCompleted(); } }); return ChainObservable; }(Observable)); /** @private */ var Map = (function () { /** * @constructor * @private */ function Map() { this.keys = []; this.values = []; } /** * @private * @memberOf Map# */ Map.prototype['delete'] = function (key) { var i = this.keys.indexOf(key); if (i !== -1) { this.keys.splice(i, 1); this.values.splice(i, 1); } return i !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.get = function (key, fallback) { var i = this.keys.indexOf(key); return i !== -1 ? this.values[i] : fallback; }; /** * @private * @memberOf Map# */ Map.prototype.set = function (key, value) { var i = this.keys.indexOf(key); if (i !== -1) { this.values[i] = value; } this.values[this.keys.push(key) - 1] = value; }; /** * @private * @memberOf Map# */ Map.prototype.size = function () { return this.keys.length; }; /** * @private * @memberOf Map# */ Map.prototype.has = function (key) { return this.keys.indexOf(key) !== -1; }; /** * @private * @memberOf Map# */ Map.prototype.getKeys = function () { return this.keys.slice(0); }; /** * @private * @memberOf Map# */ Map.prototype.getValues = function () { return this.values.slice(0); }; return Map; }()); /** * @constructor * Represents a join pattern over observable sequences. */ function Pattern(patterns) { this.patterns = patterns; } /** * Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value. * * @param other Observable sequence to match in addition to the current pattern. * @return Pattern object that matches when all observable sequences in the pattern have an available value. */ Pattern.prototype.and = function (other) { var patterns = this.patterns.slice(0); patterns.push(other); return new Pattern(patterns); }; /** * Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values. * * @param selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern. * @return Plan that produces the projected values, to be fed (with other plans) to the when operator. */ Pattern.prototype.then = function (selector) { return new Plan(this, selector); }; function Plan(expression, selector) { this.expression = expression; this.selector = selector; } Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) { var self = this; var joinObservers = []; for (var i = 0, len = this.expression.patterns.length; i < len; i++) { joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer))); } var activePlan = new ActivePlan(joinObservers, function () { var result; try { result = self.selector.apply(self, arguments); } catch (exception) { observer.onError(exception); return; } observer.onNext(result); }, function () { for (var j = 0, jlen = joinObservers.length; j < jlen; j++) { joinObservers[j].removeActivePlan(activePlan); } deactivate(activePlan); }); for (i = 0, len = joinObservers.length; i < len; i++) { joinObservers[i].addActivePlan(activePlan); } return activePlan; }; function planCreateObserver(externalSubscriptions, observable, onError) { var entry = externalSubscriptions.get(observable); if (!entry) { var observer = new JoinObserver(observable, onError); externalSubscriptions.set(observable, observer); return observer; } return entry; } // Active Plan function ActivePlan(joinObserverArray, onNext, onCompleted) { var i, joinObserver; this.joinObserverArray = joinObserverArray; this.onNext = onNext; this.onCompleted = onCompleted; this.joinObservers = new Map(); for (i = 0; i < this.joinObserverArray.length; i++) { joinObserver = this.joinObserverArray[i]; this.joinObservers.set(joinObserver, joinObserver); } } ActivePlan.prototype.dequeue = function () { var values = this.joinObservers.getValues(); for (var i = 0, len = values.length; i < len; i++) { values[i].queue.shift(); } }; ActivePlan.prototype.match = function () { var firstValues, i, len, isCompleted, values, hasValues = true; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { if (this.joinObserverArray[i].queue.length === 0) { hasValues = false; break; } } if (hasValues) { firstValues = []; isCompleted = false; for (i = 0, len = this.joinObserverArray.length; i < len; i++) { firstValues.push(this.joinObserverArray[i].queue[0]); if (this.joinObserverArray[i].queue[0].kind === 'C') { isCompleted = true; } } if (isCompleted) { this.onCompleted(); } else { this.dequeue(); values = []; for (i = 0; i < firstValues.length; i++) { values.push(firstValues[i].value); } this.onNext.apply(this, values); } } }; /** @private */ var JoinObserver = (function (_super) { inherits(JoinObserver, _super); /** * @constructor * @private */ function JoinObserver(source, onError) { _super.call(this); this.source = source; this.onError = onError; this.queue = []; this.activePlans = []; this.subscription = new SingleAssignmentDisposable(); this.isDisposed = false; } var JoinObserverPrototype = JoinObserver.prototype; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.next = function (notification) { if (!this.isDisposed) { if (notification.kind === 'E') { this.onError(notification.exception); return; } this.queue.push(notification); var activePlans = this.activePlans.slice(0); for (var i = 0, len = activePlans.length; i < len; i++) { activePlans[i].match(); } } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.error = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.completed = noop; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.addActivePlan = function (activePlan) { this.activePlans.push(activePlan); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.subscribe = function () { this.subscription.setDisposable(this.source.materialize().subscribe(this)); }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.removeActivePlan = function (activePlan) { var idx = this.activePlans.indexOf(activePlan); this.activePlans.splice(idx, 1); if (this.activePlans.length === 0) { this.dispose(); } }; /** * @memberOf JoinObserver# * @private */ JoinObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); if (!this.isDisposed) { this.isDisposed = true; this.subscription.dispose(); } }; return JoinObserver; } (AbstractObserver)); /** * Creates a pattern that matches when both observable sequences have an available value. * * @param right Observable sequence to match with the current sequence. * @return {Pattern} Pattern object that matches when both observable sequences have an available value. */ observableProto.and = function (right) { return new Pattern([this, right]); }; /** * Matches when the observable sequence has an available value and projects the value. * * @param selector Selector that will be invoked for values in the source sequence. * @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator. */ observableProto.then = function (selector) { return new Pattern([this]).then(selector); }; /** * Joins together the results from several patterns. * * @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns. * @returns {Observable} Observable sequence with the results form matching several patterns. */ Observable.when = function () { var plans = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var activePlans = [], externalSubscriptions = new Map(), group, i, len, joinObserver, joinValues, outObserver; outObserver = observerCreate(observer.onNext.bind(observer), function (exception) { var values = externalSubscriptions.getValues(); for (var j = 0, jlen = values.length; j < jlen; j++) { values[j].onError(exception); } observer.onError(exception); }, observer.onCompleted.bind(observer)); try { for (i = 0, len = plans.length; i < len; i++) { activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) { var idx = activePlans.indexOf(activePlan); activePlans.splice(idx, 1); if (activePlans.length === 0) { outObserver.onCompleted(); } })); } } catch (e) { observableThrow(e).subscribe(observer); } group = new CompositeDisposable(); joinValues = externalSubscriptions.getValues(); for (i = 0, len = joinValues.length; i < len; i++) { joinObserver = joinValues[i]; joinObserver.subscribe(); group.add(joinObserver); } return group; }); }; function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { var p = normalizeTime(period); return new AnonymousObservable(function (observer) { var count = 0, d = dueTime; return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { var now; if (p > 0) { now = scheduler.now(); d = d + p; if (d <= now) { d = now + p; } } observer.onNext(count++); self(d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { var d = normalizeTime(dueTime); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(d, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { if (dueTime === period) { return new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }); } return observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { scheduler || (scheduler = timeoutScheduler); return observableTimerTimeSpanAndPeriod(period, period, scheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * * @example * 1 - res = Rx.Observable.timer(new Date()); * 2 - res = Rx.Observable.timer(new Date(), 1000); * 3 - res = Rx.Observable.timer(new Date(), Rx.Scheduler.timeout); * 4 - res = Rx.Observable.timer(new Date(), 1000, Rx.Scheduler.timeout); * * 5 - res = Rx.Observable.timer(5000); * 6 - res = Rx.Observable.timer(5000, 1000); * 7 - res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); * 8 - res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; scheduler || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'object') { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } if (period === undefined) { return observableTimerTimeSpan(dueTime, scheduler); } return observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(dueTime, scheduler) { var source = this; return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); } function observableDelayDate(dueTime, scheduler) { var self = this; return observableDefer(function () { var timeSpan = dueTime - scheduler.now(); return observableDelayTimeSpan.call(self, timeSpan, scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate.call(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan.call(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on timing information. * * @example * 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { var source = this, timeShift; if (timeShiftOrScheduler === undefined) { timeShift = timeSpan; } if (scheduler === undefined) { scheduler = timeoutScheduler; } if (typeof timeShiftOrScheduler === 'number') { timeShift = timeShiftOrScheduler; } else if (typeof timeShiftOrScheduler === 'object') { timeShift = timeSpan; scheduler = timeShiftOrScheduler; } return new AnonymousObservable(function (observer) { var groupDisposable, nextShift = timeShift, nextSpan = timeSpan, q = [], refCountDisposable, timerD = new SerialDisposable(), totalTime = 0; groupDisposable = new CompositeDisposable(timerD), refCountDisposable = new RefCountDisposable(groupDisposable); function createTimer () { var m = new SingleAssignmentDisposable(), isSpan = false, isShift = false; timerD.setDisposable(m); if (nextSpan === nextShift) { isSpan = true; isShift = true; } else if (nextSpan < nextShift) { isSpan = true; } else { isShift = true; } var newTotalTime = isSpan ? nextSpan : nextShift, ts = newTotalTime - totalTime; totalTime = newTotalTime; if (isSpan) { nextSpan += timeShift; } if (isShift) { nextShift += timeShift; } m.setDisposable(scheduler.scheduleWithRelative(ts, function () { var s; if (isShift) { s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } if (isSpan) { s = q.shift(); s.onCompleted(); } createTimer(); })); }; q.push(new Subject()); observer.onNext(addRef(q[0], refCountDisposable)); createTimer(); groupDisposable.add(source.subscribe(function (x) { var i, s; for (i = 0; i < q.length; i++) { s = q[i]; s.onNext(x); } }, function (e) { var i, s; for (i = 0; i < q.length; i++) { s = q[i]; s.onError(e); } observer.onError(e); }, function () { var i, s; for (i = 0; i < q.length; i++) { s = q[i]; s.onCompleted(); } observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed. * @example * 1 - res = source.windowWithTimeOrCount(5000, 50); // 5s or 50 items * 2 - res = source.windowWithTimeOrCount(5000, 50, scheduler); //5s or 50 items * * @memberOf Observable# * @param {Number} timeSpan Maximum time length of a window. * @param {Number} count Maximum element count of a window. * @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var createTimer, groupDisposable, n = 0, refCountDisposable, s, timerD = new SerialDisposable(), windowId = 0; groupDisposable = new CompositeDisposable(timerD); refCountDisposable = new RefCountDisposable(groupDisposable); createTimer = function (id) { var m = new SingleAssignmentDisposable(); timerD.setDisposable(m); m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () { var newId; if (id !== windowId) { return; } n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(newId); })); }; s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); createTimer(0); groupDisposable.add(source.subscribe(function (x) { var newId = 0, newWindow = false; s.onNext(x); n++; if (n === count) { newWindow = true; n = 0; newId = ++windowId; s.onCompleted(); s = new Subject(); observer.onNext(addRef(s, refCountDisposable)); } if (newWindow) { createTimer(newId); } }, function (e) { s.onError(e); observer.onError(e); }, function () { s.onCompleted(); observer.onCompleted(); })); return refCountDisposable; }); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on timing information. * * @example * 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second * 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds * * @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds). * @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers. * @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) { return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); }); }; /** * Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed. * * @example * 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array * 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array * * @param {Number} timeSpan Maximum time length of a buffer. * @param {Number} count Maximum element count of a buffer. * @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) { return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) { return x.toArray(); }); }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.select(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { scheduler || (scheduler = timeoutScheduler); return this.select(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } if (atEnd) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { scheduler || (scheduler = timeoutScheduler); if (typeof intervalOrSampler === 'number') { return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); } return sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * * @example * 1 - res = source.timeout(new Date()); // As a date * 2 - res = source.timeout(5000); // 5 seconds * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { other || (other = observableThrow(new Error('Timeout'))); scheduler || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); var createTimer = function () { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); }; createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithAbsoluteTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return new Date(); } * }); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) { if (hasResult) { observer.onNext(result); } try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence by iterating a state from an initial state until the condition fails. * * @example * res = source.generateWithRelativeTime(0, * function (x) { return return true; }, * function (x) { return x + 1; }, * function (x) { return x; }, * function (x) { return 500; } * ); * * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used. * @returns {Observable} The generated sequence. */ Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { if (hasResult) { observer.onNext(result); } try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(function () { start(); }, observer.onError.bind(observer), function () { start(); })); } return new CompositeDisposable(subscription, delays); }); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * * @example * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); * * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; var firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false, setTimer = function (timeout) { var myId = id, timerWins = function () { return id === myId; }; var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } d.dispose(); }, function (e) { if (timerWins()) { observer.onError(e); } }, function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } })); }; setTimer(firstTimeout); var observerWins = function () { var res = !switched; if (res) { id++; } return res; }; original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(timeout); } }, function (e) { if (observerWins()) { observer.onError(e); } }, function () { if (observerWins()) { observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); * * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The throttled sequence. */ observableProto.throttleWithSelector = function (throttleDurationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(x); } catch (e) { observer.onError(e); return; } hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); if (hasValue) { observer.onNext(value); } observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } observer.onCompleted(); }); }); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * * @example * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { res.push(next.value); } } observer.onNext(res); observer.onCompleted(); }); }); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var t = scheduler.scheduleWithRelative(duration, function () { observer.onCompleted(); }); return new CompositeDisposable(t, source.subscribe(observer)); }); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false, t = scheduler.scheduleWithRelative(duration, function () { open = true; }), d = source.subscribe(function (x) { if (open) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); return new CompositeDisposable(t, d); }); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); * 2 - res = source.skipUntilWithTime(5000, [optional scheduler]); * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this, schedulerMethod = startTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var open = false; return new CompositeDisposable( scheduler[schedulerMethod](startTime, function () { open = true; }), source.subscribe( function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer))); }); }; /** * Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers. * * @example * 1 - res = source.takeUntilWithTime(new Date(), [optional scheduler]); * 2 - res = source.takeUntilWithTime(5000, [optional scheduler]); * @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} scheduler Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this, schedulerMethod = endTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler[schedulerMethod](endTime, function () { observer.onCompleted(); }), source.subscribe(observer)); }); }; /** Provides a set of extension methods for virtual time scheduling. */ Rx.VirtualTimeScheduler = (function (_super) { function notImplemented() { throw new Error('Not implemented'); } function localNow() { return this.toDateTimeOffset(this.clock); } function scheduleNow(state, action) { return this.scheduleAbsoluteWithState(state, this.clock, action); } function scheduleRelative(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime), action); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleRelativeWithState(state, this.toRelative(dueTime - this.now()), action); } function invokeAction(scheduler, action) { action(); return disposableEmpty; } inherits(VirtualTimeScheduler, _super); /** * Creates a new virtual time scheduler with the specified initial clock value and absolute time comparer. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function VirtualTimeScheduler(initialClock, comparer) { this.clock = initialClock; this.comparer = comparer; this.isEnabled = false; this.queue = new PriorityQueue(1024); _super.call(this, localNow, scheduleNow, scheduleRelative, scheduleAbsolute); } var VirtualTimeSchedulerPrototype = VirtualTimeScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ VirtualTimeSchedulerPrototype.add = notImplemented; /** * Converts an absolute time to a number * @param {Any} The absolute time. * @returns {Number} The absolute time in ms */ VirtualTimeSchedulerPrototype.toDateTimeOffset = notImplemented; /** * Converts the TimeSpan value to a relative virtual time value. * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ VirtualTimeSchedulerPrototype.toRelative = notImplemented; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be emulated using recursive scheduling. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ VirtualTimeSchedulerPrototype.schedulePeriodicWithState = function (state, period, action) { var s = new SchedulePeriodicRecursive(this, state, period, action); return s.start(); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelativeWithState = function (state, dueTime, action) { var runAt = this.add(this.clock, dueTime); return this.scheduleAbsoluteWithState(state, runAt, action); }; /** * Schedules an action to be executed at dueTime. * @param {Number} dueTime Relative time after which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleRelative = function (dueTime, action) { return this.scheduleRelativeWithState(action, dueTime, invokeAction); }; /** * Starts the virtual time scheduler. */ VirtualTimeSchedulerPrototype.start = function () { var next; if (!this.isEnabled) { this.isEnabled = true; do { next = this.getNext(); if (next !== null) { if (this.comparer(next.dueTime, this.clock) > 0) { this.clock = next.dueTime; } next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); } }; /** * Stops the virtual time scheduler. */ VirtualTimeSchedulerPrototype.stop = function () { this.isEnabled = false; }; /** * Advances the scheduler's clock to the specified time, running all work till that point. * @param {Number} time Absolute time to advance the scheduler's clock to. */ VirtualTimeSchedulerPrototype.advanceTo = function (time) { var next; var dueToClock = this.comparer(this.clock, time); if (this.comparer(this.clock, time) > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } if (!this.isEnabled) { this.isEnabled = true; do { next = this.getNext(); if (next !== null && this.comparer(next.dueTime, time) <= 0) { if (this.comparer(next.dueTime, this.clock) > 0) { this.clock = next.dueTime; } next.invoke(); } else { this.isEnabled = false; } } while (this.isEnabled); this.clock = time; } }; /** * Advances the scheduler's clock by the specified relative time, running all work scheduled for that timespan. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.advanceBy = function (time) { var dt = this.add(this.clock, time); var dueToClock = this.comparer(this.clock, dt); if (dueToClock > 0) { throw new Error(argumentOutOfRange); } if (dueToClock === 0) { return; } this.advanceTo(dt); }; /** * Advances the scheduler's clock by the specified relative time. * @param {Number} time Relative time to advance the scheduler's clock by. */ VirtualTimeSchedulerPrototype.sleep = function (time) { var dt = this.add(this.clock, time); if (this.comparer(this.clock, dt) >= 0) { throw new Error(argumentOutOfRange); } this.clock = dt; }; /** * Gets the next scheduled item to be executed. * @returns {ScheduledItem} The next scheduled item. */ VirtualTimeSchedulerPrototype.getNext = function () { var next; while (this.queue.length > 0) { next = this.queue.peek(); if (next.isCancelled()) { this.queue.dequeue(); } else { return next; } } return null; }; /** * Schedules an action to be executed at dueTime. * @param {Scheduler} scheduler Scheduler to execute the action on. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsolute = function (dueTime, action) { return this.scheduleAbsoluteWithState(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Number} dueTime Absolute time at which to execute the action. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ VirtualTimeSchedulerPrototype.scheduleAbsoluteWithState = function (state, dueTime, action) { var self = this, run = function (scheduler, state1) { self.queue.remove(si); return action(scheduler, state1); }, si = new ScheduledItem(self, state, run, dueTime, self.comparer); self.queue.enqueue(si); return si.disposable; }; return VirtualTimeScheduler; }(Scheduler)); /** Provides a virtual time scheduler that uses Date for absolute time and number for relative time. */ Rx.HistoricalScheduler = (function (_super) { inherits(HistoricalScheduler, _super); /** * Creates a new historical scheduler with the specified initial clock value. * * @constructor * @param {Number} initialClock Initial value for the clock. * @param {Function} comparer Comparer to determine causality of events based on absolute time. */ function HistoricalScheduler(initialClock, comparer) { var clock = initialClock == null ? 0 : initialClock; var cmp = comparer || defaultSubComparer; _super.call(this, clock, cmp); } var HistoricalSchedulerProto = HistoricalScheduler.prototype; /** * Adds a relative time value to an absolute time value. * @param {Number} absolute Absolute virtual time value. * @param {Number} relative Relative virtual time value to add. * @return {Number} Resulting absolute virtual time sum value. */ HistoricalSchedulerProto.add = function (absolute, relative) { return absolute + relative; }; /** * @private */ HistoricalSchedulerProto.toDateTimeOffset = function (absolute) { return new Date(absolute).getTime(); }; /** * Converts the TimeSpan value to a relative virtual time value. * * @memberOf HistoricalScheduler * @param {Number} timeSpan TimeSpan value to convert. * @return {Number} Corresponding relative virtual time value. */ HistoricalSchedulerProto.toRelative = function (timeSpan) { return timeSpan; }; return HistoricalScheduler; }(Rx.VirtualTimeScheduler)); var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (typeof subscriber === 'undefined') { subscriber = disposableEmpty; } else if (typeof subscriber === 'function') { subscriber = disposableCreate(subscriber); } return subscriber; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }); } else { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var GroupedObservable = (function (_super) { inherits(GroupedObservable, _super); function subscribe(observer) { return this.underlyingObservable.subscribe(observer); } /** * @constructor * @private */ function GroupedObservable(key, underlyingObservable, mergedDisposable) { _super.call(this, subscribe); this.key = key; this.underlyingObservable = !mergedDisposable ? underlyingObservable : new AnonymousObservable(function (observer) { return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer)); }); } return GroupedObservable; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
index.android.js
vagnerpraia/ipeasurvey
import React, { Component } from 'react'; import { AppRegistry } from 'react-native'; import Routes from './app/Routes'; export default class IpeaSurvey extends Component { render() { return ( <Routes /> ); } } AppRegistry.registerComponent('IpeaSurvey', () => IpeaSurvey);
src/components/Score.js
calesce/tab-editor
import React, { PureComponent } from 'react'; import { connect } from 'react-redux'; import { StyleSheet, css } from 'aphrodite'; import { makeMapStateToProps } from '../util/selectors'; import { makeScoreSelector } from '../util/selectors/layout'; import { getScoreSectionWidth, calcScoreHeight } from '../util/scoreLayout'; import { setSelectRange } from '../actions/cursor'; import Measure from './measure/Measure'; import SelectBox from './SelectBox'; const SVG_LEFT = 270; const SVG_TOP = 5; const SELECT_ERROR = 6; // Give some room for user error when selecting a range of notes const styles = StyleSheet.create({ scoreContainer: { overflow: 'scroll', height: '100vh', 'margin-left': 15 }, score: { position: 'relative', display: 'flex', flexWrap: 'wrap', flex: 1, 'margin-top': 5 } }); class Score extends PureComponent { constructor(props) { super(props); this.state = { dragStart: undefined, dragEnd: undefined, sectionWidth: getScoreSectionWidth() }; } componentWillMount() { window.addEventListener('resize', this.handleResize); } componentWillUnmount() { window.removeEventListener('resize', this.handleResize); } handleResize = () => { this.setState({ sectionWidth: getScoreSectionWidth() }); }; getNoteRangeForMeasure(measure, xStart, xEnd) { const notes = measure.notes.map((note, i) => { const noteX = note.x + measure.xOfMeasure; return noteX + SELECT_ERROR > xStart && noteX + SELECT_ERROR < xEnd ? i : null; }); const filteredNotes = notes.filter(note => note !== null); return filteredNotes.length === notes.length ? 'all' : filteredNotes; } getSelectedRangeForSingleRow(measure, xStart, xEnd) { if ( xStart > measure.xOfMeasure && xEnd < measure.xOfMeasure + measure.width ) { return this.getNoteRangeForMeasure(measure, xStart, xEnd); } else if ( (xStart < measure.xOfMeasure && xEnd > measure.xOfMeasure) || (xStart > measure.xOfMeasure && xStart < measure.xOfMeasure + measure.width) ) { if (measure.xOfMeasure < xStart) { return this.getNoteRangeForMeasure( measure, xStart, measure.xOfMeasure + measure.width ); } else if (xEnd < measure.xOfMeasure + measure.width) { return this.getNoteRangeForMeasure(measure, measure.xOfMeasure, xEnd); } else { return 'all'; } } else { return undefined; } } getSelectedRange(measure, xStart, xEnd, selectedRows) { if (!selectedRows) { return undefined; } const selectedRowIndex = selectedRows.indexOf(measure.rowIndex); if (selectedRowIndex === -1) { return undefined; } if (selectedRows.length === 1) { return this.getSelectedRangeForSingleRow(measure, xStart, xEnd); } else if (selectedRowIndex === 0) { if (measure.xOfMeasure + measure.width > xStart) { if (measure.xOfMeasure < xStart) { // starting measure, need note index return this.getNoteRangeForMeasure( measure, xStart, measure.xOfMeasure + measure.width ); } else { return 'all'; } } } else if (selectedRowIndex === selectedRows.length - 1) { if (xEnd > measure.xOfMeasure) { if (xEnd < measure.xOfMeasure + measure.width) { // last measure return this.getNoteRangeForMeasure(measure, measure.xOfMeasure, xEnd); } else { return 'all'; } } } else { return 'all'; } } rowFromY(dragY, measures, tuning) { const rowHeights = measures.reduce((accum, measure) => { if (!accum[measure.rowIndex]) { return accum.concat( (accum.length > 0 ? accum[accum.length - 1] : 0) + measure.yTop + measure.yBottom + 75 + tuning.length * 20 ); } return accum; }, []); return rowHeights ? rowHeights.reduce( (accum, row, i) => (accum === -1 && dragY < row ? i : accum), -1 ) : 0; } onMouseDown = e => { e.preventDefault(); const dragX = e.pageX - SVG_LEFT; const dragY = e.pageY - SVG_TOP; this.setState({ dragStart: { dragX, dragY }, dragX, dragY }); }; onMouseUp = () => { const { dragX, dragY, dragHeight, dragWidth } = this.state; let selectedRows; if (dragWidth > 5 && dragHeight > 5) { const startRow = this.rowFromY( dragY, this.props.measures, this.props.tuning ); const endRow = this.rowFromY( dragY + dragHeight, this.props.measures, this.props.tuning ); selectedRows = Array.from( { length: endRow - startRow + 1 }, (_, k) => k + startRow ); } const selectRange = this.props.measures.reduce((accum, measure, i) => { const measureRange = this.getSelectedRange( measure, dragX, dragX + dragWidth, selectedRows ); if (Array.isArray(measureRange)) { if (measureRange.length === 0) { return accum; } } const obj = {}; obj[i] = measureRange; return measureRange ? Object.assign({}, accum, obj) : accum; }, {}); if (Object.keys(selectRange).length > 0) { this.props.setSelectRange(selectRange); } else { this.props.setSelectRange(undefined); } this.setState({ dragStart: undefined, dragX: undefined, dragY: undefined, dragWidth: undefined, dragHeight: undefined }); }; onMouseMove = e => { if (this.state.dragStart) { e.preventDefault(); const x = e.pageX - SVG_LEFT; const y = e.pageY - SVG_TOP; this.setState({ dragX: Math.min(this.state.dragStart.dragX, x), dragY: Math.min(this.state.dragStart.dragY, y), dragWidth: Math.abs(this.state.dragStart.dragX - x), dragHeight: Math.abs(this.state.dragStart.dragY - y) }); } }; calcLinearWidth(measures) { return measures.reduce((width, measure) => { return measure.width + width; }, 20); } render() { const { measures, layout, tuning } = this.props; const { dragX, dragY, dragWidth, dragHeight, sectionWidth } = this.state; const width = layout === 'linear' ? this.calcLinearWidth(measures) : sectionWidth; const height = layout === 'linear' ? 'auto' : calcScoreHeight(measures, tuning); return ( <div className={css(styles.scoreContainer)} ref={this.props.scrollRef}> <div className={css(styles.score)} style={{ height, width }} onMouseDown={this.onMouseDown} onMouseUp={this.onMouseUp} onMouseMove={this.onMouseMove} ref={el => { this.scoreRef = el; }} > {measures.map((_, i) => <Measure key={i} measureIndex={i} />)} <SelectBox height={height} width={width} x={dragX} y={dragY} dragWidth={dragWidth} dragHeight={dragHeight} /> </div> </div> ); } } export default connect(makeMapStateToProps(makeScoreSelector), { setSelectRange })(Score);
src/Parser/Paladin/Protection/CONFIG.js
hasseboulen/WoWAnalyzer
import React from 'react'; import { Hewhosmites, Noichxd, Yajinni, Zerotorescue } from 'CONTRIBUTORS'; import SPECS from 'common/SPECS'; import Wrapper from 'common/Wrapper'; import Warning from 'common/Alert/Warning'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import CombatLogParser from './CombatLogParser'; import CHANGELOG from './CHANGELOG'; export default { // The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. contributors: [Yajinni, Noichxd, Hewhosmites, Zerotorescue], // The WoW client patch this spec was last updated to be fully compatible with. patchCompatibility: '7.3', // Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more. // If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component. description: ( <Wrapper> <Warning> Hey there! Right now the Protection Paladin parser only holds very basic functionality. What we do show should be good to use, but it does not show the complete picture. </Warning> <Warning> Because <SpellLink id={SPELLS.GRAND_CRUSADER.id} icon /> <dfn data-tip="The combatlog does not contain any events for random cooldown resets.">can't be tracked</dfn> properly, any cooldown information of <SpellLink id={SPELLS.AVENGERS_SHIELD.id} icon /> should be treated as <dfn data-tip="Whenever Avenger's Shield would be cast before its cooldown would have expired normally, the cooldown expiry will be set back to the last possible trigger of Grand Crusade. This may lead to higher times on cooldown than you actually experienced in-game.">educated guesses</dfn>. </Warning> </Wrapper> ), // A recent example report to see interesting parts of the spec. Will be shown on the homepage. // exampleReport: '/report/hNqbFwd7Mx3G1KnZ/18-Mythic+Antoran+High+Command+-+Kill+(6:51)/Taffly', // Don't change anything below this line; // The current spec identifier. This is the only place (in code) that specifies which spec this parser is about. spec: SPECS.PROTECTION_PALADIN, // The contents of your changelog. changelog: CHANGELOG, // The CombatLogParser class for your spec. parser: CombatLogParser, // The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code. path: __dirname, };
src/components/Navigation/index.js
saschajullmann/gatsby-starter-gatsbythemes
import React, { Component } from 'react'; import Link from 'gatsby-link'; import { css } from 'emotion'; import colors from '../../utils/colors'; import MobileNav from './mobile'; import media from '../../utils/media'; import { Box } from '../Layout'; const basicNav = css` display: flex; position: fixed; top: 0; align-items: center; color: ${colors.primary}; background-color: ${colors.secondary}; margin: 0; width: 100%; list-style-type: none; -webkit-box-shadow: 0px 1px 10px 0px rgba(0, 0, 0, 1); -moz-box-shadow: 0px 1px 10px 0px rgba(0, 0, 0, 1); box-shadow: 0px 1px 10px 0px rgba(0, 0, 0, 1); z-index: 9998; height: 3.5rem; & ul { list-style-type: none; display: flex; margin: 0 auto; padding: 0; width: 1200px; } `; const fullNav = css` ${basicNav}; display: none; & li { margin: 0; } & li img { display: inline-block; vertical-align: middle; } & ul div { display: flex; justify-content: flex-end; margin-left: auto; & li { margin-left: 1.25rem; } } ${media.mid` display: flex; `}; `; // Styles for the mobile View of the navigation const mobileNav = css` ${basicNav}; & li { margin: 0; } & li:last-child { margin-left: auto; font-weight: 600; cursor: pointer; } & li img { display: block; margin: auto; } ${media.mid` display: none; `}; `; // Styles for the overlay which pops up, when the menu is clicked const mobileStyle = css` position: fixed; background-color: ${colors.secondary}; color: ${colors.primary}; display: block; padding: 1rem; width: 100%; height: 100%; top: 0; left: 0; right: 0; bottom: 0; z-index: 9999; & ul { list-style-type: none; padding: 0; margin: 3rem 0 0 0; height: 100%; text-align: center; font-size: 2rem; & div { text-align: center; } } & ul li { margin-top: 2rem; } & div { font-weight: 600; text-align: right; } `; class Navigation extends Component { constructor(props) { super(props); this.state = { mobileActive: false }; this.toggleNav = this.toggleNav.bind(this); } toggleNav() { const { mobileActive } = this.state; if (mobileActive) { this.setState({ mobileActive: false }); } else { this.setState({ mobileActive: true }); } } render() { const { mobileActive } = this.state; return ( <nav> <Box width="100%" px={[3, 3, 4]} className={fullNav}> <ul> <li>Gatsbythemes.com starter</li> <div> <li> <Link to="/">Home</Link> </li> <li> <Link to="/about">About Us</Link> </li> <li> <Link to="/blog">Blog</Link> </li> </div> </ul> </Box> <Box width="100%" px={[3, 3, 4]} className={mobileNav}> <ul> <li>Gatsbythemes.com starter</li> <li> <div onClick={this.toggleNav} role="button" tabIndex="0" onKeyPress={this.toggleNav} > MENU </div> </li> </ul> </Box> {mobileActive && ( <MobileNav toggleNav={this.toggleNav} mobileStyle={mobileStyle}> <ul> <li> <div onClick={this.toggleNav} role="button" tabIndex="0" onKeyPress={this.toggleNav} > <Link to="/">Home</Link> </div> </li> <li> <div onClick={this.toggleNav} role="button" tabIndex="-1" onKeyPress={this.toggleNav} > <Link to="/about">About</Link> </div> </li> <li> <div onClick={this.toggleNav} role="button" tabIndex="-1" onKeyPress={this.toggleNav} > <Link to="/blog">Blog</Link> </div> </li> </ul> </MobileNav> )} </nav> ); } } export default Navigation;
src/index.js
deco3500/dark
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
docs/app/Examples/views/Comment/Variations/index.js
clemensw/stardust
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const CommentVariations = () => ( <ExampleSection title='Variations'> <ComponentExample title='Threaded' description='A comment list can be threaded to showing the relationship between conversations.' examplePath='views/Comment/Variations/CommentExampleThreaded' /> <ComponentExample title='Minimal' description='Comments can hide extra information unless a user shows intent to interact with a comment.' examplePath='views/Comment/Variations/CommentExampleMinimal' /> </ExampleSection> ) export default CommentVariations
ajax/libs/yui/3.10.1/scrollview-base/scrollview-base-coverage.js
iamso/cdnjs
if (typeof __coverage__ === 'undefined') { __coverage__ = {}; } if (!__coverage__['build/scrollview-base/scrollview-base.js']) { __coverage__['build/scrollview-base/scrollview-base.js'] = {"path":"build/scrollview-base/scrollview-base.js","s":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0,"39":0,"40":0,"41":0,"42":0,"43":0,"44":0,"45":0,"46":0,"47":0,"48":0,"49":0,"50":0,"51":0,"52":0,"53":0,"54":0,"55":0,"56":0,"57":0,"58":0,"59":0,"60":0,"61":0,"62":0,"63":0,"64":0,"65":0,"66":0,"67":0,"68":0,"69":0,"70":0,"71":0,"72":0,"73":0,"74":0,"75":0,"76":0,"77":0,"78":0,"79":0,"80":0,"81":0,"82":0,"83":0,"84":0,"85":0,"86":0,"87":0,"88":0,"89":0,"90":0,"91":0,"92":0,"93":0,"94":0,"95":0,"96":0,"97":0,"98":0,"99":0,"100":0,"101":0,"102":0,"103":0,"104":0,"105":0,"106":0,"107":0,"108":0,"109":0,"110":0,"111":0,"112":0,"113":0,"114":0,"115":0,"116":0,"117":0,"118":0,"119":0,"120":0,"121":0,"122":0,"123":0,"124":0,"125":0,"126":0,"127":0,"128":0,"129":0,"130":0,"131":0,"132":0,"133":0,"134":0,"135":0,"136":0,"137":0,"138":0,"139":0,"140":0,"141":0,"142":0,"143":0,"144":0,"145":0,"146":0,"147":0,"148":0,"149":0,"150":0,"151":0,"152":0,"153":0,"154":0,"155":0,"156":0,"157":0,"158":0,"159":0,"160":0,"161":0,"162":0,"163":0,"164":0,"165":0,"166":0,"167":0,"168":0,"169":0,"170":0,"171":0,"172":0,"173":0,"174":0,"175":0,"176":0,"177":0,"178":0,"179":0,"180":0,"181":0,"182":0,"183":0,"184":0,"185":0,"186":0,"187":0,"188":0,"189":0,"190":0,"191":0,"192":0,"193":0,"194":0,"195":0,"196":0,"197":0,"198":0,"199":0,"200":0,"201":0,"202":0,"203":0,"204":0,"205":0,"206":0,"207":0,"208":0,"209":0,"210":0,"211":0,"212":0,"213":0,"214":0,"215":0,"216":0,"217":0,"218":0,"219":0,"220":0,"221":0,"222":0,"223":0},"b":{"1":[0,0],"2":[0,0],"3":[0,0],"4":[0,0],"5":[0,0],"6":[0,0],"7":[0,0],"8":[0,0],"9":[0,0],"10":[0,0],"11":[0,0],"12":[0,0],"13":[0,0],"14":[0,0],"15":[0,0],"16":[0,0],"17":[0,0],"18":[0,0],"19":[0,0],"20":[0,0],"21":[0,0],"22":[0,0],"23":[0,0],"24":[0,0],"25":[0,0],"26":[0,0],"27":[0,0],"28":[0,0],"29":[0,0],"30":[0,0],"31":[0,0],"32":[0,0],"33":[0,0],"34":[0,0],"35":[0,0],"36":[0,0],"37":[0,0],"38":[0,0],"39":[0,0],"40":[0,0],"41":[0,0],"42":[0,0],"43":[0,0],"44":[0,0],"45":[0,0],"46":[0,0],"47":[0,0],"48":[0,0],"49":[0,0],"50":[0,0],"51":[0,0,0],"52":[0,0],"53":[0,0],"54":[0,0],"55":[0,0],"56":[0,0],"57":[0,0],"58":[0,0],"59":[0,0],"60":[0,0],"61":[0,0],"62":[0,0],"63":[0,0],"64":[0,0,0],"65":[0,0],"66":[0,0],"67":[0,0],"68":[0,0],"69":[0,0],"70":[0,0],"71":[0,0],"72":[0,0],"73":[0,0],"74":[0,0],"75":[0,0,0,0,0,0],"76":[0,0],"77":[0,0],"78":[0,0],"79":[0,0],"80":[0,0],"81":[0,0],"82":[0,0],"83":[0,0],"84":[0,0],"85":[0,0],"86":[0,0]},"f":{"1":0,"2":0,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0,"13":0,"14":0,"15":0,"16":0,"17":0,"18":0,"19":0,"20":0,"21":0,"22":0,"23":0,"24":0,"25":0,"26":0,"27":0,"28":0,"29":0,"30":0,"31":0,"32":0,"33":0,"34":0,"35":0,"36":0,"37":0,"38":0},"fnMap":{"1":{"name":"(anonymous_1)","line":1,"loc":{"start":{"line":1,"column":27},"end":{"line":1,"column":46}}},"2":{"name":"(anonymous_2)","line":49,"loc":{"start":{"line":49,"column":17},"end":{"line":49,"column":42}}},"3":{"name":"ScrollView","line":62,"loc":{"start":{"line":62,"column":0},"end":{"line":62,"column":22}}},"4":{"name":"(anonymous_4)","line":168,"loc":{"start":{"line":168,"column":17},"end":{"line":168,"column":29}}},"5":{"name":"(anonymous_5)","line":189,"loc":{"start":{"line":189,"column":12},"end":{"line":189,"column":24}}},"6":{"name":"(anonymous_6)","line":237,"loc":{"start":{"line":237,"column":16},"end":{"line":237,"column":28}}},"7":{"name":"(anonymous_7)","line":265,"loc":{"start":{"line":265,"column":15},"end":{"line":265,"column":31}}},"8":{"name":"(anonymous_8)","line":285,"loc":{"start":{"line":285,"column":16},"end":{"line":285,"column":33}}},"9":{"name":"(anonymous_9)","line":308,"loc":{"start":{"line":308,"column":21},"end":{"line":308,"column":43}}},"10":{"name":"(anonymous_10)","line":330,"loc":{"start":{"line":330,"column":12},"end":{"line":330,"column":24}}},"11":{"name":"(anonymous_11)","line":374,"loc":{"start":{"line":374,"column":20},"end":{"line":374,"column":32}}},"12":{"name":"(anonymous_12)","line":417,"loc":{"start":{"line":417,"column":25},"end":{"line":417,"column":37}}},"13":{"name":"(anonymous_13)","line":459,"loc":{"start":{"line":459,"column":16},"end":{"line":459,"column":34}}},"14":{"name":"(anonymous_14)","line":476,"loc":{"start":{"line":476,"column":16},"end":{"line":476,"column":28}}},"15":{"name":"(anonymous_15)","line":499,"loc":{"start":{"line":499,"column":14},"end":{"line":499,"column":54}}},"16":{"name":"(anonymous_16)","line":579,"loc":{"start":{"line":579,"column":16},"end":{"line":579,"column":32}}},"17":{"name":"(anonymous_17)","line":599,"loc":{"start":{"line":599,"column":14},"end":{"line":599,"column":35}}},"18":{"name":"(anonymous_18)","line":616,"loc":{"start":{"line":616,"column":17},"end":{"line":616,"column":29}}},"19":{"name":"(anonymous_19)","line":641,"loc":{"start":{"line":641,"column":25},"end":{"line":641,"column":38}}},"20":{"name":"(anonymous_20)","line":707,"loc":{"start":{"line":707,"column":20},"end":{"line":707,"column":33}}},"21":{"name":"(anonymous_21)","line":749,"loc":{"start":{"line":749,"column":23},"end":{"line":749,"column":36}}},"22":{"name":"(anonymous_22)","line":804,"loc":{"start":{"line":804,"column":12},"end":{"line":804,"column":25}}},"23":{"name":"(anonymous_23)","line":837,"loc":{"start":{"line":837,"column":17},"end":{"line":837,"column":63}}},"24":{"name":"(anonymous_24)","line":900,"loc":{"start":{"line":900,"column":18},"end":{"line":900,"column":30}}},"25":{"name":"(anonymous_25)","line":920,"loc":{"start":{"line":920,"column":17},"end":{"line":920,"column":30}}},"26":{"name":"(anonymous_26)","line":970,"loc":{"start":{"line":970,"column":20},"end":{"line":970,"column":36}}},"27":{"name":"(anonymous_27)","line":993,"loc":{"start":{"line":993,"column":15},"end":{"line":993,"column":27}}},"28":{"name":"(anonymous_28)","line":1025,"loc":{"start":{"line":1025,"column":24},"end":{"line":1025,"column":37}}},"29":{"name":"(anonymous_29)","line":1062,"loc":{"start":{"line":1062,"column":23},"end":{"line":1062,"column":36}}},"30":{"name":"(anonymous_30)","line":1073,"loc":{"start":{"line":1073,"column":26},"end":{"line":1073,"column":39}}},"31":{"name":"(anonymous_31)","line":1085,"loc":{"start":{"line":1085,"column":22},"end":{"line":1085,"column":35}}},"32":{"name":"(anonymous_32)","line":1096,"loc":{"start":{"line":1096,"column":22},"end":{"line":1096,"column":35}}},"33":{"name":"(anonymous_33)","line":1107,"loc":{"start":{"line":1107,"column":21},"end":{"line":1107,"column":33}}},"34":{"name":"(anonymous_34)","line":1118,"loc":{"start":{"line":1118,"column":21},"end":{"line":1118,"column":33}}},"35":{"name":"(anonymous_35)","line":1140,"loc":{"start":{"line":1140,"column":17},"end":{"line":1140,"column":32}}},"36":{"name":"(anonymous_36)","line":1161,"loc":{"start":{"line":1161,"column":17},"end":{"line":1161,"column":31}}},"37":{"name":"(anonymous_37)","line":1179,"loc":{"start":{"line":1179,"column":17},"end":{"line":1179,"column":31}}},"38":{"name":"(anonymous_38)","line":1191,"loc":{"start":{"line":1191,"column":17},"end":{"line":1191,"column":31}}}},"statementMap":{"1":{"start":{"line":1,"column":0},"end":{"line":1456,"column":113}},"2":{"start":{"line":11,"column":0},"end":{"line":51,"column":6}},"3":{"start":{"line":50,"column":8},"end":{"line":50,"column":49}},"4":{"start":{"line":62,"column":0},"end":{"line":64,"column":1}},"5":{"start":{"line":63,"column":4},"end":{"line":63,"column":61}},"6":{"start":{"line":66,"column":0},"end":{"line":1454,"column":3}},"7":{"start":{"line":169,"column":8},"end":{"line":169,"column":22}},"8":{"start":{"line":172,"column":8},"end":{"line":172,"column":38}},"9":{"start":{"line":173,"column":8},"end":{"line":173,"column":37}},"10":{"start":{"line":176,"column":8},"end":{"line":176,"column":33}},"11":{"start":{"line":177,"column":8},"end":{"line":177,"column":37}},"12":{"start":{"line":178,"column":8},"end":{"line":178,"column":48}},"13":{"start":{"line":179,"column":8},"end":{"line":179,"column":49}},"14":{"start":{"line":180,"column":8},"end":{"line":180,"column":52}},"15":{"start":{"line":190,"column":8},"end":{"line":190,"column":22}},"16":{"start":{"line":193,"column":8},"end":{"line":193,"column":37}},"17":{"start":{"line":194,"column":8},"end":{"line":194,"column":35}},"18":{"start":{"line":195,"column":8},"end":{"line":195,"column":33}},"19":{"start":{"line":198,"column":8},"end":{"line":198,"column":24}},"20":{"start":{"line":201,"column":8},"end":{"line":203,"column":9}},"21":{"start":{"line":202,"column":12},"end":{"line":202,"column":44}},"22":{"start":{"line":206,"column":8},"end":{"line":208,"column":9}},"23":{"start":{"line":207,"column":12},"end":{"line":207,"column":60}},"24":{"start":{"line":210,"column":8},"end":{"line":212,"column":9}},"25":{"start":{"line":211,"column":12},"end":{"line":211,"column":56}},"26":{"start":{"line":214,"column":8},"end":{"line":216,"column":9}},"27":{"start":{"line":215,"column":12},"end":{"line":215,"column":46}},"28":{"start":{"line":218,"column":8},"end":{"line":220,"column":9}},"29":{"start":{"line":219,"column":12},"end":{"line":219,"column":58}},"30":{"start":{"line":222,"column":8},"end":{"line":224,"column":9}},"31":{"start":{"line":223,"column":12},"end":{"line":223,"column":58}},"32":{"start":{"line":238,"column":8},"end":{"line":240,"column":50}},"33":{"start":{"line":243,"column":8},"end":{"line":253,"column":11}},"34":{"start":{"line":266,"column":8},"end":{"line":267,"column":24}},"35":{"start":{"line":270,"column":8},"end":{"line":270,"column":31}},"36":{"start":{"line":272,"column":8},"end":{"line":274,"column":9}},"37":{"start":{"line":273,"column":12},"end":{"line":273,"column":89}},"38":{"start":{"line":286,"column":8},"end":{"line":287,"column":24}},"39":{"start":{"line":290,"column":8},"end":{"line":290,"column":32}},"40":{"start":{"line":292,"column":8},"end":{"line":297,"column":9}},"41":{"start":{"line":293,"column":12},"end":{"line":293,"column":69}},"42":{"start":{"line":296,"column":12},"end":{"line":296,"column":39}},"43":{"start":{"line":309,"column":8},"end":{"line":310,"column":24}},"44":{"start":{"line":314,"column":8},"end":{"line":314,"column":37}},"45":{"start":{"line":317,"column":8},"end":{"line":320,"column":9}},"46":{"start":{"line":319,"column":12},"end":{"line":319,"column":71}},"47":{"start":{"line":331,"column":8},"end":{"line":336,"column":51}},"48":{"start":{"line":339,"column":8},"end":{"line":348,"column":9}},"49":{"start":{"line":342,"column":12},"end":{"line":345,"column":14}},"50":{"start":{"line":347,"column":12},"end":{"line":347,"column":37}},"51":{"start":{"line":351,"column":8},"end":{"line":351,"column":66}},"52":{"start":{"line":354,"column":8},"end":{"line":354,"column":41}},"53":{"start":{"line":357,"column":8},"end":{"line":357,"column":33}},"54":{"start":{"line":360,"column":8},"end":{"line":362,"column":9}},"55":{"start":{"line":361,"column":12},"end":{"line":361,"column":27}},"56":{"start":{"line":375,"column":8},"end":{"line":385,"column":17}},"57":{"start":{"line":388,"column":8},"end":{"line":391,"column":9}},"58":{"start":{"line":389,"column":12},"end":{"line":389,"column":46}},"59":{"start":{"line":390,"column":12},"end":{"line":390,"column":47}},"60":{"start":{"line":393,"column":8},"end":{"line":393,"column":48}},"61":{"start":{"line":394,"column":8},"end":{"line":394,"column":38}},"62":{"start":{"line":396,"column":8},"end":{"line":396,"column":29}},"63":{"start":{"line":397,"column":8},"end":{"line":402,"column":10}},"64":{"start":{"line":403,"column":8},"end":{"line":403,"column":43}},"65":{"start":{"line":405,"column":8},"end":{"line":405,"column":48}},"66":{"start":{"line":407,"column":8},"end":{"line":407,"column":20}},"67":{"start":{"line":418,"column":8},"end":{"line":430,"column":60}},"68":{"start":{"line":432,"column":8},"end":{"line":434,"column":9}},"69":{"start":{"line":433,"column":12},"end":{"line":433,"column":48}},"70":{"start":{"line":436,"column":8},"end":{"line":438,"column":9}},"71":{"start":{"line":437,"column":12},"end":{"line":437,"column":46}},"72":{"start":{"line":440,"column":8},"end":{"line":445,"column":11}},"73":{"start":{"line":460,"column":8},"end":{"line":460,"column":22}},"74":{"start":{"line":464,"column":8},"end":{"line":464,"column":43}},"75":{"start":{"line":465,"column":8},"end":{"line":465,"column":43}},"76":{"start":{"line":466,"column":8},"end":{"line":466,"column":43}},"77":{"start":{"line":467,"column":8},"end":{"line":467,"column":43}},"78":{"start":{"line":477,"column":8},"end":{"line":477,"column":22}},"79":{"start":{"line":479,"column":8},"end":{"line":484,"column":10}},"80":{"start":{"line":501,"column":8},"end":{"line":503,"column":9}},"81":{"start":{"line":502,"column":12},"end":{"line":502,"column":19}},"82":{"start":{"line":505,"column":8},"end":{"line":512,"column":22}},"83":{"start":{"line":515,"column":8},"end":{"line":515,"column":33}},"84":{"start":{"line":516,"column":8},"end":{"line":516,"column":42}},"85":{"start":{"line":517,"column":8},"end":{"line":517,"column":26}},"86":{"start":{"line":519,"column":8},"end":{"line":522,"column":9}},"87":{"start":{"line":520,"column":12},"end":{"line":520,"column":42}},"88":{"start":{"line":521,"column":12},"end":{"line":521,"column":24}},"89":{"start":{"line":524,"column":8},"end":{"line":527,"column":9}},"90":{"start":{"line":525,"column":12},"end":{"line":525,"column":42}},"91":{"start":{"line":526,"column":12},"end":{"line":526,"column":24}},"92":{"start":{"line":529,"column":8},"end":{"line":529,"column":46}},"93":{"start":{"line":531,"column":8},"end":{"line":534,"column":9}},"94":{"start":{"line":533,"column":12},"end":{"line":533,"column":80}},"95":{"start":{"line":537,"column":8},"end":{"line":567,"column":9}},"96":{"start":{"line":538,"column":12},"end":{"line":550,"column":13}},"97":{"start":{"line":539,"column":16},"end":{"line":539,"column":54}},"98":{"start":{"line":544,"column":16},"end":{"line":546,"column":17}},"99":{"start":{"line":545,"column":20},"end":{"line":545,"column":51}},"100":{"start":{"line":547,"column":16},"end":{"line":549,"column":17}},"101":{"start":{"line":548,"column":20},"end":{"line":548,"column":50}},"102":{"start":{"line":555,"column":12},"end":{"line":555,"column":39}},"103":{"start":{"line":556,"column":12},"end":{"line":556,"column":50}},"104":{"start":{"line":558,"column":12},"end":{"line":564,"column":13}},"105":{"start":{"line":559,"column":16},"end":{"line":559,"column":49}},"106":{"start":{"line":562,"column":16},"end":{"line":562,"column":44}},"107":{"start":{"line":563,"column":16},"end":{"line":563,"column":43}},"108":{"start":{"line":566,"column":12},"end":{"line":566,"column":50}},"109":{"start":{"line":581,"column":8},"end":{"line":581,"column":57}},"110":{"start":{"line":583,"column":8},"end":{"line":585,"column":9}},"111":{"start":{"line":584,"column":12},"end":{"line":584,"column":37}},"112":{"start":{"line":587,"column":8},"end":{"line":587,"column":20}},"113":{"start":{"line":600,"column":8},"end":{"line":605,"column":9}},"114":{"start":{"line":601,"column":12},"end":{"line":601,"column":62}},"115":{"start":{"line":603,"column":12},"end":{"line":603,"column":40}},"116":{"start":{"line":604,"column":12},"end":{"line":604,"column":39}},"117":{"start":{"line":617,"column":8},"end":{"line":617,"column":22}},"118":{"start":{"line":620,"column":8},"end":{"line":631,"column":9}},"119":{"start":{"line":621,"column":12},"end":{"line":621,"column":27}},"120":{"start":{"line":630,"column":12},"end":{"line":630,"column":35}},"121":{"start":{"line":643,"column":8},"end":{"line":645,"column":9}},"122":{"start":{"line":644,"column":12},"end":{"line":644,"column":25}},"123":{"start":{"line":647,"column":8},"end":{"line":652,"column":32}},"124":{"start":{"line":654,"column":8},"end":{"line":656,"column":9}},"125":{"start":{"line":655,"column":12},"end":{"line":655,"column":31}},"126":{"start":{"line":659,"column":8},"end":{"line":662,"column":9}},"127":{"start":{"line":660,"column":12},"end":{"line":660,"column":30}},"128":{"start":{"line":661,"column":12},"end":{"line":661,"column":29}},"129":{"start":{"line":665,"column":8},"end":{"line":665,"column":31}},"130":{"start":{"line":668,"column":8},"end":{"line":697,"column":10}},"131":{"start":{"line":708,"column":8},"end":{"line":718,"column":32}},"132":{"start":{"line":720,"column":8},"end":{"line":722,"column":9}},"133":{"start":{"line":721,"column":12},"end":{"line":721,"column":31}},"134":{"start":{"line":724,"column":8},"end":{"line":724,"column":48}},"135":{"start":{"line":725,"column":8},"end":{"line":725,"column":48}},"136":{"start":{"line":729,"column":8},"end":{"line":731,"column":9}},"137":{"start":{"line":730,"column":12},"end":{"line":730,"column":97}},"138":{"start":{"line":734,"column":8},"end":{"line":739,"column":9}},"139":{"start":{"line":735,"column":12},"end":{"line":735,"column":54}},"140":{"start":{"line":737,"column":13},"end":{"line":739,"column":9}},"141":{"start":{"line":738,"column":12},"end":{"line":738,"column":54}},"142":{"start":{"line":750,"column":8},"end":{"line":755,"column":18}},"143":{"start":{"line":757,"column":8},"end":{"line":759,"column":9}},"144":{"start":{"line":758,"column":12},"end":{"line":758,"column":31}},"145":{"start":{"line":762,"column":8},"end":{"line":762,"column":37}},"146":{"start":{"line":763,"column":8},"end":{"line":763,"column":37}},"147":{"start":{"line":766,"column":8},"end":{"line":766,"column":39}},"148":{"start":{"line":767,"column":8},"end":{"line":767,"column":42}},"149":{"start":{"line":770,"column":8},"end":{"line":794,"column":9}},"150":{"start":{"line":776,"column":12},"end":{"line":793,"column":13}},"151":{"start":{"line":778,"column":16},"end":{"line":778,"column":44}},"152":{"start":{"line":781,"column":16},"end":{"line":792,"column":17}},"153":{"start":{"line":782,"column":20},"end":{"line":782,"column":35}},"154":{"start":{"line":789,"column":20},"end":{"line":791,"column":21}},"155":{"start":{"line":790,"column":24},"end":{"line":790,"column":41}},"156":{"start":{"line":805,"column":8},"end":{"line":807,"column":9}},"157":{"start":{"line":806,"column":12},"end":{"line":806,"column":25}},"158":{"start":{"line":809,"column":8},"end":{"line":815,"column":45}},"159":{"start":{"line":818,"column":8},"end":{"line":820,"column":9}},"160":{"start":{"line":819,"column":12},"end":{"line":819,"column":38}},"161":{"start":{"line":823,"column":8},"end":{"line":825,"column":9}},"162":{"start":{"line":824,"column":12},"end":{"line":824,"column":68}},"163":{"start":{"line":839,"column":8},"end":{"line":864,"column":20}},"164":{"start":{"line":867,"column":8},"end":{"line":869,"column":9}},"165":{"start":{"line":868,"column":12},"end":{"line":868,"column":34}},"166":{"start":{"line":872,"column":8},"end":{"line":872,"column":61}},"167":{"start":{"line":875,"column":8},"end":{"line":897,"column":9}},"168":{"start":{"line":877,"column":12},"end":{"line":879,"column":13}},"169":{"start":{"line":878,"column":16},"end":{"line":878,"column":34}},"170":{"start":{"line":882,"column":12},"end":{"line":889,"column":13}},"171":{"start":{"line":883,"column":16},"end":{"line":883,"column":33}},"172":{"start":{"line":888,"column":16},"end":{"line":888,"column":31}},"173":{"start":{"line":895,"column":12},"end":{"line":895,"column":109}},"174":{"start":{"line":896,"column":12},"end":{"line":896,"column":42}},"175":{"start":{"line":901,"column":8},"end":{"line":901,"column":22}},"176":{"start":{"line":903,"column":8},"end":{"line":909,"column":9}},"177":{"start":{"line":905,"column":12},"end":{"line":905,"column":35}},"178":{"start":{"line":908,"column":12},"end":{"line":908,"column":33}},"179":{"start":{"line":921,"column":8},"end":{"line":927,"column":72}},"180":{"start":{"line":929,"column":8},"end":{"line":929,"column":80}},"181":{"start":{"line":935,"column":8},"end":{"line":958,"column":9}},"182":{"start":{"line":938,"column":12},"end":{"line":938,"column":35}},"183":{"start":{"line":941,"column":12},"end":{"line":941,"column":40}},"184":{"start":{"line":945,"column":12},"end":{"line":951,"column":13}},"185":{"start":{"line":947,"column":16},"end":{"line":947,"column":40}},"186":{"start":{"line":948,"column":16},"end":{"line":948,"column":38}},"187":{"start":{"line":954,"column":12},"end":{"line":954,"column":29}},"188":{"start":{"line":957,"column":12},"end":{"line":957,"column":31}},"189":{"start":{"line":971,"column":8},"end":{"line":981,"column":37}},"190":{"start":{"line":983,"column":8},"end":{"line":983,"column":118}},"191":{"start":{"line":994,"column":8},"end":{"line":1005,"column":41}},"192":{"start":{"line":1007,"column":8},"end":{"line":1015,"column":9}},"193":{"start":{"line":1008,"column":12},"end":{"line":1008,"column":71}},"194":{"start":{"line":1010,"column":13},"end":{"line":1015,"column":9}},"195":{"start":{"line":1011,"column":12},"end":{"line":1011,"column":71}},"196":{"start":{"line":1014,"column":12},"end":{"line":1014,"column":29}},"197":{"start":{"line":1026,"column":8},"end":{"line":1028,"column":9}},"198":{"start":{"line":1027,"column":12},"end":{"line":1027,"column":25}},"199":{"start":{"line":1030,"column":8},"end":{"line":1034,"column":30}},"200":{"start":{"line":1037,"column":8},"end":{"line":1037,"column":73}},"201":{"start":{"line":1040,"column":8},"end":{"line":1047,"column":9}},"202":{"start":{"line":1041,"column":12},"end":{"line":1041,"column":35}},"203":{"start":{"line":1042,"column":12},"end":{"line":1042,"column":48}},"204":{"start":{"line":1045,"column":12},"end":{"line":1045,"column":48}},"205":{"start":{"line":1046,"column":12},"end":{"line":1046,"column":35}},"206":{"start":{"line":1049,"column":8},"end":{"line":1049,"column":36}},"207":{"start":{"line":1050,"column":8},"end":{"line":1050,"column":34}},"208":{"start":{"line":1052,"column":8},"end":{"line":1052,"column":44}},"209":{"start":{"line":1063,"column":8},"end":{"line":1063,"column":34}},"210":{"start":{"line":1075,"column":8},"end":{"line":1075,"column":35}},"211":{"start":{"line":1086,"column":8},"end":{"line":1086,"column":31}},"212":{"start":{"line":1097,"column":8},"end":{"line":1097,"column":33}},"213":{"start":{"line":1108,"column":8},"end":{"line":1108,"column":35}},"214":{"start":{"line":1119,"column":8},"end":{"line":1119,"column":22}},"215":{"start":{"line":1121,"column":8},"end":{"line":1123,"column":9}},"216":{"start":{"line":1122,"column":12},"end":{"line":1122,"column":30}},"217":{"start":{"line":1143,"column":8},"end":{"line":1148,"column":9}},"218":{"start":{"line":1144,"column":12},"end":{"line":1147,"column":14}},"219":{"start":{"line":1164,"column":8},"end":{"line":1166,"column":9}},"220":{"start":{"line":1165,"column":12},"end":{"line":1165,"column":44}},"221":{"start":{"line":1168,"column":8},"end":{"line":1168,"column":19}},"222":{"start":{"line":1180,"column":8},"end":{"line":1180,"column":43}},"223":{"start":{"line":1192,"column":8},"end":{"line":1192,"column":43}}},"branchMap":{"1":{"line":78,"type":"cond-expr","locations":[{"start":{"line":78,"column":38},"end":{"line":78,"column":42}},{"start":{"line":78,"column":45},"end":{"line":78,"column":50}}]},"2":{"line":201,"type":"if","locations":[{"start":{"line":201,"column":8},"end":{"line":201,"column":8}},{"start":{"line":201,"column":8},"end":{"line":201,"column":8}}]},"3":{"line":206,"type":"if","locations":[{"start":{"line":206,"column":8},"end":{"line":206,"column":8}},{"start":{"line":206,"column":8},"end":{"line":206,"column":8}}]},"4":{"line":210,"type":"if","locations":[{"start":{"line":210,"column":8},"end":{"line":210,"column":8}},{"start":{"line":210,"column":8},"end":{"line":210,"column":8}}]},"5":{"line":214,"type":"if","locations":[{"start":{"line":214,"column":8},"end":{"line":214,"column":8}},{"start":{"line":214,"column":8},"end":{"line":214,"column":8}}]},"6":{"line":218,"type":"if","locations":[{"start":{"line":218,"column":8},"end":{"line":218,"column":8}},{"start":{"line":218,"column":8},"end":{"line":218,"column":8}}]},"7":{"line":222,"type":"if","locations":[{"start":{"line":222,"column":8},"end":{"line":222,"column":8}},{"start":{"line":222,"column":8},"end":{"line":222,"column":8}}]},"8":{"line":272,"type":"if","locations":[{"start":{"line":272,"column":8},"end":{"line":272,"column":8}},{"start":{"line":272,"column":8},"end":{"line":272,"column":8}}]},"9":{"line":292,"type":"if","locations":[{"start":{"line":292,"column":8},"end":{"line":292,"column":8}},{"start":{"line":292,"column":8},"end":{"line":292,"column":8}}]},"10":{"line":317,"type":"if","locations":[{"start":{"line":317,"column":8},"end":{"line":317,"column":8}},{"start":{"line":317,"column":8},"end":{"line":317,"column":8}}]},"11":{"line":339,"type":"if","locations":[{"start":{"line":339,"column":8},"end":{"line":339,"column":8}},{"start":{"line":339,"column":8},"end":{"line":339,"column":8}}]},"12":{"line":360,"type":"if","locations":[{"start":{"line":360,"column":8},"end":{"line":360,"column":8}},{"start":{"line":360,"column":8},"end":{"line":360,"column":8}}]},"13":{"line":388,"type":"if","locations":[{"start":{"line":388,"column":8},"end":{"line":388,"column":8}},{"start":{"line":388,"column":8},"end":{"line":388,"column":8}}]},"14":{"line":427,"type":"cond-expr","locations":[{"start":{"line":427,"column":32},"end":{"line":427,"column":67}},{"start":{"line":427,"column":70},"end":{"line":427,"column":71}}]},"15":{"line":428,"type":"cond-expr","locations":[{"start":{"line":428,"column":32},"end":{"line":428,"column":33}},{"start":{"line":428,"column":36},"end":{"line":428,"column":68}}]},"16":{"line":432,"type":"if","locations":[{"start":{"line":432,"column":8},"end":{"line":432,"column":8}},{"start":{"line":432,"column":8},"end":{"line":432,"column":8}}]},"17":{"line":432,"type":"binary-expr","locations":[{"start":{"line":432,"column":12},"end":{"line":432,"column":18}},{"start":{"line":432,"column":22},"end":{"line":432,"column":30}}]},"18":{"line":436,"type":"if","locations":[{"start":{"line":436,"column":8},"end":{"line":436,"column":8}},{"start":{"line":436,"column":8},"end":{"line":436,"column":8}}]},"19":{"line":436,"type":"binary-expr","locations":[{"start":{"line":436,"column":12},"end":{"line":436,"column":18}},{"start":{"line":436,"column":22},"end":{"line":436,"column":30}}]},"20":{"line":501,"type":"if","locations":[{"start":{"line":501,"column":8},"end":{"line":501,"column":8}},{"start":{"line":501,"column":8},"end":{"line":501,"column":8}}]},"21":{"line":515,"type":"binary-expr","locations":[{"start":{"line":515,"column":19},"end":{"line":515,"column":27}},{"start":{"line":515,"column":31},"end":{"line":515,"column":32}}]},"22":{"line":516,"type":"binary-expr","locations":[{"start":{"line":516,"column":17},"end":{"line":516,"column":23}},{"start":{"line":516,"column":27},"end":{"line":516,"column":41}}]},"23":{"line":517,"type":"binary-expr","locations":[{"start":{"line":517,"column":15},"end":{"line":517,"column":19}},{"start":{"line":517,"column":23},"end":{"line":517,"column":25}}]},"24":{"line":519,"type":"if","locations":[{"start":{"line":519,"column":8},"end":{"line":519,"column":8}},{"start":{"line":519,"column":8},"end":{"line":519,"column":8}}]},"25":{"line":524,"type":"if","locations":[{"start":{"line":524,"column":8},"end":{"line":524,"column":8}},{"start":{"line":524,"column":8},"end":{"line":524,"column":8}}]},"26":{"line":531,"type":"if","locations":[{"start":{"line":531,"column":8},"end":{"line":531,"column":8}},{"start":{"line":531,"column":8},"end":{"line":531,"column":8}}]},"27":{"line":537,"type":"if","locations":[{"start":{"line":537,"column":8},"end":{"line":537,"column":8}},{"start":{"line":537,"column":8},"end":{"line":537,"column":8}}]},"28":{"line":538,"type":"if","locations":[{"start":{"line":538,"column":12},"end":{"line":538,"column":12}},{"start":{"line":538,"column":12},"end":{"line":538,"column":12}}]},"29":{"line":544,"type":"if","locations":[{"start":{"line":544,"column":16},"end":{"line":544,"column":16}},{"start":{"line":544,"column":16},"end":{"line":544,"column":16}}]},"30":{"line":547,"type":"if","locations":[{"start":{"line":547,"column":16},"end":{"line":547,"column":16}},{"start":{"line":547,"column":16},"end":{"line":547,"column":16}}]},"31":{"line":558,"type":"if","locations":[{"start":{"line":558,"column":12},"end":{"line":558,"column":12}},{"start":{"line":558,"column":12},"end":{"line":558,"column":12}}]},"32":{"line":583,"type":"if","locations":[{"start":{"line":583,"column":8},"end":{"line":583,"column":8}},{"start":{"line":583,"column":8},"end":{"line":583,"column":8}}]},"33":{"line":600,"type":"if","locations":[{"start":{"line":600,"column":8},"end":{"line":600,"column":8}},{"start":{"line":600,"column":8},"end":{"line":600,"column":8}}]},"34":{"line":620,"type":"if","locations":[{"start":{"line":620,"column":8},"end":{"line":620,"column":8}},{"start":{"line":620,"column":8},"end":{"line":620,"column":8}}]},"35":{"line":643,"type":"if","locations":[{"start":{"line":643,"column":8},"end":{"line":643,"column":8}},{"start":{"line":643,"column":8},"end":{"line":643,"column":8}}]},"36":{"line":654,"type":"if","locations":[{"start":{"line":654,"column":8},"end":{"line":654,"column":8}},{"start":{"line":654,"column":8},"end":{"line":654,"column":8}}]},"37":{"line":659,"type":"if","locations":[{"start":{"line":659,"column":8},"end":{"line":659,"column":8}},{"start":{"line":659,"column":8},"end":{"line":659,"column":8}}]},"38":{"line":720,"type":"if","locations":[{"start":{"line":720,"column":8},"end":{"line":720,"column":8}},{"start":{"line":720,"column":8},"end":{"line":720,"column":8}}]},"39":{"line":729,"type":"if","locations":[{"start":{"line":729,"column":8},"end":{"line":729,"column":8}},{"start":{"line":729,"column":8},"end":{"line":729,"column":8}}]},"40":{"line":730,"type":"cond-expr","locations":[{"start":{"line":730,"column":83},"end":{"line":730,"column":88}},{"start":{"line":730,"column":91},"end":{"line":730,"column":96}}]},"41":{"line":734,"type":"if","locations":[{"start":{"line":734,"column":8},"end":{"line":734,"column":8}},{"start":{"line":734,"column":8},"end":{"line":734,"column":8}}]},"42":{"line":734,"type":"binary-expr","locations":[{"start":{"line":734,"column":12},"end":{"line":734,"column":34}},{"start":{"line":734,"column":38},"end":{"line":734,"column":45}}]},"43":{"line":737,"type":"if","locations":[{"start":{"line":737,"column":13},"end":{"line":737,"column":13}},{"start":{"line":737,"column":13},"end":{"line":737,"column":13}}]},"44":{"line":737,"type":"binary-expr","locations":[{"start":{"line":737,"column":17},"end":{"line":737,"column":39}},{"start":{"line":737,"column":43},"end":{"line":737,"column":50}}]},"45":{"line":757,"type":"if","locations":[{"start":{"line":757,"column":8},"end":{"line":757,"column":8}},{"start":{"line":757,"column":8},"end":{"line":757,"column":8}}]},"46":{"line":770,"type":"if","locations":[{"start":{"line":770,"column":8},"end":{"line":770,"column":8}},{"start":{"line":770,"column":8},"end":{"line":770,"column":8}}]},"47":{"line":776,"type":"if","locations":[{"start":{"line":776,"column":12},"end":{"line":776,"column":12}},{"start":{"line":776,"column":12},"end":{"line":776,"column":12}}]},"48":{"line":776,"type":"binary-expr","locations":[{"start":{"line":776,"column":16},"end":{"line":776,"column":39}},{"start":{"line":776,"column":43},"end":{"line":776,"column":66}}]},"49":{"line":781,"type":"if","locations":[{"start":{"line":781,"column":16},"end":{"line":781,"column":16}},{"start":{"line":781,"column":16},"end":{"line":781,"column":16}}]},"50":{"line":789,"type":"if","locations":[{"start":{"line":789,"column":20},"end":{"line":789,"column":20}},{"start":{"line":789,"column":20},"end":{"line":789,"column":20}}]},"51":{"line":789,"type":"binary-expr","locations":[{"start":{"line":789,"column":24},"end":{"line":789,"column":33}},{"start":{"line":789,"column":38},"end":{"line":789,"column":46}},{"start":{"line":789,"column":50},"end":{"line":789,"column":83}}]},"52":{"line":805,"type":"if","locations":[{"start":{"line":805,"column":8},"end":{"line":805,"column":8}},{"start":{"line":805,"column":8},"end":{"line":805,"column":8}}]},"53":{"line":814,"type":"cond-expr","locations":[{"start":{"line":814,"column":45},"end":{"line":814,"column":53}},{"start":{"line":814,"column":56},"end":{"line":814,"column":64}}]},"54":{"line":818,"type":"if","locations":[{"start":{"line":818,"column":8},"end":{"line":818,"column":8}},{"start":{"line":818,"column":8},"end":{"line":818,"column":8}}]},"55":{"line":823,"type":"if","locations":[{"start":{"line":823,"column":8},"end":{"line":823,"column":8}},{"start":{"line":823,"column":8},"end":{"line":823,"column":8}}]},"56":{"line":840,"type":"cond-expr","locations":[{"start":{"line":840,"column":45},"end":{"line":840,"column":53}},{"start":{"line":840,"column":56},"end":{"line":840,"column":64}}]},"57":{"line":854,"type":"cond-expr","locations":[{"start":{"line":854,"column":40},"end":{"line":854,"column":57}},{"start":{"line":854,"column":60},"end":{"line":854,"column":77}}]},"58":{"line":855,"type":"cond-expr","locations":[{"start":{"line":855,"column":40},"end":{"line":855,"column":57}},{"start":{"line":855,"column":60},"end":{"line":855,"column":77}}]},"59":{"line":861,"type":"binary-expr","locations":[{"start":{"line":861,"column":30},"end":{"line":861,"column":38}},{"start":{"line":861,"column":43},"end":{"line":861,"column":76}}]},"60":{"line":862,"type":"binary-expr","locations":[{"start":{"line":862,"column":30},"end":{"line":862,"column":38}},{"start":{"line":862,"column":43},"end":{"line":862,"column":76}}]},"61":{"line":867,"type":"if","locations":[{"start":{"line":867,"column":8},"end":{"line":867,"column":8}},{"start":{"line":867,"column":8},"end":{"line":867,"column":8}}]},"62":{"line":867,"type":"binary-expr","locations":[{"start":{"line":867,"column":12},"end":{"line":867,"column":26}},{"start":{"line":867,"column":30},"end":{"line":867,"column":44}}]},"63":{"line":875,"type":"if","locations":[{"start":{"line":875,"column":8},"end":{"line":875,"column":8}},{"start":{"line":875,"column":8},"end":{"line":875,"column":8}}]},"64":{"line":875,"type":"binary-expr","locations":[{"start":{"line":875,"column":12},"end":{"line":875,"column":19}},{"start":{"line":875,"column":23},"end":{"line":875,"column":36}},{"start":{"line":875,"column":40},"end":{"line":875,"column":53}}]},"65":{"line":877,"type":"if","locations":[{"start":{"line":877,"column":12},"end":{"line":877,"column":12}},{"start":{"line":877,"column":12},"end":{"line":877,"column":12}}]},"66":{"line":882,"type":"if","locations":[{"start":{"line":882,"column":12},"end":{"line":882,"column":12}},{"start":{"line":882,"column":12},"end":{"line":882,"column":12}}]},"67":{"line":882,"type":"binary-expr","locations":[{"start":{"line":882,"column":16},"end":{"line":882,"column":24}},{"start":{"line":882,"column":28},"end":{"line":882,"column":36}}]},"68":{"line":903,"type":"if","locations":[{"start":{"line":903,"column":8},"end":{"line":903,"column":8}},{"start":{"line":903,"column":8},"end":{"line":903,"column":8}}]},"69":{"line":927,"type":"cond-expr","locations":[{"start":{"line":927,"column":48},"end":{"line":927,"column":49}},{"start":{"line":927,"column":52},"end":{"line":927,"column":54}}]},"70":{"line":935,"type":"if","locations":[{"start":{"line":935,"column":8},"end":{"line":935,"column":8}},{"start":{"line":935,"column":8},"end":{"line":935,"column":8}}]},"71":{"line":935,"type":"binary-expr","locations":[{"start":{"line":935,"column":12},"end":{"line":935,"column":33}},{"start":{"line":935,"column":37},"end":{"line":935,"column":53}}]},"72":{"line":945,"type":"if","locations":[{"start":{"line":945,"column":12},"end":{"line":945,"column":12}},{"start":{"line":945,"column":12},"end":{"line":945,"column":12}}]},"73":{"line":975,"type":"binary-expr","locations":[{"start":{"line":975,"column":23},"end":{"line":975,"column":24}},{"start":{"line":975,"column":28},"end":{"line":975,"column":44}}]},"74":{"line":976,"type":"binary-expr","locations":[{"start":{"line":976,"column":23},"end":{"line":976,"column":24}},{"start":{"line":976,"column":28},"end":{"line":976,"column":44}}]},"75":{"line":983,"type":"binary-expr","locations":[{"start":{"line":983,"column":16},"end":{"line":983,"column":23}},{"start":{"line":983,"column":28},"end":{"line":983,"column":43}},{"start":{"line":983,"column":47},"end":{"line":983,"column":62}},{"start":{"line":983,"column":69},"end":{"line":983,"column":76}},{"start":{"line":983,"column":81},"end":{"line":983,"column":96}},{"start":{"line":983,"column":100},"end":{"line":983,"column":115}}]},"76":{"line":1007,"type":"if","locations":[{"start":{"line":1007,"column":8},"end":{"line":1007,"column":8}},{"start":{"line":1007,"column":8},"end":{"line":1007,"column":8}}]},"77":{"line":1010,"type":"if","locations":[{"start":{"line":1010,"column":13},"end":{"line":1010,"column":13}},{"start":{"line":1010,"column":13},"end":{"line":1010,"column":13}}]},"78":{"line":1026,"type":"if","locations":[{"start":{"line":1026,"column":8},"end":{"line":1026,"column":8}},{"start":{"line":1026,"column":8},"end":{"line":1026,"column":8}}]},"79":{"line":1040,"type":"if","locations":[{"start":{"line":1040,"column":8},"end":{"line":1040,"column":8}},{"start":{"line":1040,"column":8},"end":{"line":1040,"column":8}}]},"80":{"line":1121,"type":"if","locations":[{"start":{"line":1121,"column":8},"end":{"line":1121,"column":8}},{"start":{"line":1121,"column":8},"end":{"line":1121,"column":8}}]},"81":{"line":1143,"type":"if","locations":[{"start":{"line":1143,"column":8},"end":{"line":1143,"column":8}},{"start":{"line":1143,"column":8},"end":{"line":1143,"column":8}}]},"82":{"line":1145,"type":"cond-expr","locations":[{"start":{"line":1145,"column":37},"end":{"line":1145,"column":41}},{"start":{"line":1145,"column":44},"end":{"line":1145,"column":49}}]},"83":{"line":1146,"type":"cond-expr","locations":[{"start":{"line":1146,"column":37},"end":{"line":1146,"column":41}},{"start":{"line":1146,"column":44},"end":{"line":1146,"column":49}}]},"84":{"line":1164,"type":"if","locations":[{"start":{"line":1164,"column":8},"end":{"line":1164,"column":8}},{"start":{"line":1164,"column":8},"end":{"line":1164,"column":8}}]},"85":{"line":1393,"type":"cond-expr","locations":[{"start":{"line":1393,"column":34},"end":{"line":1393,"column":69}},{"start":{"line":1393,"column":72},"end":{"line":1393,"column":92}}]},"86":{"line":1394,"type":"cond-expr","locations":[{"start":{"line":1394,"column":34},"end":{"line":1394,"column":69}},{"start":{"line":1394,"column":72},"end":{"line":1394,"column":92}}]}},"code":["(function () { YUI.add('scrollview-base', function (Y, NAME) {","","/**"," * The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators"," *"," * @module scrollview"," * @submodule scrollview-base"," */",""," // Local vars","var getClassName = Y.ClassNameManager.getClassName,"," DOCUMENT = Y.config.doc,"," IE = Y.UA.ie,"," NATIVE_TRANSITIONS = Y.Transition.useNative,"," vendorPrefix = Y.Transition._VENDOR_PREFIX, // Todo: This is a private property, and alternative approaches should be investigated"," SCROLLVIEW = 'scrollview',"," CLASS_NAMES = {"," vertical: getClassName(SCROLLVIEW, 'vert'),"," horizontal: getClassName(SCROLLVIEW, 'horiz')"," },"," EV_SCROLL_END = 'scrollEnd',"," FLICK = 'flick',"," DRAG = 'drag',"," MOUSEWHEEL = 'mousewheel',"," UI = 'ui',"," TOP = 'top',"," LEFT = 'left',"," PX = 'px',"," AXIS = 'axis',"," SCROLL_Y = 'scrollY',"," SCROLL_X = 'scrollX',"," BOUNCE = 'bounce',"," DISABLED = 'disabled',"," DECELERATION = 'deceleration',"," DIM_X = 'x',"," DIM_Y = 'y',"," BOUNDING_BOX = 'boundingBox',"," CONTENT_BOX = 'contentBox',"," GESTURE_MOVE = 'gesturemove',"," START = 'start',"," END = 'end',"," EMPTY = '',"," ZERO = '0s',"," SNAP_DURATION = 'snapDuration',"," SNAP_EASING = 'snapEasing',"," EASING = 'easing',"," FRAME_DURATION = 'frameDuration',"," BOUNCE_RANGE = 'bounceRange',"," _constrain = function (val, min, max) {"," return Math.min(Math.max(val, min), max);"," };","","/**"," * ScrollView provides a scrollable widget, supporting flick gestures,"," * across both touch and mouse based devices."," *"," * @class ScrollView"," * @param config {Object} Object literal with initial attribute values"," * @extends Widget"," * @constructor"," */","function ScrollView() {"," ScrollView.superclass.constructor.apply(this, arguments);","}","","Y.ScrollView = Y.extend(ScrollView, Y.Widget, {",""," // *** Y.ScrollView prototype",""," /**"," * Flag driving whether or not we should try and force H/W acceleration when transforming. Currently enabled by default for Webkit."," * Used by the _transform method."," *"," * @property _forceHWTransforms"," * @type boolean"," * @protected"," */"," _forceHWTransforms: Y.UA.webkit ? true : false,",""," /**"," * <p>Used to control whether or not ScrollView's internal"," * gesturemovestart, gesturemove and gesturemoveend"," * event listeners should preventDefault. The value is an"," * object, with \"start\", \"move\" and \"end\" properties used to"," * specify which events should preventDefault and which shouldn't:</p>"," *"," * <pre>"," * {"," * start: false,"," * move: true,"," * end: false"," * }"," * </pre>"," *"," * <p>The default values are set up in order to prevent panning,"," * on touch devices, while allowing click listeners on elements inside"," * the ScrollView to be notified as expected.</p>"," *"," * @property _prevent"," * @type Object"," * @protected"," */"," _prevent: {"," start: false,"," move: true,"," end: false"," },",""," /**"," * Contains the distance (postive or negative) in pixels by which"," * the scrollview was last scrolled. This is useful when setting up"," * click listeners on the scrollview content, which on mouse based"," * devices are always fired, even after a drag/flick."," *"," * <p>Touch based devices don't currently fire a click event,"," * if the finger has been moved (beyond a threshold) so this"," * check isn't required, if working in a purely touch based environment</p>"," *"," * @property lastScrolledAmt"," * @type Number"," * @public"," * @default 0"," */"," lastScrolledAmt: 0,",""," /**"," * Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis"," *"," * @property _minScrollX"," * @type number"," * @protected"," */"," _minScrollX: null,",""," /**"," * Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis"," *"," * @property _maxScrollX"," * @type number"," * @protected"," */"," _maxScrollX: null,",""," /**"," * Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis"," *"," * @property _minScrollY"," * @type number"," * @protected"," */"," _minScrollY: null,",""," /**"," * Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis"," *"," * @property _maxScrollY"," * @type number"," * @protected"," */"," _maxScrollY: null,"," "," /**"," * Designated initializer"," *"," * @method initializer"," * @param {config} Configuration object for the plugin"," */"," initializer: function () {"," var sv = this;",""," // Cache these values, since they aren't going to change."," sv._bb = sv.get(BOUNDING_BOX);"," sv._cb = sv.get(CONTENT_BOX);",""," // Cache some attributes"," sv._cAxis = sv.get(AXIS);"," sv._cBounce = sv.get(BOUNCE);"," sv._cBounceRange = sv.get(BOUNCE_RANGE);"," sv._cDeceleration = sv.get(DECELERATION);"," sv._cFrameDuration = sv.get(FRAME_DURATION);"," },",""," /**"," * bindUI implementation"," *"," * Hooks up events for the widget"," * @method bindUI"," */"," bindUI: function () {"," var sv = this;",""," // Bind interaction listers"," sv._bindFlick(sv.get(FLICK));"," sv._bindDrag(sv.get(DRAG));"," sv._bindMousewheel(true);"," "," // Bind change events"," sv._bindAttrs();",""," // IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release."," if (IE) {"," sv._fixIESelect(sv._bb, sv._cb);"," }",""," // Set any deprecated static properties"," if (ScrollView.SNAP_DURATION) {"," sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION);"," }",""," if (ScrollView.SNAP_EASING) {"," sv.set(SNAP_EASING, ScrollView.SNAP_EASING);"," }",""," if (ScrollView.EASING) {"," sv.set(EASING, ScrollView.EASING);"," }",""," if (ScrollView.FRAME_STEP) {"," sv.set(FRAME_DURATION, ScrollView.FRAME_STEP);"," }",""," if (ScrollView.BOUNCE_RANGE) {"," sv.set(BOUNCE_RANGE, ScrollView.BOUNCE_RANGE);"," }",""," // Recalculate dimension properties"," // TODO: This should be throttled."," // Y.one(WINDOW).after('resize', sv._afterDimChange, sv);"," },",""," /**"," * Bind event listeners"," *"," * @method _bindAttrs"," * @private"," */"," _bindAttrs: function () {"," var sv = this,"," scrollChangeHandler = sv._afterScrollChange,"," dimChangeHandler = sv._afterDimChange;",""," // Bind any change event listeners"," sv.after({"," 'scrollEnd': sv._afterScrollEnd,"," 'disabledChange': sv._afterDisabledChange,"," 'flickChange': sv._afterFlickChange,"," 'dragChange': sv._afterDragChange,"," 'axisChange': sv._afterAxisChange,"," 'scrollYChange': scrollChangeHandler,"," 'scrollXChange': scrollChangeHandler,"," 'heightChange': dimChangeHandler,"," 'widthChange': dimChangeHandler"," });"," },",""," /**"," * Bind (or unbind) gesture move listeners required for drag support"," *"," * @method _bindDrag"," * @param drag {boolean} If true, the method binds listener to enable"," * drag (gesturemovestart). If false, the method unbinds gesturemove"," * listeners for drag support."," * @private"," */"," _bindDrag: function (drag) {"," var sv = this,"," bb = sv._bb;",""," // Unbind any previous 'drag' listeners"," bb.detach(DRAG + '|*');",""," if (drag) {"," bb.on(DRAG + '|' + GESTURE_MOVE + START, Y.bind(sv._onGestureMoveStart, sv));"," }"," },",""," /**"," * Bind (or unbind) flick listeners."," *"," * @method _bindFlick"," * @param flick {Object|boolean} If truthy, the method binds listeners for"," * flick support. If false, the method unbinds flick listeners."," * @private"," */"," _bindFlick: function (flick) {"," var sv = this,"," bb = sv._bb;",""," // Unbind any previous 'flick' listeners"," bb.detach(FLICK + '|*');",""," if (flick) {"," bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick);",""," // Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick"," sv._bindDrag(sv.get(DRAG));"," }"," },",""," /**"," * Bind (or unbind) mousewheel listeners."," *"," * @method _bindMousewheel"," * @param mousewheel {Object|boolean} If truthy, the method binds listeners for"," * mousewheel support. If false, the method unbinds mousewheel listeners."," * @private"," */"," _bindMousewheel: function (mousewheel) {"," var sv = this,"," bb = sv._bb;",""," // Unbind any previous 'mousewheel' listeners"," // TODO: This doesn't actually appear to work properly. Fix. #2532743"," bb.detach(MOUSEWHEEL + '|*');",""," // Only enable for vertical scrollviews"," if (mousewheel) {"," // Bound to document, because that's where mousewheel events fire off of."," Y.one(DOCUMENT).on(MOUSEWHEEL, Y.bind(sv._mousewheel, sv));"," }"," },",""," /**"," * syncUI implementation."," *"," * Update the scroll position, based on the current value of scrollX/scrollY."," *"," * @method syncUI"," */"," syncUI: function () {"," var sv = this,"," scrollDims = sv._getScrollDims(),"," width = scrollDims.offsetWidth,"," height = scrollDims.offsetHeight,"," scrollWidth = scrollDims.scrollWidth,"," scrollHeight = scrollDims.scrollHeight;",""," // If the axis is undefined, auto-calculate it"," if (sv._cAxis === undefined) {"," // This should only ever be run once (for now)."," // In the future SV might post-load axis changes"," sv._cAxis = {"," x: (scrollWidth > width),"," y: (scrollHeight > height)"," };",""," sv._set(AXIS, sv._cAxis);"," }"," "," // get text direction on or inherited by scrollview node"," sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl');",""," // Cache the disabled value"," sv._cDisabled = sv.get(DISABLED);",""," // Run this to set initial values"," sv._uiDimensionsChange();",""," // If we're out-of-bounds, snap back."," if (sv._isOutOfBounds()) {"," sv._snapBack();"," }"," },",""," /**"," * Utility method to obtain widget dimensions"," *"," * @method _getScrollDims"," * @return {Object} The offsetWidth, offsetHeight, scrollWidth and"," * scrollHeight as an array: [offsetWidth, offsetHeight, scrollWidth,"," * scrollHeight]"," * @private"," */"," _getScrollDims: function () {"," var sv = this,"," cb = sv._cb,"," bb = sv._bb,"," TRANS = ScrollView._TRANSITION,"," // Ideally using CSSMatrix - don't think we have it normalized yet though."," // origX = (new WebKitCSSMatrix(cb.getComputedStyle(\"transform\"))).e,"," // origY = (new WebKitCSSMatrix(cb.getComputedStyle(\"transform\"))).f,"," origX = sv.get(SCROLL_X),"," origY = sv.get(SCROLL_Y),"," origHWTransform,"," dims;",""," // TODO: Is this OK? Just in case it's called 'during' a transition."," if (NATIVE_TRANSITIONS) {"," cb.setStyle(TRANS.DURATION, ZERO);"," cb.setStyle(TRANS.PROPERTY, EMPTY);"," }",""," origHWTransform = sv._forceHWTransforms;"," sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac.",""," sv._moveTo(cb, 0, 0);"," dims = {"," 'offsetWidth': bb.get('offsetWidth'),"," 'offsetHeight': bb.get('offsetHeight'),"," 'scrollWidth': bb.get('scrollWidth'),"," 'scrollHeight': bb.get('scrollHeight')"," };"," sv._moveTo(cb, -(origX), -(origY));",""," sv._forceHWTransforms = origHWTransform;",""," return dims;"," },",""," /**"," * This method gets invoked whenever the height or width attributes change,"," * allowing us to determine which scrolling axes need to be enabled."," *"," * @method _uiDimensionsChange"," * @protected"," */"," _uiDimensionsChange: function () {"," var sv = this,"," bb = sv._bb,"," scrollDims = sv._getScrollDims(),"," width = scrollDims.offsetWidth,"," height = scrollDims.offsetHeight,"," scrollWidth = scrollDims.scrollWidth,"," scrollHeight = scrollDims.scrollHeight,"," rtl = sv.rtl,"," svAxis = sv._cAxis,"," minScrollX = (rtl ? Math.min(0, -(scrollWidth - width)) : 0),"," maxScrollX = (rtl ? 0 : Math.max(0, scrollWidth - width)),"," minScrollY = 0,"," maxScrollY = Math.max(0, scrollHeight - height);"," "," if (svAxis && svAxis.x) {"," bb.addClass(CLASS_NAMES.horizontal);"," }",""," if (svAxis && svAxis.y) {"," bb.addClass(CLASS_NAMES.vertical);"," }",""," sv._setBounds({"," minScrollX: minScrollX,"," maxScrollX: maxScrollX,"," minScrollY: minScrollY,"," maxScrollY: maxScrollY"," });"," },",""," /**"," * Set the bounding dimensions of the ScrollView"," *"," * @method _setBounds"," * @protected"," * @param bounds {Object} [duration] ms of the scroll animation. (default is 0)"," * @param {Number} [bounds.minScrollX] The minimum scroll X value"," * @param {Number} [bounds.maxScrollX] The maximum scroll X value"," * @param {Number} [bounds.minScrollY] The minimum scroll Y value"," * @param {Number} [bounds.maxScrollY] The maximum scroll Y value"," */"," _setBounds: function (bounds) {"," var sv = this;"," "," // TODO: Do a check to log if the bounds are invalid",""," sv._minScrollX = bounds.minScrollX;"," sv._maxScrollX = bounds.maxScrollX;"," sv._minScrollY = bounds.minScrollY;"," sv._maxScrollY = bounds.maxScrollY;"," },",""," /**"," * Get the bounding dimensions of the ScrollView"," *"," * @method _getBounds"," * @protected"," */"," _getBounds: function () {"," var sv = this;"," "," return {"," minScrollX: sv._minScrollX,"," maxScrollX: sv._maxScrollX,"," minScrollY: sv._minScrollY,"," maxScrollY: sv._maxScrollY"," };",""," },",""," /**"," * Scroll the element to a given xy coordinate"," *"," * @method scrollTo"," * @param x {Number} The x-position to scroll to. (null for no movement)"," * @param y {Number} The y-position to scroll to. (null for no movement)"," * @param {Number} [duration] ms of the scroll animation. (default is 0)"," * @param {String} [easing] An easing equation if duration is set. (default is `easing` attribute)"," * @param {String} [node] The node to transform. Setting this can be useful in"," * dual-axis paginated instances. (default is the instance's contentBox)"," */"," scrollTo: function (x, y, duration, easing, node) {"," // Check to see if widget is disabled"," if (this._cDisabled) {"," return;"," }",""," var sv = this,"," cb = sv._cb,"," TRANS = ScrollView._TRANSITION,"," callback = Y.bind(sv._onTransEnd, sv), // @Todo : cache this"," newX = 0,"," newY = 0,"," transition = {},"," transform;",""," // default the optional arguments"," duration = duration || 0;"," easing = easing || sv.get(EASING); // @TODO: Cache this"," node = node || cb;",""," if (x !== null) {"," sv.set(SCROLL_X, x, {src:UI});"," newX = -(x);"," }",""," if (y !== null) {"," sv.set(SCROLL_Y, y, {src:UI});"," newY = -(y);"," }",""," transform = sv._transform(newX, newY);",""," if (NATIVE_TRANSITIONS) {"," // ANDROID WORKAROUND - try and stop existing transition, before kicking off new one."," node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY);"," }",""," // Move"," if (duration === 0) {"," if (NATIVE_TRANSITIONS) {"," node.setStyle('transform', transform);"," }"," else {"," // TODO: If both set, batch them in the same update"," // Update: Nope, setStyles() just loops through each property and applies it."," if (x !== null) {"," node.setStyle(LEFT, newX + PX);"," }"," if (y !== null) {"," node.setStyle(TOP, newY + PX);"," }"," }"," }",""," // Animate"," else {"," transition.easing = easing;"," transition.duration = duration / 1000;",""," if (NATIVE_TRANSITIONS) {"," transition.transform = transform;"," }"," else {"," transition.left = newX + PX;"," transition.top = newY + PX;"," }",""," node.transition(transition, callback);"," }"," },",""," /**"," * Utility method, to create the translate transform string with the"," * x, y translation amounts provided."," *"," * @method _transform"," * @param {Number} x Number of pixels to translate along the x axis"," * @param {Number} y Number of pixels to translate along the y axis"," * @private"," */"," _transform: function (x, y) {"," // TODO: Would we be better off using a Matrix for this?"," var prop = 'translate(' + x + 'px, ' + y + 'px)';",""," if (this._forceHWTransforms) {"," prop += ' translateZ(0)';"," }",""," return prop;"," },",""," /**"," * Utility method, to move the given element to the given xy position"," *"," * @method _moveTo"," * @param node {Node} The node to move"," * @param x {Number} The x-position to move to"," * @param y {Number} The y-position to move to"," * @private"," */"," _moveTo : function(node, x, y) {"," if (NATIVE_TRANSITIONS) {"," node.setStyle('transform', this._transform(x, y));"," } else {"," node.setStyle(LEFT, x + PX);"," node.setStyle(TOP, y + PX);"," }"," },","",""," /**"," * Content box transition callback"," *"," * @method _onTransEnd"," * @param {Event.Facade} e The event facade"," * @private"," */"," _onTransEnd: function () {"," var sv = this;"," "," // If for some reason we're OOB, snapback"," if (sv._isOutOfBounds()) {"," sv._snapBack();"," }"," else {"," /**"," * Notification event fired at the end of a scroll transition"," *"," * @event scrollEnd"," * @param e {EventFacade} The default event facade."," */"," sv.fire(EV_SCROLL_END);"," }"," },",""," /**"," * gesturemovestart event handler"," *"," * @method _onGestureMoveStart"," * @param e {Event.Facade} The gesturemovestart event facade"," * @private"," */"," _onGestureMoveStart: function (e) {",""," if (this._cDisabled) {"," return false;"," }",""," var sv = this,"," bb = sv._bb,"," currentX = sv.get(SCROLL_X),"," currentY = sv.get(SCROLL_Y),"," clientX = e.clientX,"," clientY = e.clientY;",""," if (sv._prevent.start) {"," e.preventDefault();"," }",""," // if a flick animation is in progress, cancel it"," if (sv._flickAnim) {"," sv._cancelFlick();"," sv._onTransEnd();"," }",""," // Reset lastScrolledAmt"," sv.lastScrolledAmt = 0;",""," // Stores data for this gesture cycle. Cleaned up later"," sv._gesture = {",""," // Will hold the axis value"," axis: null,",""," // The current attribute values"," startX: currentX,"," startY: currentY,",""," // The X/Y coordinates where the event began"," startClientX: clientX,"," startClientY: clientY,",""," // The X/Y coordinates where the event will end"," endClientX: null,"," endClientY: null,",""," // The current delta of the event"," deltaX: null,"," deltaY: null,",""," // Will be populated for flicks"," flick: null,",""," // Create some listeners for the rest of the gesture cycle"," onGestureMove: bb.on(DRAG + '|' + GESTURE_MOVE, Y.bind(sv._onGestureMove, sv)),"," "," // @TODO: Don't bind gestureMoveEnd if it's a Flick?"," onGestureMoveEnd: bb.on(DRAG + '|' + GESTURE_MOVE + END, Y.bind(sv._onGestureMoveEnd, sv))"," };"," },",""," /**"," * gesturemove event handler"," *"," * @method _onGestureMove"," * @param e {Event.Facade} The gesturemove event facade"," * @private"," */"," _onGestureMove: function (e) {"," var sv = this,"," gesture = sv._gesture,"," svAxis = sv._cAxis,"," svAxisX = svAxis.x,"," svAxisY = svAxis.y,"," startX = gesture.startX,"," startY = gesture.startY,"," startClientX = gesture.startClientX,"," startClientY = gesture.startClientY,"," clientX = e.clientX,"," clientY = e.clientY;",""," if (sv._prevent.move) {"," e.preventDefault();"," }",""," gesture.deltaX = startClientX - clientX;"," gesture.deltaY = startClientY - clientY;",""," // Determine if this is a vertical or horizontal movement"," // @TODO: This is crude, but it works. Investigate more intelligent ways to detect intent"," if (gesture.axis === null) {"," gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y;"," }",""," // Move X or Y. @TODO: Move both if dualaxis."," if (gesture.axis === DIM_X && svAxisX) {"," sv.set(SCROLL_X, startX + gesture.deltaX);"," }"," else if (gesture.axis === DIM_Y && svAxisY) {"," sv.set(SCROLL_Y, startY + gesture.deltaY);"," }"," },",""," /**"," * gesturemoveend event handler"," *"," * @method _onGestureMoveEnd"," * @param e {Event.Facade} The gesturemoveend event facade"," * @private"," */"," _onGestureMoveEnd: function (e) {"," var sv = this,"," gesture = sv._gesture,"," flick = gesture.flick,"," clientX = e.clientX,"," clientY = e.clientY,"," isOOB;",""," if (sv._prevent.end) {"," e.preventDefault();"," }",""," // Store the end X/Y coordinates"," gesture.endClientX = clientX;"," gesture.endClientY = clientY;",""," // Cleanup the event handlers"," gesture.onGestureMove.detach();"," gesture.onGestureMoveEnd.detach();",""," // If this wasn't a flick, wrap up the gesture cycle"," if (!flick) {"," // @TODO: Be more intelligent about this. Look at the Flick attribute to see"," // if it is safe to assume _flick did or didn't fire."," // Then, the order _flick and _onGestureMoveEnd fire doesn't matter?",""," // If there was movement (_onGestureMove fired)"," if (gesture.deltaX !== null && gesture.deltaY !== null) {"," "," isOOB = sv._isOutOfBounds();"," "," // If we're out-out-bounds, then snapback"," if (isOOB) {"," sv._snapBack();"," }",""," // Inbounds"," else {"," // Fire scrollEnd unless this is a paginated instance and the gesture axis is the same as paginator's"," // Not totally confident this is ideal to access a plugin's properties from a host, @TODO revisit"," if (!sv.pages || (sv.pages && !sv.pages.get(AXIS)[gesture.axis])) {"," sv._onTransEnd();"," }"," }"," }"," }"," },",""," /**"," * Execute a flick at the end of a scroll action"," *"," * @method _flick"," * @param e {Event.Facade} The Flick event facade"," * @private"," */"," _flick: function (e) {"," if (this._cDisabled) {"," return false;"," }",""," var sv = this,"," svAxis = sv._cAxis,"," flick = e.flick,"," flickAxis = flick.axis,"," flickVelocity = flick.velocity,"," axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y,"," startPosition = sv.get(axisAttr);",""," // Sometimes flick is enabled, but drag is disabled"," if (sv._gesture) {"," sv._gesture.flick = flick;"," }",""," // Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis"," if (svAxis[flickAxis]) {"," sv._flickFrame(flickVelocity, flickAxis, startPosition);"," }"," },",""," /**"," * Execute a single frame in the flick animation"," *"," * @method _flickFrame"," * @param velocity {Number} The velocity of this animated frame"," * @param flickAxis {String} The axis on which to animate"," * @param startPosition {Number} The starting X/Y point to flick from"," * @protected"," */"," _flickFrame: function (velocity, flickAxis, startPosition) {",""," var sv = this,"," axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y,"," bounds = sv._getBounds(),",""," // Localize cached values"," bounce = sv._cBounce,"," bounceRange = sv._cBounceRange,"," deceleration = sv._cDeceleration,"," frameDuration = sv._cFrameDuration,",""," // Calculate"," newVelocity = velocity * deceleration,"," newPosition = startPosition - (frameDuration * newVelocity),",""," // Some convinience conditions"," min = flickAxis === DIM_X ? bounds.minScrollX : bounds.minScrollY,"," max = flickAxis === DIM_X ? bounds.maxScrollX : bounds.maxScrollY,"," belowMin = (newPosition < min),"," belowMax = (newPosition < max),"," aboveMin = (newPosition > min),"," aboveMax = (newPosition > max),"," belowMinRange = (newPosition < (min - bounceRange)),"," withinMinRange = (belowMin && (newPosition > (min - bounceRange))),"," withinMaxRange = (aboveMax && (newPosition < (max + bounceRange))),"," aboveMaxRange = (newPosition > (max + bounceRange)),"," tooSlow;",""," // If we're within the range but outside min/max, dampen the velocity"," if (withinMinRange || withinMaxRange) {"," newVelocity *= bounce;"," }",""," // Is the velocity too slow to bother?"," tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015);",""," // If the velocity is too slow or we're outside the range"," if (tooSlow || belowMinRange || aboveMaxRange) {"," // Cancel and delete sv._flickAnim"," if (sv._flickAnim) {"," sv._cancelFlick();"," }",""," // If we're inside the scroll area, just end"," if (aboveMin && belowMax) {"," sv._onTransEnd();"," }",""," // We're outside the scroll area, so we need to snap back"," else {"," sv._snapBack();"," }"," }",""," // Otherwise, animate to the next frame"," else {"," // @TODO: maybe use requestAnimationFrame instead"," sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]);"," sv.set(axisAttr, newPosition);"," }"," },",""," _cancelFlick: function () {"," var sv = this;",""," if (sv._flickAnim) {"," // Cancel the flick (if it exists)"," sv._flickAnim.cancel();",""," // Also delete it, otherwise _onGestureMoveStart will think we're still flicking"," delete sv._flickAnim;"," }",""," },",""," /**"," * Handle mousewheel events on the widget"," *"," * @method _mousewheel"," * @param e {Event.Facade} The mousewheel event facade"," * @private"," */"," _mousewheel: function (e) {"," var sv = this,"," scrollY = sv.get(SCROLL_Y),"," bounds = sv._getBounds(),"," bb = sv._bb,"," scrollOffset = 10, // 10px"," isForward = (e.wheelDelta > 0),"," scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset);",""," scrollToY = _constrain(scrollToY, bounds.minScrollY, bounds.maxScrollY);",""," // Because Mousewheel events fire off 'document', every ScrollView widget will react"," // to any mousewheel anywhere on the page. This check will ensure that the mouse is currently"," // over this specific ScrollView. Also, only allow mousewheel scrolling on Y-axis,"," // becuase otherwise the 'prevent' will block page scrolling."," if (bb.contains(e.target) && sv._cAxis[DIM_Y]) {",""," // Reset lastScrolledAmt"," sv.lastScrolledAmt = 0;",""," // Jump to the new offset"," sv.set(SCROLL_Y, scrollToY);",""," // if we have scrollbars plugin, update & set the flash timer on the scrollbar"," // @TODO: This probably shouldn't be in this module"," if (sv.scrollbars) {"," // @TODO: The scrollbars should handle this themselves"," sv.scrollbars._update();"," sv.scrollbars.flash();"," // or just this"," // sv.scrollbars._hostDimensionsChange();"," }",""," // Fire the 'scrollEnd' event"," sv._onTransEnd();",""," // prevent browser default behavior on mouse scroll"," e.preventDefault();"," }"," },",""," /**"," * Checks to see the current scrollX/scrollY position beyond the min/max boundary"," *"," * @method _isOutOfBounds"," * @param x {Number} [optional] The X position to check"," * @param y {Number} [optional] The Y position to check"," * @return {boolen} Whether the current X/Y position is out of bounds (true) or not (false)"," * @private"," */"," _isOutOfBounds: function (x, y) {"," var sv = this,"," svAxis = sv._cAxis,"," svAxisX = svAxis.x,"," svAxisY = svAxis.y,"," currentX = x || sv.get(SCROLL_X),"," currentY = y || sv.get(SCROLL_Y),"," bounds = sv._getBounds(),"," minX = bounds.minScrollX,"," minY = bounds.minScrollY,"," maxX = bounds.maxScrollX,"," maxY = bounds.maxScrollY;",""," return (svAxisX && (currentX < minX || currentX > maxX)) || (svAxisY && (currentY < minY || currentY > maxY));"," },",""," /**"," * Bounces back"," * @TODO: Should be more generalized and support both X and Y detection"," *"," * @method _snapBack"," * @private"," */"," _snapBack: function () {"," var sv = this,"," currentX = sv.get(SCROLL_X),"," currentY = sv.get(SCROLL_Y),"," bounds = sv._getBounds(),"," minX = bounds.minScrollX,"," minY = bounds.minScrollY,"," maxX = bounds.maxScrollX,"," maxY = bounds.maxScrollY,"," newY = _constrain(currentY, minY, maxY),"," newX = _constrain(currentX, minX, maxX),"," duration = sv.get(SNAP_DURATION),"," easing = sv.get(SNAP_EASING);",""," if (newX !== currentX) {"," sv.set(SCROLL_X, newX, {duration:duration, easing:easing});"," }"," else if (newY !== currentY) {"," sv.set(SCROLL_Y, newY, {duration:duration, easing:easing});"," }"," else {"," sv._onTransEnd();"," }"," },",""," /**"," * After listener for changes to the scrollX or scrollY attribute"," *"," * @method _afterScrollChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterScrollChange: function (e) {"," if (e.src === ScrollView.UI_SRC) {"," return false;"," }",""," var sv = this,"," duration = e.duration,"," easing = e.easing,"," val = e.newVal,"," scrollToArgs = [];",""," // Set the scrolled value"," sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal);",""," // Generate the array of args to pass to scrollTo()"," if (e.attrName === SCROLL_X) {"," scrollToArgs.push(val);"," scrollToArgs.push(sv.get(SCROLL_Y));"," }"," else {"," scrollToArgs.push(sv.get(SCROLL_X));"," scrollToArgs.push(val);"," }",""," scrollToArgs.push(duration);"," scrollToArgs.push(easing);",""," sv.scrollTo.apply(sv, scrollToArgs);"," },",""," /**"," * After listener for changes to the flick attribute"," *"," * @method _afterFlickChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterFlickChange: function (e) {"," this._bindFlick(e.newVal);"," },",""," /**"," * After listener for changes to the disabled attribute"," *"," * @method _afterDisabledChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterDisabledChange: function (e) {"," // Cache for performance - we check during move"," this._cDisabled = e.newVal;"," },",""," /**"," * After listener for the axis attribute"," *"," * @method _afterAxisChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterAxisChange: function (e) {"," this._cAxis = e.newVal;"," },",""," /**"," * After listener for changes to the drag attribute"," *"," * @method _afterDragChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterDragChange: function (e) {"," this._bindDrag(e.newVal);"," },",""," /**"," * After listener for the height or width attribute"," *"," * @method _afterDimChange"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterDimChange: function () {"," this._uiDimensionsChange();"," },",""," /**"," * After listener for scrollEnd, for cleanup"," *"," * @method _afterScrollEnd"," * @param e {Event.Facade} The event facade"," * @protected"," */"," _afterScrollEnd: function () {"," var sv = this;",""," if (sv._flickAnim) {"," sv._cancelFlick();"," }",""," // Ideally this should be removed, but doing so causing some JS errors with fast swiping"," // because _gesture is being deleted after the previous one has been overwritten"," // delete sv._gesture; // TODO: Move to sv.prevGesture?"," },",""," /**"," * Setter for 'axis' attribute"," *"," * @method _axisSetter"," * @param val {Mixed} A string ('x', 'y', 'xy') to specify which axis/axes to allow scrolling on"," * @param name {String} The attribute name"," * @return {Object} An object to specify scrollability on the x & y axes"," *"," * @protected"," */"," _axisSetter: function (val) {",""," // Turn a string into an axis object"," if (Y.Lang.isString(val)) {"," return {"," x: val.match(/x/i) ? true : false,"," y: val.match(/y/i) ? true : false"," };"," }"," },"," "," /**"," * The scrollX, scrollY setter implementation"," *"," * @method _setScroll"," * @private"," * @param {Number} val"," * @param {String} dim"," *"," * @return {Number} The value"," */"," _setScroll : function(val) {",""," // Just ensure the widget is not disabled"," if (this._cDisabled) {"," val = Y.Attribute.INVALID_VALUE;"," }",""," return val;"," },",""," /**"," * Setter for the scrollX attribute"," *"," * @method _setScrollX"," * @param val {Number} The new scrollX value"," * @return {Number} The normalized value"," * @protected"," */"," _setScrollX: function(val) {"," return this._setScroll(val, DIM_X);"," },",""," /**"," * Setter for the scrollY ATTR"," *"," * @method _setScrollY"," * @param val {Number} The new scrollY value"," * @return {Number} The normalized value"," * @protected"," */"," _setScrollY: function(val) {"," return this._setScroll(val, DIM_Y);"," }",""," // End prototype properties","","}, {",""," // Static properties",""," /**"," * The identity of the widget."," *"," * @property NAME"," * @type String"," * @default 'scrollview'"," * @readOnly"," * @protected"," * @static"," */"," NAME: 'scrollview',",""," /**"," * Static property used to define the default attribute configuration of"," * the Widget."," *"," * @property ATTRS"," * @type {Object}"," * @protected"," * @static"," */"," ATTRS: {",""," /**"," * Specifies ability to scroll on x, y, or x and y axis/axes."," *"," * @attribute axis"," * @type String"," */"," axis: {"," setter: '_axisSetter',"," writeOnce: 'initOnly'"," },",""," /**"," * The current scroll position in the x-axis"," *"," * @attribute scrollX"," * @type Number"," * @default 0"," */"," scrollX: {"," value: 0,"," setter: '_setScrollX'"," },",""," /**"," * The current scroll position in the y-axis"," *"," * @attribute scrollY"," * @type Number"," * @default 0"," */"," scrollY: {"," value: 0,"," setter: '_setScrollY'"," },",""," /**"," * Drag coefficent for inertial scrolling. The closer to 1 this"," * value is, the less friction during scrolling."," *"," * @attribute deceleration"," * @default 0.93"," */"," deceleration: {"," value: 0.93"," },",""," /**"," * Drag coefficient for intertial scrolling at the upper"," * and lower boundaries of the scrollview. Set to 0 to"," * disable \"rubber-banding\"."," *"," * @attribute bounce"," * @type Number"," * @default 0.1"," */"," bounce: {"," value: 0.1"," },",""," /**"," * The minimum distance and/or velocity which define a flick. Can be set to false,"," * to disable flick support (note: drag support is enabled/disabled separately)"," *"," * @attribute flick"," * @type Object"," * @default Object with properties minDistance = 10, minVelocity = 0.3."," */"," flick: {"," value: {"," minDistance: 10,"," minVelocity: 0.3"," }"," },",""," /**"," * Enable/Disable dragging the ScrollView content (note: flick support is enabled/disabled separately)"," * @attribute drag"," * @type boolean"," * @default true"," */"," drag: {"," value: true"," },",""," /**"," * The default duration to use when animating the bounce snap back."," *"," * @attribute snapDuration"," * @type Number"," * @default 400"," */"," snapDuration: {"," value: 400"," },",""," /**"," * The default easing to use when animating the bounce snap back."," *"," * @attribute snapEasing"," * @type String"," * @default 'ease-out'"," */"," snapEasing: {"," value: 'ease-out'"," },",""," /**"," * The default easing used when animating the flick"," *"," * @attribute easing"," * @type String"," * @default 'cubic-bezier(0, 0.1, 0, 1.0)'"," */"," easing: {"," value: 'cubic-bezier(0, 0.1, 0, 1.0)'"," },",""," /**"," * The interval (ms) used when animating the flick for JS-timer animations"," *"," * @attribute frameDuration"," * @type Number"," * @default 15"," */"," frameDuration: {"," value: 15"," },",""," /**"," * The default bounce distance in pixels"," *"," * @attribute bounceRange"," * @type Number"," * @default 150"," */"," bounceRange: {"," value: 150"," }"," },",""," /**"," * List of class names used in the scrollview's DOM"," *"," * @property CLASS_NAMES"," * @type Object"," * @static"," */"," CLASS_NAMES: CLASS_NAMES,",""," /**"," * Flag used to source property changes initiated from the DOM"," *"," * @property UI_SRC"," * @type String"," * @static"," * @default 'ui'"," */"," UI_SRC: UI,",""," /**"," * Object map of style property names used to set transition properties."," * Defaults to the vendor prefix established by the Transition module."," * The configured property names are `_TRANSITION.DURATION` (e.g. \"WebkitTransitionDuration\") and"," * `_TRANSITION.PROPERTY (e.g. \"WebkitTransitionProperty\")."," *"," * @property _TRANSITION"," * @private"," */"," _TRANSITION: {"," DURATION: (vendorPrefix ? vendorPrefix + 'TransitionDuration' : 'transitionDuration'),"," PROPERTY: (vendorPrefix ? vendorPrefix + 'TransitionProperty' : 'transitionProperty')"," },",""," /**"," * The default bounce distance in pixels"," *"," * @property BOUNCE_RANGE"," * @type Number"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," BOUNCE_RANGE: false,",""," /**"," * The interval (ms) used when animating the flick"," *"," * @property FRAME_STEP"," * @type Number"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," FRAME_STEP: false,",""," /**"," * The default easing used when animating the flick"," *"," * @property EASING"," * @type String"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," EASING: false,",""," /**"," * The default easing to use when animating the bounce snap back."," *"," * @property SNAP_EASING"," * @type String"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," SNAP_EASING: false,",""," /**"," * The default duration to use when animating the bounce snap back."," *"," * @property SNAP_DURATION"," * @type Number"," * @static"," * @default false"," * @deprecated (in 3.7.0)"," */"," SNAP_DURATION: false",""," // End static properties","","});","","}, '@VERSION@', {\"requires\": [\"widget\", \"event-gestures\", \"event-mousewheel\", \"transition\"], \"skinnable\": true});","","}());"]}; } var __cov_cyIK2vRXoVgOuWid4NBKqw = __coverage__['build/scrollview-base/scrollview-base.js']; __cov_cyIK2vRXoVgOuWid4NBKqw.s['1']++;YUI.add('scrollview-base',function(Y,NAME){__cov_cyIK2vRXoVgOuWid4NBKqw.f['1']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['2']++;var getClassName=Y.ClassNameManager.getClassName,DOCUMENT=Y.config.doc,IE=Y.UA.ie,NATIVE_TRANSITIONS=Y.Transition.useNative,vendorPrefix=Y.Transition._VENDOR_PREFIX,SCROLLVIEW='scrollview',CLASS_NAMES={vertical:getClassName(SCROLLVIEW,'vert'),horizontal:getClassName(SCROLLVIEW,'horiz')},EV_SCROLL_END='scrollEnd',FLICK='flick',DRAG='drag',MOUSEWHEEL='mousewheel',UI='ui',TOP='top',LEFT='left',PX='px',AXIS='axis',SCROLL_Y='scrollY',SCROLL_X='scrollX',BOUNCE='bounce',DISABLED='disabled',DECELERATION='deceleration',DIM_X='x',DIM_Y='y',BOUNDING_BOX='boundingBox',CONTENT_BOX='contentBox',GESTURE_MOVE='gesturemove',START='start',END='end',EMPTY='',ZERO='0s',SNAP_DURATION='snapDuration',SNAP_EASING='snapEasing',EASING='easing',FRAME_DURATION='frameDuration',BOUNCE_RANGE='bounceRange',_constrain=function(val,min,max){__cov_cyIK2vRXoVgOuWid4NBKqw.f['2']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['3']++;return Math.min(Math.max(val,min),max);};__cov_cyIK2vRXoVgOuWid4NBKqw.s['4']++;function ScrollView(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['3']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['5']++;ScrollView.superclass.constructor.apply(this,arguments);}__cov_cyIK2vRXoVgOuWid4NBKqw.s['6']++;Y.ScrollView=Y.extend(ScrollView,Y.Widget,{_forceHWTransforms:Y.UA.webkit?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['1'][0]++,true):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['1'][1]++,false),_prevent:{start:false,move:true,end:false},lastScrolledAmt:0,_minScrollX:null,_maxScrollX:null,_minScrollY:null,_maxScrollY:null,initializer:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['4']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['7']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['8']++;sv._bb=sv.get(BOUNDING_BOX);__cov_cyIK2vRXoVgOuWid4NBKqw.s['9']++;sv._cb=sv.get(CONTENT_BOX);__cov_cyIK2vRXoVgOuWid4NBKqw.s['10']++;sv._cAxis=sv.get(AXIS);__cov_cyIK2vRXoVgOuWid4NBKqw.s['11']++;sv._cBounce=sv.get(BOUNCE);__cov_cyIK2vRXoVgOuWid4NBKqw.s['12']++;sv._cBounceRange=sv.get(BOUNCE_RANGE);__cov_cyIK2vRXoVgOuWid4NBKqw.s['13']++;sv._cDeceleration=sv.get(DECELERATION);__cov_cyIK2vRXoVgOuWid4NBKqw.s['14']++;sv._cFrameDuration=sv.get(FRAME_DURATION);},bindUI:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['5']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['15']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['16']++;sv._bindFlick(sv.get(FLICK));__cov_cyIK2vRXoVgOuWid4NBKqw.s['17']++;sv._bindDrag(sv.get(DRAG));__cov_cyIK2vRXoVgOuWid4NBKqw.s['18']++;sv._bindMousewheel(true);__cov_cyIK2vRXoVgOuWid4NBKqw.s['19']++;sv._bindAttrs();__cov_cyIK2vRXoVgOuWid4NBKqw.s['20']++;if(IE){__cov_cyIK2vRXoVgOuWid4NBKqw.b['2'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['21']++;sv._fixIESelect(sv._bb,sv._cb);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['2'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['22']++;if(ScrollView.SNAP_DURATION){__cov_cyIK2vRXoVgOuWid4NBKqw.b['3'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['23']++;sv.set(SNAP_DURATION,ScrollView.SNAP_DURATION);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['3'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['24']++;if(ScrollView.SNAP_EASING){__cov_cyIK2vRXoVgOuWid4NBKqw.b['4'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['25']++;sv.set(SNAP_EASING,ScrollView.SNAP_EASING);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['4'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['26']++;if(ScrollView.EASING){__cov_cyIK2vRXoVgOuWid4NBKqw.b['5'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['27']++;sv.set(EASING,ScrollView.EASING);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['5'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['28']++;if(ScrollView.FRAME_STEP){__cov_cyIK2vRXoVgOuWid4NBKqw.b['6'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['29']++;sv.set(FRAME_DURATION,ScrollView.FRAME_STEP);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['6'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['30']++;if(ScrollView.BOUNCE_RANGE){__cov_cyIK2vRXoVgOuWid4NBKqw.b['7'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['31']++;sv.set(BOUNCE_RANGE,ScrollView.BOUNCE_RANGE);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['7'][1]++;}},_bindAttrs:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['6']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['32']++;var sv=this,scrollChangeHandler=sv._afterScrollChange,dimChangeHandler=sv._afterDimChange;__cov_cyIK2vRXoVgOuWid4NBKqw.s['33']++;sv.after({'scrollEnd':sv._afterScrollEnd,'disabledChange':sv._afterDisabledChange,'flickChange':sv._afterFlickChange,'dragChange':sv._afterDragChange,'axisChange':sv._afterAxisChange,'scrollYChange':scrollChangeHandler,'scrollXChange':scrollChangeHandler,'heightChange':dimChangeHandler,'widthChange':dimChangeHandler});},_bindDrag:function(drag){__cov_cyIK2vRXoVgOuWid4NBKqw.f['7']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['34']++;var sv=this,bb=sv._bb;__cov_cyIK2vRXoVgOuWid4NBKqw.s['35']++;bb.detach(DRAG+'|*');__cov_cyIK2vRXoVgOuWid4NBKqw.s['36']++;if(drag){__cov_cyIK2vRXoVgOuWid4NBKqw.b['8'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['37']++;bb.on(DRAG+'|'+GESTURE_MOVE+START,Y.bind(sv._onGestureMoveStart,sv));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['8'][1]++;}},_bindFlick:function(flick){__cov_cyIK2vRXoVgOuWid4NBKqw.f['8']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['38']++;var sv=this,bb=sv._bb;__cov_cyIK2vRXoVgOuWid4NBKqw.s['39']++;bb.detach(FLICK+'|*');__cov_cyIK2vRXoVgOuWid4NBKqw.s['40']++;if(flick){__cov_cyIK2vRXoVgOuWid4NBKqw.b['9'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['41']++;bb.on(FLICK+'|'+FLICK,Y.bind(sv._flick,sv),flick);__cov_cyIK2vRXoVgOuWid4NBKqw.s['42']++;sv._bindDrag(sv.get(DRAG));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['9'][1]++;}},_bindMousewheel:function(mousewheel){__cov_cyIK2vRXoVgOuWid4NBKqw.f['9']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['43']++;var sv=this,bb=sv._bb;__cov_cyIK2vRXoVgOuWid4NBKqw.s['44']++;bb.detach(MOUSEWHEEL+'|*');__cov_cyIK2vRXoVgOuWid4NBKqw.s['45']++;if(mousewheel){__cov_cyIK2vRXoVgOuWid4NBKqw.b['10'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['46']++;Y.one(DOCUMENT).on(MOUSEWHEEL,Y.bind(sv._mousewheel,sv));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['10'][1]++;}},syncUI:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['10']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['47']++;var sv=this,scrollDims=sv._getScrollDims(),width=scrollDims.offsetWidth,height=scrollDims.offsetHeight,scrollWidth=scrollDims.scrollWidth,scrollHeight=scrollDims.scrollHeight;__cov_cyIK2vRXoVgOuWid4NBKqw.s['48']++;if(sv._cAxis===undefined){__cov_cyIK2vRXoVgOuWid4NBKqw.b['11'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['49']++;sv._cAxis={x:scrollWidth>width,y:scrollHeight>height};__cov_cyIK2vRXoVgOuWid4NBKqw.s['50']++;sv._set(AXIS,sv._cAxis);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['11'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['51']++;sv.rtl=sv._cb.getComputedStyle('direction')==='rtl';__cov_cyIK2vRXoVgOuWid4NBKqw.s['52']++;sv._cDisabled=sv.get(DISABLED);__cov_cyIK2vRXoVgOuWid4NBKqw.s['53']++;sv._uiDimensionsChange();__cov_cyIK2vRXoVgOuWid4NBKqw.s['54']++;if(sv._isOutOfBounds()){__cov_cyIK2vRXoVgOuWid4NBKqw.b['12'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['55']++;sv._snapBack();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['12'][1]++;}},_getScrollDims:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['11']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['56']++;var sv=this,cb=sv._cb,bb=sv._bb,TRANS=ScrollView._TRANSITION,origX=sv.get(SCROLL_X),origY=sv.get(SCROLL_Y),origHWTransform,dims;__cov_cyIK2vRXoVgOuWid4NBKqw.s['57']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['13'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['58']++;cb.setStyle(TRANS.DURATION,ZERO);__cov_cyIK2vRXoVgOuWid4NBKqw.s['59']++;cb.setStyle(TRANS.PROPERTY,EMPTY);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['13'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['60']++;origHWTransform=sv._forceHWTransforms;__cov_cyIK2vRXoVgOuWid4NBKqw.s['61']++;sv._forceHWTransforms=false;__cov_cyIK2vRXoVgOuWid4NBKqw.s['62']++;sv._moveTo(cb,0,0);__cov_cyIK2vRXoVgOuWid4NBKqw.s['63']++;dims={'offsetWidth':bb.get('offsetWidth'),'offsetHeight':bb.get('offsetHeight'),'scrollWidth':bb.get('scrollWidth'),'scrollHeight':bb.get('scrollHeight')};__cov_cyIK2vRXoVgOuWid4NBKqw.s['64']++;sv._moveTo(cb,-origX,-origY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['65']++;sv._forceHWTransforms=origHWTransform;__cov_cyIK2vRXoVgOuWid4NBKqw.s['66']++;return dims;},_uiDimensionsChange:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['12']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['67']++;var sv=this,bb=sv._bb,scrollDims=sv._getScrollDims(),width=scrollDims.offsetWidth,height=scrollDims.offsetHeight,scrollWidth=scrollDims.scrollWidth,scrollHeight=scrollDims.scrollHeight,rtl=sv.rtl,svAxis=sv._cAxis,minScrollX=rtl?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['14'][0]++,Math.min(0,-(scrollWidth-width))):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['14'][1]++,0),maxScrollX=rtl?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['15'][0]++,0):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['15'][1]++,Math.max(0,scrollWidth-width)),minScrollY=0,maxScrollY=Math.max(0,scrollHeight-height);__cov_cyIK2vRXoVgOuWid4NBKqw.s['68']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['17'][0]++,svAxis)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['17'][1]++,svAxis.x)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['16'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['69']++;bb.addClass(CLASS_NAMES.horizontal);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['16'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['70']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['19'][0]++,svAxis)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['19'][1]++,svAxis.y)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['18'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['71']++;bb.addClass(CLASS_NAMES.vertical);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['18'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['72']++;sv._setBounds({minScrollX:minScrollX,maxScrollX:maxScrollX,minScrollY:minScrollY,maxScrollY:maxScrollY});},_setBounds:function(bounds){__cov_cyIK2vRXoVgOuWid4NBKqw.f['13']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['73']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['74']++;sv._minScrollX=bounds.minScrollX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['75']++;sv._maxScrollX=bounds.maxScrollX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['76']++;sv._minScrollY=bounds.minScrollY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['77']++;sv._maxScrollY=bounds.maxScrollY;},_getBounds:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['14']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['78']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['79']++;return{minScrollX:sv._minScrollX,maxScrollX:sv._maxScrollX,minScrollY:sv._minScrollY,maxScrollY:sv._maxScrollY};},scrollTo:function(x,y,duration,easing,node){__cov_cyIK2vRXoVgOuWid4NBKqw.f['15']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['80']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['20'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['81']++;return;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['20'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['82']++;var sv=this,cb=sv._cb,TRANS=ScrollView._TRANSITION,callback=Y.bind(sv._onTransEnd,sv),newX=0,newY=0,transition={},transform;__cov_cyIK2vRXoVgOuWid4NBKqw.s['83']++;duration=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['21'][0]++,duration)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['21'][1]++,0);__cov_cyIK2vRXoVgOuWid4NBKqw.s['84']++;easing=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['22'][0]++,easing)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['22'][1]++,sv.get(EASING));__cov_cyIK2vRXoVgOuWid4NBKqw.s['85']++;node=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['23'][0]++,node)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['23'][1]++,cb);__cov_cyIK2vRXoVgOuWid4NBKqw.s['86']++;if(x!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['24'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['87']++;sv.set(SCROLL_X,x,{src:UI});__cov_cyIK2vRXoVgOuWid4NBKqw.s['88']++;newX=-x;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['24'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['89']++;if(y!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['25'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['90']++;sv.set(SCROLL_Y,y,{src:UI});__cov_cyIK2vRXoVgOuWid4NBKqw.s['91']++;newY=-y;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['25'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['92']++;transform=sv._transform(newX,newY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['93']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['26'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['94']++;node.setStyle(TRANS.DURATION,ZERO).setStyle(TRANS.PROPERTY,EMPTY);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['26'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['95']++;if(duration===0){__cov_cyIK2vRXoVgOuWid4NBKqw.b['27'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['96']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['28'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['97']++;node.setStyle('transform',transform);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['28'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['98']++;if(x!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['29'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['99']++;node.setStyle(LEFT,newX+PX);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['29'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['100']++;if(y!==null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['30'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['101']++;node.setStyle(TOP,newY+PX);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['30'][1]++;}}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['27'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['102']++;transition.easing=easing;__cov_cyIK2vRXoVgOuWid4NBKqw.s['103']++;transition.duration=duration/1000;__cov_cyIK2vRXoVgOuWid4NBKqw.s['104']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['31'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['105']++;transition.transform=transform;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['31'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['106']++;transition.left=newX+PX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['107']++;transition.top=newY+PX;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['108']++;node.transition(transition,callback);}},_transform:function(x,y){__cov_cyIK2vRXoVgOuWid4NBKqw.f['16']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['109']++;var prop='translate('+x+'px, '+y+'px)';__cov_cyIK2vRXoVgOuWid4NBKqw.s['110']++;if(this._forceHWTransforms){__cov_cyIK2vRXoVgOuWid4NBKqw.b['32'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['111']++;prop+=' translateZ(0)';}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['32'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['112']++;return prop;},_moveTo:function(node,x,y){__cov_cyIK2vRXoVgOuWid4NBKqw.f['17']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['113']++;if(NATIVE_TRANSITIONS){__cov_cyIK2vRXoVgOuWid4NBKqw.b['33'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['114']++;node.setStyle('transform',this._transform(x,y));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['33'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['115']++;node.setStyle(LEFT,x+PX);__cov_cyIK2vRXoVgOuWid4NBKqw.s['116']++;node.setStyle(TOP,y+PX);}},_onTransEnd:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['18']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['117']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['118']++;if(sv._isOutOfBounds()){__cov_cyIK2vRXoVgOuWid4NBKqw.b['34'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['119']++;sv._snapBack();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['34'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['120']++;sv.fire(EV_SCROLL_END);}},_onGestureMoveStart:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['19']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['121']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['35'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['122']++;return false;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['35'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['123']++;var sv=this,bb=sv._bb,currentX=sv.get(SCROLL_X),currentY=sv.get(SCROLL_Y),clientX=e.clientX,clientY=e.clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['124']++;if(sv._prevent.start){__cov_cyIK2vRXoVgOuWid4NBKqw.b['36'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['125']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['36'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['126']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['37'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['127']++;sv._cancelFlick();__cov_cyIK2vRXoVgOuWid4NBKqw.s['128']++;sv._onTransEnd();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['37'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['129']++;sv.lastScrolledAmt=0;__cov_cyIK2vRXoVgOuWid4NBKqw.s['130']++;sv._gesture={axis:null,startX:currentX,startY:currentY,startClientX:clientX,startClientY:clientY,endClientX:null,endClientY:null,deltaX:null,deltaY:null,flick:null,onGestureMove:bb.on(DRAG+'|'+GESTURE_MOVE,Y.bind(sv._onGestureMove,sv)),onGestureMoveEnd:bb.on(DRAG+'|'+GESTURE_MOVE+END,Y.bind(sv._onGestureMoveEnd,sv))};},_onGestureMove:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['20']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['131']++;var sv=this,gesture=sv._gesture,svAxis=sv._cAxis,svAxisX=svAxis.x,svAxisY=svAxis.y,startX=gesture.startX,startY=gesture.startY,startClientX=gesture.startClientX,startClientY=gesture.startClientY,clientX=e.clientX,clientY=e.clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['132']++;if(sv._prevent.move){__cov_cyIK2vRXoVgOuWid4NBKqw.b['38'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['133']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['38'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['134']++;gesture.deltaX=startClientX-clientX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['135']++;gesture.deltaY=startClientY-clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['136']++;if(gesture.axis===null){__cov_cyIK2vRXoVgOuWid4NBKqw.b['39'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['137']++;gesture.axis=Math.abs(gesture.deltaX)>Math.abs(gesture.deltaY)?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['40'][0]++,DIM_X):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['40'][1]++,DIM_Y);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['39'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['138']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['42'][0]++,gesture.axis===DIM_X)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['42'][1]++,svAxisX)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['41'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['139']++;sv.set(SCROLL_X,startX+gesture.deltaX);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['41'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['140']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['44'][0]++,gesture.axis===DIM_Y)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['44'][1]++,svAxisY)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['43'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['141']++;sv.set(SCROLL_Y,startY+gesture.deltaY);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['43'][1]++;}}},_onGestureMoveEnd:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['21']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['142']++;var sv=this,gesture=sv._gesture,flick=gesture.flick,clientX=e.clientX,clientY=e.clientY,isOOB;__cov_cyIK2vRXoVgOuWid4NBKqw.s['143']++;if(sv._prevent.end){__cov_cyIK2vRXoVgOuWid4NBKqw.b['45'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['144']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['45'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['145']++;gesture.endClientX=clientX;__cov_cyIK2vRXoVgOuWid4NBKqw.s['146']++;gesture.endClientY=clientY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['147']++;gesture.onGestureMove.detach();__cov_cyIK2vRXoVgOuWid4NBKqw.s['148']++;gesture.onGestureMoveEnd.detach();__cov_cyIK2vRXoVgOuWid4NBKqw.s['149']++;if(!flick){__cov_cyIK2vRXoVgOuWid4NBKqw.b['46'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['150']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['48'][0]++,gesture.deltaX!==null)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['48'][1]++,gesture.deltaY!==null)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['47'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['151']++;isOOB=sv._isOutOfBounds();__cov_cyIK2vRXoVgOuWid4NBKqw.s['152']++;if(isOOB){__cov_cyIK2vRXoVgOuWid4NBKqw.b['49'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['153']++;sv._snapBack();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['49'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['154']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['51'][0]++,!sv.pages)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['51'][1]++,sv.pages)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['51'][2]++,!sv.pages.get(AXIS)[gesture.axis])){__cov_cyIK2vRXoVgOuWid4NBKqw.b['50'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['155']++;sv._onTransEnd();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['50'][1]++;}}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['47'][1]++;}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['46'][1]++;}},_flick:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['22']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['156']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['52'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['157']++;return false;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['52'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['158']++;var sv=this,svAxis=sv._cAxis,flick=e.flick,flickAxis=flick.axis,flickVelocity=flick.velocity,axisAttr=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['53'][0]++,SCROLL_X):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['53'][1]++,SCROLL_Y),startPosition=sv.get(axisAttr);__cov_cyIK2vRXoVgOuWid4NBKqw.s['159']++;if(sv._gesture){__cov_cyIK2vRXoVgOuWid4NBKqw.b['54'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['160']++;sv._gesture.flick=flick;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['54'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['161']++;if(svAxis[flickAxis]){__cov_cyIK2vRXoVgOuWid4NBKqw.b['55'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['162']++;sv._flickFrame(flickVelocity,flickAxis,startPosition);}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['55'][1]++;}},_flickFrame:function(velocity,flickAxis,startPosition){__cov_cyIK2vRXoVgOuWid4NBKqw.f['23']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['163']++;var sv=this,axisAttr=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['56'][0]++,SCROLL_X):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['56'][1]++,SCROLL_Y),bounds=sv._getBounds(),bounce=sv._cBounce,bounceRange=sv._cBounceRange,deceleration=sv._cDeceleration,frameDuration=sv._cFrameDuration,newVelocity=velocity*deceleration,newPosition=startPosition-frameDuration*newVelocity,min=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['57'][0]++,bounds.minScrollX):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['57'][1]++,bounds.minScrollY),max=flickAxis===DIM_X?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['58'][0]++,bounds.maxScrollX):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['58'][1]++,bounds.maxScrollY),belowMin=newPosition<min,belowMax=newPosition<max,aboveMin=newPosition>min,aboveMax=newPosition>max,belowMinRange=newPosition<min-bounceRange,withinMinRange=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['59'][0]++,belowMin)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['59'][1]++,newPosition>min-bounceRange),withinMaxRange=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['60'][0]++,aboveMax)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['60'][1]++,newPosition<max+bounceRange),aboveMaxRange=newPosition>max+bounceRange,tooSlow;__cov_cyIK2vRXoVgOuWid4NBKqw.s['164']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['62'][0]++,withinMinRange)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['62'][1]++,withinMaxRange)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['61'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['165']++;newVelocity*=bounce;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['61'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['166']++;tooSlow=Math.abs(newVelocity).toFixed(4)<0.015;__cov_cyIK2vRXoVgOuWid4NBKqw.s['167']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['64'][0]++,tooSlow)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['64'][1]++,belowMinRange)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['64'][2]++,aboveMaxRange)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['63'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['168']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['65'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['169']++;sv._cancelFlick();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['65'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['170']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['67'][0]++,aboveMin)&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['67'][1]++,belowMax)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['66'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['171']++;sv._onTransEnd();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['66'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['172']++;sv._snapBack();}}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['63'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['173']++;sv._flickAnim=Y.later(frameDuration,sv,'_flickFrame',[newVelocity,flickAxis,newPosition]);__cov_cyIK2vRXoVgOuWid4NBKqw.s['174']++;sv.set(axisAttr,newPosition);}},_cancelFlick:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['24']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['175']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['176']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['68'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['177']++;sv._flickAnim.cancel();__cov_cyIK2vRXoVgOuWid4NBKqw.s['178']++;delete sv._flickAnim;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['68'][1]++;}},_mousewheel:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['25']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['179']++;var sv=this,scrollY=sv.get(SCROLL_Y),bounds=sv._getBounds(),bb=sv._bb,scrollOffset=10,isForward=e.wheelDelta>0,scrollToY=scrollY-(isForward?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['69'][0]++,1):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['69'][1]++,-1))*scrollOffset;__cov_cyIK2vRXoVgOuWid4NBKqw.s['180']++;scrollToY=_constrain(scrollToY,bounds.minScrollY,bounds.maxScrollY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['181']++;if((__cov_cyIK2vRXoVgOuWid4NBKqw.b['71'][0]++,bb.contains(e.target))&&(__cov_cyIK2vRXoVgOuWid4NBKqw.b['71'][1]++,sv._cAxis[DIM_Y])){__cov_cyIK2vRXoVgOuWid4NBKqw.b['70'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['182']++;sv.lastScrolledAmt=0;__cov_cyIK2vRXoVgOuWid4NBKqw.s['183']++;sv.set(SCROLL_Y,scrollToY);__cov_cyIK2vRXoVgOuWid4NBKqw.s['184']++;if(sv.scrollbars){__cov_cyIK2vRXoVgOuWid4NBKqw.b['72'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['185']++;sv.scrollbars._update();__cov_cyIK2vRXoVgOuWid4NBKqw.s['186']++;sv.scrollbars.flash();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['72'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['187']++;sv._onTransEnd();__cov_cyIK2vRXoVgOuWid4NBKqw.s['188']++;e.preventDefault();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['70'][1]++;}},_isOutOfBounds:function(x,y){__cov_cyIK2vRXoVgOuWid4NBKqw.f['26']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['189']++;var sv=this,svAxis=sv._cAxis,svAxisX=svAxis.x,svAxisY=svAxis.y,currentX=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['73'][0]++,x)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['73'][1]++,sv.get(SCROLL_X)),currentY=(__cov_cyIK2vRXoVgOuWid4NBKqw.b['74'][0]++,y)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['74'][1]++,sv.get(SCROLL_Y)),bounds=sv._getBounds(),minX=bounds.minScrollX,minY=bounds.minScrollY,maxX=bounds.maxScrollX,maxY=bounds.maxScrollY;__cov_cyIK2vRXoVgOuWid4NBKqw.s['190']++;return(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][0]++,svAxisX)&&((__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][1]++,currentX<minX)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][2]++,currentX>maxX))||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][3]++,svAxisY)&&((__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][4]++,currentY<minY)||(__cov_cyIK2vRXoVgOuWid4NBKqw.b['75'][5]++,currentY>maxY));},_snapBack:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['27']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['191']++;var sv=this,currentX=sv.get(SCROLL_X),currentY=sv.get(SCROLL_Y),bounds=sv._getBounds(),minX=bounds.minScrollX,minY=bounds.minScrollY,maxX=bounds.maxScrollX,maxY=bounds.maxScrollY,newY=_constrain(currentY,minY,maxY),newX=_constrain(currentX,minX,maxX),duration=sv.get(SNAP_DURATION),easing=sv.get(SNAP_EASING);__cov_cyIK2vRXoVgOuWid4NBKqw.s['192']++;if(newX!==currentX){__cov_cyIK2vRXoVgOuWid4NBKqw.b['76'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['193']++;sv.set(SCROLL_X,newX,{duration:duration,easing:easing});}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['76'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['194']++;if(newY!==currentY){__cov_cyIK2vRXoVgOuWid4NBKqw.b['77'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['195']++;sv.set(SCROLL_Y,newY,{duration:duration,easing:easing});}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['77'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['196']++;sv._onTransEnd();}}},_afterScrollChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['28']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['197']++;if(e.src===ScrollView.UI_SRC){__cov_cyIK2vRXoVgOuWid4NBKqw.b['78'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['198']++;return false;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['78'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['199']++;var sv=this,duration=e.duration,easing=e.easing,val=e.newVal,scrollToArgs=[];__cov_cyIK2vRXoVgOuWid4NBKqw.s['200']++;sv.lastScrolledAmt=sv.lastScrolledAmt+(e.newVal-e.prevVal);__cov_cyIK2vRXoVgOuWid4NBKqw.s['201']++;if(e.attrName===SCROLL_X){__cov_cyIK2vRXoVgOuWid4NBKqw.b['79'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['202']++;scrollToArgs.push(val);__cov_cyIK2vRXoVgOuWid4NBKqw.s['203']++;scrollToArgs.push(sv.get(SCROLL_Y));}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['79'][1]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['204']++;scrollToArgs.push(sv.get(SCROLL_X));__cov_cyIK2vRXoVgOuWid4NBKqw.s['205']++;scrollToArgs.push(val);}__cov_cyIK2vRXoVgOuWid4NBKqw.s['206']++;scrollToArgs.push(duration);__cov_cyIK2vRXoVgOuWid4NBKqw.s['207']++;scrollToArgs.push(easing);__cov_cyIK2vRXoVgOuWid4NBKqw.s['208']++;sv.scrollTo.apply(sv,scrollToArgs);},_afterFlickChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['29']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['209']++;this._bindFlick(e.newVal);},_afterDisabledChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['30']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['210']++;this._cDisabled=e.newVal;},_afterAxisChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['31']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['211']++;this._cAxis=e.newVal;},_afterDragChange:function(e){__cov_cyIK2vRXoVgOuWid4NBKqw.f['32']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['212']++;this._bindDrag(e.newVal);},_afterDimChange:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['33']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['213']++;this._uiDimensionsChange();},_afterScrollEnd:function(){__cov_cyIK2vRXoVgOuWid4NBKqw.f['34']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['214']++;var sv=this;__cov_cyIK2vRXoVgOuWid4NBKqw.s['215']++;if(sv._flickAnim){__cov_cyIK2vRXoVgOuWid4NBKqw.b['80'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['216']++;sv._cancelFlick();}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['80'][1]++;}},_axisSetter:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['35']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['217']++;if(Y.Lang.isString(val)){__cov_cyIK2vRXoVgOuWid4NBKqw.b['81'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['218']++;return{x:val.match(/x/i)?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['82'][0]++,true):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['82'][1]++,false),y:val.match(/y/i)?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['83'][0]++,true):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['83'][1]++,false)};}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['81'][1]++;}},_setScroll:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['36']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['219']++;if(this._cDisabled){__cov_cyIK2vRXoVgOuWid4NBKqw.b['84'][0]++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['220']++;val=Y.Attribute.INVALID_VALUE;}else{__cov_cyIK2vRXoVgOuWid4NBKqw.b['84'][1]++;}__cov_cyIK2vRXoVgOuWid4NBKqw.s['221']++;return val;},_setScrollX:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['37']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['222']++;return this._setScroll(val,DIM_X);},_setScrollY:function(val){__cov_cyIK2vRXoVgOuWid4NBKqw.f['38']++;__cov_cyIK2vRXoVgOuWid4NBKqw.s['223']++;return this._setScroll(val,DIM_Y);}},{NAME:'scrollview',ATTRS:{axis:{setter:'_axisSetter',writeOnce:'initOnly'},scrollX:{value:0,setter:'_setScrollX'},scrollY:{value:0,setter:'_setScrollY'},deceleration:{value:0.93},bounce:{value:0.1},flick:{value:{minDistance:10,minVelocity:0.3}},drag:{value:true},snapDuration:{value:400},snapEasing:{value:'ease-out'},easing:{value:'cubic-bezier(0, 0.1, 0, 1.0)'},frameDuration:{value:15},bounceRange:{value:150}},CLASS_NAMES:CLASS_NAMES,UI_SRC:UI,_TRANSITION:{DURATION:vendorPrefix?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['85'][0]++,vendorPrefix+'TransitionDuration'):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['85'][1]++,'transitionDuration'),PROPERTY:vendorPrefix?(__cov_cyIK2vRXoVgOuWid4NBKqw.b['86'][0]++,vendorPrefix+'TransitionProperty'):(__cov_cyIK2vRXoVgOuWid4NBKqw.b['86'][1]++,'transitionProperty')},BOUNCE_RANGE:false,FRAME_STEP:false,EASING:false,SNAP_EASING:false,SNAP_DURATION:false});},'@VERSION@',{'requires':['widget','event-gestures','event-mousewheel','transition'],'skinnable':true});
ajax/libs/react-data-grid/0.12.24/react-data-grid.min.js
x112358/cdnjs
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.ReactDataGrid=t(require("react")):e.ReactDataGrid=t(e.React)}(this,function(e){return function(e){function t(o){if(r[o])return r[o].exports;var s=r[o]={exports:{},id:o,loaded:!1};return e[o].call(s.exports,s,s.exports,t),s.loaded=!0,s.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";var o=r(43),s=r(11),i=r(22);e.exports=o,e.exports.Row=s,e.exports.Cell=i},function(t,r){t.exports=e},function(e,t,r){"use strict";var o=(r(17)["default"],r(1)),s={name:o.PropTypes.string.isRequired,key:o.PropTypes.string.isRequired,width:o.PropTypes.number.isRequired};e.exports=s},function(e,t,r){"use strict";var o=r(14)["default"];t["default"]=o||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},t.__esModule=!0},function(e,t,r){function o(){for(var e,t="",r=0;r<arguments.length;r++)if(e=arguments[r])if("string"==typeof e||"number"==typeof e)t+=" "+e;else if("[object Array]"===Object.prototype.toString.call(e))t+=" "+o.apply(null,e);else if("object"==typeof e)for(var s in e)e.hasOwnProperty(s)&&e[s]&&(t+=" "+s);return t.substr(1)}var s,i;"undefined"!=typeof e&&e.exports&&(e.exports=o),s=[],i=function(){return o}.apply(t,s),!(void 0!==i&&(e.exports=i))},function(e,t,r){(function(t){"use strict";function o(e,r){"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?l(!e.ref,"You are calling cloneWithProps() on a child with a ref. This is dangerous because you're creating a new child which will not be added as a ref to its parent."):null);var o=i.mergeProps(r,e.props);return!o.hasOwnProperty(a)&&e.props.hasOwnProperty(a)&&(o.children=e.props.children),s.createElement(e.type,o)}var s=r(60),i=r(61),n=r(64),l=r(15),a=n({children:null});e.exports=o}).call(t,r(8))},function(e,t){"use strict";e.exports={getColumn:function(e,t){return Array.isArray(e)?e[t]:"undefined"!=typeof Immutable?e.get(t):void 0},spliceColumn:function(e,t,r){return Array.isArray(e.columns)?e.columns.splice(t,1,r):"undefined"!=typeof Immutable&&(e.columns=e.columns.splice(t,1,r)),e},getSize:function(e){return Array.isArray(e)?e.length:"undefined"!=typeof Immutable?e.size:void 0}}},function(e,t){function r(e){return function(){return e}}function o(){}o.thatReturns=r,o.thatReturnsFalse=r(!1),o.thatReturnsTrue=r(!0),o.thatReturnsNull=r(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},e.exports=o},function(e,t){function r(){c=!1,n.length?a=n.concat(a):p=-1,a.length&&o()}function o(){if(!c){var e=setTimeout(r);c=!0;for(var t=a.length;t;){for(n=a,a=[];++p<t;)n&&n[p].run();p=-1,t=a.length}n=null,c=!1,clearTimeout(e)}}function s(e,t){this.fun=e,this.array=t}function i(){}var n,l=e.exports={},a=[],c=!1,p=-1;l.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];a.push(new s(e,t)),1!==a.length||c||setTimeout(o,0)},s.prototype.run=function(){this.fun.apply(null,this.array)},l.title="browser",l.browser=!0,l.env={},l.argv=[],l.version="",l.versions={},l.on=i,l.addListener=i,l.once=i,l.off=i,l.removeListener=i,l.removeAllListeners=i,l.emit=i,l.binding=function(e){throw new Error("process.binding is not supported")},l.cwd=function(){return"/"},l.chdir=function(e){throw new Error("process.chdir is not supported")},l.umask=function(){return 0}},function(e,t,r){"use strict";var o=r(1),s=r(7),i=r(13),n={metricsComputator:o.PropTypes.object},l={childContextTypes:n,getChildContext:function(){return{metricsComputator:this}},getMetricImpl:function(e){return this._DOMMetrics.metrics[e].value},registerMetricsImpl:function(e,t){var r={},o=this._DOMMetrics;for(var s in t){if(void 0!==o.metrics[s])throw new Error("DOM metric "+s+" is already defined");o.metrics[s]={component:e,computator:t[s].bind(e)},r[s]=this.getMetricImpl.bind(null,s)}return-1===o.components.indexOf(e)&&o.components.push(e),r},unregisterMetricsFor:function(e){var t=this._DOMMetrics,r=t.components.indexOf(e);if(r>-1){t.components.splice(r,1);var o,s={};for(o in t.metrics)t.metrics[o].component===e&&(s[o]=!0);for(o in s)delete t.metrics[o]}},updateMetrics:function(){var e=this._DOMMetrics,t=!1;for(var r in e.metrics){var o=e.metrics[r].computator();o!==e.metrics[r].value&&(t=!0),e.metrics[r].value=o}if(t)for(var s=0,i=e.components.length;i>s;s++)e.components[s].metricsUpdated&&e.components[s].metricsUpdated()},componentWillMount:function(){this._DOMMetrics={metrics:{},components:[]}},componentDidMount:function(){window.addEventListener?window.addEventListener("resize",this.updateMetrics):window.attachEvent("resize",this.updateMetrics),this.updateMetrics()},componentWillUnmount:function(){window.removeEventListener("resize",this.updateMetrics)}},a={contextTypes:n,componentWillMount:function(){if(this.DOMMetrics){this._DOMMetricsDefs=i(this.DOMMetrics),this.DOMMetrics={};for(var e in this._DOMMetricsDefs)this.DOMMetrics[e]=s}},componentDidMount:function(){this.DOMMetrics&&(this.DOMMetrics=this.registerMetrics(this._DOMMetricsDefs))},componentWillUnmount:function(){return this.registerMetricsImpl?void(this.hasOwnProperty("DOMMetrics")&&delete this.DOMMetrics):this.context.metricsComputator.unregisterMetricsFor(this)},registerMetrics:function(e){return this.registerMetricsImpl?this.registerMetricsImpl(this,e):this.context.metricsComputator.registerMetricsImpl(this,e)},getMetric:function(e){return this.getMetricImpl?this.getMetricImpl(e):this.context.metricsComputator.getMetricImpl(e)}};e.exports={MetricsComputatorMixin:l,MetricsMixin:a}},function(e,t,r){"use strict";var o=(r(1),{onKeyDown:function(e){if(this.isCtrlKeyHeldDown(e))this.checkAndCall("onPressKeyWithCtrl",e);else if(this.isKeyExplicitlyHandled(e.key)){var t="onPress"+e.key;this.checkAndCall(t,e)}else this.isKeyPrintable(e.keyCode)&&this.checkAndCall("onPressChar",e)},isKeyPrintable:function(e){var t=e>47&&58>e||32==e||13==e||e>64&&91>e||e>95&&112>e||e>185&&193>e||e>218&&223>e;return t},isKeyExplicitlyHandled:function(e){return"function"==typeof this["onPress"+e]},isCtrlKeyHeldDown:function(e){return e.ctrlKey===!0&&"Control"!==e.key},checkAndCall:function(e,t){"function"==typeof this[e]&&this[e](t)}});e.exports=o},function(e,t,r){"use strict";var o=r(3)["default"],s=r(1),i=r(4),n=r(22),l=(r(5),r(12)),a=r(6),c=s.createClass({displayName:"Row",propTypes:{height:s.PropTypes.number.isRequired,columns:s.PropTypes.oneOfType([s.PropTypes.object,s.PropTypes.array]).isRequired,row:s.PropTypes.object.isRequired,cellRenderer:s.PropTypes.func,isSelected:s.PropTypes.bool,idx:s.PropTypes.number.isRequired,expandedRows:s.PropTypes.arrayOf(s.PropTypes.object)},mixins:[a],render:function(){var e=i("react-grid-Row","react-grid-Row--${this.props.idx % 2 === 0 ? 'even' : 'odd'}"),t={height:this.getRowHeight(this.props),overflow:"hidden"},r=this.getCells();return s.createElement("div",o({},this.props,{className:e,style:t,onDragEnter:this.handleDragEnter}),s.isValidElement(this.props.row)?this.props.row:r)},getCells:function(){var e=this,t=[],r=[],o=this.getSelectedColumn();return this.props.columns.forEach(function(i,n){var l=e.props.cellRenderer,a=s.createElement(l,{ref:n,key:n,idx:n,rowIdx:e.props.idx,value:e.getCellValue(i.key||n),column:i,height:e.getRowHeight(),formatter:i.formatter,cellMetaData:e.props.cellMetaData,rowData:e.props.row,selectedColumn:o,isRowSelected:e.props.isSelected});i.locked?r.push(a):t.push(a)}),t.concat(r)},getRowHeight:function(){var e=this.props.expandedRows||null;if(e&&this.props.key){var t=e[this.props.key]||null;if(t)return t.height}return this.props.height},getCellValue:function(e){var t;return"select-row"===e?this.props.isSelected:t="function"==typeof this.props.row.get?this.props.row.get(e):this.props.row[e]},getRowData:function(){return this.props.row.toJSON?this.props.row.toJSON():this.props.row},getDefaultProps:function(){return{cellRenderer:n,isSelected:!1,height:35}},setScrollLeft:function(e){var t=this;this.props.columns.forEach(function(r,o){if(r.locked){if(!t.refs[o])return;t.refs[o].setScrollLeft(e)}})},doesRowContainSelectedCell:function(e){var t=e.cellMetaData.selected;return t&&t.rowIdx===e.idx?!0:!1},willRowBeDraggedOver:function(e){var t=e.cellMetaData.dragged;return null!=t&&(t.rowIdx>=0||t.complete===!0)},hasRowBeenCopied:function(){var e=this.props.cellMetaData.copied;return null!=e&&e.rowIdx===this.props.idx},shouldComponentUpdate:function(e,t){return!l.sameColumns(this.props.columns,e.columns,l.sameColumn)||this.doesRowContainSelectedCell(this.props)||this.doesRowContainSelectedCell(e)||this.willRowBeDraggedOver(e)||e.row!==this.props.row||this.hasRowBeenCopied()||this.props.isSelected!==e.isSelected||e.height!==this.props.height},handleDragEnter:function(){var e=this.props.cellMetaData.handleDragEnterRow;e&&e(this.props.idx)},getSelectedColumn:function(){var e=this.props.cellMetaData.selected;return e&&e.idx?this.getColumn(this.props.columns,e.idx):void 0}});e.exports=c},function(e,t,r){"use strict";function o(e){var t=i(e.columns,e.totalWidth),r=t.filter(function(e){return e.width}).reduce(function(e,t){return e-t.width},e.totalWidth),o=t.filter(function(e){return e.width}).reduce(function(e,t){return e+t.width},0);return t=n(t,r,e.minColumnWidth),t=s(t),{columns:t,width:o,totalWidth:e.totalWidth,minColumnWidth:e.minColumnWidth}}function s(e){var t=0;return e.map(function(e){return e.left=t,t+=e.width,e})}function i(e,t){return e.map(function(e){var r=u({},e);return e.width&&/^([0-9]+)%$/.exec(e.width.toString())&&(r.width=Math.floor(e.width/100*t)),r})}function n(e,t,r){var o=e.filter(function(e){return!e.width});return e.map(function(e,s,i){return e.width||(0>=t?e.width=r:e.width=Math.floor(t/f.getSize(o))),e})}function l(e,t,r){var s=f.getColumn(e.columns,t);e=h(e),e.columns=e.columns.slice(0);var i=h(s);return i.width=Math.max(r,e.minColumnWidth),e=f.spliceColumn(e,t,i),o(e)}function a(e,t){return"undefined"!=typeof Immutable&&e instanceof Immutable.List&&t instanceof Immutable.List}function c(e,t,r){var o,s,i,n={},l={};if(f.getSize(e)!==f.getSize(t))return!1;for(o=0,s=f.getSize(e);s>o;o++)i=e[o],n[i.key]=i;for(o=0,s=f.getSize(t);s>o;o++){i=t[o],l[i.key]=i;var a=n[i.key];if(void 0===a||!r(a,i))return!1}for(o=0,s=f.getSize(e);s>o;o++){i=e[o];var c=l[i.key];if(void 0===c)return!1}return!0}function p(e,t,r){return a(e,t)?e===t:c(e,t,r)}var u=r(14)["default"],h=r(13),d=(r(1).isValidElement,r(26)),f=r(6);e.exports={recalculate:o,resizeColumn:l,sameColumn:d,sameColumns:p}},function(e,t){"use strict";function r(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t}e.exports=r},function(e,t,r){e.exports={"default":r(46),__esModule:!0}},function(e,t,r){(function(t){"use strict";var o=r(7),s=o;"production"!==t.env.NODE_ENV&&(s=function(e,t){for(var r=[],o=2,s=arguments.length;s>o;o++)r.push(arguments[o]);if(void 0===t)throw new Error("`warning(condition, format, ...args)` requires a warning message argument");if(!e){var i=0;console.warn("Warning: "+t.replace(/%s/g,function(){return r[i++]}))}}),e.exports=s}).call(t,r(8))},function(e,t){"use strict";var r=function(e){var t={};return e&&"[object Function]"===t.toString.call(e)};e.exports=r},function(e,t){"use strict";t["default"]=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},t.__esModule=!0},function(e,t){var r=e.exports={};"number"==typeof __e&&(__e=r)},function(e,t){"use strict";function r(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=Object.assign||function(e,t){for(var o,s,i=r(e),n=1;n<arguments.length;n++){o=arguments[n],s=Object.keys(Object(o));for(var l=0;l<s.length;l++)i[s[l]]=o[s[l]]}return i}},function(e,t){function r(e,t){if(null==e)throw new TypeError("Object.assign target cannot be null or undefined");for(var r=Object(e),o=Object.prototype.hasOwnProperty,s=1;s<arguments.length;s++){var i=arguments[s];if(null!=i){var n=Object(i);for(var l in n)o.call(n,l)&&(r[l]=n[l])}}return r}e.exports=r},function(e,t){"use strict";function r(e,t){if(e===t)return!0;var r;for(r in e)if(e.hasOwnProperty(r)&&(!t.hasOwnProperty(r)||e[r]!==t[r]))return!1;for(r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}e.exports=r},function(e,t,r){"use strict";var o=r(3)["default"],s=r(1),i=r(4),n=r(5),l=r(42),a=r(2),c=r(16),p=r(34),u=s.createClass({displayName:"Cell",propTypes:{rowIdx:s.PropTypes.number.isRequired,idx:s.PropTypes.number.isRequired,selected:s.PropTypes.shape({idx:s.PropTypes.number.isRequired}),tabIndex:s.PropTypes.number,ref:s.PropTypes.string,column:s.PropTypes.shape(a).isRequired,value:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number,s.PropTypes.object,s.PropTypes.bool]).isRequired,isExpanded:s.PropTypes.bool,cellMetaData:s.PropTypes.shape(p).isRequired,handleDragStart:s.PropTypes.func,className:s.PropTypes.string,rowData:s.PropTypes.object.isRequired},getDefaultProps:function(){return{tabIndex:-1,ref:"cell",isExpanded:!1}},getInitialState:function(){return{isRowChanging:!1,isCellValueChanging:!1}},componentDidMount:function(){this.checkFocus()},componentDidUpdate:function(e,t){this.checkFocus();var r=this.props.cellMetaData.dragged;r&&r.complete===!0&&this.props.cellMetaData.handleTerminateDrag(),this.state.isRowChanging&&null!=this.props.selectedColumn&&this.applyUpdateClass()},componentWillReceiveProps:function(e){this.setState({isRowChanging:this.props.rowData!==e.rowData,isCellValueChanging:this.props.value!==e.value})},shouldComponentUpdate:function(e,t){return this.props.column.width!==e.column.width||this.props.column.left!==e.column.left||this.props.rowData!==e.rowData||this.props.height!==e.height||this.props.rowIdx!==e.rowIdx||this.isCellSelectionChanging(e)||this.isDraggedCellChanging(e)||this.isCopyCellChanging(e)||this.props.isRowSelected!==e.isRowSelected||this.isSelected()},getStyle:function(){var e={position:"absolute",width:this.props.column.width,height:this.props.height,left:this.props.column.left};return e},render:function(){var e=this.getStyle(),t=this.getCellClass(),r=this.renderCellContent({value:this.props.value,column:this.props.column,rowIdx:this.props.rowIdx,isExpanded:this.props.isExpanded});return s.createElement("div",o({},this.props,{className:t,style:e,onClick:this.onCellClick,onDoubleClick:this.onCellDoubleClick}),r,s.createElement("div",{className:"drag-handle",draggable:"true"}))},renderCellContent:function(e){var t,r=this.getFormatter();return s.isValidElement(r)?(e.dependentValues=this.getFormatterDependencies(),t=n(r,e)):t=c(r)?s.createElement(r,{value:this.props.value,dependentValues:this.getFormatterDependencies()}):s.createElement(h,{value:this.props.value}),s.createElement("div",{ref:"cell",className:"react-grid-Cell__value"},t," ",this.props.cellControls)},isColumnSelected:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:e.selected&&e.selected.idx===this.props.idx},isSelected:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:e.selected&&e.selected.rowIdx===this.props.rowIdx&&e.selected.idx===this.props.idx},isActive:function(){var e=this.props.cellMetaData;return null==e||null==e.selected?!1:this.isSelected()&&e.selected.active===!0},isCellSelectionChanging:function(e){var t=this.props.cellMetaData;if(null==t||null==t.selected)return!1;var r=e.cellMetaData.selected;return t.selected&&r?this.props.idx===r.idx||this.props.idx===t.selected.idx:!0},getFormatter:function(){var e=this.props.column;return this.isActive()?s.createElement(l,{rowData:this.getRowData(),rowIdx:this.props.rowIdx,idx:this.props.idx,cellMetaData:this.props.cellMetaData,column:e,height:this.props.height}):this.props.column.formatter},getRowData:function(){return this.props.rowData.toJSON?this.props.rowData.toJSON():this.props.rowData},getFormatterDependencies:function(){this.props.column.ItemId;return"function"==typeof this.props.column.getRowMetaData?this.props.column.getRowMetaData(this.getRowData(),this.props.column):void 0},onCellClick:function(e){var t=this.props.cellMetaData;null!=t&&null!=t.onCellClick&&t.onCellClick({rowIdx:this.props.rowIdx,idx:this.props.idx})},onCellDoubleClick:function(e){var t=this.props.cellMetaData;null!=t&&null!=t.onCellDoubleClick&&t.onCellDoubleClick({rowIdx:this.props.rowIdx,idx:this.props.idx})},checkFocus:function(){this.isSelected()&&!this.isActive()&&this.getDOMNode().focus()},getCellClass:function(){var e=i(this.props.column.cellClass,"react-grid-Cell",this.props.className,this.props.column.locked?"react-grid-Cell--locked":null),t=i({selected:this.isSelected()&&!this.isActive(),editing:this.isActive(),copied:this.isCopied(),"active-drag-cell":this.isSelected()||this.isDraggedOver(),"is-dragged-over-up":this.isDraggedOverUpwards(),"is-dragged-over-down":this.isDraggedOverDownwards(),"was-dragged-over":this.wasDraggedOver()});return i(e,t)},getUpdateCellClass:function(){return this.props.column.getUpdateCellClass?this.props.column.getUpdateCellClass(this.props.selectedColumn,this.props.column,this.state.isCellValueChanging):""},applyUpdateClass:function(){var e=this.getUpdateCellClass();if(null!=e&&""!=e){var t=this.getDOMNode();t.classList?(t.classList.remove(e),t.classList.add(e)):-1===t.className.indexOf(e)&&(t.className=t.className+" "+e)}},setScrollLeft:function(e){var t=this;if(t.isMounted()){var r=this.getDOMNode(),o="translate3d("+e+"px, 0px, 0px)";r.style.webkitTransform=o,r.style.transform=o}},isCopied:function(){var e=this.props.cellMetaData.copied;return e&&e.rowIdx===this.props.rowIdx&&e.idx===this.props.idx},isDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&e.overRowIdx===this.props.rowIdx&&e.idx===this.props.idx},wasDraggedOver:function(){var e=this.props.cellMetaData.dragged;return e&&(e.overRowIdx<this.props.rowIdx&&this.props.rowIdx<e.rowIdx||e.overRowIdx>this.props.rowIdx&&this.props.rowIdx>e.rowIdx)&&e.idx===this.props.idx},isDraggedCellChanging:function(e){var t,r=this.props.cellMetaData.dragged,o=e.cellMetaData.dragged;return r?t=o&&this.props.idx===o.idx||r&&this.props.idx===r.idx:!1},isCopyCellChanging:function(e){var t,r=this.props.cellMetaData.copied,o=e.cellMetaData.copied;return r?t=o&&this.props.idx===o.idx||r&&this.props.idx===r.idx:!1},isDraggedOverUpwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx<e.rowIdx},isDraggedOverDownwards:function(){var e=this.props.cellMetaData.dragged;return!this.isSelected()&&this.isDraggedOver()&&this.props.rowIdx>e.rowIdx}}),h=s.createClass({displayName:"SimpleCellFormatter",propTypes:{value:s.PropTypes.oneOfType([s.PropTypes.string,s.PropTypes.number,s.PropTypes.object,s.PropTypes.bool]).isRequired},render:function(){return s.createElement("span",null,this.props.value)},shouldComponentUpdate:function(e,t){return e.value!==this.props.value}});e.exports=u},function(e,t,r){"use strict";var o=r(1),s=o.createClass({displayName:"CheckboxEditor",PropTypes:{value:o.PropTypes.bool.isRequired,rowIdx:o.PropTypes.number.isRequired,column:o.PropTypes.shape({key:o.PropTypes.string.isRequired,onCellChange:o.PropTypes.func.isRequired}).isRequired},render:function(){var e=null!=this.props.value?this.props.value:!1;return o.createElement("input",{className:"react-grid-CheckBox",type:"checkbox",checked:e,onClick:this.handleChange})},handleChange:function(e){this.props.column.onCellChange(this.props.rowIdx,this.props.column.key,e)}});e.exports=s},function(e,t,r){"use strict";var o=r(1),s=(r(10),r(2)),i=o.createClass({displayName:"SimpleTextEditor",propTypes:{value:o.PropTypes.any.isRequired,onBlur:o.PropTypes.func,column:o.PropTypes.shape(s).isRequired},getValue:function(){var e={};return e[this.props.column.key]=this.refs.input.getDOMNode().value,e},getInputNode:function(){return this.getDOMNode()},render:function(){return o.createElement("input",{ref:"input",type:"text",onBlur:this.props.onBlur,className:"form-control",defaultValue:this.props.value})}});e.exports=i},function(e,t,r){"use strict";var o=r(1),s=r(4),i=o.PropTypes,n=r(5),l=r(21),a=r(7),c=r(37),p=r(11),u=(r(2),o.createClass({displayName:"Canvas",mixins:[c],propTypes:{rowRenderer:i.oneOfType([i.func,i.element]),rowHeight:i.number.isRequired,height:i.number.isRequired,displayStart:i.number.isRequired,displayEnd:i.number.isRequired,rowsCount:i.number.isRequired,rowGetter:i.oneOfType([i.func.isRequired,i.array.isRequired]),onRows:i.func,columns:i.oneOfType([i.object,i.array]).isRequired},render:function(){var e=this,t=this.state.displayStart,r=this.state.displayEnd,i=this.props.rowHeight,n=this.props.rowsCount,l=this.getRows(t,r).map(function(r,o){return e.renderRow({key:t+o,ref:o,idx:t+o,row:r,height:i,columns:e.props.columns,isSelected:e.isRowSelected(t+o),expandedRows:e.props.expandedRows,cellMetaData:e.props.cellMetaData})});this._currentRowsLength=l.length,t>0&&l.unshift(this.renderPlaceholder("top",t*i)),n-r>0&&l.push(this.renderPlaceholder("bottom",(n-r)*i));var a=0;if(this.isMounted()){var c=this.getDOMNode();a=c.offsetWidth-c.clientWidth}var p={position:"absolute",top:0,left:0,overflowX:"auto",overflowY:"scroll",width:this.props.totalWidth+a,height:this.props.height,transform:"translate3d(0, 0, 0)"};return o.createElement("div",{style:p,onScroll:this.onScroll,className:s("react-grid-Canvas",this.props.className,{opaque:this.props.cellMetaData.selected&&this.props.cellMetaData.selected.active})},o.createElement("div",{style:{width:this.props.width,overflow:"hidden"}},l))},renderRow:function(e){var t=this.props.rowRenderer;return"function"==typeof t?o.createElement(t,e):o.isValidElement(this.props.rowRenderer)?n(this.props.rowRenderer,e):void 0},renderPlaceholder:function(e,t){return o.createElement("div",{key:e,style:{height:t}},this.props.columns.map(function(e,t){return o.createElement("div",{style:{width:e.width},key:t})}))},getDefaultProps:function(){return{rowRenderer:p,onRows:a}},isRowSelected:function(e){return this.props.selectedRows&&this.props.selectedRows[e]===!0},_currentRowsLength:0,_currentRowsRange:{start:0,end:0},_scroll:{scrollTop:0,scrollLeft:0},getInitialState:function(){return{shouldUpdate:!0,displayStart:this.props.displayStart,displayEnd:this.props.displayEnd}},componentWillMount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentDidMount:function(){this.onRows()},componentDidUpdate:function(e){this._scroll!=={start:0,end:0}&&this.setScrollLeft(this._scroll.scrollLeft),this.onRows()},componentWillUnmount:function(){this._currentRowsLength=0,this._currentRowsRange={start:0,end:0},this._scroll={scrollTop:0,scrollLeft:0}},componentWillReceiveProps:function(e){e.rowsCount>this.props.rowsCount&&(this.getDOMNode().scrollTop=e.rowsCount*this.props.rowHeight);var t=!(e.visibleStart>this.state.displayStart&&e.visibleEnd<this.state.displayEnd&&e.rowsCount===this.props.rowsCount&&e.rowHeight===this.props.rowHeight&&e.columns===this.props.columns&&e.width===this.props.width&&e.cellMetaData===this.props.cellMetaData&&l(e.style,this.props.style));t?this.setState({shouldUpdate:!0,displayStart:e.displayStart,displayEnd:e.displayEnd}):this.setState({shouldUpdate:!1})},shouldComponentUpdate:function(e,t){return!t||t.shouldUpdate},onRows:function(){this._currentRowsRange!=={start:0,end:0}&&(this.props.onRows(this._currentRowsRange),this._currentRowsRange={start:0,end:0})},getRows:function(e,t){if(this._currentRowsRange={start:e,end:t},Array.isArray(this.props.rowGetter))return this.props.rowGetter.slice(e,t);for(var r=[],o=e;t>o;o++)r.push(this.props.rowGetter(o));return r},setScrollLeft:function(e){if(0!==this._currentRowsLength){if(!this.refs)return;for(var t=0,r=this._currentRowsLength;r>t;t++)this.refs[t]&&this.refs[t].setScrollLeft&&this.refs[t].setScrollLeft(e)}},getScroll:function(){var e=this.getDOMNode(),t=e.scrollTop,r=e.scrollLeft;return{scrollTop:t,scrollLeft:r}},onScroll:function(e){this.appendScrollShim();var t=e.target,r=t.scrollTop,o=t.scrollLeft,s={scrollTop:r,scrollLeft:o};this._scroll=s,this.props.onScroll(s)}}));e.exports=u},function(e,t,r){"use strict";var o=r(1).isValidElement;e.exports=function(e,t){var r;for(r in e)if(e.hasOwnProperty(r)){if("function"==typeof e[r]&&"function"==typeof t[r]||o(e[r])&&o(t[r]))continue;if(!t.hasOwnProperty(r)||e[r]!==t[r])return!1}for(r in t)if(t.hasOwnProperty(r)&&!e.hasOwnProperty(r))return!1;return!0}},function(e,t,r){"use strict";var o=r(17)["default"],s=r(12),i=r(9);Object.assign=r(19);var n=r(1).PropTypes,l=r(6),a=function c(){o(this,c)};e.exports={mixins:[i.MetricsMixin],propTypes:{columns:n.arrayOf(a),minColumnWidth:n.number,columnEquality:n.func},DOMMetrics:{gridWidth:function(){return this.getDOMNode().offsetWidth-2}},getDefaultProps:function(){return{minColumnWidth:80,columnEquality:s.sameColumn}},componentWillReceiveProps:function(e){if(e.columns&&!s.sameColumns(this.props.columns,e.columns,this.props.columnEquality)){var t=this.createColumnMetrics();this.setState({columnMetrics:t})}},getTotalWidth:function(){var e=0;return e=this.isMounted()?this.DOMMetrics.gridWidth():l.getSize(this.props.columns)*this.props.minColumnWidth},getColumnMetricsType:function(e){var t=this.getTotalWidth(),r={columns:e.columns,totalWidth:t,minColumnWidth:e.minColumnWidth},o=s.recalculate(r);return o},getColumn:function(e,t){return Array.isArray(e)?e[t]:"undefined"!=typeof Immutable?e.get(t):void 0},getSize:function(){var e=this.state.columnMetrics.columns;return Array.isArray(e)?e.length:"undefined"!=typeof Immutable?e.size:void 0},metricsUpdated:function(){var e=this.createColumnMetrics();this.setState({columnMetrics:e})},createColumnMetrics:function(e){var t=this.setupGridColumns();return this.getColumnMetricsType({columns:t,minColumnWidth:this.props.minColumnWidth},e)},onColumnResize:function(e,t){var r=s.resizeColumn(this.state.columnMetrics,e,t);this.setState({columnMetrics:r})}}},function(e,t,r){"use strict";var o=r(3)["default"],s=r(1),i=s.PropTypes,n=r(7),l=s.createClass({displayName:"Draggable",propTypes:{onDragStart:i.func,onDragEnd:i.func,onDrag:i.func,component:i.oneOfType([i.func,i.constructor])},render:function(){this.props.component;return s.createElement("div",o({},this.props,{onMouseDown:this.onMouseDown,className:"react-grid-HeaderCell__draggable"}))},getDefaultProps:function(){return{onDragStart:n.thatReturnsTrue,onDragEnd:n,onDrag:n}},getInitialState:function(){return{drag:null}},onMouseDown:function(e){var t=this.props.onDragStart(e);(null!==t||0===e.button)&&(window.addEventListener("mouseup",this.onMouseUp),window.addEventListener("mousemove",this.onMouseMove),this.setState({drag:t}))},onMouseMove:function(e){null!==this.state.drag&&(e.preventDefault&&e.preventDefault(),this.props.onDrag(e))},onMouseUp:function(e){this.cleanUp(),this.props.onDragEnd(e,this.state.drag),this.setState({drag:null})},componentWillUnmount:function(){this.cleanUp()},cleanUp:function(){window.removeEventListener("mouseup",this.onMouseUp),window.removeEventListener("mousemove",this.onMouseMove)}});e.exports=l},function(e,t,r){"use strict";var o=r(3)["default"],s=r(1),i=s.PropTypes,n=r(31),l=r(38),a=(r(2),r(30)),c=r(9),p=s.createClass({displayName:"Grid",propTypes:{rowGetter:i.oneOfType([i.array,i.func]).isRequired,columns:i.oneOfType([i.array,i.object]),minHeight:i.number,headerRows:i.oneOfType([i.array,i.func]),rowHeight:i.number,rowRenderer:i.func,expandedRows:i.oneOfType([i.array,i.func]),selectedRows:i.oneOfType([i.array,i.func]),rowsCount:i.number,onRows:i.func,sortColumn:s.PropTypes.string,sortDirection:s.PropTypes.oneOf(["ASC","DESC","NONE"]),rowOffsetHeight:i.number.isRequired,onViewportKeydown:i.func.isRequired,onViewportDragStart:i.func.isRequired,onViewportDragEnd:i.func.isRequired,onViewportDoubleClick:i.func.isRequired},mixins:[a,c.MetricsComputatorMixin],getStyle:function(){return{overflow:"hidden",outline:0,position:"relative",minHeight:this.props.minHeight}},render:function(){var e=this.props.headerRows||[{ref:"row"}];return s.createElement("div",o({},this.props,{style:this.getStyle(),className:"react-grid-Grid"}),s.createElement(n,{ref:"header",columnMetrics:this.props.columnMetrics,onColumnResize:this.props.onColumnResize,height:this.props.rowHeight,totalWidth:this.props.totalWidth,headerRows:e,sortColumn:this.props.sortColumn,sortDirection:this.props.sortDirection,onSort:this.props.onSort}),s.createElement("div",{ref:"viewPortContainer",onKeyDown:this.props.onViewportKeydown,onDoubleClick:this.props.onViewportDoubleClick,onDragStart:this.props.onViewportDragStart,onDragEnd:this.props.onViewportDragEnd},s.createElement(l,{ref:"viewport",width:this.props.columnMetrics.width,rowHeight:this.props.rowHeight,rowRenderer:this.props.rowRenderer,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columnMetrics:this.props.columnMetrics,totalWidth:this.props.totalWidth,onScroll:this.onScroll,onRows:this.props.onRows,cellMetaData:this.props.cellMetaData,rowOffsetHeight:this.props.rowOffsetHeight||this.props.rowHeight*e.length,minHeight:this.props.minHeight})))},getDefaultProps:function(){return{rowHeight:35,minHeight:350}}});e.exports=p},function(e,t){"use strict";e.exports={componentDidMount:function(){this._scrollLeft=this.refs.viewport.getScroll().scrollLeft,this._onScroll()},componentDidUpdate:function(){this._onScroll()},componentWillMount:function(){this._scrollLeft=void 0},componentWillUnmount:function(){this._scrollLeft=void 0},onScroll:function(e){this._scrollLeft!==e.scrollLeft&&(this._scrollLeft=e.scrollLeft,this._onScroll())},_onScroll:function(){void 0!==this._scrollLeft&&(this.refs.header.setScrollLeft(this._scrollLeft),this.refs.viewport.setScrollLeft(this._scrollLeft))}}},function(e,t,r){"use strict";var o=r(3)["default"],s=r(1),i=r(4),n=r(13),l=r(12),a=r(6),c=r(33),p=s.createClass({displayName:"Header",propTypes:{columnMetrics:s.PropTypes.shape({width:s.PropTypes.number.isRequired}).isRequired,totalWidth:s.PropTypes.number,height:s.PropTypes.number.isRequired,headerRows:s.PropTypes.array.isRequired},render:function(){var e=(this.state.resizing||this.props,i({"react-grid-Header":!0,"react-grid-Header--resizing":!!this.state.resizing})),t=this.getHeaderRows();return s.createElement("div",o({},this.props,{style:this.getStyle(),className:e}),t)},shouldComponentUpdate:function(e,t){var r=!l.sameColumns(this.props.columnMetrics.columns,e.columnMetrics.columns,l.sameColumn)||this.props.totalWidth!=e.totalWidth||this.props.headerRows.length!=e.headerRows.length||this.state.resizing!=t.resizing||this.props.sortColumn!=e.sortColumn||this.props.sortDirection!=e.sortDirection;return r},getHeaderRows:function(){var e,t=this.getColumnMetrics();this.state.resizing&&(e=this.state.resizing.column);var r=[];return this.props.headerRows.forEach(function(o,i){var n={position:"absolute",top:this.props.height*i,left:0,width:this.props.totalWidth,overflow:"hidden"};r.push(s.createElement(c,{key:o.ref,ref:o.ref,style:n,onColumnResize:this.onColumnResize,onColumnResizeEnd:this.onColumnResizeEnd,width:t.width,height:o.height||this.props.height,columns:t.columns,resizing:e,headerCellRenderer:o.headerCellRenderer,sortColumn:this.props.sortColumn,sortDirection:this.props.sortDirection,onSort:this.props.onSort}))}.bind(this)),r},getInitialState:function(){return{resizing:null}},componentWillReceiveProps:function(e){this.setState({resizing:null})},onColumnResize:function(e,t){var r=this.state.resizing||this.props,o=this.getColumnPosition(e);if(null!=o){var s={columnMetrics:n(r.columnMetrics)};s.columnMetrics=l.resizeColumn(s.columnMetrics,o,t),s.columnMetrics.totalWidth<r.columnMetrics.totalWidth&&(s.columnMetrics.totalWidth=r.columnMetrics.totalWidth),s.column=a.getColumn(s.columnMetrics.columns,o), this.setState({resizing:s})}},getColumnMetrics:function(){var e;return e=this.state.resizing?this.state.resizing.columnMetrics:this.props.columnMetrics},getColumnPosition:function(e){var t=this.getColumnMetrics(),r=-1;return t.columns.forEach(function(t,o){t.key===e.key&&(r=o)}),-1===r?null:r},onColumnResizeEnd:function(e,t){var r=this.getColumnPosition(e);null!==r&&this.props.onColumnResize&&this.props.onColumnResize(r,t||e.width)},setScrollLeft:function(e){var t=this.refs.row.getDOMNode();t.scrollLeft=e,this.refs.row.setScrollLeft(e)},getStyle:function(){return{position:"relative",height:this.props.height*this.props.headerRows.length,overflow:"hidden"}}});e.exports=p},function(e,t,r){"use strict";function o(e){return s.createElement("div",{className:"widget-HeaderCell__value"},e.column.name)}var s=r(1),i=r(4),n=r(5),l=s.PropTypes,a=r(2),c=r(35),p=s.createClass({displayName:"HeaderCell",propTypes:{renderer:l.oneOfType([l.func,l.element]).isRequired,column:l.shape(a).isRequired,onResize:l.func.isRequired,height:l.number.isRequired,onResizeEnd:l.func.isRequired},render:function(){var e;this.props.column.resizable&&(e=s.createElement(c,{onDrag:this.onDrag,onDragStart:this.onDragStart,onDragEnd:this.onDragEnd}));var t=i({"react-grid-HeaderCell":!0,"react-grid-HeaderCell--resizing":this.state.resizing,"react-grid-HeaderCell--locked":this.props.column.locked});t=i(t,this.props.className);var r=this.getCell();return s.createElement("div",{className:t,style:this.getStyle()},r,{resizeHandle:e})},getCell:function(){return s.isValidElement(this.props.renderer)?n(this.props.renderer,{column:this.props.column}):this.props.renderer({column:this.props.column})},getDefaultProps:function(){return{renderer:o}},getInitialState:function(){return{resizing:!1}},setScrollLeft:function(e){var t=this.getDOMNode();t.style.webkitTransform="translate3d("+e+"px, 0px, 0px)",t.style.transform="translate3d("+e+"px, 0px, 0px)"},getStyle:function(){return{width:this.props.column.width,left:this.props.column.left,display:"inline-block",position:"absolute",overflow:"hidden",height:this.props.height,margin:0,textOverflow:"ellipsis",whiteSpace:"nowrap"}},onDragStart:function(e){this.setState({resizing:!0}),e&&e.dataTransfer&&e.dataTransfer.setData&&e.dataTransfer.setData("text/plain","dummy")},onDrag:function(e){var t=this.props.onResize||null;if(t){var r=this.getWidthFromMouseEvent(e);r>0&&t(this.props.column,r)}},onDragEnd:function(e){var t=this.getWidthFromMouseEvent(e);this.props.onResizeEnd(this.props.column,t),this.setState({resizing:!1})},getWidthFromMouseEvent:function(e){var t=e.pageX,r=this.getDOMNode().getBoundingClientRect().left;return t-r}});e.exports=p},function(e,t,r){"use strict";var o=r(3)["default"],s=r(1),i=s.PropTypes,n=r(21),l=r(32),a=r(44),c=(r(2),r(6)),p=r(41),u={overflow:s.PropTypes.string,width:i.oneOfType([i.number,i.string]),height:s.PropTypes.number,position:s.PropTypes.string},h={ASC:"ASC",DESC:"DESC",NONE:"NONE"},d=s.createClass({displayName:"HeaderRow",propTypes:{width:i.oneOfType([i.number,i.string]),height:i.number.isRequired,columns:i.oneOfType([i.array,i.object]),onColumnResize:i.func,onSort:i.func.isRequired,style:i.shape(u)},mixins:[c],render:function(){var e={width:this.props.width?this.props.width+a():"100%",height:this.props.height,whiteSpace:"nowrap",overflowX:"hidden",overflowY:"hidden"},t=this.getCells();return s.createElement("div",o({},this.props,{className:"react-grid-HeaderRow"}),s.createElement("div",{style:e},t))},getHeaderRenderer:function(e){if(e.sortable){var t=this.props.sortColumn===e.key?this.props.sortDirection:h.NONE;return s.createElement(p,{columnKey:e.key,onSort:this.props.onSort,sortDirection:t})}return this.props.headerCellRenderer||e.headerRenderer||this.props.cellRenderer},getCells:function(){for(var e=[],t=[],r=0,o=this.getSize(this.props.columns);o>r;r++){var i=this.getColumn(this.props.columns,r),n=s.createElement(l,{ref:r,key:r,height:this.props.height,column:i,renderer:this.getHeaderRenderer(i),resizing:this.props.resizing===i,onResize:this.props.onColumnResize,onResizeEnd:this.props.onColumnResizeEnd});i.locked?t.push(n):e.push(n)}return e.concat(t)},setScrollLeft:function(e){var t=this;this.props.columns.forEach(function(r,o){r.locked&&t.refs[o].setScrollLeft(e)})},shouldComponentUpdate:function(e){return e.width!==this.props.width||e.height!==this.props.height||e.columns!==this.props.columns||!n(e.style,this.props.style)||this.props.sortColumn!=e.sortColumn||this.props.sortDirection!=e.sortDirection},getStyle:function(){return{overflow:"hidden",width:"100%",height:this.props.height,position:"absolute"}}});e.exports=d},function(e,t,r){"use strict";var o=r(1).PropTypes;e.exports={selected:o.object.isRequired,copied:o.object,dragged:o.object,onCellClick:o.func.isRequired}},function(e,t,r){"use strict";var o=r(3)["default"],s=r(1),i=(r(4),r(28)),n=(r(5),s.PropTypes,s.createClass({displayName:"ResizeHandle",style:{position:"absolute",top:0,right:0,width:6,height:"100%"},render:function(){return s.createElement(i,o({},this.props,{className:"react-grid-HeaderCell__resizeHandle",style:this.style}))}}));e.exports=n},function(e,t){"use strict";var r={get:function(e,t){return"function"==typeof e.get?e.get(t):e[t]}};e.exports=r},function(e,t){"use strict";var r={appendScrollShim:function(){if(!this._scrollShim){var e=this._scrollShimSize(),t=document.createElement("div");t.classList?t.classList.add("react-grid-ScrollShim"):t.className+=" react-grid-ScrollShim",t.style.position="absolute",t.style.top=0,t.style.left=0,t.style.width=e.width+"px",t.style.height=e.height+"px",this.getDOMNode().appendChild(t),this._scrollShim=t}this._scheduleRemoveScrollShim()},_scrollShimSize:function(){return{width:this.props.width,height:this.props.length*this.props.rowHeight}},_scheduleRemoveScrollShim:function(){this._scheduleRemoveScrollShimTimer&&clearTimeout(this._scheduleRemoveScrollShimTimer),this._scheduleRemoveScrollShimTimer=setTimeout(this._removeScrollShim,200)},_removeScrollShim:function(){this._scrollShim&&(this._scrollShim.parentNode.removeChild(this._scrollShim),this._scrollShim=void 0)}};e.exports=r},function(e,t,r){"use strict";var o=r(1),s=r(25),i=o.PropTypes,n=r(39),l=o.createClass({displayName:"Viewport",mixins:[n],propTypes:{rowOffsetHeight:i.number.isRequired,totalWidth:i.number.isRequired,columnMetrics:i.object.isRequired,rowGetter:i.oneOfType([i.array,i.func]).isRequired,selectedRows:i.array,expandedRows:i.array,rowRenderer:i.func,rowsCount:i.number.isRequired,rowHeight:i.number.isRequired,onRows:i.func,onScroll:i.func,minHeight:i.number},render:function(){var e={padding:0,bottom:0,left:0,right:0,overflow:"hidden",position:"absolute",top:this.props.rowOffsetHeight};return o.createElement("div",{className:"react-grid-Viewport",style:e},o.createElement(s,{ref:"canvas",totalWidth:this.props.totalWidth,width:this.props.columnMetrics.width,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,selectedRows:this.props.selectedRows,expandedRows:this.props.expandedRows,columns:this.props.columnMetrics.columns,rowRenderer:this.props.rowRenderer,visibleStart:this.state.visibleStart,visibleEnd:this.state.visibleEnd,displayStart:this.state.displayStart,displayEnd:this.state.displayEnd,cellMetaData:this.props.cellMetaData,height:this.state.height,rowHeight:this.props.rowHeight,onScroll:this.onScroll,onRows:this.props.onRows}))},getScroll:function(){return this.refs.canvas.getScroll()},onScroll:function(e){this.updateScroll(e.scrollTop,e.scrollLeft,this.state.height,this.props.rowHeight,this.props.rowsCount),this.props.onScroll&&this.props.onScroll({scrollTop:e.scrollTop,scrollLeft:e.scrollLeft})},setScrollLeft:function(e){this.refs.canvas.setScrollLeft(e)}});e.exports=l},function(e,t,r){"use strict";var o=r(1),s=r(9),i=(r(45),o.PropTypes,Math.min),n=Math.max,l=Math.floor,a=Math.ceil;e.exports={mixins:[s.MetricsMixin],DOMMetrics:{viewportHeight:function(){return this.getDOMNode().offsetHeight}},propTypes:{rowHeight:o.PropTypes.number,rowsCount:o.PropTypes.number.isRequired},getDefaultProps:function(){return{rowHeight:30}},getInitialState:function(){return this.getGridState(this.props)},getGridState:function(e){var t=a((e.minHeight-e.rowHeight)/e.rowHeight),r=i(2*t,e.rowsCount);return{displayStart:0,displayEnd:r,height:e.minHeight,scrollTop:0,scrollLeft:0}},updateScroll:function(e,t,r,o,s){var c=a(r/o),p=l(e/o),u=i(p+c,s),h=n(0,p-2*c),d=i(p+2*c,s),f={visibleStart:p,visibleEnd:u,displayStart:h,displayEnd:d,height:r,scrollTop:e,scrollLeft:t};this.setState(f)},metricsUpdated:function(){var e=this.DOMMetrics.viewportHeight();e&&this.updateScroll(this.state.scrollTop,this.state.scrollLeft,e,this.props.rowHeight,this.props.rowsCount)},componentWillReceiveProps:function(e){this.props.rowHeight!==e.rowHeight?this.setState(this.getGridState(e)):this.props.rowsCount!==e.rowsCount&&this.updateScroll(this.state.scrollTop,this.state.scrollLeft,this.state.height,e.rowHeight,e.rowsCount)}}},function(e,t,r){"use strict";var o=r(1),s=r(2),i=o.createClass({displayName:"FilterableHeaderCell",propTypes:{onChange:o.PropTypes.func.isRequired,column:o.PropTypes.shape(s).isRequired},getInitialState:function(){return{filterTerm:""}},handleChange:function(e){var t=e.target.value;this.setState({filterTerm:t}),this.props.onChange({filterTerm:t,columnKey:this.props.column.key})},componentDidUpdate:function(e){var t=this.getDOMNode();t&&t.focus()},render:function(){return o.createElement("div",null,o.createElement("div",{className:"form-group"},o.createElement(this.renderInput,null)))},renderInput:function(){return this.props.column.filterable===!1?o.createElement("span",null):o.createElement("input",{type:"text",className:"form-control input-sm",placeholder:"Search",value:this.state.filterTerm,onChange:this.handleChange})}});e.exports=i},function(e,t,r){"use strict";var o=r(1),s=(r(4),r(2),{ASC:"ASC",DESC:"DESC",NONE:"NONE"}),i=o.createClass({displayName:"SortableHeaderCell",propTypes:{columnKey:o.PropTypes.string.isRequired,onSort:o.PropTypes.func.isRequired,sortDirection:o.PropTypes.oneOf(["ASC","DESC","NONE"])},onClick:function(){var e;switch(this.props.sortDirection){case null:case void 0:case s.NONE:e=s.ASC;break;case s.ASC:e=s.DESC;break;case s.DESC:e=s.NONE}this.props.onSort(this.props.columnKey,e)},getSortByText:function(){var e={ASC:"9650",DESC:"9660",NONE:""};return String.fromCharCode(e[this.props.sortDirection])},render:function(){return o.createElement("div",{onClick:this.onClick,style:{cursor:"pointer"}},this.props.column.name,o.createElement("span",{className:"pull-right"},this.getSortByText()))}});e.exports=i},function(e,t,r){"use strict";var o=r(1),s=r(4),i=r(10),n=r(24),l=r(16),a=(r(5),o.createClass({displayName:"EditorContainer",mixins:[i],propTypes:{rowData:o.PropTypes.object.isRequired,value:o.PropTypes.oneOfType([o.PropTypes.string,o.PropTypes.number,o.PropTypes.object,o.PropTypes.bool]).isRequired,cellMetaData:o.PropTypes.shape({selected:o.PropTypes.object.isRequired,copied:o.PropTypes.object,dragged:o.PropTypes.object,onCellClick:o.PropTypes.func,onCellDoubleClick:o.PropTypes.func}).isRequired,column:o.PropTypes.object.isRequired,height:o.PropTypes.number.isRequired},changeCommitted:!1,getInitialState:function(){return{isInvalid:!1}},componentDidMount:function(){var e=this.getInputNode();void 0!==e&&(this.setTextInputFocus(),this.getEditor().disableContainerStyles||(e.className+=" editor-main",e.style.height=this.props.height-1+"px"))},createEditor:function(){var e={ref:"editor",name:"editor",column:this.props.column,value:this.getInitialValue(),onCommit:this.commit,rowMetaData:this.getRowMetaData(),height:this.props.height,onBlur:this.commit,onOverrideKeyDown:this.onKeyDown},t=this.props.column.editor;return t&&o.isValidElement(t)?o.addons.cloneWithProps(t,e):o.createElement(n,{ref:"editor",column:this.props.column,value:this.getInitialValue(),rowMetaData:this.getRowMetaData()})},getRowMetaData:function(){this.props.column.ItemId;return"function"==typeof this.props.column.getRowMetaData?this.props.column.getRowMetaData(this.props.rowData,this.props.column):void 0},onPressEnter:function(e){this.commit({key:"Enter"})},onPressTab:function(e){this.commit({key:"Tab"})},onPressEscape:function(e){this.editorIsSelectOpen()?e.stopPropagation():this.props.cellMetaData.onCommitCancel()},onPressArrowDown:function(e){this.editorHasResults()?e.stopPropagation():this.commit(e)},onPressArrowUp:function(e){this.editorHasResults()?e.stopPropagation():this.commit(e)},onPressArrowLeft:function(e){this.isCaretAtBeginningOfInput()?this.commit(e):e.stopPropagation()},onPressArrowRight:function(e){this.isCaretAtEndOfInput()?this.commit(e):e.stopPropagation()},editorHasResults:function(){return"SELECT"===this.getEditor().getInputNode().tagName?!0:l(this.getEditor().hasResults)?this.getEditor().hasResults():!1},editorIsSelectOpen:function(){return l(this.getEditor().isSelectOpen)?this.getEditor().isSelectOpen():!1},getEditor:function(){return this.refs.editor},commit:function(e){var t=e||{},r=this.getEditor().getValue();if(this.isNewValueValid(r)){var o=this.props.column.key;this.props.cellMetaData.onCommit({cellKey:o,rowIdx:this.props.rowIdx,updated:r,key:t.key})}this.changeCommitted=!0},isNewValueValid:function(e){if(l(this.getEditor().validate)){var t=this.getEditor().validate(e);return this.setState({isInvalid:!t}),t}return!0},getInputNode:function(){return this.getEditor().getInputNode()},getInitialValue:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode;if("Delete"===t||"Backspace"===t)return"";if("Enter"===t)return this.props.value;var r=t?String.fromCharCode(t):this.props.value;return r},getContainerClass:function(){return s({"has-error":this.state.isInvalid===!0})},setCaretAtEndOfInput:function(){var e=this.getInputNode(),t=e.value.length;if(e.setSelectionRange)e.setSelectionRange(t,t);else if(e.createTextRange){var r=e.createTextRange();r.moveStart("character",t),r.collapse(),r.select()}},isCaretAtBeginningOfInput:function(){var e=this.getInputNode();return e.selectionStart===e.selectionEnd&&0===e.selectionStart},isCaretAtEndOfInput:function(){var e=this.getInputNode();return e.selectionStart===e.value.length},setTextInputFocus:function(){var e=this.props.cellMetaData.selected,t=e.initialKeyCode,r=this.getInputNode();r.focus(),"INPUT"===r.tagName&&(this.isKeyPrintable(t)?r.select():(r.focus(),r.select()))},componentWillUnmount:function(){this.changeCommitted||this.hasEscapeBeenPressed()||this.commit({key:"Enter"})},renderStatusIcon:function(){return this.state.isInvalid===!0?o.createElement("span",{className:"glyphicon glyphicon-remove form-control-feedback"}):void 0},hasEscapeBeenPressed:function(){var e=!1,t=27;return window.event&&(window.event.keyCode===t?e=!0:window.event.which===t&&(e=!0)),e},render:function(){return o.createElement("div",{className:this.getContainerClass(),onKeyDown:this.onKeyDown},this.createEditor(),this.renderStatusIcon())}}));e.exports=a},function(e,t,r){"use strict";var o=r(3)["default"],s=r(14)["default"],i=r(1),n=(i.PropTypes,r(29)),l=(r(11),r(2),r(10)),a=r(23),c=r(40),p=r(5),u=r(9),h=r(27),d=r(36),f=r(6);s||(Object.assign=r(19));var m=i.createClass({displayName:"ReactDataGrid",propTypes:{rowHeight:i.PropTypes.number.isRequired,minHeight:i.PropTypes.number.isRequired,enableRowSelect:i.PropTypes.bool,onRowUpdated:i.PropTypes.func,rowGetter:i.PropTypes.func.isRequired,rowsCount:i.PropTypes.number.isRequired,toolbar:i.PropTypes.element,enableCellSelect:i.PropTypes.bool,columns:i.PropTypes.oneOfType([i.PropTypes.object,i.PropTypes.array]).isRequired,onFilter:i.PropTypes.func,onCellCopyPaste:i.PropTypes.func,onCellsDragged:i.PropTypes.func,onAddFilter:i.PropTypes.func},mixins:[h,u.MetricsComputatorMixin,l],getDefaultProps:function(){return{enableCellSelect:!1,tabIndex:-1,rowHeight:35,enableRowSelect:!1,minHeight:350}},getInitialState:function(){var e=this.createColumnMetrics(!0),t={columnMetrics:e,selectedRows:this.getInitialSelectedRows(),copied:null,expandedRows:[],canFilter:!1,columnFilters:{},sortDirection:null,sortColumn:null,dragged:null,scrollOffset:0};return this.props.enableCellSelect?t.selected={rowIdx:0,idx:0}:t.selected={rowIdx:-1,idx:-1},t},getInitialSelectedRows:function(){for(var e=[],t=0;t<this.props.rowsCount;t++)e.push(!1);return e},componentWillReceiveProps:function(e){e.rowsCount===this.props.rowsCount+1&&this.onAfterAddRow(e.rowsCount+1)},componentDidMount:function(){var e=0,t=this.getDOMNode().querySelector(".react-grid-Canvas");null!=t&&(e=t.offsetWidth-t.clientWidth),this.setState({scrollOffset:e})},render:function(){var e={selected:this.state.selected,dragged:this.state.dragged,onCellClick:this.onCellClick,onCellDoubleClick:this.onCellDoubleClick,onCommit:this.onCellCommit,onCommitCancel:this.setInactive,copied:this.state.copied,handleDragEnterRow:this.handleDragEnter,handleTerminateDrag:this.handleTerminateDrag},t=this.renderToolbar(),r=this.DOMMetrics.gridWidth(),s=r+this.state.scrollOffset;return i.createElement("div",{className:"react-grid-Container",style:{width:s}},t,i.createElement("div",{className:"react-grid-Main"},i.createElement(n,o({ref:"base"},this.props,{headerRows:this.getHeaderRows(),columnMetrics:this.state.columnMetrics,rowGetter:this.props.rowGetter,rowsCount:this.props.rowsCount,rowHeight:this.props.rowHeight,cellMetaData:e,selectedRows:this.state.selectedRows,expandedRows:this.state.expandedRows,rowOffsetHeight:this.getRowOffsetHeight(),sortColumn:this.state.sortColumn,sortDirection:this.state.sortDirection,onSort:this.handleSort,minHeight:this.props.minHeight,totalWidth:r,onViewportKeydown:this.onKeyDown,onViewportDragStart:this.onDragStart,onViewportDragEnd:this.handleDragEnd,onViewportDoubleClick:this.onViewportDoubleClick,onColumnResize:this.onColumnResize}))))},renderToolbar:function(){var e=this.props.toolbar;return i.isValidElement(e)?p(e,{onToggleFilter:this.onToggleFilter,numberOfRows:this.props.rowsCount}):void 0},onSelect:function(e){if(this.props.enableCellSelect)if(this.state.selected.rowIdx===e.rowIdx&&this.state.selected.idx===e.idx&&this.state.selected.active===!0);else{var t=e.idx,r=e.rowIdx;t>=0&&r>=0&&t<f.getSize(this.state.columnMetrics.columns)&&r<this.props.rowsCount&&this.setState({selected:e})}},onCellClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx})},onCellDoubleClick:function(e){this.onSelect({rowIdx:e.rowIdx,idx:e.idx}),this.setActive("Enter")},onViewportDoubleClick:function(e){this.setActive()},onPressArrowUp:function(e){this.moveSelectedCell(e,-1,0)},onPressArrowDown:function(e){this.moveSelectedCell(e,1,0)},onPressArrowLeft:function(e){this.moveSelectedCell(e,0,-1)},onPressArrowRight:function(e){this.moveSelectedCell(e,0,1)},onPressTab:function(e){this.moveSelectedCell(e,0,e.shiftKey?-1:1)},onPressEnter:function(e){this.setActive(e.key)},onPressDelete:function(e){this.setActive(e.key)},onPressEscape:function(e){this.setInactive(e.key)},onPressBackspace:function(e){this.setActive(e.key)},onPressChar:function(e){this.isKeyPrintable(e.keyCode)&&this.setActive(e.keyCode)},onPressKeyWithCtrl:function(e){var t={KeyCode_c:99,KeyCode_C:67,KeyCode_V:86,KeyCode_v:118},r=this.state.selected.idx;if(this.canEdit(r))if(e.keyCode==t.KeyCode_c||e.keyCode==t.KeyCode_C){var o=this.getSelectedValue();this.handleCopy({value:o})}else(e.keyCode==t.KeyCode_v||e.keyCode==t.KeyCode_V)&&this.handlePaste()},onDragStart:function(e){var t=this.getSelectedValue();this.handleDragStart({idx:this.state.selected.idx,rowIdx:this.state.selected.rowIdx,value:t}),e&&e.dataTransfer&&e.dataTransfer.setData&&e.dataTransfer.setData("text/plain","dummy")},moveSelectedCell:function(e,t,r){e.preventDefault();var o=this.state.selected.rowIdx+t,s=this.state.selected.idx+r;this.onSelect({idx:s,rowIdx:o})},getSelectedValue:function(){var e=this.state.selected.rowIdx,t=this.state.selected.idx,r=this.getColumn(this.props.columns,t).key,o=this.props.rowGetter(e);return d.get(o,r)},setActive:function(e){var t=this.state.selected.rowIdx,r=this.state.selected.idx;if(this.canEdit(r)&&!this.isActive()){var o=s(this.state.selected,{idx:r,rowIdx:t,active:!0,initialKeyCode:e});this.setState({selected:o})}},setInactive:function(){var e=this.state.selected.rowIdx,t=this.state.selected.idx;if(this.canEdit(t)&&this.isActive()){var r=s(this.state.selected,{idx:t,rowIdx:e,active:!1});this.setState({selected:r})}},canEdit:function(e){var t=this.getColumn(this.props.columns,e);return this.props.enableCellSelect===!0&&(null!=t.editor||t.editable)},isActive:function(){return this.state.selected.active===!0},onCellCommit:function(e){var t=s({},this.state.selected);t.active=!1,"Tab"===e.key&&(t.idx+=1);var r=this.state.expandedRows;this.setState({selected:t,expandedRows:r}),this.props.onRowUpdated(e)},setupGridColumns:function(){var e=this.props.columns.slice(0);if(this.props.enableRowSelect){var t={key:"select-row",name:"",formatter:i.createElement(a,null),onCellChange:this.handleRowSelect,filterable:!1,headerRenderer:i.createElement("input",{type:"checkbox",onChange:this.handleCheckboxChange}),width:60,locked:!0},r=e.unshift(t);e=r>0?e:r}return e},handleCheckboxChange:function(e){var t;t=e.currentTarget instanceof HTMLInputElement&&e.currentTarget.checked===!0?!0:!1;for(var r=[],o=0;o<this.props.rowsCount;o++)r.push(t);this.setState({selectedRows:r})},handleRowSelect:function(e,t,r){if(r.stopPropagation(),null!=this.state.selectedRows&&this.state.selectedRows.length>0){var o=this.state.selectedRows.slice();null==o[e]||0==o[e]?o[e]=!0:o[e]=!1,this.setState({selectedRows:o})}},onAfterAddRow:function(e){this.setState({selected:{idx:1,rowIdx:e-2}})},onToggleFilter:function(){this.setState({canFilter:!this.state.canFilter})},getHeaderRows:function(){var e=[{ref:"row",height:this.props.rowHeight}];return this.state.canFilter===!0&&e.push({ref:"filterRow",headerCellRenderer:i.createElement(c,{onChange:this.props.onAddFilter,column:this.props.column}),height:45}),e},getRowOffsetHeight:function(){var e=0;return this.getHeaderRows().forEach(function(t){return e+=parseFloat(t.height,10)}),e},handleSort:function(e,t){this.setState({sortDirection:t,sortColumn:e},function(){this.props.onGridSort(e,t)})},copyPasteEnabled:function(){return null!==this.props.onCellCopyPaste},handleCopy:function(e){if(this.copyPasteEnabled()){var t=e.value,r=this.state.selected,o={idx:r.idx,rowIdx:r.rowIdx};this.setState({textToCopy:t,copied:o})}},handlePaste:function(){if(this.copyPasteEnabled()){var e=this.state.selected,t=this.getColumn(this.state.columnMetrics.columns,this.state.selected.idx).key;this.props.onCellCopyPaste&&this.props.onCellCopyPaste({cellKey:t,rowIdx:e.rowIdx,value:this.state.textToCopy,fromRow:this.state.copied.rowIdx,toRow:e.rowIdx}),this.setState({copied:null})}},dragEnabled:function(){return null!==this.props.onCellsDragged},handleDragStart:function(e){if(this.dragEnabled()){var t=e.idx,r=e.rowIdx;t>=0&&r>=0&&t<this.getSize()&&r<this.props.rowsCount&&this.setState({dragged:e})}},handleDragEnter:function(e){if(this.dragEnabled()){var t=(this.state.selected,this.state.dragged);t.overRowIdx=e,this.setState({dragged:t})}},handleDragEnd:function(){if(this.dragEnabled()){var e,t,r=this.state.selected,o=this.state.dragged,s=this.getColumn(this.state.columnMetrics.columns,this.state.selected.idx).key;e=r.rowIdx<o.overRowIdx?r.rowIdx:o.overRowIdx,t=r.rowIdx>o.overRowIdx?r.rowIdx:o.overRowIdx,this.props.onCellsDragged&&this.props.onCellsDragged({cellKey:s,fromRow:e,toRow:t,value:o.value}),this.setState({dragged:{complete:!0}})}},handleTerminateDrag:function(){this.dragEnabled()&&this.setState({dragged:null})}});e.exports=m},function(e,t){"use strict";function r(){if(void 0===o){var e=document.createElement("div");e.style.width="50px",e.style.height="50px",e.style.overflowY="scroll",e.style.position="absolute",e.style.top="-200px",e.style.left="-200px";var t=document.createElement("div");t.style.height="100px",t.style.width="100%",e.appendChild(t),document.body.appendChild(e);var r=e.clientWidth,s=t.clientWidth;document.body.removeChild(e),o=r-s}return o}var o;e.exports=r},function(e,t){"use strict";function r(){var e=window.innerWidth,t=window.innerHeight;return e&&t||(e=document.documentElement.clientWidth,t=document.documentElement.clientHeight),e&&t||(e=document.body.clientWidth,t=document.body.clientHeight),{width:e,height:t}}e.exports=r},function(e,t,r){r(57),e.exports=r(18).Object.assign},function(e,t,r){var o=r(56),s=r(54),i=r(51);e.exports=r(52)(function(){return Symbol()in Object.assign({})})?function(e,t){for(var r=o(e),n=arguments.length,l=1;n>l;)for(var a,c=s(arguments[l++]),p=i(c),u=p.length,h=0;u>h;)r[a=p[h++]]=c[a];return r}:Object.assign},function(e,t){var r={}.toString;e.exports=function(e){return r.call(e).slice(8,-1)}},function(e,t,r){var o=r(53),s=r(18),i="prototype",n=function(e,t){return function(){return e.apply(t,arguments)}},l=function(e,t,r){var a,c,p,u,h=e&l.G,d=e&l.P,f=h?o:e&l.S?o[t]:(o[t]||{})[i],m=h?s:s[t]||(s[t]={});h&&(r=t);for(a in r)c=!(e&l.F)&&f&&a in f,c&&a in m||(p=c?f[a]:r[a],h&&"function"!=typeof f[a]?u=r[a]:e&l.B&&c?u=n(p,o):e&l.W&&f[a]==p?!function(e){u=function(t){return this instanceof e?new e(t):e(t)},u[i]=e[i]}(p):u=d&&"function"==typeof p?n(Function.call,p):p,m[a]=u,d&&((m[i]||(m[i]={}))[a]=p))};l.F=1,l.G=2,l.S=4,l.P=8,l.B=16,l.W=32,e.exports=l},function(e,t){e.exports=function(e){if(void 0==e)throw TypeError("Can't call method on "+e);return e}},function(e,t,r){var o=r(55);e.exports=function(e){var t=o.getKeys(e),r=o.getSymbols;if(r)for(var s,i=r(e),n=o.isEnum,l=0;i.length>l;)n.call(e,s=i[l++])&&t.push(s);return t}},function(e,t){e.exports=function(e){try{return!!e()}catch(t){return!0}}},function(e,t){var r="undefined",o=e.exports=typeof window!=r&&window.Math==Math?window:typeof self!=r&&self.Math==Math?self:Function("return this")();"number"==typeof __g&&(__g=o)},function(e,t,r){var o=r(48);e.exports=0 in Object("z")?Object:function(e){return"String"==o(e)?e.split(""):Object(e)}},function(e,t){var r=Object;e.exports={create:r.create,getProto:r.getPrototypeOf,isEnum:{}.propertyIsEnumerable,getDesc:r.getOwnPropertyDescriptor,setDesc:r.defineProperty,setDescs:r.defineProperties,getKeys:r.keys,getNames:r.getOwnPropertyNames,getSymbols:r.getOwnPropertySymbols,each:[].forEach}},function(e,t,r){var o=r(50);e.exports=function(e){return Object(o(e))}},function(e,t,r){var o=r(49);o(o.S+o.F,"Object",{assign:r(47)})},function(e,t,r){"use strict";var o=r(20),s={current:{},withContext:function(e,t){var r,i=s.current;s.current=o({},i,e);try{r=t()}finally{s.current=i}return r}};e.exports=s},function(e,t){"use strict";var r={current:null};e.exports=r},function(e,t,r){(function(t){"use strict";function o(e,r){Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:function(){return this._store?this._store[r]:null},set:function(e){"production"!==t.env.NODE_ENV?l(!1,"Don't set the "+r+" property of the component. Mutate the existing props object instead."):null,this._store[r]=e}})}function s(e){try{var t={props:!0};for(var r in t)o(e,r);c=!0}catch(s){}}var i=r(58),n=r(59),l=r(15),a={key:!0,ref:!0},c=!1,p=function(e,r,o,s,i,n){return this.type=e,this.key=r,this.ref=o,this._owner=s,this._context=i,"production"!==t.env.NODE_ENV&&(this._store={validated:!1,props:n},c)?void Object.freeze(this):void(this.props=n)};p.prototype={_isReactElement:!0},"production"!==t.env.NODE_ENV&&s(p.prototype),p.createElement=function(e,r,o){var s,c={},u=null,h=null;if(null!=r){h=void 0===r.ref?null:r.ref,"production"!==t.env.NODE_ENV&&("production"!==t.env.NODE_ENV?l(null!==r.key,"createElement(...): Encountered component with a `key` of null. In a future version, this will be treated as equivalent to the string 'null'; instead, provide an explicit key or use undefined."):null),u=null==r.key?null:""+r.key;for(s in r)r.hasOwnProperty(s)&&!a.hasOwnProperty(s)&&(c[s]=r[s])}var d=arguments.length-2;if(1===d)c.children=o;else if(d>1){for(var f=Array(d),m=0;d>m;m++)f[m]=arguments[m+2];c.children=f}if(e&&e.defaultProps){var g=e.defaultProps;for(s in g)"undefined"==typeof c[s]&&(c[s]=g[s])}return new p(e,u,h,n.current,i.current,c)},p.createFactory=function(e){var t=p.createElement.bind(null,e);return t.type=e,t},p.cloneAndReplaceProps=function(e,r){var o=new p(e.type,e.key,e.ref,e._owner,e._context,r);return"production"!==t.env.NODE_ENV&&(o._store.validated=e._store.validated),o},p.isValidElement=function(e){var t=!(!e||!e._isReactElement);return t},e.exports=p}).call(t,r(8))},function(e,t,r){(function(t){"use strict";function o(e){return function(t,r,o){t.hasOwnProperty(r)?t[r]=e(t[r],o):t[r]=o}}function s(e,t){for(var r in t)if(t.hasOwnProperty(r)){var o=h[r];o&&h.hasOwnProperty(r)?o(e,r,t[r]):e.hasOwnProperty(r)||(e[r]=t[r])}return e}var i=r(20),n=r(7),l=r(62),a=r(63),c=r(15),p=!1,u=o(function(e,t){return i({},t,e)}),h={children:n,className:o(a),style:u},d={TransferStrategies:h,mergeProps:function(e,t){return s(i({},e),t)},Mixin:{transferPropsTo:function(e){return"production"!==t.env.NODE_ENV?l(e._owner===this,"%s: You can't call transferPropsTo() on a component that you don't own, %s. This usually means you are calling transferPropsTo() on a component passed in as props or children.",this.constructor.displayName,"string"==typeof e.type?e.type:e.type.displayName):l(e._owner===this),"production"!==t.env.NODE_ENV&&(p||(p=!0,"production"!==t.env.NODE_ENV?c(!1,"transferPropsTo is deprecated. See http://fb.me/react-transferpropsto for more information."):null)),s(e.props,this.props),e}}};e.exports=d}).call(t,r(8))},function(e,t,r){(function(t){"use strict";var r=function(e,r,o,s,i,n,l,a){if("production"!==t.env.NODE_ENV&&void 0===r)throw new Error("invariant requires an error message argument");if(!e){var c;if(void 0===r)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var p=[o,s,i,n,l,a],u=0;c=new Error("Invariant Violation: "+r.replace(/%s/g,function(){return p[u++]}))}throw c.framesToPop=1,c}};e.exports=r}).call(t,r(8))},function(e,t){"use strict";function r(e){e||(e="");var t,r=arguments.length;if(r>1)for(var o=1;r>o;o++)t=arguments[o],t&&(e=(e?e+" ":"")+t);return e}e.exports=r},function(e,t){var r=function(e){var t;for(t in e)if(e.hasOwnProperty(t))return t;return null};e.exports=r}])});
src/components/pages/grocerylist/grocerylistCard.js
emilmannfeldt/ettkilomjol
import React, { Component } from 'react'; import Card from '@material-ui/core/Card'; import Fade from '@material-ui/core/Fade'; import CardHeader from '@material-ui/core/CardHeader'; import DeleteIcon from '@material-ui/icons/DeleteOutlined'; import AssignmentIcon from '@material-ui/icons/AssignmentOutlined'; import IconButton from '@material-ui/core/IconButton'; import PropTypes from 'prop-types'; import Grid from '@material-ui/core/Grid'; class GrocerylistCard extends Component { constructor(props) { super(props); this.state = { }; this.chooseList = this.chooseList.bind(this); this.deleteList = this.deleteList.bind(this); } chooseList() { const { setCurrentList, grocerylist } = this.props; setCurrentList(grocerylist); } deleteList() { const { deleteList, grocerylist } = this.props; deleteList(grocerylist); } render() { const { grocerylist } = this.props; let itemString = ''; if (grocerylist.items) { itemString = grocerylist.items.reduce((result_, item, index) => { let result = result_; if (index > 0) { result += ', '; } result += item.name; return result; }, ''); } else { itemString = 'Inga varor tillagda.'; } return ( <Grid item container xs={12} className="list-item"> <Fade in timeout={500} > <Card className="grocerylist-card"> <CardHeader className="grocerylist-card-header" avatar={( <IconButton onClick={this.chooseList} className="grocerylist-icon--primarycolor"> <AssignmentIcon /> </IconButton> )} action={( <IconButton onClick={this.deleteList}> <DeleteIcon /> </IconButton> )} title={grocerylist.name} subheader={<span>{itemString}</span>} classes={{ content: 'grocerylist-cardheader-content', subheader: 'grocerylist-cardheader-subheader', }} /> </Card> </Fade> </Grid> ); } } GrocerylistCard.propTypes = { setCurrentList: PropTypes.func.isRequired, deleteList: PropTypes.func.isRequired, grocerylist: PropTypes.object.isRequired, }; export default GrocerylistCard;
ajax/libs/yui/3.10.2/simpleyui/simpleyui-debug.js
noraesae/cdnjs
/** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @main yui @submodule yui-base **/ /*jshint eqeqeq: false*/ if (typeof YUI != 'undefined') { YUI._YUI = YUI; } /** The YUI global namespace object. This is the constructor for all YUI instances. This is a self-instantiable factory function, meaning you don't need to precede it with the `new` operator. You can invoke it directly like this: YUI().use('*', function (Y) { // Y is a new YUI instance. }); But it also works like this: var Y = YUI(); The `YUI` constructor accepts an optional config object, like this: YUI({ debug: true, combine: false }).use('node', function (Y) { // Y.Node is ready to use. }); See the API docs for the <a href="config.html">Config</a> class for the complete list of supported configuration properties accepted by the YUI constuctor. If a global `YUI` object is already defined, the existing YUI object will not be overwritten, to ensure that defined namespaces are preserved. Each YUI instance has full custom event support, but only if the event system is available. @class YUI @uses EventTarget @constructor @global @param {Object} [config]* Zero or more optional configuration objects. Config values are stored in the `Y.config` property. See the <a href="config.html">Config</a> docs for the list of supported properties. **/ /*global YUI*/ /*global YUI_config*/ var YUI = function() { var i = 0, Y = this, args = arguments, l = args.length, instanceOf = function(o, type) { return (o && o.hasOwnProperty && (o instanceof type)); }, gconf = (typeof YUI_config !== 'undefined') && YUI_config; if (!(instanceOf(Y, YUI))) { Y = new YUI(); } else { // set up the core environment Y._init(); /** Master configuration that might span multiple contexts in a non- browser environment. It is applied first to all instances in all contexts. @example YUI.GlobalConfig = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} GlobalConfig @global @static **/ if (YUI.GlobalConfig) { Y.applyConfig(YUI.GlobalConfig); } /** Page-level config applied to all YUI instances created on the current page. This is applied after `YUI.GlobalConfig` and before any instance-level configuration. @example // Single global var to include before YUI seed file YUI_config = { filter: 'debug' }; YUI().use('node', function (Y) { // debug files used here }); YUI({ filter: 'min' }).use('node', function (Y) { // min files used here }); @property {Object} YUI_config @global **/ if (gconf) { Y.applyConfig(gconf); } // bind the specified additional modules for this instance if (!l) { Y._setup(); } } if (l) { // Each instance can accept one or more configuration objects. // These are applied after YUI.GlobalConfig and YUI_Config, // overriding values set in those config files if there is a // matching property. for (; i < l; i++) { Y.applyConfig(args[i]); } Y._setup(); } Y.instanceOf = instanceOf; return Y; }; (function() { var proto, prop, VERSION = '@VERSION@', PERIOD = '.', BASE = 'http://yui.yahooapis.com/', /* These CSS class names can't be generated by getClassName since it is not available at the time they are being used. */ DOC_LABEL = 'yui3-js-enabled', CSS_STAMP_EL = 'yui3-css-stamp', NOOP = function() {}, SLICE = Array.prototype.slice, APPLY_TO_AUTH = { 'io.xdrReady': 1, // the functions applyTo 'io.xdrResponse': 1, // can call. this should 'SWF.eventHandler': 1 }, // be done at build time hasWin = (typeof window != 'undefined'), win = (hasWin) ? window : null, doc = (hasWin) ? win.document : null, docEl = doc && doc.documentElement, docClass = docEl && docEl.className, instances = {}, time = new Date().getTime(), add = function(el, type, fn, capture) { if (el && el.addEventListener) { el.addEventListener(type, fn, capture); } else if (el && el.attachEvent) { el.attachEvent('on' + type, fn); } }, remove = function(el, type, fn, capture) { if (el && el.removeEventListener) { // this can throw an uncaught exception in FF try { el.removeEventListener(type, fn, capture); } catch (ex) {} } else if (el && el.detachEvent) { el.detachEvent('on' + type, fn); } }, handleLoad = function() { YUI.Env.windowLoaded = true; YUI.Env.DOMReady = true; if (hasWin) { remove(window, 'load', handleLoad); } }, getLoader = function(Y, o) { var loader = Y.Env._loader, lCore = [ 'loader-base' ], G_ENV = YUI.Env, mods = G_ENV.mods; if (loader) { //loader._config(Y.config); loader.ignoreRegistered = false; loader.onEnd = null; loader.data = null; loader.required = []; loader.loadType = null; } else { loader = new Y.Loader(Y.config); Y.Env._loader = loader; } if (mods && mods.loader) { lCore = [].concat(lCore, YUI.Env.loaderExtras); } YUI.Env.core = Y.Array.dedupe([].concat(YUI.Env.core, lCore)); return loader; }, clobber = function(r, s) { for (var i in s) { if (s.hasOwnProperty(i)) { r[i] = s[i]; } } }, ALREADY_DONE = { success: true }; // Stamp the documentElement (HTML) with a class of "yui-loaded" to // enable styles that need to key off of JS being enabled. if (docEl && docClass.indexOf(DOC_LABEL) == -1) { if (docClass) { docClass += ' '; } docClass += DOC_LABEL; docEl.className = docClass; } if (VERSION.indexOf('@') > -1) { VERSION = '3.5.0'; // dev time hack for cdn test } proto = { /** Applies a new configuration object to the config of this YUI instance. This will merge new group/module definitions, and will also update the loader cache if necessary. Updating `Y.config` directly will not update the cache. @method applyConfig @param {Object} o the configuration object. @since 3.2.0 **/ applyConfig: function(o) { o = o || NOOP; var attr, name, // detail, config = this.config, mods = config.modules, groups = config.groups, aliases = config.aliases, loader = this.Env._loader; for (name in o) { if (o.hasOwnProperty(name)) { attr = o[name]; if (mods && name == 'modules') { clobber(mods, attr); } else if (aliases && name == 'aliases') { clobber(aliases, attr); } else if (groups && name == 'groups') { clobber(groups, attr); } else if (name == 'win') { config[name] = (attr && attr.contentWindow) || attr; config.doc = config[name] ? config[name].document : null; } else if (name == '_yuid') { // preserve the guid } else { config[name] = attr; } } } if (loader) { loader._config(o); } }, /** Old way to apply a config to this instance (calls `applyConfig` under the hood). @private @method _config @param {Object} o The config to apply **/ _config: function(o) { this.applyConfig(o); }, /** Initializes this YUI instance. @private @method _init **/ _init: function() { var filter, el, Y = this, G_ENV = YUI.Env, Env = Y.Env, prop; /** The version number of this YUI instance. This value is typically updated by a script when a YUI release is built, so it may not reflect the correct version number when YUI is run from the development source tree. @property {String} version **/ Y.version = VERSION; if (!Env) { Y.Env = { core: ['get', 'features', 'intl-base', 'yui-log', 'yui-later'], loaderExtras: ['loader-rollup', 'loader-yui3'], mods: {}, // flat module map versions: {}, // version module map base: BASE, cdn: BASE + VERSION + '/build/', // bootstrapped: false, _idx: 0, _used: {}, _attached: {}, _missed: [], _yidx: 0, _uidx: 0, _guidp: 'y', _loaded: {}, // serviced: {}, // Regex in English: // I'll start at the \b(simpleyui). // 1. Look in the test string for "simpleyui" or "yui" or // "yui-base" or "yui-davglass" or "yui-foobar" that comes after a word break. That is, it // can't match "foyui" or "i_heart_simpleyui". This can be anywhere in the string. // 2. After #1 must come a forward slash followed by the string matched in #1, so // "yui-base/yui-base" or "simpleyui/simpleyui" or "yui-pants/yui-pants". // 3. The second occurence of the #1 token can optionally be followed by "-debug" or "-min", // so "yui/yui-min", "yui/yui-debug", "yui-base/yui-base-debug". NOT "yui/yui-tshirt". // 4. This is followed by ".js", so "yui/yui.js", "simpleyui/simpleyui-min.js" // 0. Going back to the beginning, now. If all that stuff in 1-4 comes after a "?" in the string, // then capture the junk between the LAST "&" and the string in 1-4. So // "blah?foo/yui/yui.js" will capture "foo/" and "blah?some/thing.js&3.3.0/build/yui-davglass/yui-davglass.js" // will capture "3.3.0/build/" // // Regex Exploded: // (?:\? Find a ? // (?:[^&]*&) followed by 0..n characters followed by an & // * in fact, find as many sets of characters followed by a & as you can // ([^&]*) capture the stuff after the last & in \1 // )? but it's ok if all this ?junk&more_junk stuff isn't even there // \b(simpleyui| after a word break find either the string "simpleyui" or // yui(?:-\w+)? the string "yui" optionally followed by a -, then more characters // ) and store the simpleyui or yui-* string in \2 // \/\2 then comes a / followed by the simpleyui or yui-* string in \2 // (?:-(min|debug))? optionally followed by "-min" or "-debug" // .js and ending in ".js" _BASE_RE: /(?:\?(?:[^&]*&)*([^&]*))?\b(simpleyui|yui(?:-\w+)?)\/\2(?:-(min|debug))?\.js/, parseBasePath: function(src, pattern) { var match = src.match(pattern), path, filter; if (match) { path = RegExp.leftContext || src.slice(0, src.indexOf(match[0])); // this is to set up the path to the loader. The file // filter for loader should match the yui include. filter = match[3]; // extract correct path for mixed combo urls // http://yuilibrary.com/projects/yui3/ticket/2528423 if (match[1]) { path += '?' + match[1]; } path = { filter: filter, path: path }; } return path; }, getBase: G_ENV && G_ENV.getBase || function(pattern) { var nodes = (doc && doc.getElementsByTagName('script')) || [], path = Env.cdn, parsed, i, len, src; for (i = 0, len = nodes.length; i < len; ++i) { src = nodes[i].src; if (src) { parsed = Y.Env.parseBasePath(src, pattern); if (parsed) { filter = parsed.filter; path = parsed.path; break; } } } // use CDN default return path; } }; Env = Y.Env; Env._loaded[VERSION] = {}; if (G_ENV && Y !== YUI) { Env._yidx = ++G_ENV._yidx; Env._guidp = ('yui_' + VERSION + '_' + Env._yidx + '_' + time).replace(/[^a-z0-9_]+/g, '_'); } else if (YUI._YUI) { G_ENV = YUI._YUI.Env; Env._yidx += G_ENV._yidx; Env._uidx += G_ENV._uidx; for (prop in G_ENV) { if (!(prop in Env)) { Env[prop] = G_ENV[prop]; } } delete YUI._YUI; } Y.id = Y.stamp(Y); instances[Y.id] = Y; } Y.constructor = YUI; // configuration defaults Y.config = Y.config || { bootstrap: true, cacheUse: true, debug: true, doc: doc, fetchCSS: true, throwFail: true, useBrowserConsole: true, useNativeES5: true, win: win, global: Function('return this')() }; //Register the CSS stamp element if (doc && !doc.getElementById(CSS_STAMP_EL)) { el = doc.createElement('div'); el.innerHTML = '<div id="' + CSS_STAMP_EL + '" style="position: absolute !important; visibility: hidden !important"></div>'; YUI.Env.cssStampEl = el.firstChild; if (doc.body) { doc.body.appendChild(YUI.Env.cssStampEl); } else { docEl.insertBefore(YUI.Env.cssStampEl, docEl.firstChild); } } else if (doc && doc.getElementById(CSS_STAMP_EL) && !YUI.Env.cssStampEl) { YUI.Env.cssStampEl = doc.getElementById(CSS_STAMP_EL); } Y.config.lang = Y.config.lang || 'en-US'; Y.config.base = YUI.config.base || Y.Env.getBase(Y.Env._BASE_RE); if (!filter || (!('mindebug').indexOf(filter))) { filter = 'min'; } filter = (filter) ? '-' + filter : filter; Y.config.loaderPath = YUI.config.loaderPath || 'loader/loader' + filter + '.js'; }, /** Finishes the instance setup. Attaches whatever YUI modules were defined at the time that this instance was created. @method _setup @private **/ _setup: function() { var i, Y = this, core = [], mods = YUI.Env.mods, extras = Y.config.core || [].concat(YUI.Env.core); //Clone it.. for (i = 0; i < extras.length; i++) { if (mods[extras[i]]) { core.push(extras[i]); } } Y._attach(['yui-base']); Y._attach(core); if (Y.Loader) { getLoader(Y); } // Y.log(Y.id + ' initialized', 'info', 'yui'); }, /** Executes the named method on the specified YUI instance if that method is whitelisted. @method applyTo @param {String} id YUI instance id. @param {String} method Name of the method to execute. For example: 'Object.keys'. @param {Array} args Arguments to apply to the method. @return {Mixed} Return value from the applied method, or `null` if the specified instance was not found or the method was not whitelisted. **/ applyTo: function(id, method, args) { if (!(method in APPLY_TO_AUTH)) { this.log(method + ': applyTo not allowed', 'warn', 'yui'); return null; } var instance = instances[id], nest, m, i; if (instance) { nest = method.split('.'); m = instance; for (i = 0; i < nest.length; i = i + 1) { m = m[nest[i]]; if (!m) { this.log('applyTo not found: ' + method, 'warn', 'yui'); } } return m && m.apply(instance, args); } return null; }, /** Registers a YUI module and makes it available for use in a `YUI().use()` call or as a dependency for other modules. The easiest way to create a first-class YUI module is to use <a href="http://yui.github.com/shifter/">Shifter</a>, the YUI component build tool. Shifter will automatically wrap your module code in a `YUI.add()` call along with any configuration info required for the module. @example YUI.add('davglass', function (Y) { Y.davglass = function () { Y.log('Dav was here!'); }; }, '3.4.0', { requires: ['harley-davidson', 'mt-dew'] }); @method add @param {String} name Module name. @param {Function} fn Function containing module code. This function will be executed whenever the module is attached to a specific YUI instance. @param {YUI} fn.Y The YUI instance to which this module is attached. @param {String} fn.name Name of the module @param {String} version Module version number. This is currently used only for informational purposes, and is not used internally by YUI. @param {Object} [config] Module config. @param {Array} [config.requires] Array of other module names that must be attached before this module can be attached. @param {Array} [config.optional] Array of optional module names that should be attached before this module is attached if they've already been loaded. If the `loadOptional` YUI option is `true`, optional modules that have not yet been loaded will be loaded just as if they were hard requirements. @param {Array} [config.use] Array of module names that are included within or otherwise provided by this module, and which should be attached automatically when this module is attached. This makes it possible to create "virtual rollup" modules that simply attach a collection of other modules or submodules. @return {YUI} This YUI instance. **/ add: function(name, fn, version, details) { details = details || {}; var env = YUI.Env, mod = { name: name, fn: fn, version: version, details: details }, //Instance hash so we don't apply it to the same instance twice applied = {}, loader, inst, i, versions = env.versions; env.mods[name] = mod; versions[version] = versions[version] || {}; versions[version][name] = mod; for (i in instances) { if (instances.hasOwnProperty(i)) { inst = instances[i]; if (!applied[inst.id]) { applied[inst.id] = true; loader = inst.Env._loader; if (loader) { if (!loader.moduleInfo[name] || loader.moduleInfo[name].temp) { loader.addModule(details, name); } } } } } return this; }, /** Executes the callback function associated with each required module, attaching the module to this YUI instance. @method _attach @param {Array} r The array of modules to attach @param {Boolean} [moot=false] If `true`, don't throw a warning if the module is not attached. @private **/ _attach: function(r, moot) { var i, name, mod, details, req, use, after, mods = YUI.Env.mods, aliases = YUI.Env.aliases, Y = this, j, cache = YUI.Env._renderedMods, loader = Y.Env._loader, done = Y.Env._attached, len = r.length, loader, def, go, c = []; //Check for conditional modules (in a second+ instance) and add their requirements //TODO I hate this entire method, it needs to be fixed ASAP (3.5.0) ^davglass for (i = 0; i < len; i++) { name = r[i]; mod = mods[name]; c.push(name); if (loader && loader.conditions[name]) { for (j in loader.conditions[name]) { if (loader.conditions[name].hasOwnProperty(j)) { def = loader.conditions[name][j]; go = def && ((def.ua && Y.UA[def.ua]) || (def.test && def.test(Y))); if (go) { c.push(def.name); } } } } } r = c; len = r.length; for (i = 0; i < len; i++) { if (!done[r[i]]) { name = r[i]; mod = mods[name]; if (aliases && aliases[name] && !mod) { Y._attach(aliases[name]); continue; } if (!mod) { if (loader && loader.moduleInfo[name]) { mod = loader.moduleInfo[name]; moot = true; } // Y.log('no js def for: ' + name, 'info', 'yui'); //if (!loader || !loader.moduleInfo[name]) { //if ((!loader || !loader.moduleInfo[name]) && !moot) { if (!moot && name) { if ((name.indexOf('skin-') === -1) && (name.indexOf('css') === -1)) { Y.Env._missed.push(name); Y.Env._missed = Y.Array.dedupe(Y.Env._missed); Y.message('NOT loaded: ' + name, 'warn', 'yui'); } } } else { done[name] = true; //Don't like this, but in case a mod was asked for once, then we fetch it //We need to remove it from the missed list ^davglass for (j = 0; j < Y.Env._missed.length; j++) { if (Y.Env._missed[j] === name) { Y.message('Found: ' + name + ' (was reported as missing earlier)', 'warn', 'yui'); Y.Env._missed.splice(j, 1); } } /* If it's a temp module, we need to redo it's requirements if it's already loaded since it may have been loaded by another instance and it's dependencies might have been redefined inside the fetched file. */ if (loader && cache && cache[name] && cache[name].temp) { loader.getRequires(cache[name]); req = []; for (j in loader.moduleInfo[name].expanded_map) { if (loader.moduleInfo[name].expanded_map.hasOwnProperty(j)) { req.push(j); } } Y._attach(req); } details = mod.details; req = details.requires; use = details.use; after = details.after; //Force Intl load if there is a language (Loader logic) @todo fix this shit if (details.lang) { req = req || []; req.unshift('intl'); } if (req) { for (j = 0; j < req.length; j++) { if (!done[req[j]]) { if (!Y._attach(req)) { return false; } break; } } } if (after) { for (j = 0; j < after.length; j++) { if (!done[after[j]]) { if (!Y._attach(after, true)) { return false; } break; } } } if (mod.fn) { if (Y.config.throwFail) { mod.fn(Y, name); } else { try { mod.fn(Y, name); } catch (e) { Y.error('Attach error: ' + name, e, name); return false; } } } if (use) { for (j = 0; j < use.length; j++) { if (!done[use[j]]) { if (!Y._attach(use)) { return false; } break; } } } } } } return true; }, /** Delays the `use` callback until another event has taken place such as `window.onload`, `domready`, `contentready`, or `available`. @private @method _delayCallback @param {Function} cb The original `use` callback. @param {String|Object} until Either an event name ('load', 'domready', etc.) or an object containing event/args keys for contentready/available. @return {Function} **/ _delayCallback: function(cb, until) { var Y = this, mod = ['event-base']; until = (Y.Lang.isObject(until) ? until : { event: until }); if (until.event === 'load') { mod.push('event-synthetic'); } Y.log('Delaying use callback until: ' + until.event, 'info', 'yui'); return function() { Y.log('Use callback fired, waiting on delay', 'info', 'yui'); var args = arguments; Y._use(mod, function() { Y.log('Delayed use wrapper callback after dependencies', 'info', 'yui'); Y.on(until.event, function() { args[1].delayUntil = until.event; Y.log('Delayed use callback done after ' + until.event, 'info', 'yui'); cb.apply(Y, args); }, until.args); }); }; }, /** Attaches one or more modules to this YUI instance. When this is executed, the requirements of the desired modules are analyzed, and one of several things can happen: * All required modules have already been loaded, and just need to be attached to this YUI instance. In this case, the `use()` callback will be executed synchronously after the modules are attached. * One or more modules have not yet been loaded, or the Get utility is not available, or the `bootstrap` config option is `false`. In this case, a warning is issued indicating that modules are missing, but all available modules will still be attached and the `use()` callback will be executed synchronously. * One or more modules are missing and the Loader is not available but the Get utility is, and `bootstrap` is not `false`. In this case, the Get utility will be used to load the Loader, and we will then proceed to the following state: * One or more modules are missing and the Loader is available. In this case, the Loader will be used to resolve the dependency tree for the missing modules and load them and their dependencies. When the Loader is finished loading modules, the `use()` callback will be executed asynchronously. @example // Loads and attaches dd and its dependencies. YUI().use('dd', function (Y) { // ... }); // Loads and attaches dd and node as well as all of their dependencies. YUI().use(['dd', 'node'], function (Y) { // ... }); // Attaches all modules that have already been loaded. YUI().use('*', function (Y) { // ... }); // Attaches a gallery module. YUI().use('gallery-yql', function (Y) { // ... }); // Attaches a YUI 2in3 module. YUI().use('yui2-datatable', function (Y) { // ... }); @method use @param {String|Array} modules* One or more module names to attach. @param {Function} [callback] Callback function to be executed once all specified modules and their dependencies have been attached. @param {YUI} callback.Y The YUI instance created for this sandbox. @param {Object} callback.status Object containing `success`, `msg` and `data` properties. @chainable **/ use: function() { var args = SLICE.call(arguments, 0), callback = args[args.length - 1], Y = this, i = 0, name, Env = Y.Env, provisioned = true; // The last argument supplied to use can be a load complete callback if (Y.Lang.isFunction(callback)) { args.pop(); if (Y.config.delayUntil) { callback = Y._delayCallback(callback, Y.config.delayUntil); } } else { callback = null; } if (Y.Lang.isArray(args[0])) { args = args[0]; } if (Y.config.cacheUse) { while ((name = args[i++])) { if (!Env._attached[name]) { provisioned = false; break; } } if (provisioned) { if (args.length) { Y.log('already provisioned: ' + args, 'info', 'yui'); } Y._notify(callback, ALREADY_DONE, args); return Y; } } if (Y._loading) { Y._useQueue = Y._useQueue || new Y.Queue(); Y._useQueue.add([args, callback]); } else { Y._use(args, function(Y, response) { Y._notify(callback, response, args); }); } return Y; }, /** Handles Loader notifications about attachment/load errors. @method _notify @param {Function} callback Callback to pass to `Y.config.loadErrorFn`. @param {Object} response Response returned from Loader. @param {Array} args Arguments passed from Loader. @private **/ _notify: function(callback, response, args) { if (!response.success && this.config.loadErrorFn) { this.config.loadErrorFn.call(this, this, callback, response, args); } else if (callback) { if (this.Env._missed && this.Env._missed.length) { response.msg = 'Missing modules: ' + this.Env._missed.join(); response.success = false; } if (this.config.throwFail) { callback(this, response); } else { try { callback(this, response); } catch (e) { this.error('use callback error', e, args); } } } }, /** Called from the `use` method queue to ensure that only one set of loading logic is performed at a time. @method _use @param {String} args* One or more modules to attach. @param {Function} [callback] Function to call once all required modules have been attached. @private **/ _use: function(args, callback) { if (!this.Array) { this._attach(['yui-base']); } var len, loader, handleBoot, Y = this, G_ENV = YUI.Env, mods = G_ENV.mods, Env = Y.Env, used = Env._used, aliases = G_ENV.aliases, queue = G_ENV._loaderQueue, firstArg = args[0], YArray = Y.Array, config = Y.config, boot = config.bootstrap, missing = [], i, r = [], ret = true, fetchCSS = config.fetchCSS, process = function(names, skip) { var i = 0, a = [], name, len, m, req, use; if (!names.length) { return; } if (aliases) { len = names.length; for (i = 0; i < len; i++) { if (aliases[names[i]] && !mods[names[i]]) { a = [].concat(a, aliases[names[i]]); } else { a.push(names[i]); } } names = a; } len = names.length; for (i = 0; i < len; i++) { name = names[i]; if (!skip) { r.push(name); } // only attach a module once if (used[name]) { continue; } m = mods[name]; req = null; use = null; if (m) { used[name] = true; req = m.details.requires; use = m.details.use; } else { // CSS files don't register themselves, see if it has // been loaded if (!G_ENV._loaded[VERSION][name]) { missing.push(name); } else { used[name] = true; // probably css } } // make sure requirements are attached if (req && req.length) { process(req); } // make sure we grab the submodule dependencies too if (use && use.length) { process(use, 1); } } }, handleLoader = function(fromLoader) { var response = fromLoader || { success: true, msg: 'not dynamic' }, redo, origMissing, ret = true, data = response.data; Y._loading = false; if (data) { origMissing = missing; missing = []; r = []; process(data); redo = missing.length; if (redo) { if ([].concat(missing).sort().join() == origMissing.sort().join()) { redo = false; } } } if (redo && data) { Y._loading = true; Y._use(missing, function() { Y.log('Nested use callback: ' + data, 'info', 'yui'); if (Y._attach(data)) { Y._notify(callback, response, data); } }); } else { if (data) { // Y.log('attaching from loader: ' + data, 'info', 'yui'); ret = Y._attach(data); } if (ret) { Y._notify(callback, response, args); } } if (Y._useQueue && Y._useQueue.size() && !Y._loading) { Y._use.apply(Y, Y._useQueue.next()); } }; // Y.log(Y.id + ': use called: ' + a + ' :: ' + callback, 'info', 'yui'); // YUI().use('*'); // bind everything available if (firstArg === '*') { args = []; for (i in mods) { if (mods.hasOwnProperty(i)) { args.push(i); } } ret = Y._attach(args); if (ret) { handleLoader(); } return Y; } if ((mods.loader || mods['loader-base']) && !Y.Loader) { Y.log('Loader was found in meta, but it is not attached. Attaching..', 'info', 'yui'); Y._attach(['loader' + ((!mods.loader) ? '-base' : '')]); } // Y.log('before loader requirements: ' + args, 'info', 'yui'); // use loader to expand dependencies and sort the // requirements if it is available. if (boot && Y.Loader && args.length) { Y.log('Using loader to expand dependencies', 'info', 'yui'); loader = getLoader(Y); loader.require(args); loader.ignoreRegistered = true; loader._boot = true; loader.calculate(null, (fetchCSS) ? null : 'js'); args = loader.sorted; loader._boot = false; } process(args); len = missing.length; if (len) { missing = YArray.dedupe(missing); len = missing.length; Y.log('Modules missing: ' + missing + ', ' + missing.length, 'info', 'yui'); } // dynamic load if (boot && len && Y.Loader) { // Y.log('Using loader to fetch missing deps: ' + missing, 'info', 'yui'); Y.log('Using Loader', 'info', 'yui'); Y._loading = true; loader = getLoader(Y); loader.onEnd = handleLoader; loader.context = Y; loader.data = args; loader.ignoreRegistered = false; loader.require(missing); loader.insert(null, (fetchCSS) ? null : 'js'); } else if (boot && len && Y.Get && !Env.bootstrapped) { Y._loading = true; handleBoot = function() { Y._loading = false; queue.running = false; Env.bootstrapped = true; G_ENV._bootstrapping = false; if (Y._attach(['loader'])) { Y._use(args, callback); } }; if (G_ENV._bootstrapping) { Y.log('Waiting for loader', 'info', 'yui'); queue.add(handleBoot); } else { G_ENV._bootstrapping = true; Y.log('Fetching loader: ' + config.base + config.loaderPath, 'info', 'yui'); Y.Get.script(config.base + config.loaderPath, { onEnd: handleBoot }); } } else { Y.log('Attaching available dependencies: ' + args, 'info', 'yui'); ret = Y._attach(args); if (ret) { handleLoader(); } } return Y; }, /** Utility method for safely creating namespaces if they don't already exist. May be called statically on the YUI global object or as a method on a YUI instance. When called statically, a namespace will be created on the YUI global object: // Create `YUI.your.namespace.here` as nested objects, preserving any // objects that already exist instead of overwriting them. YUI.namespace('your.namespace.here'); When called as a method on a YUI instance, a namespace will be created on that instance: // Creates `Y.property.package`. Y.namespace('property.package'); Dots in the input string cause `namespace` to create nested objects for each token. If any part of the requested namespace already exists, the current object will be left in place and will not be overwritten. This allows multiple calls to `namespace` to preserve existing namespaced properties. If the first token in the namespace string is "YAHOO", that token is discarded. This is legacy behavior for backwards compatibility with YUI 2. Be careful with namespace tokens. Reserved words may work in some browsers and not others. For instance, the following will fail in some browsers because the supported version of JavaScript reserves the word "long": Y.namespace('really.long.nested.namespace'); Note: If you pass multiple arguments to create multiple namespaces, only the last one created is returned from this function. @method namespace @param {String} namespace* One or more namespaces to create. @return {Object} Reference to the last namespace object created. **/ namespace: function() { var a = arguments, o, i = 0, j, d, arg; for (; i < a.length; i++) { o = this; //Reset base object per argument or it will get reused from the last arg = a[i]; if (arg.indexOf(PERIOD) > -1) { //Skip this if no "." is present d = arg.split(PERIOD); for (j = (d[0] == 'YAHOO') ? 1 : 0; j < d.length; j++) { o[d[j]] = o[d[j]] || {}; o = o[d[j]]; } } else { o[arg] = o[arg] || {}; o = o[arg]; //Reset base object to the new object so it's returned } } return o; }, // this is replaced if the log module is included log: NOOP, message: NOOP, // this is replaced if the dump module is included dump: function (o) { return ''+o; }, /** Reports an error. The reporting mechanism is controlled by the `throwFail` configuration attribute. If `throwFail` is falsy, the message is logged. If `throwFail` is truthy, a JS exception is thrown. If an `errorFn` is specified in the config it must return `true` to indicate that the exception was handled and keep it from being thrown. @method error @param {String} msg Error message. @param {Error|String} [e] JavaScript error object or an error string. @param {String} [src] Source of the error (such as the name of the module in which the error occurred). @chainable **/ error: function(msg, e, src) { //TODO Add check for window.onerror here var Y = this, ret; if (Y.config.errorFn) { ret = Y.config.errorFn.apply(Y, arguments); } if (!ret) { throw (e || new Error(msg)); } else { Y.message(msg, 'error', ''+src); // don't scrub this one } return Y; }, /** Generates an id string that is unique among all YUI instances in this execution context. @method guid @param {String} [pre] Prefix. @return {String} Unique id. **/ guid: function(pre) { var id = this.Env._guidp + '_' + (++this.Env._uidx); return (pre) ? (pre + id) : id; }, /** Returns a unique id associated with the given object and (if *readOnly* is falsy) stamps the object with that id so it can be identified in the future. Stamping an object involves adding a `_yuid` property to it that contains the object's id. One exception to this is that in Internet Explorer, DOM nodes have a `uniqueID` property that contains a browser-generated unique id, which will be used instead of a YUI-generated id when available. @method stamp @param {Object} o Object to stamp. @param {Boolean} readOnly If truthy and the given object has not already been stamped, the object will not be modified and `null` will be returned. @return {String} Object's unique id, or `null` if *readOnly* was truthy and the given object was not already stamped. **/ stamp: function(o, readOnly) { var uid; if (!o) { return o; } // IE generates its own unique ID for dom nodes // The uniqueID property of a document node returns a new ID if (o.uniqueID && o.nodeType && o.nodeType !== 9) { uid = o.uniqueID; } else { uid = (typeof o === 'string') ? o : o._yuid; } if (!uid) { uid = this.guid(); if (!readOnly) { try { o._yuid = uid; } catch (e) { uid = null; } } } return uid; }, /** Destroys this YUI instance. @method destroy @since 3.3.0 **/ destroy: function() { var Y = this; if (Y.Event) { Y.Event._unload(); } delete instances[Y.id]; delete Y.Env; delete Y.config; } /** Safe `instanceof` wrapper that works around a memory leak in IE when the object being tested is `window` or `document`. Unless you are testing objects that may be `window` or `document`, you should use the native `instanceof` operator instead of this method. @method instanceOf @param {Object} o Object to check. @param {Object} type Class to check against. @since 3.3.0 **/ }; YUI.prototype = proto; // inheritance utilities are not available yet for (prop in proto) { if (proto.hasOwnProperty(prop)) { YUI[prop] = proto[prop]; } } /** Applies a configuration to all YUI instances in this execution context. The main use case for this method is in "mashups" where several third-party scripts need to write to a global YUI config, but cannot share a single centrally-managed config object. This way they can all call `YUI.applyConfig({})` instead of overwriting the single global config. @example YUI.applyConfig({ modules: { davglass: { fullpath: './davglass.js' } } }); YUI.applyConfig({ modules: { foo: { fullpath: './foo.js' } } }); YUI().use('davglass', function (Y) { // Module davglass will be available here. }); @method applyConfig @param {Object} o Configuration object to apply. @static @since 3.5.0 **/ YUI.applyConfig = function(o) { if (!o) { return; } //If there is a GlobalConfig, apply it first to set the defaults if (YUI.GlobalConfig) { this.prototype.applyConfig.call(this, YUI.GlobalConfig); } //Apply this config to it this.prototype.applyConfig.call(this, o); //Reset GlobalConfig to the combined config YUI.GlobalConfig = this.config; }; // set up the environment YUI._init(); if (hasWin) { // add a window load event at load time so we can capture // the case where it fires before dynamic loading is // complete. add(window, 'load', handleLoad); } else { handleLoad(); } YUI.Env.add = add; YUI.Env.remove = remove; /*global exports*/ // Support the CommonJS method for exporting our single global if (typeof exports == 'object') { exports.YUI = YUI; /** * Set a method to be called when `Get.script` is called in Node.js * `Get` will open the file, then pass it's content and it's path * to this method before attaching it. Commonly used for code coverage * instrumentation. <strong>Calling this multiple times will only * attach the last hook method</strong>. This method is only * available in Node.js. * @method setLoadHook * @static * @param {Function} fn The function to set * @param {String} fn.data The content of the file * @param {String} fn.path The file path of the file */ YUI.setLoadHook = function(fn) { YUI._getLoadHook = fn; }; /** * Load hook for `Y.Get.script` in Node.js, see `YUI.setLoadHook` * @method _getLoadHook * @private * @param {String} data The content of the file * @param {String} path The file path of the file */ YUI._getLoadHook = null; } }()); /** Config object that contains all of the configuration options for this `YUI` instance. This object is supplied by the implementer when instantiating YUI. Some properties have default values if they are not supplied by the implementer. This object should not be updated directly because some values are cached. Use `applyConfig()` to update the config object on a YUI instance that has already been configured. @class config @static **/ /** If `true` (the default), YUI will "bootstrap" the YUI Loader and module metadata if they're needed to load additional dependencies and aren't already available. Setting this to `false` will prevent YUI from automatically loading the Loader and module metadata, so you will need to manually ensure that they're available or handle dependency resolution yourself. @property {Boolean} bootstrap @default true **/ /** If `true`, `Y.log()` messages will be written to the browser's debug console when available and when `useBrowserConsole` is also `true`. @property {Boolean} debug @default true **/ /** Log messages to the browser console if `debug` is `true` and the browser has a supported console. @property {Boolean} useBrowserConsole @default true **/ /** A hash of log sources that should be logged. If specified, only messages from these sources will be logged. Others will be discarded. @property {Object} logInclude @type object **/ /** A hash of log sources that should be not be logged. If specified, all sources will be logged *except* those on this list. @property {Object} logExclude **/ /** When the YUI seed file is dynamically loaded after the `window.onload` event has fired, set this to `true` to tell YUI that it shouldn't wait for `window.onload` to occur. This ensures that components that rely on `window.onload` and the `domready` custom event will work as expected even when YUI is dynamically injected. @property {Boolean} injected @default false **/ /** If `true`, `Y.error()` will generate or re-throw a JavaScript error. Otherwise, errors are merely logged silently. @property {Boolean} throwFail @default true **/ /** Reference to the global object for this execution context. In a browser, this is the current `window` object. In Node.js, this is the Node.js `global` object. @property {Object} global **/ /** The browser window or frame that this YUI instance should operate in. When running in Node.js, this property is `undefined`, since there is no `window` object. Use `global` to get a reference to the global object that will work in both browsers and Node.js. @property {Window} win **/ /** The browser `document` object associated with this YUI instance's `win` object. When running in Node.js, this property is `undefined`, since there is no `document` object. @property {Document} doc **/ /** A list of modules that defines the YUI core (overrides the default list). @property {Array} core @type Array @default ['get', 'features', 'intl-base', 'yui-log', 'yui-later', 'loader-base', 'loader-rollup', 'loader-yui3'] **/ /** A list of languages to use in order of preference. This list is matched against the list of available languages in modules that the YUI instance uses to determine the best possible localization of language sensitive modules. Languages are represented using BCP 47 language tags, such as "en-GB" for English as used in the United Kingdom, or "zh-Hans-CN" for simplified Chinese as used in China. The list may be provided as a comma-separated string or as an array. @property {String|String[]} lang **/ /** Default date format. @property {String} dateFormat @deprecated Use configuration in `DataType.Date.format()` instead. **/ /** Default locale. @property {String} locale @deprecated Use `config.lang` instead. **/ /** Default generic polling interval in milliseconds. @property {Number} pollInterval @default 20 **/ /** The number of dynamic `<script>` nodes to insert by default before automatically removing them when loading scripts. This applies only to script nodes because removing the node will not make the evaluated script unavailable. Dynamic CSS nodes are not auto purged, because removing a linked style sheet will also remove the style definitions. @property {Number} purgethreshold @default 20 **/ /** Delay in milliseconds to wait after a window `resize` event before firing the event. If another `resize` event occurs before this delay has elapsed, the delay will start over to ensure that `resize` events are throttled. @property {Number} windowResizeDelay @default 40 **/ /** Base directory for dynamic loading. @property {String} base **/ /** Base URL for a dynamic combo handler. This will be used to make combo-handled module requests if `combine` is set to `true. @property {String} comboBase @default "http://yui.yahooapis.com/combo?" **/ /** Root path to prepend to each module path when creating a combo-handled request. This is updated for each YUI release to point to a specific version of the library; for example: "3.8.0/build/". @property {String} root **/ /** Filter to apply to module urls. This filter will modify the default path for all modules. The default path for the YUI library is the minified version of the files (e.g., event-min.js). The filter property can be a predefined filter or a custom filter. The valid predefined filters are: - **debug**: Loads debug versions of modules (e.g., event-debug.js). - **raw**: Loads raw, non-minified versions of modules without debug logging (e.g., event.js). You can also define a custom filter, which must be an object literal containing a search regular expression and a replacement string: myFilter: { searchExp : "-min\\.js", replaceStr: "-debug.js" } @property {Object|String} filter **/ /** Skin configuration and customizations. @property {Object} skin @param {String} [skin.defaultSkin='sam'] Default skin name. This skin will be applied automatically to skinnable components if not overridden by a component-specific skin name. @param {String} [skin.base='assets/skins/'] Default base path for a skin, relative to Loader's `base` path. @param {Object} [skin.overrides] Component-specific skin name overrides. Specify a component name as the key and, as the value, a string or array of strings for a skin or skins that should be loaded for that component instead of the `defaultSkin`. **/ /** Hash of per-component filter specifications. If specified for a given component, this overrides the global `filter` config. @property {Object} filters **/ /** If `true`, YUI will use a combo handler to load multiple modules in as few requests as possible. The YUI CDN (which YUI uses by default) supports combo handling, but other servers may not. If the server from which you're loading YUI does not support combo handling, set this to `false`. Providing a value for the `base` config property will cause `combine` to default to `false` instead of `true`. @property {Boolean} combine @default true */ /** Array of module names that should never be dynamically loaded. @property {String[]} ignore **/ /** Array of module names that should always be loaded when required, even if already present on the page. @property {String[]} force **/ /** DOM element or id that should be used as the insertion point for dynamically added `<script>` and `<link>` nodes. @property {HTMLElement|String} insertBefore **/ /** Object hash containing attributes to add to dynamically added `<script>` nodes. @property {Object} jsAttributes **/ /** Object hash containing attributes to add to dynamically added `<link>` nodes. @property {Object} cssAttributes **/ /** Timeout in milliseconds before a dynamic JS or CSS request will be considered a failure. If not set, no timeout will be enforced. @property {Number} timeout **/ /** Callback for the 'CSSComplete' event. When dynamically loading YUI components with CSS, this property fires when the CSS is finished loading. This provides an opportunity to enhance the presentation of a loading page a little bit before the entire loading process is done. @property {Function} onCSS **/ /** A hash of module definitions to add to the list of available YUI modules. These modules can then be dynamically loaded via the `use()` method. This is a hash in which keys are module names and values are objects containing module metadata. See `Loader.addModule()` for the supported module metadata fields. Also see `groups`, which provides a way to configure the base and combo spec for a set of modules. @example modules: { mymod1: { requires: ['node'], fullpath: '/mymod1/mymod1.js' }, mymod2: { requires: ['mymod1'], fullpath: '/mymod2/mymod2.js' }, mymod3: '/js/mymod3.js', mycssmod: '/css/mycssmod.css' } @property {Object} modules **/ /** Aliases are dynamic groups of modules that can be used as shortcuts. @example YUI({ aliases: { davglass: [ 'node', 'yql', 'dd' ], mine: [ 'davglass', 'autocomplete'] } }).use('mine', function (Y) { // Node, YQL, DD & AutoComplete available here. }); @property {Object} aliases **/ /** A hash of module group definitions. For each group you can specify a list of modules and the base path and combo spec to use when dynamically loading the modules. @example groups: { yui2: { // specify whether or not this group has a combo service combine: true, // The comboSeperator to use with this group's combo handler comboSep: ';', // The maxURLLength for this server maxURLLength: 500, // the base path for non-combo paths base: 'http://yui.yahooapis.com/2.8.0r4/build/', // the path to the combo service comboBase: 'http://yui.yahooapis.com/combo?', // a fragment to prepend to the path attribute when // when building combo urls root: '2.8.0r4/build/', // the module definitions modules: { yui2_yde: { path: "yahoo-dom-event/yahoo-dom-event.js" }, yui2_anim: { path: "animation/animation.js", requires: ['yui2_yde'] } } } } @property {Object} groups **/ /** Path to the Loader JS file, relative to the `base` path. This is used to dynamically bootstrap the Loader when it's needed and isn't yet available. @property {String} loaderPath @default "loader/loader-min.js" **/ /** If `true`, YUI will attempt to load CSS dependencies and skins. Set this to `false` to prevent YUI from loading any CSS, or set it to the string `"force"` to force CSS dependencies to be loaded even if their associated JS modules are already loaded. @property {Boolean|String} fetchCSS @default true **/ /** Default gallery version used to build gallery module urls. @property {String} gallery @since 3.1.0 **/ /** Default YUI 2 version used to build YUI 2 module urls. This is used for intrinsic YUI 2 support via the 2in3 project. Also see the `2in3` config for pulling different revisions of the wrapped YUI 2 modules. @property {String} yui2 @default "2.9.0" @since 3.1.0 **/ /** Revision number of YUI 2in3 modules that should be used when loading YUI 2in3. @property {String} 2in3 @default "4" @since 3.1.0 **/ /** Alternate console log function that should be used in environments without a supported native console. This function is executed with the YUI instance as its `this` object. @property {Function} logFn @since 3.1.0 **/ /** The minimum log level to log messages for. Log levels are defined incrementally. Messages greater than or equal to the level specified will be shown. All others will be discarded. The order of log levels in increasing priority is: debug info warn error @property {String} logLevel @default 'debug' @since 3.10.0 **/ /** Callback to execute when `Y.error()` is called. It receives the error message and a JavaScript error object if one was provided. This function is executed with the YUI instance as its `this` object. Returning `true` from this function will prevent an exception from being thrown. @property {Function} errorFn @param {String} errorFn.msg Error message @param {Object} [errorFn.err] Error object (if one was provided). @since 3.2.0 **/ /** A callback to execute when Loader fails to load one or more resources. This could be because of a script load failure. It could also be because a module fails to register itself when the `requireRegistration` config is `true`. If this function is defined, the `use()` callback will only be called when the loader succeeds. Otherwise, `use()` will always executes unless there was a JavaScript error when attaching a module. @property {Function} loadErrorFn @since 3.3.0 **/ /** If `true`, Loader will expect all loaded scripts to be first-class YUI modules that register themselves with the YUI global, and will trigger a failure if a loaded script does not register a YUI module. @property {Boolean} requireRegistration @default false @since 3.3.0 **/ /** Cache serviced use() requests. @property {Boolean} cacheUse @default true @since 3.3.0 @deprecated No longer used. **/ /** Whether or not YUI should use native ES5 functionality when available for features like `Y.Array.each()`, `Y.Object()`, etc. When `false`, YUI will always use its own fallback implementations instead of relying on ES5 functionality, even when ES5 functionality is available. @property {Boolean} useNativeES5 @default true @since 3.5.0 **/ /** * Leverage native JSON stringify if the browser has a native * implementation. In general, this is a good idea. See the Known Issues * section in the JSON user guide for caveats. The default value is true * for browsers with native JSON support. * * @property useNativeJSONStringify * @type Boolean * @default true * @since 3.8.0 */ /** * Leverage native JSON parse if the browser has a native implementation. * In general, this is a good idea. See the Known Issues section in the * JSON user guide for caveats. The default value is true for browsers with * native JSON support. * * @property useNativeJSONParse * @type Boolean * @default true * @since 3.8.0 */ /** Delay the `use` callback until a specific event has passed (`load`, `domready`, `contentready` or `available`) @property {Object|String} delayUntil @since 3.6.0 @example You can use `load` or `domready` strings by default: YUI({ delayUntil: 'domready' }, function (Y) { // This will not execute until 'domeready' occurs. }); Or you can delay until a node is available (with `available` or `contentready`): YUI({ delayUntil: { event: 'available', args : '#foo' } }, function (Y) { // This will not execute until a node matching the selector "#foo" is // available in the DOM. }); **/ YUI.add('yui-base', function (Y, NAME) { /* * YUI stub * @module yui * @submodule yui-base */ /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Provides core language utilites and extensions used throughout YUI. * * @class Lang * @static */ var L = Y.Lang || (Y.Lang = {}), STRING_PROTO = String.prototype, TOSTRING = Object.prototype.toString, TYPES = { 'undefined' : 'undefined', 'number' : 'number', 'boolean' : 'boolean', 'string' : 'string', '[object Function]': 'function', '[object RegExp]' : 'regexp', '[object Array]' : 'array', '[object Date]' : 'date', '[object Error]' : 'error' }, SUBREGEX = /\{\s*([^|}]+?)\s*(?:\|([^}]*))?\s*\}/g, TRIMREGEX = /^\s+|\s+$/g, NATIVE_FN_REGEX = /\{\s*\[(?:native code|function)\]\s*\}/i; // -- Protected Methods -------------------------------------------------------- /** Returns `true` if the given function appears to be implemented in native code, `false` otherwise. Will always return `false` -- even in ES5-capable browsers -- if the `useNativeES5` YUI config option is set to `false`. This isn't guaranteed to be 100% accurate and won't work for anything other than functions, but it can be useful for determining whether a function like `Array.prototype.forEach` is native or a JS shim provided by another library. There's a great article by @kangax discussing certain flaws with this technique: <http://perfectionkills.com/detecting-built-in-host-methods/> While his points are valid, it's still possible to benefit from this function as long as it's used carefully and sparingly, and in such a way that false negatives have minimal consequences. It's used internally to avoid using potentially broken non-native ES5 shims that have been added to the page by other libraries. @method _isNative @param {Function} fn Function to test. @return {Boolean} `true` if _fn_ appears to be native, `false` otherwise. @static @protected @since 3.5.0 **/ L._isNative = function (fn) { return !!(Y.config.useNativeES5 && fn && NATIVE_FN_REGEX.test(fn)); }; // -- Public Methods ----------------------------------------------------------- /** * Determines whether or not the provided item is an array. * * Returns `false` for array-like collections such as the function `arguments` * collection or `HTMLElement` collections. Use `Y.Array.test()` if you want to * test for an array-like collection. * * @method isArray * @param o The object to test. * @return {boolean} true if o is an array. * @static */ L.isArray = L._isNative(Array.isArray) ? Array.isArray : function (o) { return L.type(o) === 'array'; }; /** * Determines whether or not the provided item is a boolean. * @method isBoolean * @static * @param o The object to test. * @return {boolean} true if o is a boolean. */ L.isBoolean = function(o) { return typeof o === 'boolean'; }; /** * Determines whether or not the supplied item is a date instance. * @method isDate * @static * @param o The object to test. * @return {boolean} true if o is a date. */ L.isDate = function(o) { return L.type(o) === 'date' && o.toString() !== 'Invalid Date' && !isNaN(o); }; /** * <p> * Determines whether or not the provided item is a function. * Note: Internet Explorer thinks certain functions are objects: * </p> * * <pre> * var obj = document.createElement("object"); * Y.Lang.isFunction(obj.getAttribute) // reports false in IE * &nbsp; * var input = document.createElement("input"); // append to body * Y.Lang.isFunction(input.focus) // reports false in IE * </pre> * * <p> * You will have to implement additional tests if these functions * matter to you. * </p> * * @method isFunction * @static * @param o The object to test. * @return {boolean} true if o is a function. */ L.isFunction = function(o) { return L.type(o) === 'function'; }; /** * Determines whether or not the provided item is null. * @method isNull * @static * @param o The object to test. * @return {boolean} true if o is null. */ L.isNull = function(o) { return o === null; }; /** * Determines whether or not the provided item is a legal number. * @method isNumber * @static * @param o The object to test. * @return {boolean} true if o is a number. */ L.isNumber = function(o) { return typeof o === 'number' && isFinite(o); }; /** * Determines whether or not the provided item is of type object * or function. Note that arrays are also objects, so * <code>Y.Lang.isObject([]) === true</code>. * @method isObject * @static * @param o The object to test. * @param failfn {boolean} fail if the input is a function. * @return {boolean} true if o is an object. * @see isPlainObject */ L.isObject = function(o, failfn) { var t = typeof o; return (o && (t === 'object' || (!failfn && (t === 'function' || L.isFunction(o))))) || false; }; /** * Determines whether or not the provided item is a string. * @method isString * @static * @param o The object to test. * @return {boolean} true if o is a string. */ L.isString = function(o) { return typeof o === 'string'; }; /** * Determines whether or not the provided item is undefined. * @method isUndefined * @static * @param o The object to test. * @return {boolean} true if o is undefined. */ L.isUndefined = function(o) { return typeof o === 'undefined'; }; /** * A convenience method for detecting a legitimate non-null value. * Returns false for null/undefined/NaN, true for other values, * including 0/false/'' * @method isValue * @static * @param o The item to test. * @return {boolean} true if it is not null/undefined/NaN || false. */ L.isValue = function(o) { var t = L.type(o); switch (t) { case 'number': return isFinite(o); case 'null': // fallthru case 'undefined': return false; default: return !!t; } }; /** * Returns the current time in milliseconds. * * @method now * @return {Number} Current time in milliseconds. * @static * @since 3.3.0 */ L.now = Date.now || function () { return new Date().getTime(); }; /** * Lightweight version of <code>Y.substitute</code>. Uses the same template * structure as <code>Y.substitute</code>, but doesn't support recursion, * auto-object coersion, or formats. * @method sub * @param {string} s String to be modified. * @param {object} o Object containing replacement values. * @return {string} the substitute result. * @static * @since 3.2.0 */ L.sub = function(s, o) { return s.replace ? s.replace(SUBREGEX, function (match, key) { return L.isUndefined(o[key]) ? match : o[key]; }) : s; }; /** * Returns a string without any leading or trailing whitespace. If * the input is not a string, the input will be returned untouched. * @method trim * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trim = STRING_PROTO.trim ? function(s) { return s && s.trim ? s.trim() : s; } : function (s) { try { return s.replace(TRIMREGEX, ''); } catch (e) { return s; } }; /** * Returns a string without any leading whitespace. * @method trimLeft * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimLeft = STRING_PROTO.trimLeft ? function (s) { return s.trimLeft(); } : function (s) { return s.replace(/^\s+/, ''); }; /** * Returns a string without any trailing whitespace. * @method trimRight * @static * @param s {string} the string to trim. * @return {string} the trimmed string. */ L.trimRight = STRING_PROTO.trimRight ? function (s) { return s.trimRight(); } : function (s) { return s.replace(/\s+$/, ''); }; /** Returns one of the following strings, representing the type of the item passed in: * "array" * "boolean" * "date" * "error" * "function" * "null" * "number" * "object" * "regexp" * "string" * "undefined" Known issues: * `typeof HTMLElementCollection` returns function in Safari, but `Y.Lang.type()` reports "object", which could be a good thing -- but it actually caused the logic in <code>Y.Lang.isObject</code> to fail. @method type @param o the item to test. @return {string} the detected type. @static **/ L.type = function(o) { return TYPES[typeof o] || TYPES[TOSTRING.call(o)] || (o ? 'object' : 'null'); }; /** @module yui @submodule yui-base */ var Lang = Y.Lang, Native = Array.prototype, hasOwn = Object.prototype.hasOwnProperty; /** Provides utility methods for working with arrays. Additional array helpers can be found in the `collection` and `array-extras` modules. `Y.Array(thing)` returns a native array created from _thing_. Depending on _thing_'s type, one of the following will happen: * Arrays are returned unmodified unless a non-zero _startIndex_ is specified. * Array-like collections (see `Array.test()`) are converted to arrays. * For everything else, a new array is created with _thing_ as the sole item. Note: elements that are also collections, such as `<form>` and `<select>` elements, are not automatically converted to arrays. To force a conversion, pass `true` as the value of the _force_ parameter. @class Array @constructor @param {Any} thing The thing to arrayify. @param {Number} [startIndex=0] If non-zero and _thing_ is an array or array-like collection, a subset of items starting at the specified index will be returned. @param {Boolean} [force=false] If `true`, _thing_ will be treated as an array-like collection no matter what. @return {Array} A native array created from _thing_, according to the rules described above. **/ function YArray(thing, startIndex, force) { var len, result; /*jshint expr: true*/ startIndex || (startIndex = 0); if (force || YArray.test(thing)) { // IE throws when trying to slice HTMLElement collections. try { return Native.slice.call(thing, startIndex); } catch (ex) { result = []; for (len = thing.length; startIndex < len; ++startIndex) { result.push(thing[startIndex]); } return result; } } return [thing]; } Y.Array = YArray; /** Dedupes an array of strings, returning an array that's guaranteed to contain only one copy of a given string. This method differs from `Array.unique()` in that it's optimized for use only with strings, whereas `unique` may be used with other types (but is slower). Using `dedupe()` with non-string values may result in unexpected behavior. @method dedupe @param {String[]} array Array of strings to dedupe. @return {Array} Deduped copy of _array_. @static @since 3.4.0 **/ YArray.dedupe = function (array) { var hash = {}, results = [], i, item, len; for (i = 0, len = array.length; i < len; ++i) { item = array[i]; if (!hasOwn.call(hash, item)) { hash[item] = 1; results.push(item); } } return results; }; /** Executes the supplied function on each item in the array. This method wraps the native ES5 `Array.forEach()` method if available. @method each @param {Array} array Array to iterate. @param {Function} fn Function to execute on each item in the array. The function will receive the following arguments: @param {Any} fn.item Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {YUI} The YUI instance. @static **/ YArray.each = YArray.forEach = Lang._isNative(Native.forEach) ? function (array, fn, thisObj) { Native.forEach.call(array || [], fn, thisObj || Y); return Y; } : function (array, fn, thisObj) { for (var i = 0, len = (array && array.length) || 0; i < len; ++i) { if (i in array) { fn.call(thisObj || Y, array[i], i, array); } } return Y; }; /** Alias for `each()`. @method forEach @static **/ /** Returns an object using the first array as keys and the second as values. If the second array is not provided, or if it doesn't contain the same number of values as the first array, then `true` will be used in place of the missing values. @example Y.Array.hash(['a', 'b', 'c'], ['foo', 'bar']); // => {a: 'foo', b: 'bar', c: true} @method hash @param {String[]} keys Array of strings to use as keys. @param {Array} [values] Array to use as values. @return {Object} Hash using the first array as keys and the second as values. @static **/ YArray.hash = function (keys, values) { var hash = {}, vlen = (values && values.length) || 0, i, len; for (i = 0, len = keys.length; i < len; ++i) { if (i in keys) { hash[keys[i]] = vlen > i && i in values ? values[i] : true; } } return hash; }; /** Returns the index of the first item in the array that's equal (using a strict equality check) to the specified _value_, or `-1` if the value isn't found. This method wraps the native ES5 `Array.indexOf()` method if available. @method indexOf @param {Array} array Array to search. @param {Any} value Value to search for. @param {Number} [from=0] The index at which to begin the search. @return {Number} Index of the item strictly equal to _value_, or `-1` if not found. @static **/ YArray.indexOf = Lang._isNative(Native.indexOf) ? function (array, value, from) { return Native.indexOf.call(array, value, from); } : function (array, value, from) { // http://es5.github.com/#x15.4.4.14 var len = array.length; from = +from || 0; from = (from > 0 || -1) * Math.floor(Math.abs(from)); if (from < 0) { from += len; if (from < 0) { from = 0; } } for (; from < len; ++from) { if (from in array && array[from] === value) { return from; } } return -1; }; /** Numeric sort convenience function. The native `Array.prototype.sort()` function converts values to strings and sorts them in lexicographic order, which is unsuitable for sorting numeric values. Provide `Array.numericSort` as a custom sort function when you want to sort values in numeric order. @example [42, 23, 8, 16, 4, 15].sort(Y.Array.numericSort); // => [4, 8, 15, 16, 23, 42] @method numericSort @param {Number} a First value to compare. @param {Number} b Second value to compare. @return {Number} Difference between _a_ and _b_. @static **/ YArray.numericSort = function (a, b) { return a - b; }; /** Executes the supplied function on each item in the array. Returning a truthy value from the function will stop the processing of remaining items. @method some @param {Array} array Array to iterate over. @param {Function} fn Function to execute on each item. The function will receive the following arguments: @param {Any} fn.value Current array item. @param {Number} fn.index Current array index. @param {Array} fn.array Array being iterated over. @param {Object} [thisObj] `this` object to use when calling _fn_. @return {Boolean} `true` if the function returns a truthy value on any of the items in the array; `false` otherwise. @static **/ YArray.some = Lang._isNative(Native.some) ? function (array, fn, thisObj) { return Native.some.call(array, fn, thisObj); } : function (array, fn, thisObj) { for (var i = 0, len = array.length; i < len; ++i) { if (i in array && fn.call(thisObj, array[i], i, array)) { return true; } } return false; }; /** Evaluates _obj_ to determine if it's an array, an array-like collection, or something else. This is useful when working with the function `arguments` collection and `HTMLElement` collections. Note: This implementation doesn't consider elements that are also collections, such as `<form>` and `<select>`, to be array-like. @method test @param {Object} obj Object to test. @return {Number} A number indicating the results of the test: * 0: Neither an array nor an array-like collection. * 1: Real array. * 2: Array-like collection. @static **/ YArray.test = function (obj) { var result = 0; if (Lang.isArray(obj)) { result = 1; } else if (Lang.isObject(obj)) { try { // indexed, but no tagName (element) or scrollTo/document (window. From DOM.isWindow test which we can't use here), // or functions without apply/call (Safari // HTMLElementCollection bug). if ('length' in obj && !obj.tagName && !(obj.scrollTo && obj.document) && !obj.apply) { result = 2; } } catch (ex) {} } return result; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * A simple FIFO queue. Items are added to the Queue with add(1..n items) and * removed using next(). * * @class Queue * @constructor * @param {MIXED} item* 0..n items to seed the queue. */ function Queue() { this._init(); this.add.apply(this, arguments); } Queue.prototype = { /** * Initialize the queue * * @method _init * @protected */ _init: function() { /** * The collection of enqueued items * * @property _q * @type Array * @protected */ this._q = []; }, /** * Get the next item in the queue. FIFO support * * @method next * @return {MIXED} the next item in the queue. */ next: function() { return this._q.shift(); }, /** * Get the last in the queue. LIFO support. * * @method last * @return {MIXED} the last item in the queue. */ last: function() { return this._q.pop(); }, /** * Add 0..n items to the end of the queue. * * @method add * @param {MIXED} item* 0..n items. * @return {object} this queue. */ add: function() { this._q.push.apply(this._q, arguments); return this; }, /** * Returns the current number of queued items. * * @method size * @return {Number} The size. */ size: function() { return this._q.length; } }; Y.Queue = Queue; YUI.Env._loaderQueue = YUI.Env._loaderQueue || new Queue(); /** The YUI module contains the components required for building the YUI seed file. This includes the script loading mechanism, a simple queue, and the core utilities for the library. @module yui @submodule yui-base **/ var CACHED_DELIMITER = '__', hasOwn = Object.prototype.hasOwnProperty, isObject = Y.Lang.isObject; /** Returns a wrapper for a function which caches the return value of that function, keyed off of the combined string representation of the argument values provided when the wrapper is called. Calling this function again with the same arguments will return the cached value rather than executing the wrapped function. Note that since the cache is keyed off of the string representation of arguments passed to the wrapper function, arguments that aren't strings and don't provide a meaningful `toString()` method may result in unexpected caching behavior. For example, the objects `{}` and `{foo: 'bar'}` would both be converted to the string `[object Object]` when used as a cache key. @method cached @param {Function} source The function to memoize. @param {Object} [cache={}] Object in which to store cached values. You may seed this object with pre-existing cached values if desired. @param {any} [refetch] If supplied, this value is compared with the cached value using a `==` comparison. If the values are equal, the wrapped function is executed again even though a cached value exists. @return {Function} Wrapped function. @for YUI **/ Y.cached = function (source, cache, refetch) { /*jshint expr: true*/ cache || (cache = {}); return function (arg) { var key = arguments.length > 1 ? Array.prototype.join.call(arguments, CACHED_DELIMITER) : String(arg); /*jshint eqeqeq: false*/ if (!(key in cache) || (refetch && cache[key] == refetch)) { cache[key] = source.apply(source, arguments); } return cache[key]; }; }; /** Returns the `location` object from the window/frame in which this YUI instance operates, or `undefined` when executing in a non-browser environment (e.g. Node.js). It is _not_ recommended to hold references to the `window.location` object outside of the scope of a function in which its properties are being accessed or its methods are being called. This is because of a nasty bug/issue that exists in both Safari and MobileSafari browsers: [WebKit Bug 34679](https://bugs.webkit.org/show_bug.cgi?id=34679). @method getLocation @return {location} The `location` object from the window/frame in which this YUI instance operates. @since 3.5.0 **/ Y.getLocation = function () { // It is safer to look this up every time because yui-base is attached to a // YUI instance before a user's config is applied; i.e. `Y.config.win` does // not point the correct window object when this file is loaded. var win = Y.config.win; // It is not safe to hold a reference to the `location` object outside the // scope in which it is being used. The WebKit engine used in Safari and // MobileSafari will "disconnect" the `location` object from the `window` // when a page is restored from back/forward history cache. return win && win.location; }; /** Returns a new object containing all of the properties of all the supplied objects. The properties from later objects will overwrite those in earlier objects. Passing in a single object will create a shallow copy of it. For a deep copy, use `clone()`. @method merge @param {Object} objects* One or more objects to merge. @return {Object} A new merged object. **/ Y.merge = function () { var i = 0, len = arguments.length, result = {}, key, obj; for (; i < len; ++i) { obj = arguments[i]; for (key in obj) { if (hasOwn.call(obj, key)) { result[key] = obj[key]; } } } return result; }; /** Mixes _supplier_'s properties into _receiver_. Properties on _receiver_ or _receiver_'s prototype will not be overwritten or shadowed unless the _overwrite_ parameter is `true`, and will not be merged unless the _merge_ parameter is `true`. In the default mode (0), only properties the supplier owns are copied (prototype properties are not copied). The following copying modes are available: * `0`: _Default_. Object to object. * `1`: Prototype to prototype. * `2`: Prototype to prototype and object to object. * `3`: Prototype to object. * `4`: Object to prototype. @method mix @param {Function|Object} receiver The object or function to receive the mixed properties. @param {Function|Object} supplier The object or function supplying the properties to be mixed. @param {Boolean} [overwrite=false] If `true`, properties that already exist on the receiver will be overwritten with properties from the supplier. @param {String[]} [whitelist] An array of property names to copy. If specified, only the whitelisted properties will be copied, and all others will be ignored. @param {Number} [mode=0] Mix mode to use. See above for available modes. @param {Boolean} [merge=false] If `true`, objects and arrays that already exist on the receiver will have the corresponding object/array from the supplier merged into them, rather than being skipped or overwritten. When both _overwrite_ and _merge_ are `true`, _merge_ takes precedence. @return {Function|Object|YUI} The receiver, or the YUI instance if the specified receiver is falsy. **/ Y.mix = function(receiver, supplier, overwrite, whitelist, mode, merge) { var alwaysOverwrite, exists, from, i, key, len, to; // If no supplier is given, we return the receiver. If no receiver is given, // we return Y. Returning Y doesn't make much sense to me, but it's // grandfathered in for backcompat reasons. if (!receiver || !supplier) { return receiver || Y; } if (mode) { // In mode 2 (prototype to prototype and object to object), we recurse // once to do the proto to proto mix. The object to object mix will be // handled later on. if (mode === 2) { Y.mix(receiver.prototype, supplier.prototype, overwrite, whitelist, 0, merge); } // Depending on which mode is specified, we may be copying from or to // the prototypes of the supplier and receiver. from = mode === 1 || mode === 3 ? supplier.prototype : supplier; to = mode === 1 || mode === 4 ? receiver.prototype : receiver; // If either the supplier or receiver doesn't actually have a // prototype property, then we could end up with an undefined `from` // or `to`. If that happens, we abort and return the receiver. if (!from || !to) { return receiver; } } else { from = supplier; to = receiver; } // If `overwrite` is truthy and `merge` is falsy, then we can skip a // property existence check on each iteration and save some time. alwaysOverwrite = overwrite && !merge; if (whitelist) { for (i = 0, len = whitelist.length; i < len; ++i) { key = whitelist[i]; // We call `Object.prototype.hasOwnProperty` instead of calling // `hasOwnProperty` on the object itself, since the object's // `hasOwnProperty` method may have been overridden or removed. // Also, some native objects don't implement a `hasOwnProperty` // method. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { // If we're in merge mode, and the key is present on both // objects, and the value on both objects is either an object or // an array (but not a function), then we recurse to merge the // `from` value into the `to` value instead of overwriting it. // // Note: It's intentional that the whitelist isn't passed to the // recursive call here. This is legacy behavior that lots of // code still depends on. Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { // We're not in merge mode, so we'll only copy the `from` value // to the `to` value if we're in overwrite mode or if the // current key doesn't exist on the `to` object. to[key] = from[key]; } } } else { for (key in from) { // The code duplication here is for runtime performance reasons. // Combining whitelist and non-whitelist operations into a single // loop or breaking the shared logic out into a function both result // in worse performance, and Y.mix is critical enough that the byte // tradeoff is worth it. if (!hasOwn.call(from, key)) { continue; } // The `key in to` check here is (sadly) intentional for backwards // compatibility reasons. It prevents undesired shadowing of // prototype members on `to`. exists = alwaysOverwrite ? false : key in to; if (merge && exists && isObject(to[key], true) && isObject(from[key], true)) { Y.mix(to[key], from[key], overwrite, null, 0, merge); } else if (overwrite || !exists) { to[key] = from[key]; } } // If this is an IE browser with the JScript enumeration bug, force // enumeration of the buggy properties by making a recursive call with // the buggy properties as the whitelist. if (Y.Object._hasEnumBug) { Y.mix(to, from, overwrite, Y.Object._forceEnum, mode, merge); } } return receiver; }; /** * The YUI module contains the components required for building the YUI * seed file. This includes the script loading mechanism, a simple queue, * and the core utilities for the library. * @module yui * @submodule yui-base */ /** * Adds utilities to the YUI instance for working with objects. * * @class Object */ var Lang = Y.Lang, hasOwn = Object.prototype.hasOwnProperty, UNDEFINED, // <-- Note the comma. We're still declaring vars. /** * Returns a new object that uses _obj_ as its prototype. This method wraps the * native ES5 `Object.create()` method if available, but doesn't currently * pass through `Object.create()`'s second argument (properties) in order to * ensure compatibility with older browsers. * * @method () * @param {Object} obj Prototype object. * @return {Object} New object using _obj_ as its prototype. * @static */ O = Y.Object = Lang._isNative(Object.create) ? function (obj) { // We currently wrap the native Object.create instead of simply aliasing it // to ensure consistency with our fallback shim, which currently doesn't // support Object.create()'s second argument (properties). Once we have a // safe fallback for the properties arg, we can stop wrapping // Object.create(). return Object.create(obj); } : (function () { // Reusable constructor function for the Object.create() shim. function F() {} // The actual shim. return function (obj) { F.prototype = obj; return new F(); }; }()), /** * Property names that IE doesn't enumerate in for..in loops, even when they * should be enumerable. When `_hasEnumBug` is `true`, it's necessary to * manually enumerate these properties. * * @property _forceEnum * @type String[] * @protected * @static */ forceEnum = O._forceEnum = [ 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toString', 'toLocaleString', 'valueOf' ], /** * `true` if this browser has the JScript enumeration bug that prevents * enumeration of the properties named in the `_forceEnum` array, `false` * otherwise. * * See: * - <https://developer.mozilla.org/en/ECMAScript_DontEnum_attribute#JScript_DontEnum_Bug> * - <http://whattheheadsaid.com/2010/10/a-safer-object-keys-compatibility-implementation> * * @property _hasEnumBug * @type Boolean * @protected * @static */ hasEnumBug = O._hasEnumBug = !{valueOf: 0}.propertyIsEnumerable('valueOf'), /** * `true` if this browser incorrectly considers the `prototype` property of * functions to be enumerable. Currently known to affect Opera 11.50. * * @property _hasProtoEnumBug * @type Boolean * @protected * @static */ hasProtoEnumBug = O._hasProtoEnumBug = (function () {}).propertyIsEnumerable('prototype'), /** * Returns `true` if _key_ exists on _obj_, `false` if _key_ doesn't exist or * exists only on _obj_'s prototype. This is essentially a safer version of * `obj.hasOwnProperty()`. * * @method owns * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ owns = O.owns = function (obj, key) { return !!obj && hasOwn.call(obj, key); }; // <-- End of var declarations. /** * Alias for `owns()`. * * @method hasKey * @param {Object} obj Object to test. * @param {String} key Property name to look for. * @return {Boolean} `true` if _key_ exists on _obj_, `false` otherwise. * @static */ O.hasKey = owns; /** * Returns an array containing the object's enumerable keys. Does not include * prototype keys or non-enumerable keys. * * Note that keys are returned in enumeration order (that is, in the same order * that they would be enumerated by a `for-in` loop), which may not be the same * as the order in which they were defined. * * This method is an alias for the native ES5 `Object.keys()` method if * available. * * @example * * Y.Object.keys({a: 'foo', b: 'bar', c: 'baz'}); * // => ['a', 'b', 'c'] * * @method keys * @param {Object} obj An object. * @return {String[]} Array of keys. * @static */ O.keys = Lang._isNative(Object.keys) ? Object.keys : function (obj) { if (!Lang.isObject(obj)) { throw new TypeError('Object.keys called on a non-object'); } var keys = [], i, key, len; if (hasProtoEnumBug && typeof obj === 'function') { for (key in obj) { if (owns(obj, key) && key !== 'prototype') { keys.push(key); } } } else { for (key in obj) { if (owns(obj, key)) { keys.push(key); } } } if (hasEnumBug) { for (i = 0, len = forceEnum.length; i < len; ++i) { key = forceEnum[i]; if (owns(obj, key)) { keys.push(key); } } } return keys; }; /** * Returns an array containing the values of the object's enumerable keys. * * Note that values are returned in enumeration order (that is, in the same * order that they would be enumerated by a `for-in` loop), which may not be the * same as the order in which they were defined. * * @example * * Y.Object.values({a: 'foo', b: 'bar', c: 'baz'}); * // => ['foo', 'bar', 'baz'] * * @method values * @param {Object} obj An object. * @return {Array} Array of values. * @static */ O.values = function (obj) { var keys = O.keys(obj), i = 0, len = keys.length, values = []; for (; i < len; ++i) { values.push(obj[keys[i]]); } return values; }; /** * Returns the number of enumerable keys owned by an object. * * @method size * @param {Object} obj An object. * @return {Number} The object's size. * @static */ O.size = function (obj) { try { return O.keys(obj).length; } catch (ex) { return 0; // Legacy behavior for non-objects. } }; /** * Returns `true` if the object owns an enumerable property with the specified * value. * * @method hasValue * @param {Object} obj An object. * @param {any} value The value to search for. * @return {Boolean} `true` if _obj_ contains _value_, `false` otherwise. * @static */ O.hasValue = function (obj, value) { return Y.Array.indexOf(O.values(obj), value) > -1; }; /** * Executes a function on each enumerable property in _obj_. The function * receives the value, the key, and the object itself as parameters (in that * order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method each * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {YUI} the YUI instance. * @chainable * @static */ O.each = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { fn.call(thisObj || Y, obj[key], key, obj); } } return Y; }; /** * Executes a function on each enumerable property in _obj_, but halts if the * function returns a truthy value. The function receives the value, the key, * and the object itself as paramters (in that order). * * By default, only properties owned by _obj_ are enumerated. To include * prototype properties, set the _proto_ parameter to `true`. * * @method some * @param {Object} obj Object to enumerate. * @param {Function} fn Function to execute on each enumerable property. * @param {mixed} fn.value Value of the current property. * @param {String} fn.key Key of the current property. * @param {Object} fn.obj Object being enumerated. * @param {Object} [thisObj] `this` object to use when calling _fn_. * @param {Boolean} [proto=false] Include prototype properties. * @return {Boolean} `true` if any execution of _fn_ returns a truthy value, * `false` otherwise. * @static */ O.some = function (obj, fn, thisObj, proto) { var key; for (key in obj) { if (proto || owns(obj, key)) { if (fn.call(thisObj || Y, obj[key], key, obj)) { return true; } } } return false; }; /** * Retrieves the sub value at the provided path, * from the value object provided. * * @method getValue * @static * @param o The object from which to extract the property value. * @param path {Array} A path array, specifying the object traversal path * from which to obtain the sub value. * @return {Any} The value stored in the path, undefined if not found, * undefined if the source is not an object. Returns the source object * if an empty path is provided. */ O.getValue = function(o, path) { if (!Lang.isObject(o)) { return UNDEFINED; } var i, p = Y.Array(path), l = p.length; for (i = 0; o !== UNDEFINED && i < l; i++) { o = o[p[i]]; } return o; }; /** * Sets the sub-attribute value at the provided path on the * value object. Returns the modified value object, or * undefined if the path is invalid. * * @method setValue * @static * @param o The object on which to set the sub value. * @param path {Array} A path array, specifying the object traversal path * at which to set the sub value. * @param val {Any} The new value for the sub-attribute. * @return {Object} The modified object, with the new sub value set, or * undefined, if the path was invalid. */ O.setValue = function(o, path, val) { var i, p = Y.Array(path), leafIdx = p.length - 1, ref = o; if (leafIdx >= 0) { for (i = 0; ref !== UNDEFINED && i < leafIdx; i++) { ref = ref[p[i]]; } if (ref !== UNDEFINED) { ref[p[i]] = val; } else { return UNDEFINED; } } return o; }; /** * Returns `true` if the object has no enumerable properties of its own. * * @method isEmpty * @param {Object} obj An object. * @return {Boolean} `true` if the object is empty. * @static * @since 3.2.0 */ O.isEmpty = function (obj) { return !O.keys(Object(obj)).length; }; /** * The YUI module contains the components required for building the YUI seed * file. This includes the script loading mechanism, a simple queue, and the * core utilities for the library. * @module yui * @submodule yui-base */ /** * YUI user agent detection. * Do not fork for a browser if it can be avoided. Use feature detection when * you can. Use the user agent as a last resort. For all fields listed * as @type float, UA stores a version number for the browser engine, * 0 otherwise. This value may or may not map to the version number of * the browser using the engine. The value is presented as a float so * that it can easily be used for boolean evaluation as well as for * looking for a particular range of versions. Because of this, * some of the granularity of the version info may be lost. The fields that * are @type string default to null. The API docs list the values that * these fields can have. * @class UA * @static */ /** * Static method on `YUI.Env` for parsing a UA string. Called at instantiation * to populate `Y.UA`. * * @static * @method parseUA * @param {String} [subUA=navigator.userAgent] UA string to parse * @return {Object} The Y.UA object */ YUI.Env.parseUA = function(subUA) { var numberify = function(s) { var c = 0; return parseFloat(s.replace(/\./g, function() { return (c++ === 1) ? '' : '.'; })); }, win = Y.config.win, nav = win && win.navigator, o = { /** * Internet Explorer version number or 0. Example: 6 * @property ie * @type float * @static */ ie: 0, /** * Opera version number or 0. Example: 9.2 * @property opera * @type float * @static */ opera: 0, /** * Gecko engine revision number. Will evaluate to 1 if Gecko * is detected but the revision could not be found. Other browsers * will be 0. Example: 1.8 * <pre> * Firefox 1.0.0.4: 1.7.8 <-- Reports 1.7 * Firefox 1.5.0.9: 1.8.0.9 <-- 1.8 * Firefox 2.0.0.3: 1.8.1.3 <-- 1.81 * Firefox 3.0 <-- 1.9 * Firefox 3.5 <-- 1.91 * </pre> * @property gecko * @type float * @static */ gecko: 0, /** * AppleWebKit version. KHTML browsers that are not WebKit browsers * will evaluate to 1, other browsers 0. Example: 418.9 * <pre> * Safari 1.3.2 (312.6): 312.8.1 <-- Reports 312.8 -- currently the * latest available for Mac OSX 10.3. * Safari 2.0.2: 416 <-- hasOwnProperty introduced * Safari 2.0.4: 418 <-- preventDefault fixed * Safari 2.0.4 (419.3): 418.9.1 <-- One version of Safari may run * different versions of webkit * Safari 2.0.4 (419.3): 419 <-- Tiger installations that have been * updated, but not updated * to the latest patch. * Webkit 212 nightly: 522+ <-- Safari 3.0 precursor (with native * SVG and many major issues fixed). * Safari 3.0.4 (523.12) 523.12 <-- First Tiger release - automatic * update from 2.x via the 10.4.11 OS patch. * Webkit nightly 1/2008:525+ <-- Supports DOMContentLoaded event. * yahoo.com user agent hack removed. * </pre> * http://en.wikipedia.org/wiki/Safari_version_history * @property webkit * @type float * @static */ webkit: 0, /** * Safari will be detected as webkit, but this property will also * be populated with the Safari version number * @property safari * @type float * @static */ safari: 0, /** * Chrome will be detected as webkit, but this property will also * be populated with the Chrome version number * @property chrome * @type float * @static */ chrome: 0, /** * The mobile property will be set to a string containing any relevant * user agent information when a modern mobile browser is detected. * Currently limited to Safari on the iPhone/iPod Touch, Nokia N-series * devices with the WebKit-based browser, and Opera Mini. * @property mobile * @type string * @default null * @static */ mobile: null, /** * Adobe AIR version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property air * @type float */ air: 0, /** * PhantomJS version number or 0. Only populated if webkit is detected. * Example: 1.0 * @property phantomjs * @type float */ phantomjs: 0, /** * Detects Apple iPad's OS version * @property ipad * @type float * @static */ ipad: 0, /** * Detects Apple iPhone's OS version * @property iphone * @type float * @static */ iphone: 0, /** * Detects Apples iPod's OS version * @property ipod * @type float * @static */ ipod: 0, /** * General truthy check for iPad, iPhone or iPod * @property ios * @type Boolean * @default null * @static */ ios: null, /** * Detects Googles Android OS version * @property android * @type float * @static */ android: 0, /** * Detects Kindle Silk * @property silk * @type float * @static */ silk: 0, /** * Detects Kindle Silk Acceleration * @property accel * @type Boolean * @static */ accel: false, /** * Detects Palms WebOS version * @property webos * @type float * @static */ webos: 0, /** * Google Caja version number or 0. * @property caja * @type float */ caja: nav && nav.cajaVersion, /** * Set to true if the page appears to be in SSL * @property secure * @type boolean * @static */ secure: false, /** * The operating system. Currently only detecting windows or macintosh * @property os * @type string * @default null * @static */ os: null, /** * The Nodejs Version * @property nodejs * @type float * @default 0 * @static */ nodejs: 0, /** * Window8/IE10 Application host environment * @property winjs * @type Boolean * @static */ winjs: !!((typeof Windows !== "undefined") && Windows.System), /** * Are touch/msPointer events available on this device * @property touchEnabled * @type Boolean * @static */ touchEnabled: false }, ua = subUA || nav && nav.userAgent, loc = win && win.location, href = loc && loc.href, m; /** * The User Agent string that was parsed * @property userAgent * @type String * @static */ o.userAgent = ua; o.secure = href && (href.toLowerCase().indexOf('https') === 0); if (ua) { if ((/windows|win32/i).test(ua)) { o.os = 'windows'; } else if ((/macintosh|mac_powerpc/i).test(ua)) { o.os = 'macintosh'; } else if ((/android/i).test(ua)) { o.os = 'android'; } else if ((/symbos/i).test(ua)) { o.os = 'symbos'; } else if ((/linux/i).test(ua)) { o.os = 'linux'; } else if ((/rhino/i).test(ua)) { o.os = 'rhino'; } // Modern KHTML browsers should qualify as Safari X-Grade if ((/KHTML/).test(ua)) { o.webkit = 1; } if ((/IEMobile|XBLWP7/).test(ua)) { o.mobile = 'windows'; } if ((/Fennec/).test(ua)) { o.mobile = 'gecko'; } // Modern WebKit browsers are at least X-Grade m = ua.match(/AppleWebKit\/([^\s]*)/); if (m && m[1]) { o.webkit = numberify(m[1]); o.safari = o.webkit; if (/PhantomJS/.test(ua)) { m = ua.match(/PhantomJS\/([^\s]*)/); if (m && m[1]) { o.phantomjs = numberify(m[1]); } } // Mobile browser check if (/ Mobile\//.test(ua) || (/iPad|iPod|iPhone/).test(ua)) { o.mobile = 'Apple'; // iPhone or iPod Touch m = ua.match(/OS ([^\s]*)/); if (m && m[1]) { m = numberify(m[1].replace('_', '.')); } o.ios = m; o.os = 'ios'; o.ipad = o.ipod = o.iphone = 0; m = ua.match(/iPad|iPod|iPhone/); if (m && m[0]) { o[m[0].toLowerCase()] = o.ios; } } else { m = ua.match(/NokiaN[^\/]*|webOS\/\d\.\d/); if (m) { // Nokia N-series, webOS, ex: NokiaN95 o.mobile = m[0]; } if (/webOS/.test(ua)) { o.mobile = 'WebOS'; m = ua.match(/webOS\/([^\s]*);/); if (m && m[1]) { o.webos = numberify(m[1]); } } if (/ Android/.test(ua)) { if (/Mobile/.test(ua)) { o.mobile = 'Android'; } m = ua.match(/Android ([^\s]*);/); if (m && m[1]) { o.android = numberify(m[1]); } } if (/Silk/.test(ua)) { m = ua.match(/Silk\/([^\s]*)\)/); if (m && m[1]) { o.silk = numberify(m[1]); } if (!o.android) { o.android = 2.34; //Hack for desktop mode in Kindle o.os = 'Android'; } if (/Accelerated=true/.test(ua)) { o.accel = true; } } } m = ua.match(/(Chrome|CrMo|CriOS)\/([^\s]*)/); if (m && m[1] && m[2]) { o.chrome = numberify(m[2]); // Chrome o.safari = 0; //Reset safari back to 0 if (m[1] === 'CrMo') { o.mobile = 'chrome'; } } else { m = ua.match(/AdobeAIR\/([^\s]*)/); if (m) { o.air = m[0]; // Adobe AIR 1.0 or better } } } if (!o.webkit) { // not webkit // @todo check Opera/8.01 (J2ME/MIDP; Opera Mini/2.0.4509/1316; fi; U; ssr) if (/Opera/.test(ua)) { m = ua.match(/Opera[\s\/]([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } m = ua.match(/Version\/([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); // opera 10+ } if (/Opera Mobi/.test(ua)) { o.mobile = 'opera'; m = ua.replace('Opera Mobi', '').match(/Opera ([^\s]*)/); if (m && m[1]) { o.opera = numberify(m[1]); } } m = ua.match(/Opera Mini[^;]*/); if (m) { o.mobile = m[0]; // ex: Opera Mini/2.0.4509/1316 } } else { // not opera or webkit m = ua.match(/MSIE\s([^;]*)/); if (m && m[1]) { o.ie = numberify(m[1]); } else { // not opera, webkit, or ie m = ua.match(/Gecko\/([^\s]*)/); if (m) { o.gecko = 1; // Gecko detected, look for revision m = ua.match(/rv:([^\s\)]*)/); if (m && m[1]) { o.gecko = numberify(m[1]); if (/Mobile|Tablet/.test(ua)) { o.mobile = "ffos"; } } } } } } } //Check for known properties to tell if touch events are enabled on this device or if //the number of MSPointer touchpoints on this device is greater than 0. if (win && nav && !(o.chrome && o.chrome < 6)) { o.touchEnabled = (("ontouchstart" in win) || (("msMaxTouchPoints" in nav) && (nav.msMaxTouchPoints > 0))); } //It was a parsed UA, do not assign the global value. if (!subUA) { if (typeof process === 'object') { if (process.versions && process.versions.node) { //NodeJS o.os = process.platform; o.nodejs = numberify(process.versions.node); } } YUI.Env.UA = o; } return o; }; Y.UA = YUI.Env.UA || YUI.Env.parseUA(); /** Performs a simple comparison between two version numbers, accounting for standard versioning logic such as the fact that "535.8" is a lower version than "535.24", even though a simple numerical comparison would indicate that it's greater. Also accounts for cases such as "1.1" vs. "1.1.0", which are considered equivalent. Returns -1 if version _a_ is lower than version _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. Versions may be numbers or strings containing numbers and dots. For example, both `535` and `"535.8.10"` are acceptable. A version string containing non-numeric characters, like `"535.8.beta"`, may produce unexpected results. @method compareVersions @param {Number|String} a First version number to compare. @param {Number|String} b Second version number to compare. @return -1 if _a_ is lower than _b_, 0 if they're equivalent, 1 if _a_ is higher than _b_. **/ Y.UA.compareVersions = function (a, b) { var aPart, aParts, bPart, bParts, i, len; if (a === b) { return 0; } aParts = (a + '').split('.'); bParts = (b + '').split('.'); for (i = 0, len = Math.max(aParts.length, bParts.length); i < len; ++i) { aPart = parseInt(aParts[i], 10); bPart = parseInt(bParts[i], 10); /*jshint expr: true*/ isNaN(aPart) && (aPart = 0); isNaN(bPart) && (bPart = 0); if (aPart < bPart) { return -1; } if (aPart > bPart) { return 1; } } return 0; }; YUI.Env.aliases = { "anim": ["anim-base","anim-color","anim-curve","anim-easing","anim-node-plugin","anim-scroll","anim-xy"], "anim-shape-transform": ["anim-shape"], "app": ["app-base","app-content","app-transitions","lazy-model-list","model","model-list","model-sync-rest","router","view","view-node-map"], "attribute": ["attribute-base","attribute-complex"], "attribute-events": ["attribute-observable"], "autocomplete": ["autocomplete-base","autocomplete-sources","autocomplete-list","autocomplete-plugin"], "axes": ["axis-numeric","axis-category","axis-time","axis-stacked"], "axes-base": ["axis-numeric-base","axis-category-base","axis-time-base","axis-stacked-base"], "base": ["base-base","base-pluginhost","base-build"], "cache": ["cache-base","cache-offline","cache-plugin"], "charts": ["charts-base"], "collection": ["array-extras","arraylist","arraylist-add","arraylist-filter","array-invoke"], "color": ["color-base","color-hsl","color-harmony"], "controller": ["router"], "dataschema": ["dataschema-base","dataschema-json","dataschema-xml","dataschema-array","dataschema-text"], "datasource": ["datasource-local","datasource-io","datasource-get","datasource-function","datasource-cache","datasource-jsonschema","datasource-xmlschema","datasource-arrayschema","datasource-textschema","datasource-polling"], "datatable": ["datatable-core","datatable-table","datatable-head","datatable-body","datatable-base","datatable-column-widths","datatable-message","datatable-mutable","datatable-sort","datatable-datasource"], "datatype": ["datatype-date","datatype-number","datatype-xml"], "datatype-date": ["datatype-date-parse","datatype-date-format","datatype-date-math"], "datatype-number": ["datatype-number-parse","datatype-number-format"], "datatype-xml": ["datatype-xml-parse","datatype-xml-format"], "dd": ["dd-ddm-base","dd-ddm","dd-ddm-drop","dd-drag","dd-proxy","dd-constrain","dd-drop","dd-scroll","dd-delegate"], "dom": ["dom-base","dom-screen","dom-style","selector-native","selector"], "editor": ["frame","editor-selection","exec-command","editor-base","editor-para","editor-br","editor-bidi","editor-tab","createlink-base"], "event": ["event-base","event-delegate","event-synthetic","event-mousewheel","event-mouseenter","event-key","event-focus","event-resize","event-hover","event-outside","event-touch","event-move","event-flick","event-valuechange","event-tap"], "event-custom": ["event-custom-base","event-custom-complex"], "event-gestures": ["event-flick","event-move"], "handlebars": ["handlebars-compiler"], "highlight": ["highlight-base","highlight-accentfold"], "history": ["history-base","history-hash","history-hash-ie","history-html5"], "io": ["io-base","io-xdr","io-form","io-upload-iframe","io-queue"], "json": ["json-parse","json-stringify"], "loader": ["loader-base","loader-rollup","loader-yui3"], "node": ["node-base","node-event-delegate","node-pluginhost","node-screen","node-style"], "pluginhost": ["pluginhost-base","pluginhost-config"], "querystring": ["querystring-parse","querystring-stringify"], "recordset": ["recordset-base","recordset-sort","recordset-filter","recordset-indexer"], "resize": ["resize-base","resize-proxy","resize-constrain"], "slider": ["slider-base","slider-value-range","clickable-rail","range-slider"], "template": ["template-base","template-micro"], "text": ["text-accentfold","text-wordbreak"], "widget": ["widget-base","widget-htmlparser","widget-skin","widget-uievents"] }; }, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('get', function (Y, NAME) { /*jslint boss:true, expr:true, laxbreak: true */ /** Provides dynamic loading of remote JavaScript and CSS resources. @module get @class Get @static **/ var Lang = Y.Lang, CUSTOM_ATTRS, // defined lazily in Y.Get.Transaction._createNode() Get, Transaction; Y.Get = Get = { // -- Public Properties ---------------------------------------------------- /** Default options for CSS requests. Options specified here will override global defaults for CSS requests. See the `options` property for all available options. @property cssOptions @type Object @static @since 3.5.0 **/ cssOptions: { attributes: { rel: 'stylesheet' }, doc : Y.config.linkDoc || Y.config.doc, pollInterval: 50 }, /** Default options for JS requests. Options specified here will override global defaults for JS requests. See the `options` property for all available options. @property jsOptions @type Object @static @since 3.5.0 **/ jsOptions: { autopurge: true, doc : Y.config.scriptDoc || Y.config.doc }, /** Default options to use for all requests. Note that while all available options are documented here for ease of discovery, some options (like callback functions) only make sense at the transaction level. Callback functions specified via the options object or the `options` parameter of the `css()`, `js()`, or `load()` methods will receive the transaction object as a parameter. See `Y.Get.Transaction` for details on the properties and methods available on transactions. @static @since 3.5.0 @property {Object} options @property {Boolean} [options.async=false] Whether or not to load scripts asynchronously, meaning they're requested in parallel and execution order is not guaranteed. Has no effect on CSS, since CSS is always loaded asynchronously. @property {Object} [options.attributes] HTML attribute name/value pairs that should be added to inserted nodes. By default, the `charset` attribute will be set to "utf-8" and nodes will be given an auto-generated `id` attribute, but you can override these with your own values if desired. @property {Boolean} [options.autopurge] Whether or not to automatically purge inserted nodes after the purge threshold is reached. This is `true` by default for JavaScript, but `false` for CSS since purging a CSS node will also remove any styling applied by the referenced file. @property {Object} [options.context] `this` object to use when calling callback functions. Defaults to the transaction object. @property {Mixed} [options.data] Arbitrary data object to pass to "on*" callbacks. @property {Document} [options.doc] Document into which nodes should be inserted. By default, the current document is used. @property {HTMLElement|String} [options.insertBefore] HTML element or id string of an element before which all generated nodes should be inserted. If not specified, Get will automatically determine the best place to insert nodes for maximum compatibility. @property {Function} [options.onEnd] Callback to execute after a transaction is complete, regardless of whether it succeeded or failed. @property {Function} [options.onFailure] Callback to execute after a transaction fails, times out, or is aborted. @property {Function} [options.onProgress] Callback to execute after each individual request in a transaction either succeeds or fails. @property {Function} [options.onSuccess] Callback to execute after a transaction completes successfully with no errors. Note that in browsers that don't support the `error` event on CSS `<link>` nodes, a failed CSS request may still be reported as a success because in these browsers it can be difficult or impossible to distinguish between success and failure for CSS resources. @property {Function} [options.onTimeout] Callback to execute after a transaction times out. @property {Number} [options.pollInterval=50] Polling interval (in milliseconds) for detecting CSS load completion in browsers that don't support the `load` event on `<link>` nodes. This isn't used for JavaScript. @property {Number} [options.purgethreshold=20] Number of nodes to insert before triggering an automatic purge when `autopurge` is `true`. @property {Number} [options.timeout] Number of milliseconds to wait before aborting a transaction. When a timeout occurs, the `onTimeout` callback is called, followed by `onFailure` and finally `onEnd`. By default, there is no timeout. @property {String} [options.type] Resource type ("css" or "js"). This option is set automatically by the `css()` and `js()` functions and will be ignored there, but may be useful when using the `load()` function. If not specified, the type will be inferred from the URL, defaulting to "js" if the URL doesn't contain a recognizable file extension. **/ options: { attributes: { charset: 'utf-8' }, purgethreshold: 20 }, // -- Protected Properties ------------------------------------------------- /** Regex that matches a CSS URL. Used to guess the file type when it's not specified. @property REGEX_CSS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_CSS: /\.css(?:[?;].*)?$/i, /** Regex that matches a JS URL. Used to guess the file type when it's not specified. @property REGEX_JS @type RegExp @final @protected @static @since 3.5.0 **/ REGEX_JS : /\.js(?:[?;].*)?$/i, /** Contains information about the current environment, such as what script and link injection features it supports. This object is created and populated the first time the `_getEnv()` method is called. @property _env @type Object @protected @static @since 3.5.0 **/ /** Mapping of document _yuid strings to <head> or <base> node references so we don't have to look the node up each time we want to insert a request node. @property _insertCache @type Object @protected @static @since 3.5.0 **/ _insertCache: {}, /** Information about the currently pending transaction, if any. This is actually an object with two properties: `callback`, containing the optional callback passed to `css()`, `load()`, or `js()`; and `transaction`, containing the actual transaction instance. @property _pending @type Object @protected @static @since 3.5.0 **/ _pending: null, /** HTML nodes eligible to be purged next time autopurge is triggered. @property _purgeNodes @type HTMLElement[] @protected @static @since 3.5.0 **/ _purgeNodes: [], /** Queued transactions and associated callbacks. @property _queue @type Object[] @protected @static @since 3.5.0 **/ _queue: [], // -- Public Methods ------------------------------------------------------- /** Aborts the specified transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). *Note:* This method is deprecated as of 3.5.0, and will be removed in a future version of YUI. Use the transaction-level `abort()` method instead. @method abort @param {Get.Transaction} transaction Transaction to abort. @deprecated Use the `abort()` method on the transaction instead. @static **/ abort: function (transaction) { var i, id, item, len, pending; Y.log('`Y.Get.abort()` is deprecated as of 3.5.0. Use the `abort()` method on the transaction instead.', 'warn', 'get'); if (!transaction.abort) { id = transaction; pending = this._pending; transaction = null; if (pending && pending.transaction.id === id) { transaction = pending.transaction; this._pending = null; } else { for (i = 0, len = this._queue.length; i < len; ++i) { item = this._queue[i].transaction; if (item.id === id) { transaction = item; this._queue.splice(i, 1); break; } } } } transaction && transaction.abort(); }, /** Loads one or more CSS files. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. @example // Load a single CSS file and log a message on completion. Y.Get.css('foo.css', function (err) { if (err) { Y.log('foo.css failed to load!'); } else { Y.log('foo.css was loaded successfully'); } }); // Load multiple CSS files and log a message when all have finished // loading. var urls = ['foo.css', 'http://example.com/bar.css', 'baz/quux.css']; Y.Get.css(urls, function (err) { if (err) { Y.log('one or more files failed to load!'); } else { Y.log('all files loaded successfully'); } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.css(urls, { attributes: {'class': 'my-css'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.css([ {url: 'foo.css', attributes: {id: 'foo'}}, {url: 'bar.css', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method css @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @static **/ css: function (urls, options, callback) { return this._load('css', urls, options, callback); }, /** Loads one or more JavaScript resources. The _urls_ parameter may be provided as a URL string, a request object, or an array of URL strings and/or request objects. A request object is just an object that contains a `url` property and zero or more options that should apply specifically to that request. Request-specific options take priority over transaction-level options and default options. URLs may be relative or absolute, and do not have to have the same origin as the current page. The `options` parameter may be omitted completely and a callback passed in its place, if desired. Scripts will be executed in the order they're specified unless the `async` option is `true`, in which case they'll be loaded in parallel and executed in whatever order they finish loading. @example // Load a single JS file and log a message on completion. Y.Get.js('foo.js', function (err) { if (err) { Y.log('foo.js failed to load!'); } else { Y.log('foo.js was loaded successfully'); } }); // Load multiple JS files, execute them in order, and log a message when // all have finished loading. var urls = ['foo.js', 'http://example.com/bar.js', 'baz/quux.js']; Y.Get.js(urls, function (err) { if (err) { Y.log('one or more files failed to load!'); } else { Y.log('all files loaded successfully'); } }); // Specify transaction-level options, which will apply to all requests // within the transaction. Y.Get.js(urls, { attributes: {'class': 'my-js'}, timeout : 5000 }); // Specify per-request options, which override transaction-level and // default options. Y.Get.js([ {url: 'foo.js', attributes: {id: 'foo'}}, {url: 'bar.js', attributes: {id: 'bar', charset: 'iso-8859-1'}} ]); @method js @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} callback.err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} callback.transaction Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ js: function (urls, options, callback) { return this._load('js', urls, options, callback); }, /** Loads one or more CSS and/or JavaScript resources in the same transaction. Use this method when you want to load both CSS and JavaScript in a single transaction and be notified when all requested URLs have finished loading, regardless of type. Behavior and options are the same as for the `css()` and `js()` methods. If a resource type isn't specified in per-request options or transaction-level options, Get will guess the file type based on the URL's extension (`.css` or `.js`, with or without a following query string). If the file type can't be guessed from the URL, a warning will be logged and Get will assume the URL is a JavaScript resource. @example // Load both CSS and JS files in a single transaction, and log a message // when all files have finished loading. Y.Get.load(['foo.css', 'bar.js', 'baz.css'], function (err) { if (err) { Y.log('one or more files failed to load!'); } else { Y.log('all files loaded successfully'); } }); @method load @param {String|Object|Array} urls URL string, request object, or array of URLs and/or request objects to load. @param {Object} [options] Options for this transaction. See the `Y.Get.options` property for a complete list of available options. @param {Function} [callback] Callback function to be called on completion. This is a general callback and will be called before any more granular callbacks (`onSuccess`, `onFailure`, etc.) specified in the `options` object. @param {Array|null} err Array of errors that occurred during the transaction, or `null` on success. @param {Get.Transaction} Transaction object. @return {Get.Transaction} Transaction object. @since 3.5.0 @static **/ load: function (urls, options, callback) { return this._load(null, urls, options, callback); }, // -- Protected Methods ---------------------------------------------------- /** Triggers an automatic purge if the purge threshold has been reached. @method _autoPurge @param {Number} threshold Purge threshold to use, in milliseconds. @protected @since 3.5.0 @static **/ _autoPurge: function (threshold) { if (threshold && this._purgeNodes.length >= threshold) { Y.log('autopurge triggered after ' + this._purgeNodes.length + ' nodes', 'info', 'get'); this._purge(this._purgeNodes); } }, /** Populates the `_env` property with information about the current environment. @method _getEnv @return {Object} Environment information. @protected @since 3.5.0 @static **/ _getEnv: function () { var doc = Y.config.doc, ua = Y.UA; // Note: some of these checks require browser sniffs since it's not // feasible to load test files on every pageview just to perform a // feature test. I'm sorry if this makes you sad. return (this._env = { // True if this is a browser that supports disabling async mode on // dynamically created script nodes. See // https://developer.mozilla.org/En/HTML/Element/Script#Attributes // IE10 doesn't return true for the MDN feature test, so setting it explicitly, // because it is async by default, and allows you to disable async by setting it to false async: (doc && doc.createElement('script').async === true) || (ua.ie >= 10), // True if this browser fires an event when a dynamically injected // link node fails to load. This is currently true for Firefox 9+ // and WebKit 535.24+ cssFail: ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0, // True if this browser fires an event when a dynamically injected // link node finishes loading. This is currently true for IE, Opera, // Firefox 9+, and WebKit 535.24+. Note that IE versions <9 fire the // DOM 0 "onload" event, but not "load". All versions of IE fire // "onload". // davglass: Seems that Chrome on Android needs this to be false. cssLoad: ( (!ua.gecko && !ua.webkit) || ua.gecko >= 9 || ua.compareVersions(ua.webkit, 535.24) >= 0 ) && !(ua.chrome && ua.chrome <= 18), // True if this browser preserves script execution order while // loading scripts in parallel as long as the script node's `async` // attribute is set to false to explicitly disable async execution. preservesScriptOrder: !!(ua.gecko || ua.opera || (ua.ie && ua.ie >= 10)) }); }, _getTransaction: function (urls, options) { var requests = [], i, len, req, url; if (!Lang.isArray(urls)) { urls = [urls]; } options = Y.merge(this.options, options); // Clone the attributes object so we don't end up modifying it by ref. options.attributes = Y.merge(this.options.attributes, options.attributes); for (i = 0, len = urls.length; i < len; ++i) { url = urls[i]; req = {attributes: {}}; // If `url` is a string, we create a URL object for it, then mix in // global options and request-specific options. If it's an object // with a "url" property, we assume it's a request object containing // URL-specific options. if (typeof url === 'string') { req.url = url; } else if (url.url) { // URL-specific options override both global defaults and // request-specific options. Y.mix(req, url, false, null, 0, true); url = url.url; // Make url a string so we can use it later. } else { Y.log('URL must be a string or an object with a `url` property.', 'error', 'get'); continue; } Y.mix(req, options, false, null, 0, true); // If we didn't get an explicit type for this URL either in the // request options or the URL-specific options, try to determine // one from the file extension. if (!req.type) { if (this.REGEX_CSS.test(url)) { req.type = 'css'; } else { if (!this.REGEX_JS.test(url)) { Y.log("Can't guess file type from URL. Assuming JS: " + url, 'warn', 'get'); } req.type = 'js'; } } // Mix in type-specific default options, but don't overwrite any // options that have already been set. Y.mix(req, req.type === 'js' ? this.jsOptions : this.cssOptions, false, null, 0, true); // Give the node an id attribute if it doesn't already have one. req.attributes.id || (req.attributes.id = Y.guid()); // Backcompat for <3.5.0 behavior. if (req.win) { Y.log('The `win` option is deprecated as of 3.5.0. Use `doc` instead.', 'warn', 'get'); req.doc = req.win.document; } else { req.win = req.doc.defaultView || req.doc.parentWindow; } if (req.charset) { Y.log('The `charset` option is deprecated as of 3.5.0. Set `attributes.charset` instead.', 'warn', 'get'); req.attributes.charset = req.charset; } requests.push(req); } return new Transaction(requests, options); }, _load: function (type, urls, options, callback) { var transaction; // Allow callback as third param. if (typeof options === 'function') { callback = options; options = {}; } options || (options = {}); options.type = type; options._onFinish = Get._onTransactionFinish; if (!this._env) { this._getEnv(); } transaction = this._getTransaction(urls, options); this._queue.push({ callback : callback, transaction: transaction }); this._next(); return transaction; }, _onTransactionFinish : function() { Get._pending = null; Get._next(); }, _next: function () { var item; if (this._pending) { return; } item = this._queue.shift(); if (item) { this._pending = item; item.transaction.execute(item.callback); } }, _purge: function (nodes) { var purgeNodes = this._purgeNodes, isTransaction = nodes !== purgeNodes, index, node; while (node = nodes.pop()) { // assignment // Don't purge nodes that haven't finished loading (or errored out), // since this can hang the transaction. if (!node._yuiget_finished) { continue; } node.parentNode && node.parentNode.removeChild(node); // If this is a transaction-level purge and this node also exists in // the Get-level _purgeNodes array, we need to remove it from // _purgeNodes to avoid creating a memory leak. The indexOf lookup // sucks, but until we get WeakMaps, this is the least troublesome // way to do this (we can't just hold onto node ids because they may // not be in the same document). if (isTransaction) { index = Y.Array.indexOf(purgeNodes, node); if (index > -1) { purgeNodes.splice(index, 1); } } } } }; /** Alias for `js()`. @method script @static **/ Get.script = Get.js; /** Represents a Get transaction, which may contain requests for one or more JS or CSS files. This class should not be instantiated manually. Instances will be created and returned as needed by Y.Get's `css()`, `js()`, and `load()` methods. @class Get.Transaction @constructor @since 3.5.0 **/ Get.Transaction = Transaction = function (requests, options) { var self = this; self.id = Transaction._lastId += 1; self.data = options.data; self.errors = []; self.nodes = []; self.options = options; self.requests = requests; self._callbacks = []; // callbacks to call after execution finishes self._queue = []; self._reqsWaiting = 0; // Deprecated pre-3.5.0 properties. self.tId = self.id; // Use `id` instead. self.win = options.win || Y.config.win; }; /** Arbitrary data object associated with this transaction. This object comes from the options passed to `Get.css()`, `Get.js()`, or `Get.load()`, and will be `undefined` if no data object was specified. @property {Object} data **/ /** Array of errors that have occurred during this transaction, if any. @since 3.5.0 @property {Object[]} errors @property {String} errors.error Error message. @property {Object} errors.request Request object related to the error. **/ /** Numeric id for this transaction, unique among all transactions within the same YUI sandbox in the current pageview. @property {Number} id @since 3.5.0 **/ /** HTMLElement nodes (native ones, not YUI Node instances) that have been inserted during the current transaction. @property {HTMLElement[]} nodes **/ /** Options associated with this transaction. See `Get.options` for the full list of available options. @property {Object} options @since 3.5.0 **/ /** Request objects contained in this transaction. Each request object represents one CSS or JS URL that will be (or has been) requested and loaded into the page. @property {Object} requests @since 3.5.0 **/ /** Id of the most recent transaction. @property _lastId @type Number @protected @static **/ Transaction._lastId = 0; Transaction.prototype = { // -- Public Properties ---------------------------------------------------- /** Current state of this transaction. One of "new", "executing", or "done". @property _state @type String @protected **/ _state: 'new', // "new", "executing", or "done" // -- Public Methods ------------------------------------------------------- /** Aborts this transaction. This will cause the transaction's `onFailure` callback to be called and will prevent any new script and link nodes from being added to the document, but any resources that have already been requested will continue loading (there's no safe way to prevent this, unfortunately). @method abort @param {String} [msg="Aborted."] Optional message to use in the `errors` array describing why the transaction was aborted. **/ abort: function (msg) { this._pending = null; this._pendingCSS = null; this._pollTimer = clearTimeout(this._pollTimer); this._queue = []; this._reqsWaiting = 0; this.errors.push({error: msg || 'Aborted'}); this._finish(); }, /** Begins execting the transaction. There's usually no reason to call this manually, since Get will call it automatically when other pending transactions have finished. If you really want to execute your transaction before Get does, you can, but be aware that this transaction's scripts may end up executing before the scripts in other pending transactions. If the transaction is already executing, the specified callback (if any) will be queued and called after execution finishes. If the transaction has already finished, the callback will be called immediately (the transaction will not be executed again). @method execute @param {Function} callback Callback function to execute after all requests in the transaction are complete, or after the transaction is aborted. **/ execute: function (callback) { var self = this, requests = self.requests, state = self._state, i, len, queue, req; if (state === 'done') { callback && callback(self.errors.length ? self.errors : null, self); return; } else { callback && self._callbacks.push(callback); if (state === 'executing') { return; } } self._state = 'executing'; self._queue = queue = []; if (self.options.timeout) { self._timeout = setTimeout(function () { self.abort('Timeout'); }, self.options.timeout); } self._reqsWaiting = requests.length; for (i = 0, len = requests.length; i < len; ++i) { req = requests[i]; if (req.async || req.type === 'css') { // No need to queue CSS or fully async JS. self._insert(req); } else { queue.push(req); } } self._next(); }, /** Manually purges any `<script>` or `<link>` nodes this transaction has created. Be careful when purging a transaction that contains CSS requests, since removing `<link>` nodes will also remove any styles they applied. @method purge **/ purge: function () { Get._purge(this.nodes); }, // -- Protected Methods ---------------------------------------------------- _createNode: function (name, attrs, doc) { var node = doc.createElement(name), attr, testEl; if (!CUSTOM_ATTRS) { // IE6 and IE7 expect property names rather than attribute names for // certain attributes. Rather than sniffing, we do a quick feature // test the first time _createNode() runs to determine whether we // need to provide a workaround. testEl = doc.createElement('div'); testEl.setAttribute('class', 'a'); CUSTOM_ATTRS = testEl.className === 'a' ? {} : { 'for' : 'htmlFor', 'class': 'className' }; } for (attr in attrs) { if (attrs.hasOwnProperty(attr)) { node.setAttribute(CUSTOM_ATTRS[attr] || attr, attrs[attr]); } } return node; }, _finish: function () { var errors = this.errors.length ? this.errors : null, options = this.options, thisObj = options.context || this, data, i, len; if (this._state === 'done') { return; } this._state = 'done'; for (i = 0, len = this._callbacks.length; i < len; ++i) { this._callbacks[i].call(thisObj, errors, this); } data = this._getEventData(); if (errors) { if (options.onTimeout && errors[errors.length - 1].error === 'Timeout') { options.onTimeout.call(thisObj, data); } if (options.onFailure) { options.onFailure.call(thisObj, data); } } else if (options.onSuccess) { options.onSuccess.call(thisObj, data); } if (options.onEnd) { options.onEnd.call(thisObj, data); } if (options._onFinish) { options._onFinish(); } }, _getEventData: function (req) { if (req) { // This merge is necessary for backcompat. I hate it. return Y.merge(this, { abort : this.abort, // have to copy these because the prototype isn't preserved purge : this.purge, request: req, url : req.url, win : req.win }); } else { return this; } }, _getInsertBefore: function (req) { var doc = req.doc, el = req.insertBefore, cache, docStamp; if (el) { return typeof el === 'string' ? doc.getElementById(el) : el; } cache = Get._insertCache; docStamp = Y.stamp(doc); if ((el = cache[docStamp])) { // assignment return el; } // Inserting before a <base> tag apparently works around an IE bug // (according to a comment from pre-3.5.0 Y.Get), but I'm not sure what // bug that is, exactly. Better safe than sorry? if ((el = doc.getElementsByTagName('base')[0])) { // assignment return (cache[docStamp] = el); } // Look for a <head> element. el = doc.head || doc.getElementsByTagName('head')[0]; if (el) { // Create a marker node at the end of <head> to use as an insertion // point. Inserting before this node will ensure that all our CSS // gets inserted in the correct order, to maintain style precedence. el.appendChild(doc.createTextNode('')); return (cache[docStamp] = el.lastChild); } // If all else fails, just insert before the first script node on the // page, which is virtually guaranteed to exist. return (cache[docStamp] = doc.getElementsByTagName('script')[0]); }, _insert: function (req) { var env = Get._env, insertBefore = this._getInsertBefore(req), isScript = req.type === 'js', node = req.node, self = this, ua = Y.UA, cssTimeout, nodeType; if (!node) { if (isScript) { nodeType = 'script'; } else if (!env.cssLoad && ua.gecko) { nodeType = 'style'; } else { nodeType = 'link'; } node = req.node = this._createNode(nodeType, req.attributes, req.doc); } function onError() { self._progress('Failed to load ' + req.url, req); } function onLoad() { if (cssTimeout) { clearTimeout(cssTimeout); } self._progress(null, req); } // Deal with script asynchronicity. if (isScript) { node.setAttribute('src', req.url); if (req.async) { // Explicitly indicate that we want the browser to execute this // script asynchronously. This is necessary for older browsers // like Firefox <4. node.async = true; } else { if (env.async) { // This browser treats injected scripts as async by default // (standard HTML5 behavior) but asynchronous loading isn't // desired, so tell the browser not to mark this script as // async. node.async = false; } // If this browser doesn't preserve script execution order based // on insertion order, we'll need to avoid inserting other // scripts until this one finishes loading. if (!env.preservesScriptOrder) { this._pending = req; } } } else { if (!env.cssLoad && ua.gecko) { // In Firefox <9, we can import the requested URL into a <style> // node and poll for the existence of node.sheet.cssRules. This // gives us a reliable way to determine CSS load completion that // also works for cross-domain stylesheets. // // Props to Zach Leatherman for calling my attention to this // technique. node.innerHTML = (req.attributes.charset ? '@charset "' + req.attributes.charset + '";' : '') + '@import "' + req.url + '";'; } else { node.setAttribute('href', req.url); } } // Inject the node. if (isScript && ua.ie && (ua.ie < 9 || (document.documentMode && document.documentMode < 9))) { // Script on IE < 9, and IE 9+ when in IE 8 or older modes, including quirks mode. node.onreadystatechange = function () { if (/loaded|complete/.test(node.readyState)) { node.onreadystatechange = null; onLoad(); } }; } else if (!isScript && !env.cssLoad) { // CSS on Firefox <9 or WebKit. this._poll(req); } else { // Script or CSS on everything else. Using DOM 0 events because that // evens the playing field with older IEs. if (ua.ie >= 10) { // We currently need to introduce a timeout for IE10, since it // calls onerror/onload synchronously for 304s - messing up existing // program flow. // Remove this block if the following bug gets fixed by GA /*jshint maxlen: 1500 */ // https://connect.microsoft.com/IE/feedback/details/763871/dynamically-loaded-scripts-with-304s-responses-interrupt-the-currently-executing-js-thread-onload node.onerror = function() { setTimeout(onError, 0); }; node.onload = function() { setTimeout(onLoad, 0); }; } else { node.onerror = onError; node.onload = onLoad; } // If this browser doesn't fire an event when CSS fails to load, // fail after a timeout to avoid blocking the transaction queue. if (!env.cssFail && !isScript) { cssTimeout = setTimeout(onError, req.timeout || 3000); } } this.nodes.push(node); insertBefore.parentNode.insertBefore(node, insertBefore); }, _next: function () { if (this._pending) { return; } // If there are requests in the queue, insert the next queued request. // Otherwise, if we're waiting on already-inserted requests to finish, // wait longer. If there are no queued requests and we're not waiting // for anything to load, then we're done! if (this._queue.length) { this._insert(this._queue.shift()); } else if (!this._reqsWaiting) { this._finish(); } }, _poll: function (newReq) { var self = this, pendingCSS = self._pendingCSS, isWebKit = Y.UA.webkit, i, hasRules, j, nodeHref, req, sheets; if (newReq) { pendingCSS || (pendingCSS = self._pendingCSS = []); pendingCSS.push(newReq); if (self._pollTimer) { // A poll timeout is already pending, so no need to create a // new one. return; } } self._pollTimer = null; // Note: in both the WebKit and Gecko hacks below, a CSS URL that 404s // will still be treated as a success. There's no good workaround for // this. for (i = 0; i < pendingCSS.length; ++i) { req = pendingCSS[i]; if (isWebKit) { // Look for a stylesheet matching the pending URL. sheets = req.doc.styleSheets; j = sheets.length; nodeHref = req.node.href; while (--j >= 0) { if (sheets[j].href === nodeHref) { pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); break; } } } else { // Many thanks to Zach Leatherman for calling my attention to // the @import-based cross-domain technique used here, and to // Oleg Slobodskoi for an earlier same-domain implementation. // // See Zach's blog for more details: // http://www.zachleat.com/web/2010/07/29/load-css-dynamically/ try { // We don't really need to store this value since we never // use it again, but if we don't store it, Closure Compiler // assumes the code is useless and removes it. hasRules = !!req.node.sheet.cssRules; // If we get here, the stylesheet has loaded. pendingCSS.splice(i, 1); i -= 1; self._progress(null, req); } catch (ex) { // An exception means the stylesheet is still loading. } } } if (pendingCSS.length) { self._pollTimer = setTimeout(function () { self._poll.call(self); }, self.options.pollInterval); } }, _progress: function (err, req) { var options = this.options; if (err) { req.error = err; this.errors.push({ error : err, request: req }); Y.log(err, 'error', 'get'); } req.node._yuiget_finished = req.finished = true; if (options.onProgress) { options.onProgress.call(options.context || this, this._getEventData(req)); } if (req.autopurge) { // Pre-3.5.0 Get always excludes the most recent node from an // autopurge. I find this odd, but I'm keeping that behavior for // the sake of backcompat. Get._autoPurge(this.options.purgethreshold); Get._purgeNodes.push(req.node); } if (this._pending === req) { this._pending = null; } this._reqsWaiting -= 1; this._next(); } }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { Y.log('Feature test ' + cat + ', ' + name + ' not found'); } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('intl-base', function (Y, NAME) { /** * The Intl utility provides a central location for managing sets of * localized resources (strings and formatting patterns). * * @class Intl * @uses EventTarget * @static */ var SPLIT_REGEX = /[, ]/; Y.mix(Y.namespace('Intl'), { /** * Returns the language among those available that * best matches the preferred language list, using the Lookup * algorithm of BCP 47. * If none of the available languages meets the user's preferences, * then "" is returned. * Extended language ranges are not supported. * * @method lookupBestLang * @param {String[] | String} preferredLanguages The list of preferred * languages in descending preference order, represented as BCP 47 * language tags. A string array or a comma-separated list. * @param {String[]} availableLanguages The list of languages * that the application supports, represented as BCP 47 language * tags. * * @return {String} The available language that best matches the * preferred language list, or "". * @since 3.1.0 */ lookupBestLang: function(preferredLanguages, availableLanguages) { var i, language, result, index; // check whether the list of available languages contains language; // if so return it function scan(language) { var i; for (i = 0; i < availableLanguages.length; i += 1) { if (language.toLowerCase() === availableLanguages[i].toLowerCase()) { return availableLanguages[i]; } } } if (Y.Lang.isString(preferredLanguages)) { preferredLanguages = preferredLanguages.split(SPLIT_REGEX); } for (i = 0; i < preferredLanguages.length; i += 1) { language = preferredLanguages[i]; if (!language || language === '*') { continue; } // check the fallback sequence for one language while (language.length > 0) { result = scan(language); if (result) { return result; } else { index = language.lastIndexOf('-'); if (index >= 0) { language = language.substring(0, index); // one-character subtags get cut along with the // following subtag if (index >= 2 && language.charAt(index - 2) === '-') { language = language.substring(0, index - 2); } } else { // nothing available for this language break; } } } } return ''; } }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 2, warn: 4, error: 8 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, minlevel, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } // Determine the current minlevel as defined in configuration Y.config.logLevel = Y.config.logLevel || 'debug'; minlevel = LEVELS[Y.config.logLevel.toLowerCase()]; if (cat in LEVELS && LEVELS[cat] < minlevel) { // Skip this message if the we don't meet the defined minlevel bail = 1; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console !== UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera !== UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher === Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui-later', function (Y, NAME) { /** * Provides a setTimeout/setInterval wrapper. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_later">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-later */ var NO_ARGS = []; /** * Executes the supplied function in the context of the supplied * object 'when' milliseconds later. Executes the function a * single time unless periodic is set to true. * @for YUI * @method later * @param when {int} the number of milliseconds to wait until the fn * is executed. * @param o the context object. * @param fn {Function|String} the function to execute or the name of * the method in the 'o' object to execute. * @param data [Array] data that is provided to the function. This * accepts either a single item or an array. If an array is provided, * the function is executed with one parameter for each array item. * If you need to pass a single array parameter, it needs to be wrapped * in an array [myarray]. * * Note: native methods in IE may not have the call and apply methods. * In this case, it will work, but you are limited to four arguments. * * @param periodic {boolean} if true, executes continuously at supplied * interval until canceled. * @return {object} a timer object. Call the cancel() method on this * object to stop the timer. */ Y.later = function(when, o, fn, data, periodic) { when = when || 0; data = (!Y.Lang.isUndefined(data)) ? Y.Array(data) : NO_ARGS; o = o || Y.config.win || Y; var cancelled = false, method = (o && Y.Lang.isString(fn)) ? o[fn] : fn, wrapper = function() { // IE 8- may execute a setInterval callback one last time // after clearInterval was called, so in order to preserve // the cancel() === no more runny-run, we have to jump through // an extra hoop. if (!cancelled) { if (!method.apply) { method(data[0], data[1], data[2], data[3]); } else { method.apply(o, data || NO_ARGS); } } }, id = (periodic) ? setInterval(wrapper, when) : setTimeout(wrapper, when); return { id: id, interval: periodic, cancel: function() { cancelled = true; if (this.interval) { clearInterval(id); } else { clearTimeout(id); } } }; }; Y.Lang.later = Y.later; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('yui', function (Y, NAME) {}, '@VERSION@', {"use": ["get", "features", "intl-base", "yui-log", "yui-later"]}); YUI.add('oop', function (Y, NAME) { /** Adds object inheritance and manipulation utilities to the YUI instance. This module is required by most YUI components. @module oop **/ var L = Y.Lang, A = Y.Array, OP = Object.prototype, CLONE_MARKER = '_~yuim~_', hasOwn = OP.hasOwnProperty, toString = OP.toString; function dispatch(o, f, c, proto, action) { if (o && o[action] && o !== Y) { return o[action].call(o, f, c); } else { switch (A.test(o)) { case 1: return A[action](o, f, c); case 2: return A[action](Y.Array(o, 0, true), f, c); default: return Y.Object[action](o, f, c, proto); } } } /** Augments the _receiver_ with prototype properties from the _supplier_. The receiver may be a constructor function or an object. The supplier must be a constructor function. If the _receiver_ is an object, then the _supplier_ constructor will be called immediately after _receiver_ is augmented, with _receiver_ as the `this` object. If the _receiver_ is a constructor function, then all prototype methods of _supplier_ that are copied to _receiver_ will be sequestered, and the _supplier_ constructor will not be called immediately. The first time any sequestered method is called on the _receiver_'s prototype, all sequestered methods will be immediately copied to the _receiver_'s prototype, the _supplier_'s constructor will be executed, and finally the newly unsequestered method that was called will be executed. This sequestering logic sounds like a bunch of complicated voodoo, but it makes it cheap to perform frequent augmentation by ensuring that suppliers' constructors are only called if a supplied method is actually used. If none of the supplied methods is ever used, then there's no need to take the performance hit of calling the _supplier_'s constructor. @method augment @param {Function|Object} receiver Object or function to be augmented. @param {Function} supplier Function that supplies the prototype properties with which to augment the _receiver_. @param {Boolean} [overwrite=false] If `true`, properties already on the receiver will be overwritten if found on the supplier's prototype. @param {String[]} [whitelist] An array of property names. If specified, only the whitelisted prototype properties will be applied to the receiver, and all others will be ignored. @param {Array|any} [args] Argument or array of arguments to pass to the supplier's constructor when initializing. @return {Function} Augmented object. @for YUI **/ Y.augment = function (receiver, supplier, overwrite, whitelist, args) { var rProto = receiver.prototype, sequester = rProto && supplier, sProto = supplier.prototype, to = rProto || receiver, copy, newPrototype, replacements, sequestered, unsequester; args = args ? Y.Array(args) : []; if (sequester) { newPrototype = {}; replacements = {}; sequestered = {}; copy = function (value, key) { if (overwrite || !(key in rProto)) { if (toString.call(value) === '[object Function]') { sequestered[key] = value; newPrototype[key] = replacements[key] = function () { return unsequester(this, value, arguments); }; } else { newPrototype[key] = value; } } }; unsequester = function (instance, fn, fnArgs) { // Unsequester all sequestered functions. for (var key in sequestered) { if (hasOwn.call(sequestered, key) && instance[key] === replacements[key]) { instance[key] = sequestered[key]; } } // Execute the supplier constructor. supplier.apply(instance, args); // Finally, execute the original sequestered function. return fn.apply(instance, fnArgs); }; if (whitelist) { Y.Array.each(whitelist, function (name) { if (name in sProto) { copy(sProto[name], name); } }); } else { Y.Object.each(sProto, copy, null, true); } } Y.mix(to, newPrototype || sProto, overwrite, whitelist); if (!sequester) { supplier.apply(to, args); } return receiver; }; /** * Copies object properties from the supplier to the receiver. If the target has * the property, and the property is an object, the target object will be * augmented with the supplier's value. * * @method aggregate * @param {Object} receiver Object to receive the augmentation. * @param {Object} supplier Object that supplies the properties with which to * augment the receiver. * @param {Boolean} [overwrite=false] If `true`, properties already on the receiver * will be overwritten if found on the supplier. * @param {String[]} [whitelist] Whitelist. If supplied, only properties in this * list will be applied to the receiver. * @return {Object} Augmented object. */ Y.aggregate = function(r, s, ov, wl) { return Y.mix(r, s, ov, wl, 0, true); }; /** * Utility to set up the prototype, constructor and superclass properties to * support an inheritance strategy that can chain constructors and methods. * Static members will not be inherited. * * @method extend * @param {function} r the object to modify. * @param {function} s the object to inherit. * @param {object} px prototype properties to add/override. * @param {object} sx static properties to add/override. * @return {object} the extended object. */ Y.extend = function(r, s, px, sx) { if (!s || !r) { Y.error('extend failed, verify dependencies'); } var sp = s.prototype, rp = Y.Object(sp); r.prototype = rp; rp.constructor = r; r.superclass = sp; // assign constructor property if (s != Object && sp.constructor == OP.constructor) { sp.constructor = s; } // add prototype overrides if (px) { Y.mix(rp, px, true); } // add object overrides if (sx) { Y.mix(r, sx, true); } return r; }; /** * Executes the supplied function for each item in * a collection. Supports arrays, objects, and * NodeLists * @method each * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {YUI} the YUI instance. */ Y.each = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'each'); }; /** * Executes the supplied function for each item in * a collection. The operation stops if the function * returns true. Supports arrays, objects, and * NodeLists. * @method some * @param {object} o the object to iterate. * @param {function} f the function to execute. This function * receives the value, key, and object as parameters. * @param {object} c the execution context for the function. * @param {boolean} proto if true, prototype properties are * iterated on objects. * @return {boolean} true if the function ever returns true, * false otherwise. */ Y.some = function(o, f, c, proto) { return dispatch(o, f, c, proto, 'some'); }; /** Deep object/array copy. Function clones are actually wrappers around the original function. Array-like objects are treated as arrays. Primitives are returned untouched. Optionally, a function can be provided to handle other data types, filter keys, validate values, etc. **Note:** Cloning a non-trivial object is a reasonably heavy operation, due to the need to recursively iterate down non-primitive properties. Clone should be used only when a deep clone down to leaf level properties is explicitly required. This method will also In many cases (for example, when trying to isolate objects used as hashes for configuration properties), a shallow copy, using `Y.merge()` is normally sufficient. If more than one level of isolation is required, `Y.merge()` can be used selectively at each level which needs to be isolated from the original without going all the way to leaf properties. @method clone @param {object} o what to clone. @param {boolean} safe if true, objects will not have prototype items from the source. If false, they will. In this case, the original is initially protected, but the clone is not completely immune from changes to the source object prototype. Also, cloned prototype items that are deleted from the clone will result in the value of the source prototype being exposed. If operating on a non-safe clone, items should be nulled out rather than deleted. @param {function} f optional function to apply to each item in a collection; it will be executed prior to applying the value to the new object. Return false to prevent the copy. @param {object} c optional execution context for f. @param {object} owner Owner object passed when clone is iterating an object. Used to set up context for cloned functions. @param {object} cloned hash of previously cloned objects to avoid multiple clones. @return {Array|Object} the cloned object. **/ Y.clone = function(o, safe, f, c, owner, cloned) { var o2, marked, stamp; // Does not attempt to clone: // // * Non-typeof-object values, "primitive" values don't need cloning. // // * YUI instances, cloning complex object like YUI instances is not // advised, this is like cloning the world. // // * DOM nodes (#2528250), common host objects like DOM nodes cannot be // "subclassed" in Firefox and old versions of IE. Trying to use // `Object.create()` or `Y.extend()` on a DOM node will throw an error in // these browsers. // // Instad, the passed-in `o` will be return as-is when it matches one of the // above criteria. if (!L.isObject(o) || Y.instanceOf(o, YUI) || (o.addEventListener || o.attachEvent)) { return o; } marked = cloned || {}; switch (L.type(o)) { case 'date': return new Date(o); case 'regexp': // if we do this we need to set the flags too // return new RegExp(o.source); return o; case 'function': // o2 = Y.bind(o, owner); // break; return o; case 'array': o2 = []; break; default: // #2528250 only one clone of a given object should be created. if (o[CLONE_MARKER]) { return marked[o[CLONE_MARKER]]; } stamp = Y.guid(); o2 = (safe) ? {} : Y.Object(o); o[CLONE_MARKER] = stamp; marked[stamp] = o; } Y.each(o, function(v, k) { if ((k || k === 0) && (!f || (f.call(c || this, v, k, this, o) !== false))) { if (k !== CLONE_MARKER) { if (k == 'prototype') { // skip the prototype // } else if (o[k] === o) { // this[k] = this; } else { this[k] = Y.clone(v, safe, f, c, owner || o, marked); } } } }, o2); if (!cloned) { Y.Object.each(marked, function(v, k) { if (v[CLONE_MARKER]) { try { delete v[CLONE_MARKER]; } catch (e) { v[CLONE_MARKER] = null; } } }, this); marked = null; } return o2; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the beginning of the arguments collection the * supplied to the function. * * @method bind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to include before the arguments the * function is executed with. * @return {function} the wrapped function. */ Y.bind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? xargs.concat(Y.Array(arguments, 0, true)) : arguments; return fn.apply(c || fn, args); }; }; /** * Returns a function that will execute the supplied function in the * supplied object's context, optionally adding any additional * supplied parameters to the end of the arguments the function * is executed with. * * @method rbind * @param {Function|String} f the function to bind, or a function name * to execute on the context object. * @param {object} c the execution context. * @param {any} args* 0..n arguments to append to the end of * arguments collection supplied to the function. * @return {function} the wrapped function. */ Y.rbind = function(f, c) { var xargs = arguments.length > 2 ? Y.Array(arguments, 2, true) : null; return function() { var fn = L.isString(f) ? c[f] : f, args = (xargs) ? Y.Array(arguments, 0, true).concat(xargs) : arguments; return fn.apply(c || fn, args); }; }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('features', function (Y, NAME) { var feature_tests = {}; /** Contains the core of YUI's feature test architecture. @module features */ /** * Feature detection * @class Features * @static */ Y.mix(Y.namespace('Features'), { /** * Object hash of all registered feature tests * @property tests * @type Object */ tests: feature_tests, /** * Add a test to the system * * ``` * Y.Features.add("load", "1", {}); * ``` * * @method add * @param {String} cat The category, right now only 'load' is supported * @param {String} name The number sequence of the test, how it's reported in the URL or config: 1, 2, 3 * @param {Object} o Object containing test properties * @param {String} o.name The name of the test * @param {Function} o.test The test function to execute, the only argument to the function is the `Y` instance * @param {String} o.trigger The module that triggers this test. */ add: function(cat, name, o) { feature_tests[cat] = feature_tests[cat] || {}; feature_tests[cat][name] = o; }, /** * Execute all tests of a given category and return the serialized results * * ``` * caps=1:1;2:1;3:0 * ``` * @method all * @param {String} cat The category to execute * @param {Array} args The arguments to pass to the test function * @return {String} A semi-colon separated string of tests and their success/failure: 1:1;2:1;3:0 */ all: function(cat, args) { var cat_o = feature_tests[cat], // results = {}; result = []; if (cat_o) { Y.Object.each(cat_o, function(v, k) { result.push(k + ':' + (Y.Features.test(cat, k, args) ? 1 : 0)); }); } return (result.length) ? result.join(';') : ''; }, /** * Run a sepecific test and return a Boolean response. * * ``` * Y.Features.test("load", "1"); * ``` * * @method test * @param {String} cat The category of the test to run * @param {String} name The name of the test to run * @param {Array} args The arguments to pass to the test function * @return {Boolean} True or false if the test passed/failed. */ test: function(cat, name, args) { args = args || []; var result, ua, test, cat_o = feature_tests[cat], feature = cat_o && cat_o[name]; if (!feature) { Y.log('Feature test ' + cat + ', ' + name + ' not found'); } else { result = feature.result; if (Y.Lang.isUndefined(result)) { ua = feature.ua; if (ua) { result = (Y.UA[ua]); } test = feature.test; if (test && ((!ua) || result)) { result = test.apply(Y, args); } feature.result = result; } } return result; } }); // Y.Features.add("load", "1", {}); // Y.Features.test("load", "1"); // caps=1:1;2:0;3:1; /* This file is auto-generated by (yogi loader --yes --mix --start ../) */ /*jshint maxlen:900, eqeqeq: false */ var add = Y.Features.add; // app-transitions-native add('load', '0', { "name": "app-transitions-native", "test": function (Y) { var doc = Y.config.doc, node = doc ? doc.documentElement : null; if (node && node.style) { return ('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return false; }, "trigger": "app-transitions" }); // autocomplete-list-keys add('load', '1', { "name": "autocomplete-list-keys", "test": function (Y) { // Only add keyboard support to autocomplete-list if this doesn't appear to // be an iOS or Android-based mobile device. // // There's currently no feasible way to actually detect whether a device has // a hardware keyboard, so this sniff will have to do. It can easily be // overridden by manually loading the autocomplete-list-keys module. // // Worth noting: even though iOS supports bluetooth keyboards, Mobile Safari // doesn't fire the keyboard events used by AutoCompleteList, so there's // no point loading the -keys module even when a bluetooth keyboard may be // available. return !(Y.UA.ios || Y.UA.android); }, "trigger": "autocomplete-list" }); // dd-gestures add('load', '2', { "name": "dd-gestures", "trigger": "dd-drag", "ua": "touchEnabled" }); // dom-style-ie add('load', '3', { "name": "dom-style-ie", "test": function (Y) { var testFeature = Y.Features.test, addFeature = Y.Features.add, WINDOW = Y.config.win, DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', ret = false; addFeature('style', 'computedStyle', { test: function() { return WINDOW && 'getComputedStyle' in WINDOW; } }); addFeature('style', 'opacity', { test: function() { return DOCUMENT && 'opacity' in DOCUMENT[DOCUMENT_ELEMENT].style; } }); ret = (!testFeature('style', 'opacity') && !testFeature('style', 'computedStyle')); return ret; }, "trigger": "dom-style" }); // editor-para-ie add('load', '4', { "name": "editor-para-ie", "trigger": "editor-para", "ua": "ie", "when": "instead" }); // event-base-ie add('load', '5', { "name": "event-base-ie", "test": function(Y) { var imp = Y.config.doc && Y.config.doc.implementation; return (imp && (!imp.hasFeature('Events', '2.0'))); }, "trigger": "node-base" }); // graphics-canvas add('load', '6', { "name": "graphics-canvas", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-canvas-default add('load', '7', { "name": "graphics-canvas-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useCanvas = Y.config.defaultGraphicEngine && Y.config.defaultGraphicEngine == "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return (!svg || useCanvas) && (canvas && canvas.getContext && canvas.getContext("2d")); }, "trigger": "graphics" }); // graphics-svg add('load', '8', { "name": "graphics-svg", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-svg-default add('load', '9', { "name": "graphics-svg-default", "test": function(Y) { var DOCUMENT = Y.config.doc, useSVG = !Y.config.defaultGraphicEngine || Y.config.defaultGraphicEngine != "canvas", canvas = DOCUMENT && DOCUMENT.createElement("canvas"), svg = (DOCUMENT && DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")); return svg && (useSVG || !canvas); }, "trigger": "graphics" }); // graphics-vml add('load', '10', { "name": "graphics-vml", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // graphics-vml-default add('load', '11', { "name": "graphics-vml-default", "test": function(Y) { var DOCUMENT = Y.config.doc, canvas = DOCUMENT && DOCUMENT.createElement("canvas"); return (DOCUMENT && !DOCUMENT.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1") && (!canvas || !canvas.getContext || !canvas.getContext("2d"))); }, "trigger": "graphics" }); // history-hash-ie add('load', '12', { "name": "history-hash-ie", "test": function (Y) { var docMode = Y.config.doc && Y.config.doc.documentMode; return Y.UA.ie && (!('onhashchange' in Y.config.win) || !docMode || docMode < 8); }, "trigger": "history-hash" }); // io-nodejs add('load', '13', { "name": "io-nodejs", "trigger": "io-base", "ua": "nodejs" }); // json-parse-shim add('load', '14', { "name": "json-parse-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONParse !== false && !!Native; function workingNative( k, v ) { return k === "ok" ? true : v; } // Double check basic functionality. This is mainly to catch early broken // implementations of the JSON API in Firefox 3.1 beta1 and beta2 if ( nativeSupport ) { try { nativeSupport = ( Native.parse( '{"ok":false}', workingNative ) ).ok; } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-parse" }); // json-stringify-shim add('load', '15', { "name": "json-stringify-shim", "test": function (Y) { var _JSON = Y.config.global.JSON, Native = Object.prototype.toString.call(_JSON) === '[object JSON]' && _JSON, nativeSupport = Y.config.useNativeJSONStringify !== false && !!Native; // Double check basic native functionality. This is primarily to catch broken // early JSON API implementations in Firefox 3.1 beta1 and beta2. if ( nativeSupport ) { try { nativeSupport = ( '0' === Native.stringify(0) ); } catch ( e ) { nativeSupport = false; } } return !nativeSupport; }, "trigger": "json-stringify" }); // scrollview-base-ie add('load', '16', { "name": "scrollview-base-ie", "trigger": "scrollview-base", "ua": "ie" }); // selector-css2 add('load', '17', { "name": "selector-css2", "test": function (Y) { var DOCUMENT = Y.config.doc, ret = DOCUMENT && !('querySelectorAll' in DOCUMENT); return ret; }, "trigger": "selector" }); // transition-timer add('load', '18', { "name": "transition-timer", "test": function (Y) { var DOCUMENT = Y.config.doc, node = (DOCUMENT) ? DOCUMENT.documentElement: null, ret = true; if (node && node.style) { ret = !('MozTransition' in node.style || 'WebkitTransition' in node.style || 'transition' in node.style); } return ret; }, "trigger": "transition" }); // widget-base-ie add('load', '19', { "name": "widget-base-ie", "trigger": "widget-base", "ua": "ie" }); // yql-jsonp add('load', '20', { "name": "yql-jsonp", "test": function (Y) { /* Only load the JSONP module when not in nodejs or winjs TODO Make the winjs module a CORS module */ return (!Y.UA.nodejs && !Y.UA.winjs); }, "trigger": "yql", "when": "after" }); // yql-nodejs add('load', '21', { "name": "yql-nodejs", "trigger": "yql", "ua": "nodejs", "when": "after" }); // yql-winjs add('load', '22', { "name": "yql-winjs", "trigger": "yql", "ua": "winjs", "when": "after" }); }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dom-core', function (Y, NAME) { var NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', PARENT_WINDOW = 'parentWindow', TAG_NAME = 'tagName', PARENT_NODE = 'parentNode', PREVIOUS_SIBLING = 'previousSibling', NEXT_SIBLING = 'nextSibling', CONTAINS = 'contains', COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', EMPTY_ARRAY = [], // IE < 8 throws on node.contains(textNode) supportsContainsTextNode = (function() { var node = Y.config.doc.createElement('div'), textNode = node.appendChild(Y.config.doc.createTextNode('')), result = false; try { result = node.contains(textNode); } catch(e) {} return result; })(), /** * The DOM utility provides a cross-browser abtraction layer * normalizing DOM tasks, and adds extra helper functionality * for other common tasks. * @module dom * @main dom * @submodule dom-base * @for DOM * */ /** * Provides DOM helper methods. * @class DOM * */ Y_DOM = { /** * Returns the HTMLElement with the given ID (Wrapper for document.getElementById). * @method byId * @param {String} id the id attribute * @param {Object} doc optional The document to search. Defaults to current document * @return {HTMLElement | null} The HTMLElement with the id, or null if none found. */ byId: function(id, doc) { // handle dupe IDs and IE name collision return Y_DOM.allById(id, doc)[0] || null; }, getId: function(node) { var id; // HTMLElement returned from FORM when INPUT name === "id" // IE < 8: HTMLCollection returned when INPUT id === "id" // via both getAttribute and form.id if (node.id && !node.id.tagName && !node.id.item) { id = node.id; } else if (node.attributes && node.attributes.id) { id = node.attributes.id.value; } return id; }, setId: function(node, id) { if (node.setAttribute) { node.setAttribute('id', id); } else { node.id = id; } }, /* * Finds the ancestor of the element. * @method ancestor * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, the parentNode is returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {HTMLElement | null} The matching DOM node or null if none found. */ ancestor: function(element, fn, testSelf, stopFn) { var ret = null; if (testSelf) { ret = (!fn || fn(element)) ? element : null; } return ret || Y_DOM.elementByAxis(element, PARENT_NODE, fn, null, stopFn); }, /* * Finds the ancestors of the element. * @method ancestors * @param {HTMLElement} element The html element. * @param {Function} fn optional An optional boolean test to apply. * The optional function is passed the current DOM node being tested as its only argument. * If no function is given, all ancestors are returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @return {Array} An array containing all matching DOM nodes. */ ancestors: function(element, fn, testSelf, stopFn) { var ancestor = element, ret = []; while ((ancestor = Y_DOM.ancestor(ancestor, fn, testSelf, stopFn))) { testSelf = false; if (ancestor) { ret.unshift(ancestor); if (stopFn && stopFn(ancestor)) { return ret; } } } return ret; }, /** * Searches the element by the given axis for the first matching element. * @method elementByAxis * @param {HTMLElement} element The html element. * @param {String} axis The axis to search (parentNode, nextSibling, previousSibling). * @param {Function} fn optional An optional boolean test to apply. * @param {Boolean} all optional Whether all node types should be returned, or just element nodes. * The optional function is passed the current HTMLElement being tested as its only argument. * If no function is given, the first element is returned. * @return {HTMLElement | null} The matching element or null if none found. */ elementByAxis: function(element, axis, fn, all, stopAt) { while (element && (element = element[axis])) { // NOTE: assignment if ( (all || element[TAG_NAME]) && (!fn || fn(element)) ) { return element; } if (stopAt && stopAt(element)) { return null; } } return null; }, /** * Determines whether or not one HTMLElement is or contains another HTMLElement. * @method contains * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ contains: function(element, needle) { var ret = false; if ( !needle || !element || !needle[NODE_TYPE] || !element[NODE_TYPE]) { ret = false; } else if (element[CONTAINS] && // IE < 8 throws on node.contains(textNode) so fall back to brute. // Falling back for other nodeTypes as well. (needle[NODE_TYPE] === 1 || supportsContainsTextNode)) { ret = element[CONTAINS](needle); } else if (element[COMPARE_DOCUMENT_POSITION]) { // Match contains behavior (node.contains(node) === true). // Needed for Firefox < 4. if (element === needle || !!(element[COMPARE_DOCUMENT_POSITION](needle) & 16)) { ret = true; } } else { ret = Y_DOM._bruteContains(element, needle); } return ret; }, /** * Determines whether or not the HTMLElement is part of the document. * @method inDoc * @param {HTMLElement} element The containing html element. * @param {HTMLElement} doc optional The document to check. * @return {Boolean} Whether or not the element is attached to the document. */ inDoc: function(element, doc) { var ret = false, rootNode; if (element && element.nodeType) { (doc) || (doc = element[OWNER_DOCUMENT]); rootNode = doc[DOCUMENT_ELEMENT]; // contains only works with HTML_ELEMENT if (rootNode && rootNode.contains && element.tagName) { ret = rootNode.contains(element); } else { ret = Y_DOM.contains(rootNode, element); } } return ret; }, allById: function(id, root) { root = root || Y.config.doc; var nodes = [], ret = [], i, node; if (root.querySelectorAll) { ret = root.querySelectorAll('[id="' + id + '"]'); } else if (root.all) { nodes = root.all(id); if (nodes) { // root.all may return HTMLElement or HTMLCollection. // some elements are also HTMLCollection (FORM, SELECT). if (nodes.nodeName) { if (nodes.id === id) { // avoid false positive on name ret.push(nodes); nodes = EMPTY_ARRAY; // done, no need to filter } else { // prep for filtering nodes = [nodes]; } } if (nodes.length) { // filter out matches on node.name // and element.id as reference to element with id === 'id' for (i = 0; node = nodes[i++];) { if (node.id === id || (node.attributes && node.attributes.id && node.attributes.id.value === id)) { ret.push(node); } } } } } else { ret = [Y_DOM._getDoc(root).getElementById(id)]; } return ret; }, isWindow: function(obj) { return !!(obj && obj.scrollTo && obj.document); }, _removeChildNodes: function(node) { while (node.firstChild) { node.removeChild(node.firstChild); } }, siblings: function(node, fn) { var nodes = [], sibling = node; while ((sibling = sibling[PREVIOUS_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.unshift(sibling); } } sibling = node; while ((sibling = sibling[NEXT_SIBLING])) { if (sibling[TAG_NAME] && (!fn || fn(sibling))) { nodes.push(sibling); } } return nodes; }, /** * Brute force version of contains. * Used for browsers without contains support for non-HTMLElement Nodes (textNodes, etc). * @method _bruteContains * @private * @param {HTMLElement} element The containing html element. * @param {HTMLElement} needle The html element that may be contained. * @return {Boolean} Whether or not the element is or contains the needle. */ _bruteContains: function(element, needle) { while (needle) { if (element === needle) { return true; } needle = needle.parentNode; } return false; }, // TODO: move to Lang? /** * Memoizes dynamic regular expressions to boost runtime performance. * @method _getRegExp * @private * @param {String} str The string to convert to a regular expression. * @param {String} flags optional An optinal string of flags. * @return {RegExp} An instance of RegExp */ _getRegExp: function(str, flags) { flags = flags || ''; Y_DOM._regexCache = Y_DOM._regexCache || {}; if (!Y_DOM._regexCache[str + flags]) { Y_DOM._regexCache[str + flags] = new RegExp(str, flags); } return Y_DOM._regexCache[str + flags]; }, // TODO: make getDoc/Win true privates? /** * returns the appropriate document. * @method _getDoc * @private * @param {HTMLElement} element optional Target element. * @return {Object} The document for the given element or the default document. */ _getDoc: function(element) { var doc = Y.config.doc; if (element) { doc = (element[NODE_TYPE] === 9) ? element : // element === document element[OWNER_DOCUMENT] || // element === DOM node element.document || // element === window Y.config.doc; // default } return doc; }, /** * returns the appropriate window. * @method _getWin * @private * @param {HTMLElement} element optional Target element. * @return {Object} The window for the given element or the default window. */ _getWin: function(element) { var doc = Y_DOM._getDoc(element); return doc[DEFAULT_VIEW] || doc[PARENT_WINDOW] || Y.config.win; }, _batch: function(nodes, fn, arg1, arg2, arg3, etc) { fn = (typeof fn === 'string') ? Y_DOM[fn] : fn; var result, i = 0, node, ret; if (fn && nodes) { while ((node = nodes[i++])) { result = result = fn.call(Y_DOM, node, arg1, arg2, arg3, etc); if (typeof result !== 'undefined') { (ret) || (ret = []); ret.push(result); } } } return (typeof ret !== 'undefined') ? ret : nodes; }, generateID: function(el) { var id = el.id; if (!id) { id = Y.stamp(el); el.id = id; } return id; } }; Y.DOM = Y_DOM; }, '@VERSION@', {"requires": ["oop", "features"]}); YUI.add('dom-base', function (Y, NAME) { /** * @for DOM * @module dom */ var documentElement = Y.config.doc.documentElement, Y_DOM = Y.DOM, TAG_NAME = 'tagName', OWNER_DOCUMENT = 'ownerDocument', EMPTY_STRING = '', addFeature = Y.Features.add, testFeature = Y.Features.test; Y.mix(Y_DOM, { /** * Returns the text content of the HTMLElement. * @method getText * @param {HTMLElement} element The html element. * @return {String} The text content of the element (includes text of any descending elements). */ getText: (documentElement.textContent !== undefined) ? function(element) { var ret = ''; if (element) { ret = element.textContent; } return ret || ''; } : function(element) { var ret = ''; if (element) { ret = element.innerText || element.nodeValue; // might be a textNode } return ret || ''; }, /** * Sets the text content of the HTMLElement. * @method setText * @param {HTMLElement} element The html element. * @param {String} content The content to add. */ setText: (documentElement.textContent !== undefined) ? function(element, content) { if (element) { element.textContent = content; } } : function(element, content) { if ('innerText' in element) { element.innerText = content; } else if ('nodeValue' in element) { element.nodeValue = content; } }, CUSTOM_ATTRIBUTES: (!documentElement.hasAttribute) ? { // IE < 8 'for': 'htmlFor', 'class': 'className' } : { // w3c 'htmlFor': 'for', 'className': 'class' }, /** * Provides a normalized attribute interface. * @method setAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to set. * @param {String} val The value of the attribute. */ setAttribute: function(el, attr, val, ieAttr) { if (el && attr && el.setAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; el.setAttribute(attr, val, ieAttr); } else { Y.log('bad input to setAttribute', 'warn', 'dom'); } }, /** * Provides a normalized attribute interface. * @method getAttribute * @param {HTMLElement} el The target element for the attribute. * @param {String} attr The attribute to get. * @return {String} The current value of the attribute. */ getAttribute: function(el, attr, ieAttr) { ieAttr = (ieAttr !== undefined) ? ieAttr : 2; var ret = ''; if (el && attr && el.getAttribute) { attr = Y_DOM.CUSTOM_ATTRIBUTES[attr] || attr; ret = el.getAttribute(attr, ieAttr); if (ret === null) { ret = ''; // per DOM spec } } else { Y.log('bad input to getAttribute', 'warn', 'dom'); } return ret; }, VALUE_SETTERS: {}, VALUE_GETTERS: {}, getValue: function(node) { var ret = '', // TODO: return null? getter; if (node && node[TAG_NAME]) { getter = Y_DOM.VALUE_GETTERS[node[TAG_NAME].toLowerCase()]; if (getter) { ret = getter(node); } else { ret = node.value; } } // workaround for IE8 JSON stringify bug // which converts empty string values to null if (ret === EMPTY_STRING) { ret = EMPTY_STRING; // for real } return (typeof ret === 'string') ? ret : ''; }, setValue: function(node, val) { var setter; if (node && node[TAG_NAME]) { setter = Y_DOM.VALUE_SETTERS[node[TAG_NAME].toLowerCase()]; if (setter) { setter(node, val); } else { node.value = val; } } }, creators: {} }); addFeature('value-set', 'select', { test: function() { var node = Y.config.doc.createElement('select'); node.innerHTML = '<option>1</option><option>2</option>'; node.value = '2'; return (node.value && node.value === '2'); } }); if (!testFeature('value-set', 'select')) { Y_DOM.VALUE_SETTERS.select = function(node, val) { for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) { if (Y_DOM.getValue(option) === val) { option.selected = true; //Y_DOM.setAttribute(option, 'selected', 'selected'); break; } } }; } Y.mix(Y_DOM.VALUE_GETTERS, { button: function(node) { return (node.attributes && node.attributes.value) ? node.attributes.value.value : ''; } }); Y.mix(Y_DOM.VALUE_SETTERS, { // IE: node.value changes the button text, which should be handled via innerHTML button: function(node, val) { var attr = node.attributes.value; if (!attr) { attr = node[OWNER_DOCUMENT].createAttribute('value'); node.setAttributeNode(attr); } attr.value = val; } }); Y.mix(Y_DOM.VALUE_GETTERS, { option: function(node) { var attrs = node.attributes; return (attrs.value && attrs.value.specified) ? node.value : node.text; }, select: function(node) { var val = node.value, options = node.options; if (options && options.length) { // TODO: implement multipe select if (node.multiple) { Y.log('multiple select normalization not implemented', 'warn', 'DOM'); } else if (node.selectedIndex > -1) { val = Y_DOM.getValue(options[node.selectedIndex]); } } return val; } }); var addClass, hasClass, removeClass; Y.mix(Y.DOM, { /** * Determines whether a DOM element has the given className. * @method hasClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the given class. */ hasClass: function(node, className) { var re = Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'); return re.test(node.className); }, /** * Adds a class name to a given DOM element. * @method addClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to add to the class attribute */ addClass: function(node, className) { if (!Y.DOM.hasClass(node, className)) { // skip if already present node.className = Y.Lang.trim([node.className, className].join(' ')); } }, /** * Removes a class name from a given element. * @method removeClass * @for DOM * @param {HTMLElement} element The DOM element. * @param {String} className the class name to remove from the class attribute */ removeClass: function(node, className) { if (className && hasClass(node, className)) { node.className = Y.Lang.trim(node.className.replace(Y.DOM._getRegExp('(?:^|\\s+)' + className + '(?:\\s+|$)'), ' ')); if ( hasClass(node, className) ) { // in case of multiple adjacent removeClass(node, className); } } }, /** * Replace a class with another class for a given element. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name */ replaceClass: function(node, oldC, newC) { //Y.log('replaceClass replacing ' + oldC + ' with ' + newC, 'info', 'Node'); removeClass(node, oldC); // remove first in case oldC === newC addClass(node, newC); }, /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @for DOM * @param {HTMLElement} element The DOM element * @param {String} className the class name to be toggled * @param {Boolean} addClass optional boolean to indicate whether class * should be added or removed regardless of current state */ toggleClass: function(node, className, force) { var add = (force !== undefined) ? force : !(hasClass(node, className)); if (add) { addClass(node, className); } else { removeClass(node, className); } } }); hasClass = Y.DOM.hasClass; removeClass = Y.DOM.removeClass; addClass = Y.DOM.addClass; var re_tag = /<([a-z]+)/i, Y_DOM = Y.DOM, addFeature = Y.Features.add, testFeature = Y.Features.test, creators = {}, createFromDIV = function(html, tag) { var div = Y.config.doc.createElement('div'), ret = true; div.innerHTML = html; if (!div.firstChild || div.firstChild.tagName !== tag.toUpperCase()) { ret = false; } return ret; }, re_tbody = /(?:\/(?:thead|tfoot|tbody|caption|col|colgroup)>)+\s*<tbody/, TABLE_OPEN = '<table>', TABLE_CLOSE = '</table>'; Y.mix(Y.DOM, { _fragClones: {}, _create: function(html, doc, tag) { tag = tag || 'div'; var frag = Y_DOM._fragClones[tag]; if (frag) { frag = frag.cloneNode(false); } else { frag = Y_DOM._fragClones[tag] = doc.createElement(tag); } frag.innerHTML = html; return frag; }, _children: function(node, tag) { var i = 0, children = node.children, childNodes, hasComments, child; if (children && children.tags) { // use tags filter when possible if (tag) { children = node.children.tags(tag); } else { // IE leaks comments into children hasComments = children.tags('!').length; } } if (!children || (!children.tags && tag) || hasComments) { childNodes = children || node.childNodes; children = []; while ((child = childNodes[i++])) { if (child.nodeType === 1) { if (!tag || tag === child.tagName) { children.push(child); } } } } return children || []; }, /** * Creates a new dom node using the provided markup string. * @method create * @param {String} html The markup used to create the element * @param {HTMLDocument} doc An optional document context * @return {HTMLElement|DocumentFragment} returns a single HTMLElement * when creating one node, and a documentFragment when creating * multiple nodes. */ create: function(html, doc) { if (typeof html === 'string') { html = Y.Lang.trim(html); // match IE which trims whitespace from innerHTML } doc = doc || Y.config.doc; var m = re_tag.exec(html), create = Y_DOM._create, custom = creators, ret = null, creator, tag, nodes; if (html != undefined) { // not undefined or null if (m && m[1]) { creator = custom[m[1].toLowerCase()]; if (typeof creator === 'function') { create = creator; } else { tag = creator; } } nodes = create(html, doc, tag).childNodes; if (nodes.length === 1) { // return single node, breaking parentNode ref from "fragment" ret = nodes[0].parentNode.removeChild(nodes[0]); } else if (nodes[0] && nodes[0].className === 'yui3-big-dummy') { // using dummy node to preserve some attributes (e.g. OPTION not selected) if (nodes.length === 2) { ret = nodes[0].nextSibling; } else { nodes[0].parentNode.removeChild(nodes[0]); ret = Y_DOM._nl2frag(nodes, doc); } } else { // return multiple nodes as a fragment ret = Y_DOM._nl2frag(nodes, doc); } } return ret; }, _nl2frag: function(nodes, doc) { var ret = null, i, len; if (nodes && (nodes.push || nodes.item) && nodes[0]) { doc = doc || nodes[0].ownerDocument; ret = doc.createDocumentFragment(); if (nodes.item) { // convert live list to static array nodes = Y.Array(nodes, 0, true); } for (i = 0, len = nodes.length; i < len; i++) { ret.appendChild(nodes[i]); } } // else inline with log for minification return ret; }, /** * Inserts content in a node at the given location * @method addHTML * @param {HTMLElement} node The node to insert into * @param {HTMLElement | Array | HTMLCollection} content The content to be inserted * @param {HTMLElement} where Where to insert the content * If no "where" is given, content is appended to the node * Possible values for "where" * <dl> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> */ addHTML: function(node, content, where) { var nodeParent = node.parentNode, i = 0, item, ret = content, newNode; if (content != undefined) { // not null or undefined (maybe 0) if (content.nodeType) { // DOM node, just add it newNode = content; } else if (typeof content == 'string' || typeof content == 'number') { ret = newNode = Y_DOM.create(content); } else if (content[0] && content[0].nodeType) { // array or collection newNode = Y.config.doc.createDocumentFragment(); while ((item = content[i++])) { newNode.appendChild(item); // append to fragment for insertion } } } if (where) { if (newNode && where.parentNode) { // insert regardless of relationship to node where.parentNode.insertBefore(newNode, where); } else { switch (where) { case 'replace': while (node.firstChild) { node.removeChild(node.firstChild); } if (newNode) { // allow empty content to clear node node.appendChild(newNode); } break; case 'before': if (newNode) { nodeParent.insertBefore(newNode, node); } break; case 'after': if (newNode) { if (node.nextSibling) { // IE errors if refNode is null nodeParent.insertBefore(newNode, node.nextSibling); } else { nodeParent.appendChild(newNode); } } break; default: if (newNode) { node.appendChild(newNode); } } } } else if (newNode) { node.appendChild(newNode); } return ret; }, wrap: function(node, html) { var parent = (html && html.nodeType) ? html : Y.DOM.create(html), nodes = parent.getElementsByTagName('*'); if (nodes.length) { parent = nodes[nodes.length - 1]; } if (node.parentNode) { node.parentNode.replaceChild(parent, node); } parent.appendChild(node); }, unwrap: function(node) { var parent = node.parentNode, lastChild = parent.lastChild, next = node, grandparent; if (parent) { grandparent = parent.parentNode; if (grandparent) { node = parent.firstChild; while (node !== lastChild) { next = node.nextSibling; grandparent.insertBefore(node, parent); node = next; } grandparent.replaceChild(lastChild, parent); } else { parent.removeChild(node); } } } }); addFeature('innerhtml', 'table', { test: function() { var node = Y.config.doc.createElement('table'); try { node.innerHTML = '<tbody></tbody>'; } catch(e) { return false; } return (node.firstChild && node.firstChild.nodeName === 'TBODY'); } }); addFeature('innerhtml-div', 'tr', { test: function() { return createFromDIV('<tr></tr>', 'tr'); } }); addFeature('innerhtml-div', 'script', { test: function() { return createFromDIV('<script></script>', 'script'); } }); if (!testFeature('innerhtml', 'table')) { // TODO: thead/tfoot with nested tbody // IE adds TBODY when creating TABLE elements (which may share this impl) creators.tbody = function(html, doc) { var frag = Y_DOM.create(TABLE_OPEN + html + TABLE_CLOSE, doc), tb = Y.DOM._children(frag, 'tbody')[0]; if (frag.children.length > 1 && tb && !re_tbody.test(html)) { tb.parentNode.removeChild(tb); // strip extraneous tbody } return frag; }; } if (!testFeature('innerhtml-div', 'script')) { creators.script = function(html, doc) { var frag = doc.createElement('div'); frag.innerHTML = '-' + html; frag.removeChild(frag.firstChild); return frag; }; creators.link = creators.style = creators.script; } if (!testFeature('innerhtml-div', 'tr')) { Y.mix(creators, { option: function(html, doc) { return Y_DOM.create('<select><option class="yui3-big-dummy" selected></option>' + html + '</select>', doc); }, tr: function(html, doc) { return Y_DOM.create('<tbody>' + html + '</tbody>', doc); }, td: function(html, doc) { return Y_DOM.create('<tr>' + html + '</tr>', doc); }, col: function(html, doc) { return Y_DOM.create('<colgroup>' + html + '</colgroup>', doc); }, tbody: 'table' }); Y.mix(creators, { legend: 'fieldset', th: creators.td, thead: creators.tbody, tfoot: creators.tbody, caption: creators.tbody, colgroup: creators.tbody, optgroup: creators.option }); } Y_DOM.creators = creators; Y.mix(Y.DOM, { /** * Sets the width of the element to the given size, regardless * of box model, border, padding, etc. * @method setWidth * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setWidth: function(node, size) { Y.DOM._setSize(node, 'width', size); }, /** * Sets the height of the element to the given size, regardless * of box model, border, padding, etc. * @method setHeight * @param {HTMLElement} element The DOM element. * @param {String|Number} size The pixel height to size to */ setHeight: function(node, size) { Y.DOM._setSize(node, 'height', size); }, _setSize: function(node, prop, val) { val = (val > 0) ? val : 0; var size = 0; node.style[prop] = val + 'px'; size = (prop === 'height') ? node.offsetHeight : node.offsetWidth; if (size > val) { val = val - (size - val); if (val < 0) { val = 0; } node.style[prop] = val + 'px'; } } }); }, '@VERSION@', {"requires": ["dom-core"]}); YUI.add('color-base', function (Y, NAME) { /** Color provides static methods for color conversion. Y.Color.toRGB('f00'); // rgb(255, 0, 0) Y.Color.toHex('rgb(255, 255, 0)'); // #ffff00 @module color @submodule color-base @class Color @since 3.8.0 **/ var REGEX_HEX = /^#?([\da-fA-F]{2})([\da-fA-F]{2})([\da-fA-F]{2})(\ufffe)?/, REGEX_HEX3 = /^#?([\da-fA-F]{1})([\da-fA-F]{1})([\da-fA-F]{1})(\ufffe)?/, REGEX_RGB = /rgba?\(([\d]{1,3}), ?([\d]{1,3}), ?([\d]{1,3}),? ?([.\d]*)?\)/, TYPES = { 'HEX': 'hex', 'RGB': 'rgb', 'RGBA': 'rgba' }, CONVERTS = { 'hex': 'toHex', 'rgb': 'toRGB', 'rgba': 'toRGBA' }; Y.Color = { /** @static @property KEYWORDS @type Object @since 3.8.0 **/ KEYWORDS: { 'black': '000', 'silver': 'c0c0c0', 'gray': '808080', 'white': 'fff', 'maroon': '800000', 'red': 'f00', 'purple': '800080', 'fuchsia': 'f0f', 'green': '008000', 'lime': '0f0', 'olive': '808000', 'yellow': 'ff0', 'navy': '000080', 'blue': '00f', 'teal': '008080', 'aqua': '0ff' }, /** NOTE: `(\ufffe)?` is added to the Regular Expression to carve out a place for the alpha channel that is returned from toArray without compromising any usage of the Regular Expression @static @property REGEX_HEX @type RegExp @default /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})(\ufffe)?/ @since 3.8.0 **/ REGEX_HEX: REGEX_HEX, /** NOTE: `(\ufffe)?` is added to the Regular Expression to carve out a place for the alpha channel that is returned from toArray without compromising any usage of the Regular Expression @static @property REGEX_HEX3 @type RegExp @default /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})(\ufffe)?/ @since 3.8.0 **/ REGEX_HEX3: REGEX_HEX3, /** @static @property REGEX_RGB @type RegExp @default /rgba?\(([0-9]{1,3}), ?([0-9]{1,3}), ?([0-9]{1,3}),? ?([.0-9]{1,3})?\)/ @since 3.8.0 **/ REGEX_RGB: REGEX_RGB, re_RGB: REGEX_RGB, re_hex: REGEX_HEX, re_hex3: REGEX_HEX3, /** @static @property STR_HEX @type String @default #{*}{*}{*} @since 3.8.0 **/ STR_HEX: '#{*}{*}{*}', /** @static @property STR_RGB @type String @default rgb({*}, {*}, {*}) @since 3.8.0 **/ STR_RGB: 'rgb({*}, {*}, {*})', /** @static @property STR_RGBA @type String @default rgba({*}, {*}, {*}, {*}) @since 3.8.0 **/ STR_RGBA: 'rgba({*}, {*}, {*}, {*})', /** @static @property TYPES @type Object @default {'rgb':'rgb', 'rgba':'rgba'} @since 3.8.0 **/ TYPES: TYPES, /** @static @property CONVERTS @type Object @default {} @since 3.8.0 **/ CONVERTS: CONVERTS, /** Converts the provided string to the provided type. You can use the `Y.Color.TYPES` to get a valid `to` type. If the color cannot be converted, the original color will be returned. @public @method convert @param {String} str @param {String} to @return {String} @since 3.8.0 **/ convert: function (str, to) { var convert = Y.Color.CONVERTS[to.toLowerCase()], clr = str; if (convert && Y.Color[convert]) { clr = Y.Color[convert](str); } return clr; }, /** Converts provided color value to a hex value string @public @method toHex @param {String} str Hex or RGB value string @return {String} returns array of values or CSS string if options.css is true @since 3.8.0 **/ toHex: function (str) { var clr = Y.Color._convertTo(str, 'hex'), isTransparent = clr.toLowerCase() === 'transparent'; if (clr.charAt(0) !== '#' && !isTransparent) { clr = '#' + clr; } return isTransparent ? clr.toLowerCase() : clr.toUpperCase(); }, /** Converts provided color value to an RGB value string @public @method toRGB @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGB: function (str) { var clr = Y.Color._convertTo(str, 'rgb'); return clr.toLowerCase(); }, /** Converts provided color value to an RGB value string @public @method toRGBA @param {String} str Hex or RGB value string @return {String} @since 3.8.0 **/ toRGBA: function (str) { var clr = Y.Color._convertTo(str, 'rgba' ); return clr.toLowerCase(); }, /** Converts the provided color string to an array of values where the last value is the alpha value. Will return an empty array if the provided string is not able to be parsed. NOTE: `(\ufffe)?` is added to `HEX` and `HEX3` Regular Expressions to carve out a place for the alpha channel that is returned from toArray without compromising any usage of the Regular Expression Y.Color.toArray('fff'); // ['ff', 'ff', 'ff', 1] Y.Color.toArray('rgb(0, 0, 0)'); // ['0', '0', '0', 1] Y.Color.toArray('rgba(0, 0, 0, 0)'); // ['0', '0', '0', 1] @public @method toArray @param {String} str @return {Array} @since 3.8.0 **/ toArray: function(str) { // parse with regex and return "matches" array var type = Y.Color.findType(str).toUpperCase(), regex, arr, length, lastItem; if (type === 'HEX' && str.length < 5) { type = 'HEX3'; } if (type.charAt(type.length - 1) === 'A') { type = type.slice(0, -1); } regex = Y.Color['REGEX_' + type]; if (regex) { arr = regex.exec(str) || []; length = arr.length; if (length) { arr.shift(); length--; if (type === 'HEX3') { arr[0] += arr[0]; arr[1] += arr[1]; arr[2] += arr[2]; } lastItem = arr[length - 1]; if (!lastItem) { arr[length - 1] = 1; } } } return arr; }, /** Converts the array of values to a string based on the provided template. @public @method fromArray @param {Array} arr @param {String} template @return {String} @since 3.8.0 **/ fromArray: function(arr, template) { arr = arr.concat(); if (typeof template === 'undefined') { return arr.join(', '); } var replace = '{*}'; template = Y.Color['STR_' + template.toUpperCase()]; if (arr.length === 3 && template.match(/\{\*\}/g).length === 4) { arr.push(1); } while ( template.indexOf(replace) >= 0 && arr.length > 0) { template = template.replace(replace, arr.shift()); } return template; }, /** Finds the value type based on the str value provided. @public @method findType @param {String} str @return {String} @since 3.8.0 **/ findType: function (str) { if (Y.Color.KEYWORDS[str]) { return 'keyword'; } var index = str.indexOf('('), key; if (index > 0) { key = str.substr(0, index); } if (key && Y.Color.TYPES[key.toUpperCase()]) { return Y.Color.TYPES[key.toUpperCase()]; } return 'hex'; }, // return 'keyword', 'hex', 'rgb' /** Retrives the alpha channel from the provided string. If no alpha channel is present, `1` will be returned. @protected @method _getAlpha @param {String} clr @return {Number} @since 3.8.0 **/ _getAlpha: function (clr) { var alpha, arr = Y.Color.toArray(clr); if (arr.length > 3) { alpha = arr.pop(); } return +alpha || 1; }, /** Returns the hex value string if found in the KEYWORDS object @protected @method _keywordToHex @param {String} clr @return {String} @since 3.8.0 **/ _keywordToHex: function (clr) { var keyword = Y.Color.KEYWORDS[clr]; if (keyword) { return keyword; } }, /** Converts the provided color string to the value type provided as `to` @protected @method _convertTo @param {String} clr @param {String} to @return {String} @since 3.8.0 **/ _convertTo: function(clr, to) { if (clr === 'transparent') { return clr; } var from = Y.Color.findType(clr), originalTo = to, needsAlpha, alpha, method, ucTo; if (from === 'keyword') { clr = Y.Color._keywordToHex(clr); from = 'hex'; } if (from === 'hex' && clr.length < 5) { if (clr.charAt(0) === '#') { clr = clr.substr(1); } clr = '#' + clr.charAt(0) + clr.charAt(0) + clr.charAt(1) + clr.charAt(1) + clr.charAt(2) + clr.charAt(2); } if (from === to) { return clr; } if (from.charAt(from.length - 1) === 'a') { from = from.slice(0, -1); } needsAlpha = (to.charAt(to.length - 1) === 'a'); if (needsAlpha) { to = to.slice(0, -1); alpha = Y.Color._getAlpha(clr); } ucTo = to.charAt(0).toUpperCase() + to.substr(1).toLowerCase(); method = Y.Color['_' + from + 'To' + ucTo ]; // check to see if need conversion to rgb first // check to see if there is a direct conversion method // convertions are: hex <-> rgb <-> hsl if (!method) { if (from !== 'rgb' && to !== 'rgb') { clr = Y.Color['_' + from + 'ToRgb'](clr); from = 'rgb'; method = Y.Color['_' + from + 'To' + ucTo ]; } } if (method) { clr = ((method)(clr, needsAlpha)); } // process clr from arrays to strings after conversions if alpha is needed if (needsAlpha) { if (!Y.Lang.isArray(clr)) { clr = Y.Color.toArray(clr); } clr.push(alpha); clr = Y.Color.fromArray(clr, originalTo.toUpperCase()); } return clr; }, /** Processes the hex string into r, g, b values. Will return values as an array, or as an rgb string. @protected @method _hexToRgb @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _hexToRgb: function (str, toArray) { var r, g, b; /*jshint bitwise:false*/ if (str.charAt(0) === '#') { str = str.substr(1); } str = parseInt(str, 16); r = str >> 16; g = str >> 8 & 0xFF; b = str & 0xFF; if (toArray) { return [r, g, b]; } return 'rgb(' + r + ', ' + g + ', ' + b + ')'; }, /** Processes the rgb string into r, g, b values. Will return values as an array, or as a hex string. @protected @method _rgbToHex @param {String} str @param {Boolean} [toArray] @return {String|Array} @since 3.8.0 **/ _rgbToHex: function (str) { /*jshint bitwise:false*/ var rgb = Y.Color.toArray(str), hex = rgb[2] | (rgb[1] << 8) | (rgb[0] << 16); hex = (+hex).toString(16); while (hex.length < 6) { hex = '0' + hex; } return '#' + hex; } }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dom-style', function (Y, NAME) { (function(Y) { /** * Add style management functionality to DOM. * @module dom * @submodule dom-style * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', DEFAULT_VIEW = 'defaultView', OWNER_DOCUMENT = 'ownerDocument', STYLE = 'style', FLOAT = 'float', CSS_FLOAT = 'cssFloat', STYLE_FLOAT = 'styleFloat', TRANSPARENT = 'transparent', GET_COMPUTED_STYLE = 'getComputedStyle', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', WINDOW = Y.config.win, DOCUMENT = Y.config.doc, UNDEFINED = undefined, Y_DOM = Y.DOM, TRANSFORM = 'transform', TRANSFORMORIGIN = 'transformOrigin', VENDOR_TRANSFORM = [ 'WebkitTransform', 'MozTransform', 'OTransform', 'msTransform' ], re_color = /color$/i, re_unit = /width|height|top|left|right|bottom|margin|padding/i; Y.Array.each(VENDOR_TRANSFORM, function(val) { if (val in DOCUMENT[DOCUMENT_ELEMENT].style) { TRANSFORM = val; TRANSFORMORIGIN = val + "Origin"; } }); Y.mix(Y_DOM, { DEFAULT_UNIT: 'px', CUSTOM_STYLES: { }, /** * Sets a style property for a given element. * @method setStyle * @param {HTMLElement} An HTMLElement to apply the style to. * @param {String} att The style property to set. * @param {String|Number} val The value. */ setStyle: function(node, att, val, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES; if (style) { if (val === null || val === '') { // normalize unsetting val = ''; } else if (!isNaN(new Number(val)) && re_unit.test(att)) { // number values may need a unit val += Y_DOM.DEFAULT_UNIT; } if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].set) { CUSTOM_STYLES[att].set(node, val, style); return; // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } else if (att === '') { // unset inline styles att = 'cssText'; val = ''; } style[att] = val; } }, /** * Returns the current style value for the given property. * @method getStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. */ getStyle: function(node, att, style) { style = style || node.style; var CUSTOM_STYLES = Y_DOM.CUSTOM_STYLES, val = ''; if (style) { if (att in CUSTOM_STYLES) { if (CUSTOM_STYLES[att].get) { return CUSTOM_STYLES[att].get(node, att, style); // NOTE: return } else if (typeof CUSTOM_STYLES[att] === 'string') { att = CUSTOM_STYLES[att]; } } val = style[att]; if (val === '') { // TODO: is empty string sufficient? val = Y_DOM[GET_COMPUTED_STYLE](node, att); } } return val; }, /** * Sets multiple style properties. * @method setStyles * @param {HTMLElement} node An HTMLElement to apply the styles to. * @param {Object} hash An object literal of property:value pairs. */ setStyles: function(node, hash) { var style = node.style; Y.each(hash, function(v, n) { Y_DOM.setStyle(node, n, v, style); }, Y_DOM); }, /** * Returns the computed style for the given node. * @method getComputedStyle * @param {HTMLElement} An HTMLElement to get the style from. * @param {String} att The style property to get. * @return {String} The computed value of the style property. */ getComputedStyle: function(node, att) { var val = '', doc = node[OWNER_DOCUMENT], computed; if (node[STYLE] && doc[DEFAULT_VIEW] && doc[DEFAULT_VIEW][GET_COMPUTED_STYLE]) { computed = doc[DEFAULT_VIEW][GET_COMPUTED_STYLE](node, null); if (computed) { // FF may be null in some cases (ticket #2530548) val = computed[att]; } } return val; } }); // normalize reserved word float alternatives ("cssFloat" or "styleFloat") if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][CSS_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = CSS_FLOAT; } else if (DOCUMENT[DOCUMENT_ELEMENT][STYLE][STYLE_FLOAT] !== UNDEFINED) { Y_DOM.CUSTOM_STYLES[FLOAT] = STYLE_FLOAT; } // fix opera computedStyle default color unit (convert to rgb) if (Y.UA.opera) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (re_color.test(att)) { val = Y.Color.toRGB(val); } return val; }; } // safari converts transparent to rgba(), others use "transparent" if (Y.UA.webkit) { Y_DOM[GET_COMPUTED_STYLE] = function(node, att) { var view = node[OWNER_DOCUMENT][DEFAULT_VIEW], val = view[GET_COMPUTED_STYLE](node, '')[att]; if (val === 'rgba(0, 0, 0, 0)') { val = TRANSPARENT; } return val; }; } Y.DOM._getAttrOffset = function(node, attr) { var val = Y.DOM[GET_COMPUTED_STYLE](node, attr), offsetParent = node.offsetParent, position, parentOffset, offset; if (val === 'auto') { position = Y.DOM.getStyle(node, 'position'); if (position === 'static' || position === 'relative') { val = 0; } else if (offsetParent && offsetParent[GET_BOUNDING_CLIENT_RECT]) { parentOffset = offsetParent[GET_BOUNDING_CLIENT_RECT]()[attr]; offset = node[GET_BOUNDING_CLIENT_RECT]()[attr]; if (attr === 'left' || attr === 'top') { val = offset - parentOffset; } else { val = parentOffset - node[GET_BOUNDING_CLIENT_RECT]()[attr]; } } } return val; }; Y.DOM._getOffset = function(node) { var pos, xy = null; if (node) { pos = Y_DOM.getStyle(node, 'position'); xy = [ parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'left'), 10), parseInt(Y_DOM[GET_COMPUTED_STYLE](node, 'top'), 10) ]; if ( isNaN(xy[0]) ) { // in case of 'auto' xy[0] = parseInt(Y_DOM.getStyle(node, 'left'), 10); // try inline if ( isNaN(xy[0]) ) { // default to offset value xy[0] = (pos === 'relative') ? 0 : node.offsetLeft || 0; } } if ( isNaN(xy[1]) ) { // in case of 'auto' xy[1] = parseInt(Y_DOM.getStyle(node, 'top'), 10); // try inline if ( isNaN(xy[1]) ) { // default to offset value xy[1] = (pos === 'relative') ? 0 : node.offsetTop || 0; } } } return xy; }; Y_DOM.CUSTOM_STYLES.transform = { set: function(node, val, style) { style[TRANSFORM] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORM); } }; Y_DOM.CUSTOM_STYLES.transformOrigin = { set: function(node, val, style) { style[TRANSFORMORIGIN] = val; }, get: function(node, style) { return Y_DOM[GET_COMPUTED_STYLE](node, TRANSFORMORIGIN); } }; })(Y); }, '@VERSION@', {"requires": ["dom-base", "color-base"]}); YUI.add('dom-style-ie', function (Y, NAME) { (function(Y) { var HAS_LAYOUT = 'hasLayout', PX = 'px', FILTER = 'filter', FILTERS = 'filters', OPACITY = 'opacity', AUTO = 'auto', BORDER_WIDTH = 'borderWidth', BORDER_TOP_WIDTH = 'borderTopWidth', BORDER_RIGHT_WIDTH = 'borderRightWidth', BORDER_BOTTOM_WIDTH = 'borderBottomWidth', BORDER_LEFT_WIDTH = 'borderLeftWidth', WIDTH = 'width', HEIGHT = 'height', TRANSPARENT = 'transparent', VISIBLE = 'visible', GET_COMPUTED_STYLE = 'getComputedStyle', UNDEFINED = undefined, documentElement = Y.config.doc.documentElement, testFeature = Y.Features.test, addFeature = Y.Features.add, // TODO: unit-less lineHeight (e.g. 1.22) re_unit = /^(\d[.\d]*)+(em|ex|px|gd|rem|vw|vh|vm|ch|mm|cm|in|pt|pc|deg|rad|ms|s|hz|khz|%){1}?/i, isIE8 = (Y.UA.ie >= 8), _getStyleObj = function(node) { return node.currentStyle || node.style; }, ComputedStyle = { CUSTOM_STYLES: {}, get: function(el, property) { var value = '', current; if (el) { current = _getStyleObj(el)[property]; if (property === OPACITY && Y.DOM.CUSTOM_STYLES[OPACITY]) { value = Y.DOM.CUSTOM_STYLES[OPACITY].get(el); } else if (!current || (current.indexOf && current.indexOf(PX) > -1)) { // no need to convert value = current; } else if (Y.DOM.IE.COMPUTED[property]) { // use compute function value = Y.DOM.IE.COMPUTED[property](el, property); } else if (re_unit.test(current)) { // convert to pixel value = ComputedStyle.getPixel(el, property) + PX; } else { value = current; } } return value; }, sizeOffsets: { width: ['Left', 'Right'], height: ['Top', 'Bottom'], top: ['Top'], bottom: ['Bottom'] }, getOffset: function(el, prop) { var current = _getStyleObj(el)[prop], // value of "width", "top", etc. capped = prop.charAt(0).toUpperCase() + prop.substr(1), // "Width", "Top", etc. offset = 'offset' + capped, // "offsetWidth", "offsetTop", etc. pixel = 'pixel' + capped, // "pixelWidth", "pixelTop", etc. sizeOffsets = ComputedStyle.sizeOffsets[prop], mode = el.ownerDocument.compatMode, value = ''; // IE pixelWidth incorrect for percent // manually compute by subtracting padding and border from offset size // NOTE: clientWidth/Height (size minus border) is 0 when current === AUTO so offsetHeight is used // reverting to auto from auto causes position stacking issues (old impl) if (current === AUTO || current.indexOf('%') > -1) { value = el['offset' + capped]; if (mode !== 'BackCompat') { if (sizeOffsets[0]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[0]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[0] + 'Width', 1); } if (sizeOffsets[1]) { value -= ComputedStyle.getPixel(el, 'padding' + sizeOffsets[1]); value -= ComputedStyle.getBorderWidth(el, 'border' + sizeOffsets[1] + 'Width', 1); } } } else { // use style.pixelWidth, etc. to convert to pixels // need to map style.width to currentStyle (no currentStyle.pixelWidth) if (!el.style[pixel] && !el.style[prop]) { el.style[prop] = current; } value = el.style[pixel]; } return value + PX; }, borderMap: { thin: (isIE8) ? '1px' : '2px', medium: (isIE8) ? '3px': '4px', thick: (isIE8) ? '5px' : '6px' }, getBorderWidth: function(el, property, omitUnit) { var unit = omitUnit ? '' : PX, current = el.currentStyle[property]; if (current.indexOf(PX) < 0) { // look up keywords if a border exists if (ComputedStyle.borderMap[current] && el.currentStyle.borderStyle !== 'none') { current = ComputedStyle.borderMap[current]; } else { // otherwise no border (default is "medium") current = 0; } } return (omitUnit) ? parseFloat(current) : current; }, getPixel: function(node, att) { // use pixelRight to convert to px var val = null, style = _getStyleObj(node), styleRight = style.right, current = style[att]; node.style.right = current; val = node.style.pixelRight; node.style.right = styleRight; // revert return val; }, getMargin: function(node, att) { var val, style = _getStyleObj(node); if (style[att] == AUTO) { val = 0; } else { val = ComputedStyle.getPixel(node, att); } return val + PX; }, getVisibility: function(node, att) { var current; while ( (current = node.currentStyle) && current[att] == 'inherit') { // NOTE: assignment in test node = node.parentNode; } return (current) ? current[att] : VISIBLE; }, getColor: function(node, att) { var current = _getStyleObj(node)[att]; if (!current || current === TRANSPARENT) { Y.DOM.elementByAxis(node, 'parentNode', null, function(parent) { current = _getStyleObj(parent)[att]; if (current && current !== TRANSPARENT) { node = parent; return true; } }); } return Y.Color.toRGB(current); }, getBorderColor: function(node, att) { var current = _getStyleObj(node), val = current[att] || current.color; return Y.Color.toRGB(Y.Color.toHex(val)); } }, //fontSize: getPixelFont, IEComputed = {}; addFeature('style', 'computedStyle', { test: function() { return 'getComputedStyle' in Y.config.win; } }); addFeature('style', 'opacity', { test: function() { return 'opacity' in documentElement.style; } }); addFeature('style', 'filter', { test: function() { return 'filters' in documentElement; } }); // use alpha filter for IE opacity if (!testFeature('style', 'opacity') && testFeature('style', 'filter')) { Y.DOM.CUSTOM_STYLES[OPACITY] = { get: function(node) { var val = 100; try { // will error if no DXImageTransform val = node[FILTERS]['DXImageTransform.Microsoft.Alpha'][OPACITY]; } catch(e) { try { // make sure its in the document val = node[FILTERS]('alpha')[OPACITY]; } catch(err) { Y.log('getStyle: IE opacity filter not found; returning 1', 'warn', 'dom-style'); } } return val / 100; }, set: function(node, val, style) { var current, styleObj = _getStyleObj(node), currentFilter = styleObj[FILTER]; style = style || node.style; if (val === '') { // normalize inline style behavior current = (OPACITY in styleObj) ? styleObj[OPACITY] : 1; // revert to original opacity val = current; } if (typeof currentFilter == 'string') { // in case not appended style[FILTER] = currentFilter.replace(/alpha([^)]*\))/gi, '') + ((val < 1) ? 'alpha(' + OPACITY + '=' + val * 100 + ')' : ''); if (!style[FILTER]) { style.removeAttribute(FILTER); } if (!styleObj[HAS_LAYOUT]) { style.zoom = 1; // needs layout } } } }; } try { Y.config.doc.createElement('div').style.height = '-1px'; } catch(e) { // IE throws error on invalid style set; trap common cases Y.DOM.CUSTOM_STYLES.height = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.height = val; } else { Y.log('invalid style value for height: ' + val, 'warn', 'dom-style'); } } }; Y.DOM.CUSTOM_STYLES.width = { set: function(node, val, style) { var floatVal = parseFloat(val); if (floatVal >= 0 || val === 'auto' || val === '') { style.width = val; } else { Y.log('invalid style value for width: ' + val, 'warn', 'dom-style'); } } }; } if (!testFeature('style', 'computedStyle')) { // TODO: top, right, bottom, left IEComputed[WIDTH] = IEComputed[HEIGHT] = ComputedStyle.getOffset; IEComputed.color = IEComputed.backgroundColor = ComputedStyle.getColor; IEComputed[BORDER_WIDTH] = IEComputed[BORDER_TOP_WIDTH] = IEComputed[BORDER_RIGHT_WIDTH] = IEComputed[BORDER_BOTTOM_WIDTH] = IEComputed[BORDER_LEFT_WIDTH] = ComputedStyle.getBorderWidth; IEComputed.marginTop = IEComputed.marginRight = IEComputed.marginBottom = IEComputed.marginLeft = ComputedStyle.getMargin; IEComputed.visibility = ComputedStyle.getVisibility; IEComputed.borderColor = IEComputed.borderTopColor = IEComputed.borderRightColor = IEComputed.borderBottomColor = IEComputed.borderLeftColor = ComputedStyle.getBorderColor; Y.DOM[GET_COMPUTED_STYLE] = ComputedStyle.get; Y.namespace('DOM.IE'); Y.DOM.IE.COMPUTED = IEComputed; Y.DOM.IE.ComputedStyle = ComputedStyle; } })(Y); }, '@VERSION@', {"requires": ["dom-style"]}); YUI.add('dom-screen', function (Y, NAME) { (function(Y) { /** * Adds position and region management functionality to DOM. * @module dom * @submodule dom-screen * @for DOM */ var DOCUMENT_ELEMENT = 'documentElement', COMPAT_MODE = 'compatMode', POSITION = 'position', FIXED = 'fixed', RELATIVE = 'relative', LEFT = 'left', TOP = 'top', _BACK_COMPAT = 'BackCompat', MEDIUM = 'medium', BORDER_LEFT_WIDTH = 'borderLeftWidth', BORDER_TOP_WIDTH = 'borderTopWidth', GET_BOUNDING_CLIENT_RECT = 'getBoundingClientRect', GET_COMPUTED_STYLE = 'getComputedStyle', Y_DOM = Y.DOM, // TODO: how about thead/tbody/tfoot/tr? // TODO: does caption matter? RE_TABLE = /^t(?:able|d|h)$/i, SCROLL_NODE; if (Y.UA.ie) { if (Y.config.doc[COMPAT_MODE] !== 'BackCompat') { SCROLL_NODE = DOCUMENT_ELEMENT; } else { SCROLL_NODE = 'body'; } } Y.mix(Y_DOM, { /** * Returns the inner height of the viewport (exludes scrollbar). * @method winHeight * @return {Number} The current height of the viewport. */ winHeight: function(node) { var h = Y_DOM._getWinSize(node).height; Y.log('winHeight returning ' + h, 'info', 'dom-screen'); return h; }, /** * Returns the inner width of the viewport (exludes scrollbar). * @method winWidth * @return {Number} The current width of the viewport. */ winWidth: function(node) { var w = Y_DOM._getWinSize(node).width; Y.log('winWidth returning ' + w, 'info', 'dom-screen'); return w; }, /** * Document height * @method docHeight * @return {Number} The current height of the document. */ docHeight: function(node) { var h = Y_DOM._getDocSize(node).height; Y.log('docHeight returning ' + h, 'info', 'dom-screen'); return Math.max(h, Y_DOM._getWinSize(node).height); }, /** * Document width * @method docWidth * @return {Number} The current width of the document. */ docWidth: function(node) { var w = Y_DOM._getDocSize(node).width; Y.log('docWidth returning ' + w, 'info', 'dom-screen'); return Math.max(w, Y_DOM._getWinSize(node).width); }, /** * Amount page has been scroll horizontally * @method docScrollX * @return {Number} The current amount the screen is scrolled horizontally. */ docScrollX: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageXOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollLeft, doc.body.scrollLeft, pageOffset); }, /** * Amount page has been scroll vertically * @method docScrollY * @return {Number} The current amount the screen is scrolled vertically. */ docScrollY: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; // perf optimization var dv = doc.defaultView, pageOffset = (dv) ? dv.pageYOffset : 0; return Math.max(doc[DOCUMENT_ELEMENT].scrollTop, doc.body.scrollTop, pageOffset); }, /** * Gets the current position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getXY * @param element The target element * @return {Array} The XY position of the element TODO: test inDocument/display? */ getXY: function() { if (Y.config.doc[DOCUMENT_ELEMENT][GET_BOUNDING_CLIENT_RECT]) { return function(node) { var xy = null, scrollLeft, scrollTop, mode, box, offX, offY, doc, win, inDoc, rootNode; if (node && node.tagName) { doc = node.ownerDocument; mode = doc[COMPAT_MODE]; if (mode !== _BACK_COMPAT) { rootNode = doc[DOCUMENT_ELEMENT]; } else { rootNode = doc.body; } // inline inDoc check for perf if (rootNode.contains) { inDoc = rootNode.contains(node); } else { inDoc = Y.DOM.contains(rootNode, node); } if (inDoc) { win = doc.defaultView; // inline scroll calc for perf if (win && 'pageXOffset' in win) { scrollLeft = win.pageXOffset; scrollTop = win.pageYOffset; } else { scrollLeft = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollLeft : Y_DOM.docScrollX(node, doc); scrollTop = (SCROLL_NODE) ? doc[SCROLL_NODE].scrollTop : Y_DOM.docScrollY(node, doc); } if (Y.UA.ie) { // IE < 8, quirks, or compatMode if (!doc.documentMode || doc.documentMode < 8 || mode === _BACK_COMPAT) { offX = rootNode.clientLeft; offY = rootNode.clientTop; } } box = node[GET_BOUNDING_CLIENT_RECT](); xy = [box.left, box.top]; if (offX || offY) { xy[0] -= offX; xy[1] -= offY; } if ((scrollTop || scrollLeft)) { if (!Y.UA.ios || (Y.UA.ios >= 4.2)) { xy[0] += scrollLeft; xy[1] += scrollTop; } } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } else { return function(node) { // manually calculate by crawling up offsetParents //Calculate the Top and Left border sizes (assumes pixels) var xy = null, doc, parentNode, bCheck, scrollTop, scrollLeft; if (node) { if (Y_DOM.inDoc(node)) { xy = [node.offsetLeft, node.offsetTop]; doc = node.ownerDocument; parentNode = node; // TODO: refactor with !! or just falsey bCheck = ((Y.UA.gecko || Y.UA.webkit > 519) ? true : false); // TODO: worth refactoring for TOP/LEFT only? while ((parentNode = parentNode.offsetParent)) { xy[0] += parentNode.offsetLeft; xy[1] += parentNode.offsetTop; if (bCheck) { xy = Y_DOM._calcBorders(parentNode, xy); } } // account for any scrolled ancestors if (Y_DOM.getStyle(node, POSITION) != FIXED) { parentNode = node; while ((parentNode = parentNode.parentNode)) { scrollTop = parentNode.scrollTop; scrollLeft = parentNode.scrollLeft; //Firefox does something funky with borders when overflow is not visible. if (Y.UA.gecko && (Y_DOM.getStyle(parentNode, 'overflow') !== 'visible')) { xy = Y_DOM._calcBorders(parentNode, xy); } if (scrollTop || scrollLeft) { xy[0] -= scrollLeft; xy[1] -= scrollTop; } } xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } else { //Fix FIXED position -- add scrollbars xy[0] += Y_DOM.docScrollX(node, doc); xy[1] += Y_DOM.docScrollY(node, doc); } } else { xy = Y_DOM._getOffset(node); } } return xy; }; } }(),// NOTE: Executing for loadtime branching /** Gets the width of vertical scrollbars on overflowed containers in the body content. @method getScrollbarWidth @return {Number} Pixel width of a scrollbar in the current browser **/ getScrollbarWidth: Y.cached(function () { var doc = Y.config.doc, testNode = doc.createElement('div'), body = doc.getElementsByTagName('body')[0], // 0.1 because cached doesn't support falsy refetch values width = 0.1; if (body) { testNode.style.cssText = "position:absolute;visibility:hidden;overflow:scroll;width:20px;"; testNode.appendChild(doc.createElement('p')).style.height = '1px'; body.insertBefore(testNode, body.firstChild); width = testNode.offsetWidth - testNode.clientWidth; body.removeChild(testNode); } return width; }, null, 0.1), /** * Gets the current X position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getX * @param element The target element * @return {Number} The X position of the element */ getX: function(node) { return Y_DOM.getXY(node)[0]; }, /** * Gets the current Y position of an element based on page coordinates. * Element must be part of the DOM tree to have page coordinates * (display:none or elements not appended return false). * @method getY * @param element The target element * @return {Number} The Y position of the element */ getY: function(node) { return Y_DOM.getXY(node)[1]; }, /** * Set the position of an html element in page coordinates. * The element must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setXY * @param element The target element * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @param {Boolean} noRetry By default we try and set the position a second time if the first fails */ setXY: function(node, xy, noRetry) { var setStyle = Y_DOM.setStyle, pos, delta, newXY, currentXY; if (node && xy) { pos = Y_DOM.getStyle(node, POSITION); delta = Y_DOM._getOffset(node); if (pos == 'static') { // default to relative pos = RELATIVE; setStyle(node, POSITION, pos); } currentXY = Y_DOM.getXY(node); if (xy[0] !== null) { setStyle(node, LEFT, xy[0] - currentXY[0] + delta[0] + 'px'); } if (xy[1] !== null) { setStyle(node, TOP, xy[1] - currentXY[1] + delta[1] + 'px'); } if (!noRetry) { newXY = Y_DOM.getXY(node); if (newXY[0] !== xy[0] || newXY[1] !== xy[1]) { Y_DOM.setXY(node, xy, true); } } Y.log('setXY setting position to ' + xy, 'info', 'dom-screen'); } else { Y.log('setXY failed to set ' + node + ' to ' + xy, 'info', 'dom-screen'); } }, /** * Set the X position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setX * @param element The target element * @param {Number} x The X values for new position (coordinates are page-based) */ setX: function(node, x) { return Y_DOM.setXY(node, [x, null]); }, /** * Set the Y position of an html element in page coordinates, regardless of how the element is positioned. * The element(s) must be part of the DOM tree to have page coordinates (display:none or elements not appended return false). * @method setY * @param element The target element * @param {Number} y The Y values for new position (coordinates are page-based) */ setY: function(node, y) { return Y_DOM.setXY(node, [null, y]); }, /** * @method swapXY * @description Swap the xy position with another node * @param {Node} node The node to swap with * @param {Node} otherNode The other node to swap with * @return {Node} */ swapXY: function(node, otherNode) { var xy = Y_DOM.getXY(node); Y_DOM.setXY(node, Y_DOM.getXY(otherNode)); Y_DOM.setXY(otherNode, xy); }, _calcBorders: function(node, xy2) { var t = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_TOP_WIDTH), 10) || 0, l = parseInt(Y_DOM[GET_COMPUTED_STYLE](node, BORDER_LEFT_WIDTH), 10) || 0; if (Y.UA.gecko) { if (RE_TABLE.test(node.tagName)) { t = 0; l = 0; } } xy2[0] += l; xy2[1] += t; return xy2; }, _getWinSize: function(node, doc) { doc = doc || (node) ? Y_DOM._getDoc(node) : Y.config.doc; var win = doc.defaultView || doc.parentWindow, mode = doc[COMPAT_MODE], h = win.innerHeight, w = win.innerWidth, root = doc[DOCUMENT_ELEMENT]; if ( mode && !Y.UA.opera ) { // IE, Gecko if (mode != 'CSS1Compat') { // Quirks root = doc.body; } h = root.clientHeight; w = root.clientWidth; } return { height: h, width: w }; }, _getDocSize: function(node) { var doc = (node) ? Y_DOM._getDoc(node) : Y.config.doc, root = doc[DOCUMENT_ELEMENT]; if (doc[COMPAT_MODE] != 'CSS1Compat') { root = doc.body; } return { height: root.scrollHeight, width: root.scrollWidth }; } }); })(Y); (function(Y) { var TOP = 'top', RIGHT = 'right', BOTTOM = 'bottom', LEFT = 'left', getOffsets = function(r1, r2) { var t = Math.max(r1[TOP], r2[TOP]), r = Math.min(r1[RIGHT], r2[RIGHT]), b = Math.min(r1[BOTTOM], r2[BOTTOM]), l = Math.max(r1[LEFT], r2[LEFT]), ret = {}; ret[TOP] = t; ret[RIGHT] = r; ret[BOTTOM] = b; ret[LEFT] = l; return ret; }, DOM = Y.DOM; Y.mix(DOM, { /** * Returns an Object literal containing the following about this element: (top, right, bottom, left) * @for DOM * @method region * @param {HTMLElement} element The DOM element. * @return {Object} Object literal containing the following about this element: (top, right, bottom, left) */ region: function(node) { var xy = DOM.getXY(node), ret = false; if (node && xy) { ret = DOM._getRegion( xy[1], // top xy[0] + node.offsetWidth, // right xy[1] + node.offsetHeight, // bottom xy[0] // left ); } return ret; }, /** * Find the intersect information for the passed nodes. * @method intersect * @for DOM * @param {HTMLElement} element The first element * @param {HTMLElement | Object} element2 The element or region to check the interect with * @param {Object} altRegion An object literal containing the region for the first element if we already have the data (for performance e.g. DragDrop) * @return {Object} Object literal containing the following intersection data: (top, right, bottom, left, area, yoff, xoff, inRegion) */ intersect: function(node, node2, altRegion) { var r = altRegion || DOM.region(node), region = {}, n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } off = getOffsets(region, r); return { top: off[TOP], right: off[RIGHT], bottom: off[BOTTOM], left: off[LEFT], area: ((off[BOTTOM] - off[TOP]) * (off[RIGHT] - off[LEFT])), yoff: ((off[BOTTOM] - off[TOP])), xoff: (off[RIGHT] - off[LEFT]), inRegion: DOM.inRegion(node, node2, false, altRegion) }; }, /** * Check if any part of this node is in the passed region * @method inRegion * @for DOM * @param {Object} node The node to get the region from * @param {Object} node2 The second node to get the region from or an Object literal of the region * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inRegion: function(node, node2, all, altRegion) { var region = {}, r = altRegion || DOM.region(node), n = node2, off; if (n.tagName) { region = DOM.region(n); } else if (Y.Lang.isObject(node2)) { region = node2; } else { return false; } if (all) { return ( r[LEFT] >= region[LEFT] && r[RIGHT] <= region[RIGHT] && r[TOP] >= region[TOP] && r[BOTTOM] <= region[BOTTOM] ); } else { off = getOffsets(region, r); if (off[BOTTOM] >= off[TOP] && off[RIGHT] >= off[LEFT]) { return true; } else { return false; } } }, /** * Check if any part of this element is in the viewport * @method inViewportRegion * @for DOM * @param {HTMLElement} element The DOM element. * @param {Boolean} all Should all of the node be inside the region * @param {Object} altRegion An object literal containing the region for this node if we already have the data (for performance e.g. DragDrop) * @return {Boolean} True if in region, false if not. */ inViewportRegion: function(node, all, altRegion) { return DOM.inRegion(node, DOM.viewportRegion(node), all, altRegion); }, _getRegion: function(t, r, b, l) { var region = {}; region[TOP] = region[1] = t; region[LEFT] = region[0] = l; region[BOTTOM] = b; region[RIGHT] = r; region.width = region[RIGHT] - region[LEFT]; region.height = region[BOTTOM] - region[TOP]; return region; }, /** * Returns an Object literal containing the following about the visible region of viewport: (top, right, bottom, left) * @method viewportRegion * @for DOM * @return {Object} Object literal containing the following about the visible region of the viewport: (top, right, bottom, left) */ viewportRegion: function(node) { node = node || Y.config.doc.documentElement; var ret = false, scrollX, scrollY; if (node) { scrollX = DOM.docScrollX(node); scrollY = DOM.docScrollY(node); ret = DOM._getRegion(scrollY, // top DOM.winWidth(node) + scrollX, // right scrollY + DOM.winHeight(node), // bottom scrollX); // left } return ret; } }); })(Y); }, '@VERSION@', {"requires": ["dom-base", "dom-style"]}); YUI.add('selector-native', function (Y, NAME) { (function(Y) { /** * The selector-native module provides support for native querySelector * @module dom * @submodule selector-native * @for Selector */ /** * Provides support for using CSS selectors to query the DOM * @class Selector * @static * @for Selector */ Y.namespace('Selector'); // allow native module to standalone var COMPARE_DOCUMENT_POSITION = 'compareDocumentPosition', OWNER_DOCUMENT = 'ownerDocument'; var Selector = { _types: { esc: { token: '\uE000', re: /\\[:\[\]\(\)#\.\'\>+~"]/gi }, attr: { token: '\uE001', re: /(\[[^\]]*\])/g }, pseudo: { token: '\uE002', re: /(\([^\)]*\))/g } }, useNative: true, _escapeId: function(id) { if (id) { id = id.replace(/([:\[\]\(\)#\.'<>+~"])/g,'\\$1'); } return id; }, _compare: ('sourceIndex' in Y.config.doc.documentElement) ? function(nodeA, nodeB) { var a = nodeA.sourceIndex, b = nodeB.sourceIndex; if (a === b) { return 0; } else if (a > b) { return 1; } return -1; } : (Y.config.doc.documentElement[COMPARE_DOCUMENT_POSITION] ? function(nodeA, nodeB) { if (nodeA[COMPARE_DOCUMENT_POSITION](nodeB) & 4) { return -1; } else { return 1; } } : function(nodeA, nodeB) { var rangeA, rangeB, compare; if (nodeA && nodeB) { rangeA = nodeA[OWNER_DOCUMENT].createRange(); rangeA.setStart(nodeA, 0); rangeB = nodeB[OWNER_DOCUMENT].createRange(); rangeB.setStart(nodeB, 0); compare = rangeA.compareBoundaryPoints(1, rangeB); // 1 === Range.START_TO_END } return compare; }), _sort: function(nodes) { if (nodes) { nodes = Y.Array(nodes, 0, true); if (nodes.sort) { nodes.sort(Selector._compare); } } return nodes; }, _deDupe: function(nodes) { var ret = [], i, node; for (i = 0; (node = nodes[i++]);) { if (!node._found) { ret[ret.length] = node; node._found = true; } } for (i = 0; (node = ret[i++]);) { node._found = null; node.removeAttribute('_found'); } return ret; }, /** * Retrieves a set of nodes based on a given CSS selector. * @method query * * @param {string} selector The CSS Selector to test the node against. * @param {HTMLElement} root optional An HTMLElement to start the query from. Defaults to Y.config.doc * @param {Boolean} firstOnly optional Whether or not to return only the first match. * @return {Array} An array of nodes that match the given selector. * @static */ query: function(selector, root, firstOnly, skipNative) { root = root || Y.config.doc; var ret = [], useNative = (Y.Selector.useNative && Y.config.doc.querySelector && !skipNative), queries = [[selector, root]], query, result, i, fn = (useNative) ? Y.Selector._nativeQuery : Y.Selector._bruteQuery; if (selector && fn) { // split group into seperate queries if (!skipNative && // already done if skipping (!useNative || root.tagName)) { // split native when element scoping is needed queries = Selector._splitQueries(selector, root); } for (i = 0; (query = queries[i++]);) { result = fn(query[0], query[1], firstOnly); if (!firstOnly) { // coerce DOM Collection to Array result = Y.Array(result, 0, true); } if (result) { ret = ret.concat(result); } } if (queries.length > 1) { // remove dupes and sort by doc order ret = Selector._sort(Selector._deDupe(ret)); } } Y.log('query: ' + selector + ' returning: ' + ret.length, 'info', 'Selector'); return (firstOnly) ? (ret[0] || null) : ret; }, _replaceSelector: function(selector) { var esc = Y.Selector._parse('esc', selector), // pull escaped colon, brackets, etc. attrs, pseudos; // first replace escaped chars, which could be present in attrs or pseudos selector = Y.Selector._replace('esc', selector); // then replace pseudos before attrs to avoid replacing :not([foo]) pseudos = Y.Selector._parse('pseudo', selector); selector = Selector._replace('pseudo', selector); attrs = Y.Selector._parse('attr', selector); selector = Y.Selector._replace('attr', selector); return { esc: esc, attrs: attrs, pseudos: pseudos, selector: selector }; }, _restoreSelector: function(replaced) { var selector = replaced.selector; selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _replaceCommas: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; if (selector) { selector = selector.replace(/,/g, '\uE007'); replaced.selector = selector; selector = Y.Selector._restoreSelector(replaced); } return selector; }, // allows element scoped queries to begin with combinator // e.g. query('> p', document.body) === query('body > p') _splitQueries: function(selector, node) { if (selector.indexOf(',') > -1) { selector = Y.Selector._replaceCommas(selector); } var groups = selector.split('\uE007'), // split on replaced comma token queries = [], prefix = '', id, i, len; if (node) { // enforce for element scoping if (node.nodeType === 1) { // Elements only id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } prefix = '[id="' + id + '"] '; } for (i = 0, len = groups.length; i < len; ++i) { selector = prefix + groups[i]; queries.push([selector, node]); } } return queries; }, _nativeQuery: function(selector, root, one) { if (Y.UA.webkit && selector.indexOf(':checked') > -1 && (Y.Selector.pseudos && Y.Selector.pseudos.checked)) { // webkit (chrome, safari) fails to pick up "selected" with "checked" return Y.Selector.query(selector, root, one, true); // redo with skipNative true to try brute query } try { //Y.log('trying native query with: ' + selector, 'info', 'selector-native'); return root['querySelector' + (one ? '' : 'All')](selector); } catch(e) { // fallback to brute if available //Y.log('native query error; reverting to brute query with: ' + selector, 'info', 'selector-native'); return Y.Selector.query(selector, root, one, true); // redo with skipNative true } }, filter: function(nodes, selector) { var ret = [], i, node; if (nodes && selector) { for (i = 0; (node = nodes[i++]);) { if (Y.Selector.test(node, selector)) { ret[ret.length] = node; } } } else { Y.log('invalid filter input (nodes: ' + nodes + ', selector: ' + selector + ')', 'warn', 'Selector'); } return ret; }, test: function(node, selector, root) { var ret = false, useFrag = false, groups, parent, item, items, frag, id, i, j, group; if (node && node.tagName) { // only test HTMLElements if (typeof selector == 'function') { // test with function ret = selector.call(node, node); } else { // test with query // we need a root if off-doc groups = selector.split(','); if (!root && !Y.DOM.inDoc(node)) { parent = node.parentNode; if (parent) { root = parent; } else { // only use frag when no parent to query frag = node[OWNER_DOCUMENT].createDocumentFragment(); frag.appendChild(node); root = frag; useFrag = true; } } root = root || node[OWNER_DOCUMENT]; id = Y.Selector._escapeId(Y.DOM.getId(node)); if (!id) { id = Y.guid(); Y.DOM.setId(node, id); } for (i = 0; (group = groups[i++]);) { // TODO: off-dom test group += '[id="' + id + '"]'; items = Y.Selector.query(group, root); for (j = 0; item = items[j++];) { if (item === node) { ret = true; break; } } if (ret) { break; } } if (useFrag) { // cleanup frag.removeChild(node); } }; } return ret; }, /** * A convenience function to emulate Y.Node's aNode.ancestor(selector). * @param {HTMLElement} element An HTMLElement to start the query from. * @param {String} selector The CSS selector to test the node against. * @return {HTMLElement} The ancestor node matching the selector, or null. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @static * @method ancestor */ ancestor: function (element, selector, testSelf) { return Y.DOM.ancestor(element, function(n) { return Y.Selector.test(n, selector); }, testSelf); }, _parse: function(name, selector) { return selector.match(Y.Selector._types[name].re); }, _replace: function(name, selector) { var o = Y.Selector._types[name]; return selector.replace(o.re, o.token); }, _restore: function(name, selector, items) { if (items) { var token = Y.Selector._types[name].token, i, len; for (i = 0, len = items.length; i < len; ++i) { selector = selector.replace(token, items[i]); } } return selector; } }; Y.mix(Y.Selector, Selector, true); })(Y); }, '@VERSION@', {"requires": ["dom-base"]}); YUI.add('selector', function (Y, NAME) { }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('event-custom-base', function (Y, NAME) { /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom */ Y.Env.evt = { handles: {}, plugins: {} }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * Allows for the insertion of methods that are executed before or after * a specified method * @class Do * @static */ var DO_BEFORE = 0, DO_AFTER = 1, DO = { /** * Cache of objects touched by the utility * @property objs * @static * @deprecated Since 3.6.0. The `_yuiaop` property on the AOP'd object * replaces the role of this property, but is considered to be private, and * is only mentioned to provide a migration path. * * If you have a use case which warrants migration to the _yuiaop property, * please file a ticket to let us know what it's used for and we can see if * we need to expose hooks for that functionality more formally. */ objs: null, /** * <p>Execute the supplied method before the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterArgs(message, newArgArray)</code></dt> * <dd>Replace the arguments that the original function will be * called with.</dd> * <dt></code>Y.Do.Prevent(message)</code></dt> * <dd>Don't execute the wrapped function. Other before phase * wrappers will be executed.</dd> * </dl> * * @method before * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * when the event fires. * @return {string} handle for the subscription * @static */ before: function(fn, obj, sFn, c) { // Y.log('Do before: ' + sFn, 'info', 'event'); var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_BEFORE, f, obj, sFn); }, /** * <p>Execute the supplied method after the specified function. Wrapping * function may optionally return an instance of the following classes to * further alter runtime behavior:</p> * <dl> * <dt></code>Y.Do.Halt(message, returnValue)</code></dt> * <dd>Immediatly stop execution and return * <code>returnValue</code>. No other wrapping functions will be * executed.</dd> * <dt></code>Y.Do.AlterReturn(message, returnValue)</code></dt> * <dd>Return <code>returnValue</code> instead of the wrapped * method's original return value. This can be further altered by * other after phase wrappers.</dd> * </dl> * * <p>The static properties <code>Y.Do.originalRetVal</code> and * <code>Y.Do.currentRetVal</code> will be populated for reference.</p> * * @method after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @param arg* {mixed} 0..n additional arguments to supply to the subscriber * @return {string} handle for the subscription * @static */ after: function(fn, obj, sFn, c) { var f = fn, a; if (c) { a = [fn, c].concat(Y.Array(arguments, 4, true)); f = Y.rbind.apply(Y, a); } return this._inject(DO_AFTER, f, obj, sFn); }, /** * Execute the supplied method before or after the specified function. * Used by <code>before</code> and <code>after</code>. * * @method _inject * @param when {string} before or after * @param fn {Function} the function to execute * @param obj the object hosting the method to displace * @param sFn {string} the name of the method to displace * @param c The execution context for fn * @return {string} handle for the subscription * @private * @static */ _inject: function(when, fn, obj, sFn) { // object id var id = Y.stamp(obj), o, sid; if (!obj._yuiaop) { // create a map entry for the obj if it doesn't exist, to hold overridden methods obj._yuiaop = {}; } o = obj._yuiaop; if (!o[sFn]) { // create a map entry for the method if it doesn't exist o[sFn] = new Y.Do.Method(obj, sFn); // re-route the method to our wrapper obj[sFn] = function() { return o[sFn].exec.apply(o[sFn], arguments); }; } // subscriber id sid = id + Y.stamp(fn) + sFn; // register the callback o[sFn].register(sid, fn, when); return new Y.EventHandle(o[sFn], sid); }, /** * Detach a before or after subscription. * * @method detach * @param handle {string} the subscription handle * @static */ detach: function(handle) { if (handle.detach) { handle.detach(); } } }; Y.Do = DO; ////////////////////////////////////////////////////////////////////////// /** * Contains the return value from the wrapped method, accessible * by 'after' event listeners. * * @property originalRetVal * @static * @since 3.2.0 */ /** * Contains the current state of the return value, consumable by * 'after' event listeners, and updated if an after subscriber * changes the return value generated by the wrapped function. * * @property currentRetVal * @static * @since 3.2.0 */ ////////////////////////////////////////////////////////////////////////// /** * Wrapper for a displaced method with aop enabled * @class Do.Method * @constructor * @param obj The object to operate on * @param sFn The name of the method to displace */ DO.Method = function(obj, sFn) { this.obj = obj; this.methodName = sFn; this.method = obj[sFn]; this.before = {}; this.after = {}; }; /** * Register a aop subscriber * @method register * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype.register = function (sid, fn, when) { if (when) { this.after[sid] = fn; } else { this.before[sid] = fn; } }; /** * Unregister a aop subscriber * @method delete * @param sid {string} the subscriber id * @param fn {Function} the function to execute * @param when {string} when to execute the function */ DO.Method.prototype._delete = function (sid) { // Y.log('Y.Do._delete: ' + sid, 'info', 'Event'); delete this.before[sid]; delete this.after[sid]; }; /** * <p>Execute the wrapped method. All arguments are passed into the wrapping * functions. If any of the before wrappers return an instance of * <code>Y.Do.Halt</code> or <code>Y.Do.Prevent</code>, neither the wrapped * function nor any after phase subscribers will be executed.</p> * * <p>The return value will be the return value of the wrapped function or one * provided by a wrapper function via an instance of <code>Y.Do.Halt</code> or * <code>Y.Do.AlterReturn</code>. * * @method exec * @param arg* {any} Arguments are passed to the wrapping and wrapped functions * @return {any} Return value of wrapped function unless overwritten (see above) */ DO.Method.prototype.exec = function () { var args = Y.Array(arguments, 0, true), i, ret, newRet, bf = this.before, af = this.after, prevented = false; // execute before for (i in bf) { if (bf.hasOwnProperty(i)) { ret = bf[i].apply(this.obj, args); if (ret) { switch (ret.constructor) { case DO.Halt: return ret.retVal; case DO.AlterArgs: args = ret.newArgs; break; case DO.Prevent: prevented = true; break; default: } } } } // execute method if (!prevented) { ret = this.method.apply(this.obj, args); } DO.originalRetVal = ret; DO.currentRetVal = ret; // execute after methods. for (i in af) { if (af.hasOwnProperty(i)) { newRet = af[i].apply(this.obj, args); // Stop processing if a Halt object is returned if (newRet && newRet.constructor === DO.Halt) { return newRet.retVal; // Check for a new return value } else if (newRet && newRet.constructor === DO.AlterReturn) { ret = newRet.newRetVal; // Update the static retval state DO.currentRetVal = ret; } } } return ret; }; ////////////////////////////////////////////////////////////////////////// /** * Return an AlterArgs object when you want to change the arguments that * were passed into the function. Useful for Do.before subscribers. An * example would be a service that scrubs out illegal characters prior to * executing the core business logic. * @class Do.AlterArgs * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newArgs {Array} Call parameters to be used for the original method * instead of the arguments originally passed in. */ DO.AlterArgs = function(msg, newArgs) { this.msg = msg; this.newArgs = newArgs; }; /** * Return an AlterReturn object when you want to change the result returned * from the core method to the caller. Useful for Do.after subscribers. * @class Do.AlterReturn * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param newRetVal {any} Return value passed to code that invoked the wrapped * function. */ DO.AlterReturn = function(msg, newRetVal) { this.msg = msg; this.newRetVal = newRetVal; }; /** * Return a Halt object when you want to terminate the execution * of all subsequent subscribers as well as the wrapped method * if it has not exectued yet. Useful for Do.before subscribers. * @class Do.Halt * @constructor * @param msg {String} (optional) Explanation of why the termination was done * @param retVal {any} Return value passed to code that invoked the wrapped * function. */ DO.Halt = function(msg, retVal) { this.msg = msg; this.retVal = retVal; }; /** * Return a Prevent object when you want to prevent the wrapped function * from executing, but want the remaining listeners to execute. Useful * for Do.before subscribers. * @class Do.Prevent * @constructor * @param msg {String} (optional) Explanation of why the termination was done */ DO.Prevent = function(msg) { this.msg = msg; }; /** * Return an Error object when you want to terminate the execution * of all subsequent method calls. * @class Do.Error * @constructor * @param msg {String} (optional) Explanation of the altered return value * @param retVal {any} Return value passed to code that invoked the wrapped * function. * @deprecated use Y.Do.Halt or Y.Do.Prevent */ DO.Error = DO.Halt; ////////////////////////////////////////////////////////////////////////// /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ // var onsubscribeType = "_event:onsub", var YArray = Y.Array, AFTER = 'after', CONFIGS = [ 'broadcast', 'monitored', 'bubbles', 'context', 'contextFn', 'currentTarget', 'defaultFn', 'defaultTargetOnly', 'details', 'emitFacade', 'fireOnce', 'async', 'host', 'preventable', 'preventedFn', 'queuable', 'silent', 'stoppedFn', 'target', 'type' ], CONFIGS_HASH = YArray.hash(CONFIGS), nativeSlice = Array.prototype.slice, YUI3_SIGNATURE = 9, YUI_LOG = 'yui:log', mixConfigs = function(r, s, ov) { var p; for (p in s) { if (CONFIGS_HASH[p] && (ov || !(p in r))) { r[p] = s[p]; } } return r; }; /** * The CustomEvent class lets you define events for your application * that can be subscribed to by one or more independent component. * * @param {String} type The type of event, which is passed to the callback * when the event fires. * @param {object} defaults configuration object. * @class CustomEvent * @constructor */ /** * The type of event, returned to subscribers when the event fires * @property type * @type string */ /** * By default all custom events are logged in the debug build, set silent * to true to disable debug outpu for this event. * @property silent * @type boolean */ Y.CustomEvent = function(type, defaults) { this._kds = Y.CustomEvent.keepDeprecatedSubs; this.id = Y.guid(); this.type = type; this.silent = this.logSystem = (type === YUI_LOG); if (this._kds) { /** * The subscribers to this event * @property subscribers * @type Subscriber {} * @deprecated */ /** * 'After' subscribers * @property afters * @type Subscriber {} * @deprecated */ this.subscribers = {}; this.afters = {}; } if (defaults) { mixConfigs(this, defaults, true); } }; /** * Static flag to enable population of the <a href="#property_subscribers">`subscribers`</a> * and <a href="#property_subscribers">`afters`</a> properties held on a `CustomEvent` instance. * * These properties were changed to private properties (`_subscribers` and `_afters`), and * converted from objects to arrays for performance reasons. * * Setting this property to true will populate the deprecated `subscribers` and `afters` * properties for people who may be using them (which is expected to be rare). There will * be a performance hit, compared to the new array based implementation. * * If you are using these deprecated properties for a use case which the public API * does not support, please file an enhancement request, and we can provide an alternate * public implementation which doesn't have the performance cost required to maintiain the * properties as objects. * * @property keepDeprecatedSubs * @static * @for CustomEvent * @type boolean * @default false * @deprecated */ Y.CustomEvent.keepDeprecatedSubs = false; Y.CustomEvent.mixConfigs = mixConfigs; Y.CustomEvent.prototype = { constructor: Y.CustomEvent, /** * Monitor when an event is attached or detached. * * @property monitored * @type boolean */ /** * If 0, this event does not broadcast. If 1, the YUI instance is notified * every time this event fires. If 2, the YUI instance and the YUI global * (if event is enabled on the global) are notified every time this event * fires. * @property broadcast * @type int */ /** * Specifies whether this event should be queued when the host is actively * processing an event. This will effect exectution order of the callbacks * for the various events. * @property queuable * @type boolean * @default false */ /** * This event has fired if true * * @property fired * @type boolean * @default false; */ /** * An array containing the arguments the custom event * was last fired with. * @property firedWith * @type Array */ /** * This event should only fire one time if true, and if * it has fired, any new subscribers should be notified * immediately. * * @property fireOnce * @type boolean * @default false; */ /** * fireOnce listeners will fire syncronously unless async * is set to true * @property async * @type boolean * @default false */ /** * Flag for stopPropagation that is modified during fire() * 1 means to stop propagation to bubble targets. 2 means * to also stop additional subscribers on this target. * @property stopped * @type int */ /** * Flag for preventDefault that is modified during fire(). * if it is not 0, the default behavior for this event * @property prevented * @type int */ /** * Specifies the host for this custom event. This is used * to enable event bubbling * @property host * @type EventTarget */ /** * The default function to execute after event listeners * have fire, but only if the default action was not * prevented. * @property defaultFn * @type Function */ /** * The function to execute if a subscriber calls * stopPropagation or stopImmediatePropagation * @property stoppedFn * @type Function */ /** * The function to execute if a subscriber calls * preventDefault * @property preventedFn * @type Function */ /** * The subscribers to this event * @property _subscribers * @type Subscriber [] * @private */ /** * 'After' subscribers * @property _afters * @type Subscriber [] * @private */ /** * If set to true, the custom event will deliver an EventFacade object * that is similar to a DOM event object. * @property emitFacade * @type boolean * @default false */ /** * Supports multiple options for listener signatures in order to * port YUI 2 apps. * @property signature * @type int * @default 9 */ signature : YUI3_SIGNATURE, /** * The context the the event will fire from by default. Defaults to the YUI * instance. * @property context * @type object */ context : Y, /** * Specifies whether or not this event's default function * can be cancelled by a subscriber by executing preventDefault() * on the event facade * @property preventable * @type boolean * @default true */ preventable : true, /** * Specifies whether or not a subscriber can stop the event propagation * via stopPropagation(), stopImmediatePropagation(), or halt() * * Events can only bubble if emitFacade is true. * * @property bubbles * @type boolean * @default true */ bubbles : true, /** * Returns the number of subscribers for this event as the sum of the on() * subscribers and after() subscribers. * * @method hasSubs * @return Number */ hasSubs: function(when) { var s = 0, a = 0, subs = this._subscribers, afters = this._afters, sib = this.sibling; if (subs) { s = subs.length; } if (afters) { a = afters.length; } if (sib) { subs = sib._subscribers; afters = sib._afters; if (subs) { s += subs.length; } if (afters) { a += afters.length; } } if (when) { return (when === 'after') ? a : s; } return (s + a); }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('detach', 'attach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { this.monitored = true; var type = this.id + '|' + this.type + '_' + what, args = nativeSlice.call(arguments, 0); args[0] = type; return this.host.on.apply(this.host, args); }, /** * Get all of the subscribers to this event and any sibling event * @method getSubs * @return {Array} first item is the on subscribers, second the after. */ getSubs: function() { var sibling = this.sibling, subs = this._subscribers, afters = this._afters, siblingSubs, siblingAfters; if (sibling) { siblingSubs = sibling._subscribers; siblingAfters = sibling._afters; } if (siblingSubs) { if (subs) { subs = subs.concat(siblingSubs); } else { subs = siblingSubs.concat(); } } else { if (subs) { subs = subs.concat(); } else { subs = []; } } if (siblingAfters) { if (afters) { afters = afters.concat(siblingAfters); } else { afters = siblingAfters.concat(); } } else { if (afters) { afters = afters.concat(); } else { afters = []; } } return [subs, afters]; }, /** * Apply configuration properties. Only applies the CONFIG whitelist * @method applyConfig * @param o hash of properties to apply. * @param force {boolean} if true, properties that exist on the event * will be overwritten. */ applyConfig: function(o, force) { mixConfigs(this, o, force); }, /** * Create the Subscription for subscribing function, context, and bound * arguments. If this is a fireOnce event, the subscriber is immediately * notified. * * @method _on * @param fn {Function} Subscription callback * @param [context] {Object} Override `this` in the callback * @param [args] {Array} bound arguments that will be passed to the callback after the arguments generated by fire() * @param [when] {String} "after" to slot into after subscribers * @return {EventHandle} * @protected */ _on: function(fn, context, args, when) { if (!fn) { this.log('Invalid callback for CE: ' + this.type); } var s = new Y.Subscriber(fn, context, args, when); if (this.fireOnce && this.fired) { if (this.async) { setTimeout(Y.bind(this._notify, this, s, this.firedWith), 0); } else { this._notify(s, this.firedWith); } } if (when === AFTER) { if (!this._afters) { this._afters = []; this._hasAfters = true; } this._afters.push(s); } else { if (!this._subscribers) { this._subscribers = []; this._hasSubs = true; } this._subscribers.push(s); } if (this._kds) { if (when === AFTER) { this.afters[s.id] = s; } else { this.subscribers[s.id] = s; } } return new Y.EventHandle(this, s); }, /** * Listen for this event * @method subscribe * @param {Function} fn The function to execute. * @return {EventHandle} Unsubscribe handle. * @deprecated use on. */ subscribe: function(fn, context) { Y.log('ce.subscribe deprecated, use "on"', 'warn', 'deprecated'); var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, true); }, /** * Listen for this event * @method on * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} An object with a detach method to detch the handler(s). */ on: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; if (this.monitored && this.host) { this.host._monitor('attach', this, { args: arguments }); } return this._on(fn, context, a, true); }, /** * Listen for this event after the normal subscribers have been notified and * the default behavior has been applied. If a normal subscriber prevents the * default behavior, it also prevents after listeners from firing. * @method after * @param {Function} fn The function to execute. * @param {object} context optional execution context. * @param {mixed} arg* 0..n additional arguments to supply to the subscriber * when the event fires. * @return {EventHandle} handle Unsubscribe handle. */ after: function(fn, context) { var a = (arguments.length > 2) ? nativeSlice.call(arguments, 2) : null; return this._on(fn, context, a, AFTER); }, /** * Detach listeners. * @method detach * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int} returns the number of subscribers unsubscribed. */ detach: function(fn, context) { // unsubscribe handle if (fn && fn.detach) { return fn.detach(); } var i, s, found = 0, subs = this._subscribers, afters = this._afters; if (subs) { for (i = subs.length; i >= 0; i--) { s = subs[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, subs, i); found++; } } } if (afters) { for (i = afters.length; i >= 0; i--) { s = afters[i]; if (s && (!fn || fn === s.fn)) { this._delete(s, afters, i); found++; } } } return found; }, /** * Detach listeners. * @method unsubscribe * @param {Function} fn The subscribed function to remove, if not supplied * all will be removed. * @param {Object} context The context object passed to subscribe. * @return {int|undefined} returns the number of subscribers unsubscribed. * @deprecated use detach. */ unsubscribe: function() { return this.detach.apply(this, arguments); }, /** * Notify a single subscriber * @method _notify * @param {Subscriber} s the subscriber. * @param {Array} args the arguments array to apply to the listener. * @protected */ _notify: function(s, args, ef) { this.log(this.type + '->' + 'sub: ' + s.id); var ret; ret = s.notify(args, this); if (false === ret || this.stopped > 1) { this.log(this.type + ' cancelled by subscriber'); return false; } return true; }, /** * Logger abstraction to centralize the application of the silent flag * @method log * @param {string} msg message to log. * @param {string} cat log category. */ log: function(msg, cat) { if (!this.silent) { Y.log(this.id + ': ' + msg, cat || 'info', 'event'); } }, /** * Notifies the subscribers. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters: * <ul> * <li>The type of event</li> * <li>All of the arguments fire() was executed with as an array</li> * <li>The custom object (if any) that was passed into the subscribe() * method</li> * </ul> * @method fire * @param {Object*} arguments an arbitrary set of parameters to pass to * the handler. * @return {boolean} false if one of the subscribers returned false, * true otherwise. * */ fire: function() { // push is the fastest way to go from arguments to arrays // for most browsers currently // http://jsperf.com/push-vs-concat-vs-slice/2 var args = []; args.push.apply(args, arguments); return this._fire(args); }, /** * Private internal implementation for `fire`, which is can be used directly by * `EventTarget` and other event module classes which have already converted from * an `arguments` list to an array, to avoid the repeated overhead. * * @method _fire * @private * @param {Array} args The array of arguments passed to be passed to handlers. * @return {boolean} false if one of the subscribers returned false, true otherwise. */ _fire: function(args) { if (this.fireOnce && this.fired) { this.log('fireOnce event: ' + this.type + ' already fired'); return true; } else { // this doesn't happen if the event isn't published // this.host._monitor('fire', this.type, args); this.fired = true; if (this.fireOnce) { this.firedWith = args; } if (this.emitFacade) { return this.fireComplex(args); } else { return this.fireSimple(args); } } }, /** * Set up for notifying subscribers of non-emitFacade events. * * @method fireSimple * @param args {Array} Arguments passed to fire() * @return Boolean false if a subscriber returned false * @protected */ fireSimple: function(args) { this.stopped = 0; this.prevented = 0; if (this.hasSubs()) { var subs = this.getSubs(); this._procSubs(subs[0], args); this._procSubs(subs[1], args); } if (this.broadcast) { this._broadcast(args); } return this.stopped ? false : true; }, // Requires the event-custom-complex module for full funcitonality. fireComplex: function(args) { this.log('Missing event-custom-complex needed to emit a facade for: ' + this.type); args[0] = args[0] || {}; return this.fireSimple(args); }, /** * Notifies a list of subscribers. * * @method _procSubs * @param subs {Array} List of subscribers * @param args {Array} Arguments passed to fire() * @param ef {} * @return Boolean false if a subscriber returns false or stops the event * propagation via e.stopPropagation(), * e.stopImmediatePropagation(), or e.halt() * @private */ _procSubs: function(subs, args, ef) { var s, i, l; for (i = 0, l = subs.length; i < l; i++) { s = subs[i]; if (s && s.fn) { if (false === this._notify(s, args, ef)) { this.stopped = 2; } if (this.stopped === 2) { return false; } } } return true; }, /** * Notifies the YUI instance if the event is configured with broadcast = 1, * and both the YUI instance and Y.Global if configured with broadcast = 2. * * @method _broadcast * @param args {Array} Arguments sent to fire() * @private */ _broadcast: function(args) { if (!this.stopped && this.broadcast) { var a = args.concat(); a.unshift(this.type); if (this.host !== Y) { Y.fire.apply(Y, a); } if (this.broadcast === 2) { Y.Global.fire.apply(Y.Global, a); } } }, /** * Removes all listeners * @method unsubscribeAll * @return {int} The number of listeners unsubscribed. * @deprecated use detachAll. */ unsubscribeAll: function() { return this.detachAll.apply(this, arguments); }, /** * Removes all listeners * @method detachAll * @return {int} The number of listeners unsubscribed. */ detachAll: function() { return this.detach(); }, /** * Deletes the subscriber from the internal store of on() and after() * subscribers. * * @method _delete * @param s subscriber object. * @param subs (optional) on or after subscriber array * @param index (optional) The index found. * @private */ _delete: function(s, subs, i) { var when = s._when; if (!subs) { subs = (when === AFTER) ? this._afters : this._subscribers; } if (subs) { i = YArray.indexOf(subs, s, 0); if (s && subs[i] === s) { subs.splice(i, 1); if (subs.length === 0) { if (when === AFTER) { this._hasAfters = false; } else { this._hasSubs = false; } } } } if (this._kds) { if (when === AFTER) { delete this.afters[s.id]; } else { delete this.subscribers[s.id]; } } if (this.monitored && this.host) { this.host._monitor('detach', this, { ce: this, sub: s }); } if (s) { s.deleted = true; } } }; /** * Stores the subscriber information to be used when the event fires. * @param {Function} fn The wrapped function to execute. * @param {Object} context The value of the keyword 'this' in the listener. * @param {Array} args* 0..n additional arguments to supply the listener. * * @class Subscriber * @constructor */ Y.Subscriber = function(fn, context, args, when) { /** * The callback that will be execute when the event fires * This is wrapped by Y.rbind if obj was supplied. * @property fn * @type Function */ this.fn = fn; /** * Optional 'this' keyword for the listener * @property context * @type Object */ this.context = context; /** * Unique subscriber id * @property id * @type String */ this.id = Y.guid(); /** * Additional arguments to propagate to the subscriber * @property args * @type Array */ this.args = args; this._when = when; /** * Custom events for a given fire transaction. * @property events * @type {EventTarget} */ // this.events = null; /** * This listener only reacts to the event once * @property once */ // this.once = false; }; Y.Subscriber.prototype = { constructor: Y.Subscriber, _notify: function(c, args, ce) { if (this.deleted && !this.postponed) { if (this.postponed) { delete this.fn; delete this.context; } else { delete this.postponed; return null; } } var a = this.args, ret; switch (ce.signature) { case 0: ret = this.fn.call(c, ce.type, args, c); break; case 1: ret = this.fn.call(c, args[0] || null, c); break; default: if (a || args) { args = args || []; a = (a) ? args.concat(a) : args; ret = this.fn.apply(c, a); } else { ret = this.fn.call(c); } } if (this.once) { ce._delete(this); } return ret; }, /** * Executes the subscriber. * @method notify * @param args {Array} Arguments array for the subscriber. * @param ce {CustomEvent} The custom event that sent the notification. */ notify: function(args, ce) { var c = this.context, ret = true; if (!c) { c = (ce.contextFn) ? ce.contextFn() : ce.context; } // only catch errors if we will not re-throw them. if (Y.config && Y.config.throwFail) { ret = this._notify(c, args, ce); } else { try { ret = this._notify(c, args, ce); } catch (e) { Y.error(this + ' failed: ' + e.message, e); } } return ret; }, /** * Returns true if the fn and obj match this objects properties. * Used by the unsubscribe method to match the right subscriber. * * @method contains * @param {Function} fn the function to execute. * @param {Object} context optional 'this' keyword for the listener. * @return {boolean} true if the supplied arguments match this * subscriber's signature. */ contains: function(fn, context) { if (context) { return ((this.fn === fn) && this.context === context); } else { return (this.fn === fn); } }, valueOf : function() { return this.id; } }; /** * Return value from all subscribe operations * @class EventHandle * @constructor * @param {CustomEvent} evt the custom event. * @param {Subscriber} sub the subscriber. */ Y.EventHandle = function(evt, sub) { /** * The custom event * * @property evt * @type CustomEvent */ this.evt = evt; /** * The subscriber object * * @property sub * @type Subscriber */ this.sub = sub; }; Y.EventHandle.prototype = { batch: function(f, c) { f.call(c || this, this); if (Y.Lang.isArray(this.evt)) { Y.Array.each(this.evt, function(h) { h.batch.call(c || h, f); }); } }, /** * Detaches this subscriber * @method detach * @return {int} the number of detached listeners */ detach: function() { var evt = this.evt, detached = 0, i; if (evt) { // Y.log('EventHandle.detach: ' + this.sub, 'info', 'Event'); if (Y.Lang.isArray(evt)) { for (i = 0; i < evt.length; i++) { detached += evt[i].detach(); } } else { evt._delete(this.sub); detached = 1; } } return detached; }, /** * Monitor the event state for the subscribed event. The first parameter * is what should be monitored, the rest are the normal parameters when * subscribing to an event. * @method monitor * @param what {string} what to monitor ('attach', 'detach', 'publish'). * @return {EventHandle} return value from the monitor event subscription. */ monitor: function(what) { return this.evt.monitor.apply(this.evt, arguments); } }; /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event-custom * @submodule event-custom-base */ /** * EventTarget provides the implementation for any object to * publish, subscribe and fire to custom events, and also * alows other EventTargets to target the object with events * sourced from the other object. * EventTarget is designed to be used with Y.augment to wrap * EventCustom in an interface that allows events to be listened to * and fired by name. This makes it possible for implementing code to * subscribe to an event that either has not been created yet, or will * not be created at all. * @class EventTarget * @param opts a configuration object * @config emitFacade {boolean} if true, all events will emit event * facade payloads by default (default false) * @config prefix {String} the prefix to apply to non-prefixed event names */ var L = Y.Lang, PREFIX_DELIMITER = ':', CATEGORY_DELIMITER = '|', AFTER_PREFIX = '~AFTER~', WILD_TYPE_RE = /(.*?)(:)(.*?)/, _wildType = Y.cached(function(type) { return type.replace(WILD_TYPE_RE, "*$2$3"); }), /** * If the instance has a prefix attribute and the * event type is not prefixed, the instance prefix is * applied to the supplied type. * @method _getType * @private */ _getType = function(type, pre) { if (!pre || type.indexOf(PREFIX_DELIMITER) > -1) { return type; } return pre + PREFIX_DELIMITER + type; }, /** * Returns an array with the detach key (if provided), * and the prefixed event name from _getType * Y.on('detachcategory| menu:click', fn) * @method _parseType * @private */ _parseType = Y.cached(function(type, pre) { var t = type, detachcategory, after, i; if (!L.isString(t)) { return t; } i = t.indexOf(AFTER_PREFIX); if (i > -1) { after = true; t = t.substr(AFTER_PREFIX.length); } i = t.indexOf(CATEGORY_DELIMITER); if (i > -1) { detachcategory = t.substr(0, (i)); t = t.substr(i+1); if (t === '*') { t = null; } } // detach category, full type with instance prefix, is this an after listener, short type return [detachcategory, (pre) ? _getType(t, pre) : t, after, t]; }), ET = function(opts) { var etState = this._yuievt, etConfig; if (!etState) { etState = this._yuievt = { events: {}, // PERF: Not much point instantiating lazily. We're bound to have events targets: null, // PERF: Instantiate lazily, if user actually adds target, config: { host: this, context: this }, chain: Y.config.chain }; } etConfig = etState.config; if (opts) { mixConfigs(etConfig, opts, true); if (opts.chain !== undefined) { etState.chain = opts.chain; } if (opts.prefix) { etConfig.prefix = opts.prefix; } } }; ET.prototype = { constructor: ET, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>on</code> except the * listener is immediatelly detached when it is executed. * @method once * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ once: function() { var handle = this.on.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Listen to a custom event hosted by this object one time. * This is the equivalent to <code>after</code> except the * listener is immediatelly detached when it is executed. * @method onceAfter * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ onceAfter: function() { var handle = this.after.apply(this, arguments); handle.batch(function(hand) { if (hand.sub) { hand.sub.once = true; } }); return handle; }, /** * Takes the type parameter passed to 'on' and parses out the * various pieces that could be included in the type. If the * event type is passed without a prefix, it will be expanded * to include the prefix one is supplied or the event target * is configured with a default prefix. * @method parseType * @param {String} type the type * @param {String} [pre=this._yuievt.config.prefix] the prefix * @since 3.3.0 * @return {Array} an array containing: * * the detach category, if supplied, * * the prefixed event type, * * whether or not this is an after listener, * * the supplied event type */ parseType: function(type, pre) { return _parseType(type, pre || this._yuievt.config.prefix); }, /** * Subscribe a callback function to a custom event fired by this object or * from an object that bubbles its events to this object. * * Callback functions for events published with `emitFacade = true` will * receive an `EventFacade` as the first argument (typically named "e"). * These callbacks can then call `e.preventDefault()` to disable the * behavior published to that event's `defaultFn`. See the `EventFacade` * API for all available properties and methods. Subscribers to * non-`emitFacade` events will receive the arguments passed to `fire()` * after the event name. * * To subscribe to multiple events at once, pass an object as the first * argument, where the key:value pairs correspond to the eventName:callback, * or pass an array of event names as the first argument to subscribe to * all listed events with the same callback. * * Returning `false` from a callback is supported as an alternative to * calling `e.preventDefault(); e.stopPropagation();`. However, it is * recommended to use the event methods whenever possible. * * @method on * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching that * subscription */ on: function(type, fn, context) { var yuievt = this._yuievt, parts = _parseType(type, yuievt.config.prefix), f, c, args, ret, ce, detachcategory, handle, store = Y.Env.evt.handles, after, adapt, shorttype, Node = Y.Node, n, domevent, isArr; // full name, args, detachcategory, after this._monitor('attach', parts[1], { args: arguments, category: parts[0], after: parts[2] }); if (L.isObject(type)) { if (L.isFunction(type)) { return Y.Do.before.apply(Y.Do, arguments); } f = fn; c = context; args = nativeSlice.call(arguments, 0); ret = []; if (L.isArray(type)) { isArr = true; } after = type._after; delete type._after; Y.each(type, function(v, k) { if (L.isObject(v)) { f = v.fn || ((L.isFunction(v)) ? v : f); c = v.context || c; } var nv = (after) ? AFTER_PREFIX : ''; args[0] = nv + ((isArr) ? v : k); args[1] = f; args[2] = c; ret.push(this.on.apply(this, args)); }, this); return (yuievt.chain) ? this : new Y.EventHandle(ret); } detachcategory = parts[0]; after = parts[2]; shorttype = parts[3]; // extra redirection so we catch adaptor events too. take a look at this. if (Node && Y.instanceOf(this, Node) && (shorttype in Node.DOM_EVENTS)) { args = nativeSlice.call(arguments, 0); args.splice(2, 0, Node.getDOMNode(this)); // Y.log("Node detected, redirecting with these args: " + args); return Y.on.apply(Y, args); } type = parts[1]; if (Y.instanceOf(this, YUI)) { adapt = Y.Env.evt.plugins[type]; args = nativeSlice.call(arguments, 0); args[0] = shorttype; if (Node) { n = args[2]; if (Y.instanceOf(n, Y.NodeList)) { n = Y.NodeList.getDOMNodes(n); } else if (Y.instanceOf(n, Node)) { n = Node.getDOMNode(n); } domevent = (shorttype in Node.DOM_EVENTS); // Captures both DOM events and event plugins. if (domevent) { args[2] = n; } } // check for the existance of an event adaptor if (adapt) { Y.log('Using adaptor for ' + shorttype + ', ' + n, 'info', 'event'); handle = adapt.on.apply(Y, args); } else if ((!type) || domevent) { handle = Y.Event._attach(args); } } if (!handle) { ce = yuievt.events[type] || this.publish(type); handle = ce._on(fn, context, (arguments.length > 3) ? nativeSlice.call(arguments, 3) : null, (after) ? 'after' : true); // TODO: More robust regex, accounting for category if (type.indexOf("*:") !== -1) { this._hasSiblings = true; } } if (detachcategory) { store[detachcategory] = store[detachcategory] || {}; store[detachcategory][type] = store[detachcategory][type] || []; store[detachcategory][type].push(handle); } return (yuievt.chain) ? this : handle; }, /** * subscribe to an event * @method subscribe * @deprecated use on */ subscribe: function() { Y.log('EventTarget subscribe() is deprecated, use on()', 'warn', 'deprecated'); return this.on.apply(this, arguments); }, /** * Detach one or more listeners the from the specified event * @method detach * @param type {string|Object} Either the handle to the subscriber or the * type of event. If the type * is not specified, it will attempt to remove * the listener from all hosted events. * @param fn {Function} The subscribed function to unsubscribe, if not * supplied, all subscribers will be removed. * @param context {Object} The custom object passed to subscribe. This is * optional, but if supplied will be used to * disambiguate multiple listeners that are the same * (e.g., you subscribe many object using a function * that lives on the prototype) * @return {EventTarget} the host */ detach: function(type, fn, context) { var evts = this._yuievt.events, i, Node = Y.Node, isNode = Node && (Y.instanceOf(this, Node)); // detachAll disabled on the Y instance. if (!type && (this !== Y)) { for (i in evts) { if (evts.hasOwnProperty(i)) { evts[i].detach(fn, context); } } if (isNode) { Y.Event.purgeElement(Node.getDOMNode(this)); } return this; } var parts = _parseType(type, this._yuievt.config.prefix), detachcategory = L.isArray(parts) ? parts[0] : null, shorttype = (parts) ? parts[3] : null, adapt, store = Y.Env.evt.handles, detachhost, cat, args, ce, keyDetacher = function(lcat, ltype, host) { var handles = lcat[ltype], ce, i; if (handles) { for (i = handles.length - 1; i >= 0; --i) { ce = handles[i].evt; if (ce.host === host || ce.el === host) { handles[i].detach(); } } } }; if (detachcategory) { cat = store[detachcategory]; type = parts[1]; detachhost = (isNode) ? Y.Node.getDOMNode(this) : this; if (cat) { if (type) { keyDetacher(cat, type, detachhost); } else { for (i in cat) { if (cat.hasOwnProperty(i)) { keyDetacher(cat, i, detachhost); } } } return this; } // If this is an event handle, use it to detach } else if (L.isObject(type) && type.detach) { type.detach(); return this; // extra redirection so we catch adaptor events too. take a look at this. } else if (isNode && ((!shorttype) || (shorttype in Node.DOM_EVENTS))) { args = nativeSlice.call(arguments, 0); args[2] = Node.getDOMNode(this); Y.detach.apply(Y, args); return this; } adapt = Y.Env.evt.plugins[shorttype]; // The YUI instance handles DOM events and adaptors if (Y.instanceOf(this, YUI)) { args = nativeSlice.call(arguments, 0); // use the adaptor specific detach code if if (adapt && adapt.detach) { adapt.detach.apply(Y, args); return this; // DOM event fork } else if (!type || (!adapt && Node && (type in Node.DOM_EVENTS))) { args[0] = type; Y.Event.detach.apply(Y.Event, args); return this; } } // ce = evts[type]; ce = evts[parts[1]]; if (ce) { ce.detach(fn, context); } return this; }, /** * detach a listener * @method unsubscribe * @deprecated use detach */ unsubscribe: function() { Y.log('EventTarget unsubscribe() is deprecated, use detach()', 'warn', 'deprecated'); return this.detach.apply(this, arguments); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method detachAll * @param type {String} The type, or name of the event */ detachAll: function(type) { return this.detach(type); }, /** * Removes all listeners from the specified event. If the event type * is not specified, all listeners from all hosted custom events will * be removed. * @method unsubscribeAll * @param type {String} The type, or name of the event * @deprecated use detachAll */ unsubscribeAll: function() { Y.log('EventTarget unsubscribeAll() is deprecated, use detachAll()', 'warn', 'deprecated'); return this.detachAll.apply(this, arguments); }, /** * Creates a new custom event of the specified type. If a custom event * by that name already exists, it will not be re-created. In either * case the custom event is returned. * * @method publish * * @param type {String} the type, or name of the event * @param opts {object} optional config params. Valid properties are: * * <ul> * <li> * 'broadcast': whether or not the YUI instance and YUI global are notified when the event is fired (false) * </li> * <li> * 'bubbles': whether or not this event bubbles (true) * Events can only bubble if emitFacade is true. * </li> * <li> * 'context': the default execution context for the listeners (this) * </li> * <li> * 'defaultFn': the default function to execute when this event fires if preventDefault was not called * </li> * <li> * 'emitFacade': whether or not this event emits a facade (false) * </li> * <li> * 'prefix': the prefix for this targets events, e.g., 'menu' in 'menu:click' * </li> * <li> * 'fireOnce': if an event is configured to fire once, new subscribers after * the fire will be notified immediately. * </li> * <li> * 'async': fireOnce event listeners will fire synchronously if the event has already * fired unless async is true. * </li> * <li> * 'preventable': whether or not preventDefault() has an effect (true) * </li> * <li> * 'preventedFn': a function that is executed when preventDefault is called * </li> * <li> * 'queuable': whether or not this event can be queued during bubbling (false) * </li> * <li> * 'silent': if silent is true, debug messages are not provided for this event. * </li> * <li> * 'stoppedFn': a function that is executed when stopPropagation is called * </li> * * <li> * 'monitored': specifies whether or not this event should send notifications about * when the event has been attached, detached, or published. * </li> * <li> * 'type': the event type (valid option if not provided as the first parameter to publish) * </li> * </ul> * * @return {CustomEvent} the custom event * */ publish: function(type, opts) { var ret, etState = this._yuievt, etConfig = etState.config, pre = etConfig.prefix; if (typeof type === "string") { if (pre) { type = _getType(type, pre); } ret = this._publish(type, etConfig, opts); } else { ret = {}; Y.each(type, function(v, k) { if (pre) { k = _getType(k, pre); } ret[k] = this._publish(k, etConfig, v || opts); }, this); } return ret; }, /** * Returns the fully qualified type, given a short type string. * That is, returns "foo:bar" when given "bar" if "foo" is the configured prefix. * * NOTE: This method, unlike _getType, does no checking of the value passed in, and * is designed to be used with the low level _publish() method, for critical path * implementations which need to fast-track publish for performance reasons. * * @method _getFullType * @private * @param {String} type The short type to prefix * @return {String} The prefixed type, if a prefix is set, otherwise the type passed in */ _getFullType : function(type) { var pre = this._yuievt.config.prefix; if (pre) { return pre + PREFIX_DELIMITER + type; } else { return type; } }, /** * The low level event publish implementation. It expects all the massaging to have been done * outside of this method. e.g. the `type` to `fullType` conversion. It's designed to be a fast * path publish, which can be used by critical code paths to improve performance. * * @method _publish * @private * @param {String} fullType The prefixed type of the event to publish. * @param {Object} etOpts The EventTarget specific configuration to mix into the published event. * @param {Object} ceOpts The publish specific configuration to mix into the published event. * @return {CustomEvent} The published event. If called without `etOpts` or `ceOpts`, this will * be the default `CustomEvent` instance, and can be configured independently. */ _publish : function(fullType, etOpts, ceOpts) { var ce, etState = this._yuievt, etConfig = etState.config, host = etConfig.host, context = etConfig.context, events = etState.events; ce = events[fullType]; // PERF: Hate to pull the check out of monitor, but trying to keep critical path tight. if ((etConfig.monitored && !ce) || (ce && ce.monitored)) { this._monitor('publish', fullType, { args: arguments }); } if (!ce) { // Publish event ce = events[fullType] = new Y.CustomEvent(fullType, etOpts); if (!etOpts) { ce.host = host; ce.context = context; } } if (ceOpts) { mixConfigs(ce, ceOpts, true); } return ce; }, /** * This is the entry point for the event monitoring system. * You can monitor 'attach', 'detach', 'fire', and 'publish'. * When configured, these events generate an event. click -> * click_attach, click_detach, click_publish -- these can * be subscribed to like other events to monitor the event * system. Inividual published events can have monitoring * turned on or off (publish can't be turned off before it * it published) by setting the events 'monitor' config. * * @method _monitor * @param what {String} 'attach', 'detach', 'fire', or 'publish' * @param eventType {String|CustomEvent} The prefixed name of the event being monitored, or the CustomEvent object. * @param o {Object} Information about the event interaction, such as * fire() args, subscription category, publish config * @private */ _monitor: function(what, eventType, o) { var monitorevt, ce, type; if (eventType) { if (typeof eventType === "string") { type = eventType; ce = this.getEvent(eventType, true); } else { ce = eventType; type = eventType.type; } if ((this._yuievt.config.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { monitorevt = type + '_' + what; o.monitored = what; this.fire.call(this, monitorevt, o); } } }, /** * Fire a custom event by name. The callback functions will be executed * from the context specified when the event was created, and with the * following parameters. * * If the custom event object hasn't been created, then the event hasn't * been published and it has no subscribers. For performance sake, we * immediate exit in this case. This means the event won't bubble, so * if the intention is that a bubble target be notified, the event must * be published on this object first. * * The first argument is the event type, and any additional arguments are * passed to the listeners as parameters. If the first of these is an * object literal, and the event is configured to emit an event facade, * that object is mixed into the event facade and the facade is provided * in place of the original object. * * @method fire * @param type {String|Object} The type of the event, or an object that contains * a 'type' property. * @param arguments {Object*} an arbitrary set of parameters to pass to * the handler. If the first of these is an object literal and the event is * configured to emit an event facade, the event facade will replace that * parameter after the properties the object literal contains are copied to * the event facade. * @return {EventTarget} the event host */ fire: function(type) { var typeIncluded = (typeof type === "string"), argCount = arguments.length, t = type, yuievt = this._yuievt, etConfig = yuievt.config, pre = etConfig.prefix, ret, ce, ce2, args; if (typeIncluded && argCount <= 3) { // PERF: Try to avoid slice/iteration for the common signatures // Most common if (argCount === 2) { args = [arguments[1]]; // fire("foo", {}) } else if (argCount === 3) { args = [arguments[1], arguments[2]]; // fire("foo", {}, opts) } else { args = []; // fire("foo") } } else { args = nativeSlice.call(arguments, ((typeIncluded) ? 1 : 0)); } if (!typeIncluded) { t = (type && type.type); } if (pre) { t = _getType(t, pre); } ce = yuievt.events[t]; if (this._hasSiblings) { ce2 = this.getSibling(t, ce); if (ce2 && !ce) { ce = this.publish(t); } } // PERF: trying to avoid function call, since this is a critical path if ((etConfig.monitored && (!ce || ce.monitored)) || (ce && ce.monitored)) { this._monitor('fire', (ce || t), { args: args }); } // this event has not been published or subscribed to if (!ce) { if (yuievt.hasTargets) { return this.bubble({ type: t }, args, this); } // otherwise there is nothing to be done ret = true; } else { if (ce2) { ce.sibling = ce2; } ret = ce._fire(args); } return (yuievt.chain) ? this : ret; }, getSibling: function(type, ce) { var ce2; // delegate to *:type events if there are subscribers if (type.indexOf(PREFIX_DELIMITER) > -1) { type = _wildType(type); ce2 = this.getEvent(type, true); if (ce2) { ce2.applyConfig(ce); ce2.bubbles = false; ce2.broadcast = 0; } } return ce2; }, /** * Returns the custom event of the provided type has been created, a * falsy value otherwise * @method getEvent * @param type {String} the type, or name of the event * @param prefixed {String} if true, the type is prefixed already * @return {CustomEvent} the custom event or null */ getEvent: function(type, prefixed) { var pre, e; if (!prefixed) { pre = this._yuievt.config.prefix; type = (pre) ? _getType(type, pre) : type; } e = this._yuievt.events; return e[type] || null; }, /** * Subscribe to a custom event hosted by this object. The * supplied callback will execute after any listeners add * via the subscribe method, and after the default function, * if configured for the event, has executed. * * @method after * @param {String} type The name of the event * @param {Function} fn The callback to execute in response to the event * @param {Object} [context] Override `this` object in callback * @param {Any} [arg*] 0..n additional arguments to supply to the subscriber * @return {EventHandle} A subscription handle capable of detaching the * subscription */ after: function(type, fn) { var a = nativeSlice.call(arguments, 0); switch (L.type(type)) { case 'function': return Y.Do.after.apply(Y.Do, arguments); case 'array': // YArray.each(a[0], function(v) { // v = AFTER_PREFIX + v; // }); // break; case 'object': a[0]._after = true; break; default: a[0] = AFTER_PREFIX + type; } return this.on.apply(this, a); }, /** * Executes the callback before a DOM event, custom event * or method. If the first argument is a function, it * is assumed the target is a method. For DOM and custom * events, this is an alias for Y.on. * * For DOM and custom events: * type, callback, context, 0-n arguments * * For methods: * callback, object (method host), methodName, context, 0-n arguments * * @method before * @return detach handle */ before: function() { return this.on.apply(this, arguments); } }; Y.EventTarget = ET; // make Y an event target Y.mix(Y, ET.prototype); ET.call(Y, { bubbles: false }); YUI.Env.globalEvents = YUI.Env.globalEvents || new ET(); /** * Hosts YUI page level events. This is where events bubble to * when the broadcast config is set to 2. This property is * only available if the custom event module is loaded. * @property Global * @type EventTarget * @for YUI */ Y.Global = YUI.Env.globalEvents; // @TODO implement a global namespace function on Y.Global? /** `Y.on()` can do many things: <ul> <li>Subscribe to custom events `publish`ed and `fire`d from Y</li> <li>Subscribe to custom events `publish`ed with `broadcast` 1 or 2 and `fire`d from any object in the YUI instance sandbox</li> <li>Subscribe to DOM events</li> <li>Subscribe to the execution of a method on any object, effectively treating that method as an event</li> </ul> For custom event subscriptions, pass the custom event name as the first argument and callback as the second. The `this` object in the callback will be `Y` unless an override is passed as the third argument. Y.on('io:complete', function () { Y.MyApp.updateStatus('Transaction complete'); }); To subscribe to DOM events, pass the name of a DOM event as the first argument and a CSS selector string as the third argument after the callback function. Alternately, the third argument can be a `Node`, `NodeList`, `HTMLElement`, array, or simply omitted (the default is the `window` object). Y.on('click', function (e) { e.preventDefault(); // proceed with ajax form submission var url = this.get('action'); ... }, '#my-form'); The `this` object in DOM event callbacks will be the `Node` targeted by the CSS selector or other identifier. `on()` subscribers for DOM events or custom events `publish`ed with a `defaultFn` can prevent the default behavior with `e.preventDefault()` from the event object passed as the first parameter to the subscription callback. To subscribe to the execution of an object method, pass arguments corresponding to the call signature for <a href="../classes/Do.html#methods_before">`Y.Do.before(...)`</a>. NOTE: The formal parameter list below is for events, not for function injection. See `Y.Do.before` for that signature. @method on @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @see Do.before @for YUI **/ /** Listen for an event one time. Equivalent to `on()`, except that the listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see on @method once @param {String} type DOM or custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Listen for an event one time. Equivalent to `once()`, except, like `after()`, the subscription callback executes after all `on()` subscribers and the event's `defaultFn` (if configured) have executed. Like `after()` if any `on()` phase subscriber calls `e.preventDefault()`, neither the `defaultFn` nor the `after()` subscribers will execute. The listener is immediately detached when executed. See the <a href="#methods_on">`on()` method</a> for additional subscription options. @see once @method onceAfter @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ /** Like `on()`, this method creates a subscription to a custom event or to the execution of a method on an object. For events, `after()` subscribers are executed after the event's `defaultFn` unless `e.preventDefault()` was called from an `on()` subscriber. See the <a href="#methods_on">`on()` method</a> for additional subscription options. NOTE: The subscription signature shown is for events, not for function injection. See <a href="../classes/Do.html#methods_after">`Y.Do.after`</a> for that signature. @see on @see Do.after @method after @param {String} type The custom event name @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [args*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching the subscription @for YUI **/ }, '@VERSION@', {"requires": ["oop"]}); YUI.add('event-custom-complex', function (Y, NAME) { /** * Adds event facades, preventable default behavior, and bubbling. * events. * @module event-custom * @submodule event-custom-complex */ var FACADE, FACADE_KEYS, YObject = Y.Object, key, EMPTY = {}, CEProto = Y.CustomEvent.prototype, ETProto = Y.EventTarget.prototype, mixFacadeProps = function(facade, payload) { var p; for (p in payload) { if (!(FACADE_KEYS.hasOwnProperty(p))) { facade[p] = payload[p]; } } }; /** * Wraps and protects a custom event for use when emitFacade is set to true. * Requires the event-custom-complex module * @class EventFacade * @param e {Event} the custom event * @param currentTarget {HTMLElement} the element the listener was attached to */ Y.EventFacade = function(e, currentTarget) { if (!e) { e = EMPTY; } this._event = e; /** * The arguments passed to fire * @property details * @type Array */ this.details = e.details; /** * The event type, this can be overridden by the fire() payload * @property type * @type string */ this.type = e.type; /** * The real event type * @property _type * @type string * @private */ this._type = e.type; ////////////////////////////////////////////////////// /** * Node reference for the targeted eventtarget * @property target * @type Node */ this.target = e.target; /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type Node */ this.currentTarget = currentTarget; /** * Node reference to the relatedTarget * @property relatedTarget * @type Node */ this.relatedTarget = e.relatedTarget; }; Y.mix(Y.EventFacade.prototype, { /** * Stops the propagation to the next bubble target * @method stopPropagation */ stopPropagation: function() { this._event.stopPropagation(); this.stopped = 1; }, /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ stopImmediatePropagation: function() { this._event.stopImmediatePropagation(); this.stopped = 2; }, /** * Prevents the event's default behavior * @method preventDefault */ preventDefault: function() { this._event.preventDefault(); this.prevented = 1; }, /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ halt: function(immediate) { this._event.halt(immediate); this.prevented = 1; this.stopped = (immediate) ? 2 : 1; } }); CEProto.fireComplex = function(args) { var es, ef, q, queue, ce, ret = true, events, subs, ons, afters, afterQueue, postponed, prevented, preventedFn, defaultFn, self = this, host = self.host || self, next, oldbubble, stack, yuievt = host._yuievt, hasPotentialSubscribers; stack = self.stack; if (stack) { // queue this event if the current item in the queue bubbles if (self.queuable && self.type !== stack.next.type) { self.log('queue ' + self.type); if (!stack.queue) { stack.queue = []; } stack.queue.push([self, args]); return true; } } hasPotentialSubscribers = self.hasSubs() || yuievt.hasTargets || self.broadcast; self.target = self.target || host; self.currentTarget = host; self.details = args.concat(); if (hasPotentialSubscribers) { es = stack || { id: self.id, // id of the first event in the stack next: self, silent: self.silent, stopped: 0, prevented: 0, bubbling: null, type: self.type, // defaultFnQueue: new Y.Queue(), defaultTargetOnly: self.defaultTargetOnly }; subs = self.getSubs(); ons = subs[0]; afters = subs[1]; self.stopped = (self.type !== es.type) ? 0 : es.stopped; self.prevented = (self.type !== es.type) ? 0 : es.prevented; if (self.stoppedFn) { // PERF TODO: Can we replace with callback, like preventedFn. Look into history events = new Y.EventTarget({ fireOnce: true, context: host }); self.events = events; events.on('stopped', self.stoppedFn); } // self.log("Firing " + self + ", " + "args: " + args); self.log("Firing " + self.type); self._facade = null; // kill facade to eliminate stale properties ef = self._getFacade(args); if (ons) { self._procSubs(ons, args, ef); } // bubble if this is hosted in an event target and propagation has not been stopped if (self.bubbles && host.bubble && !self.stopped) { oldbubble = es.bubbling; es.bubbling = self.type; if (es.type !== self.type) { es.stopped = 0; es.prevented = 0; } ret = host.bubble(self, args, null, es); self.stopped = Math.max(self.stopped, es.stopped); self.prevented = Math.max(self.prevented, es.prevented); es.bubbling = oldbubble; } prevented = self.prevented; if (prevented) { preventedFn = self.preventedFn; if (preventedFn) { preventedFn.apply(host, args); } } else { defaultFn = self.defaultFn; if (defaultFn && ((!self.defaultTargetOnly && !es.defaultTargetOnly) || host === ef.target)) { defaultFn.apply(host, args); } } // broadcast listeners are fired as discreet events on the // YUI instance and potentially the YUI global. if (self.broadcast) { self._broadcast(args); } if (afters && !self.prevented && self.stopped < 2) { // Queue the after afterQueue = es.afterQueue; if (es.id === self.id || self.type !== yuievt.bubbling) { self._procSubs(afters, args, ef); if (afterQueue) { while ((next = afterQueue.last())) { next(); } } } else { postponed = afters; if (es.execDefaultCnt) { postponed = Y.merge(postponed); Y.each(postponed, function(s) { s.postponed = true; }); } if (!afterQueue) { es.afterQueue = new Y.Queue(); } es.afterQueue.add(function() { self._procSubs(postponed, args, ef); }); } } self.target = null; if (es.id === self.id) { queue = es.queue; if (queue) { while (queue.length) { q = queue.pop(); ce = q[0]; // set up stack to allow the next item to be processed es.next = ce; ce._fire(q[1]); } } self.stack = null; } ret = !(self.stopped); if (self.type !== yuievt.bubbling) { es.stopped = 0; es.prevented = 0; self.stopped = 0; self.prevented = 0; } } else { defaultFn = self.defaultFn; if(defaultFn) { ef = self._getFacade(args); if ((!self.defaultTargetOnly) || (host === ef.target)) { defaultFn.apply(host, args); } } } // Kill the cached facade to free up memory. // Otherwise we have the facade from the last fire, sitting around forever. self._facade = null; return ret; }; CEProto._getFacade = function(fireArgs) { var userArgs = this.details, firstArg = userArgs && userArgs[0], firstArgIsObj = (firstArg && (typeof firstArg === "object")), ef = this._facade; if (!ef) { ef = new Y.EventFacade(this, this.currentTarget); } if (firstArgIsObj) { // protect the event facade properties mixFacadeProps(ef, firstArg); // Allow the event type to be faked http://yuilibrary.com/projects/yui3/ticket/2528376 if (firstArg.type) { ef.type = firstArg.type; } if (fireArgs) { fireArgs[0] = ef; } } else { if (fireArgs) { fireArgs.unshift(ef); } } // update the details field with the arguments ef.details = this.details; // use the original target when the event bubbled to this target ef.target = this.originalTarget || this.target; ef.currentTarget = this.currentTarget; ef.stopped = 0; ef.prevented = 0; this._facade = ef; return this._facade; }; /** * Stop propagation to bubble targets * @for CustomEvent * @method stopPropagation */ CEProto.stopPropagation = function() { this.stopped = 1; if (this.stack) { this.stack.stopped = 1; } if (this.events) { this.events.fire('stopped', this); } }; /** * Stops propagation to bubble targets, and prevents any remaining * subscribers on the current target from executing. * @method stopImmediatePropagation */ CEProto.stopImmediatePropagation = function() { this.stopped = 2; if (this.stack) { this.stack.stopped = 2; } if (this.events) { this.events.fire('stopped', this); } }; /** * Prevents the execution of this event's defaultFn * @method preventDefault */ CEProto.preventDefault = function() { if (this.preventable) { this.prevented = 1; if (this.stack) { this.stack.prevented = 1; } } }; /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ CEProto.halt = function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); }; /** * Registers another EventTarget as a bubble target. Bubble order * is determined by the order registered. Multiple targets can * be specified. * * Events can only bubble if emitFacade is true. * * Included in the event-custom-complex submodule. * * @method addTarget * @param o {EventTarget} the target to add * @for EventTarget */ ETProto.addTarget = function(o) { var etState = this._yuievt; if (!etState.targets) { etState.targets = {}; } etState.targets[Y.stamp(o)] = o; etState.hasTargets = true; }; /** * Returns an array of bubble targets for this object. * @method getTargets * @return EventTarget[] */ ETProto.getTargets = function() { var targets = this._yuievt.targets; return targets ? YObject.values(targets) : []; }; /** * Removes a bubble target * @method removeTarget * @param o {EventTarget} the target to remove * @for EventTarget */ ETProto.removeTarget = function(o) { var targets = this._yuievt.targets; if (targets) { delete targets[Y.stamp(o, true)]; if (YObject.size(targets) === 0) { this._yuievt.hasTargets = false; } } }; /** * Propagate an event. Requires the event-custom-complex module. * @method bubble * @param evt {CustomEvent} the custom event to propagate * @return {boolean} the aggregated return value from Event.Custom.fire * @for EventTarget */ ETProto.bubble = function(evt, args, target, es) { var targs = this._yuievt.targets, ret = true, t, ce, i, bc, ce2, type = evt && evt.type, originalTarget = target || (evt && evt.target) || this, oldbubble; if (!evt || ((!evt.stopped) && targs)) { for (i in targs) { if (targs.hasOwnProperty(i)) { t = targs[i]; ce = t._yuievt.events[type]; if (t._hasSiblings) { ce2 = t.getSibling(type, ce); } if (ce2 && !ce) { ce = t.publish(type); } oldbubble = t._yuievt.bubbling; t._yuievt.bubbling = type; // if this event was not published on the bubble target, // continue propagating the event. if (!ce) { if (t._yuievt.hasTargets) { t.bubble(evt, args, originalTarget, es); } } else { if (ce2) { ce.sibling = ce2; } // set the original target to that the target payload on the facade is correct. ce.target = originalTarget; ce.originalTarget = originalTarget; ce.currentTarget = t; bc = ce.broadcast; ce.broadcast = false; // default publish may not have emitFacade true -- that // shouldn't be what the implementer meant to do ce.emitFacade = true; ce.stack = es; // TODO: See what's getting in the way of changing this to use // the more performant ce._fire(args || evt.details || []). // Something in Widget Parent/Child tests is not happy if we // change it - maybe evt.details related? ret = ret && ce.fire.apply(ce, args || evt.details || []); ce.broadcast = bc; ce.originalTarget = null; // stopPropagation() was called if (ce.stopped) { break; } } t._yuievt.bubbling = oldbubble; } } } return ret; }; FACADE = new Y.EventFacade(); FACADE_KEYS = {}; // Flatten whitelist for (key in FACADE) { FACADE_KEYS[key] = true; } }, '@VERSION@', {"requires": ["event-custom-base"]}); YUI.add('node-core', function (Y, NAME) { /** * The Node Utility provides a DOM-like interface for interacting with DOM nodes. * @module node * @main node * @submodule node-core */ /** * The Node class provides a wrapper for manipulating DOM Nodes. * Node properties can be accessed via the set/get methods. * Use `Y.one()` to retrieve Node instances. * * <strong>NOTE:</strong> Node properties are accessed using * the <code>set</code> and <code>get</code> methods. * * @class Node * @constructor * @param {DOMNode} node the DOM node to be mapped to the Node instance. * @uses EventTarget */ // "globals" var DOT = '.', NODE_NAME = 'nodeName', NODE_TYPE = 'nodeType', OWNER_DOCUMENT = 'ownerDocument', TAG_NAME = 'tagName', UID = '_yuid', EMPTY_OBJ = {}, _slice = Array.prototype.slice, Y_DOM = Y.DOM, Y_Node = function(node) { if (!this.getDOMNode) { // support optional "new" return new Y_Node(node); } if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } var uid = (node.nodeType !== 9) ? node.uniqueID : node[UID]; if (uid && Y_Node._instances[uid] && Y_Node._instances[uid]._node !== node) { node[UID] = null; // unset existing uid to prevent collision (via clone or hack) } uid = uid || Y.stamp(node); if (!uid) { // stamp failed; likely IE non-HTMLElement uid = Y.guid(); } this[UID] = uid; /** * The underlying DOM node bound to the Y.Node instance * @property _node * @type DOMNode * @private */ this._node = node; this._stateProxy = node; // when augmented with Attribute if (this._initPlugins) { // when augmented with Plugin.Host this._initPlugins(); } }, // used with previous/next/ancestor tests _wrapFn = function(fn) { var ret = null; if (fn) { ret = (typeof fn == 'string') ? function(n) { return Y.Selector.test(n, fn); } : function(n) { return fn(Y.one(n)); }; } return ret; }; // end "globals" Y_Node.ATTRS = {}; Y_Node.DOM_EVENTS = {}; Y_Node._fromString = function(node) { if (node) { if (node.indexOf('doc') === 0) { // doc OR document node = Y.config.doc; } else if (node.indexOf('win') === 0) { // win OR window node = Y.config.win; } else { node = Y.Selector.query(node, null, true); } } return node || null; }; /** * The name of the component * @static * @type String * @property NAME */ Y_Node.NAME = 'node'; /* * The pattern used to identify ARIA attributes */ Y_Node.re_aria = /^(?:role$|aria-)/; Y_Node.SHOW_TRANSITION = 'fadeIn'; Y_Node.HIDE_TRANSITION = 'fadeOut'; /** * A list of Node instances that have been created * @private * @type Object * @property _instances * @static * */ Y_Node._instances = {}; /** * Retrieves the DOM node bound to a Node instance * @method getDOMNode * @static * * @param {Node | HTMLNode} node The Node instance or an HTMLNode * @return {HTMLNode} The DOM node bound to the Node instance. If a DOM node is passed * as the node argument, it is simply returned. */ Y_Node.getDOMNode = function(node) { if (node) { return (node.nodeType) ? node : node._node || null; } return null; }; /** * Checks Node return values and wraps DOM Nodes as Y.Node instances * and DOM Collections / Arrays as Y.NodeList instances. * Other return values just pass thru. If undefined is returned (e.g. no return) * then the Node instance is returned for chainability. * @method scrubVal * @static * * @param {any} node The Node instance or an HTMLNode * @return {Node | NodeList | Any} Depends on what is returned from the DOM node. */ Y_Node.scrubVal = function(val, node) { if (val) { // only truthy values are risky if (typeof val == 'object' || typeof val == 'function') { // safari nodeList === function if (NODE_TYPE in val || Y_DOM.isWindow(val)) {// node || window val = Y.one(val); } else if ((val.item && !val._nodes) || // dom collection or Node instance (val[0] && val[0][NODE_TYPE])) { // array of DOM Nodes val = Y.all(val); } } } else if (typeof val === 'undefined') { val = node; // for chaining } else if (val === null) { val = null; // IE: DOM null not the same as null } return val; }; /** * Adds methods to the Y.Node prototype, routing through scrubVal. * @method addMethod * @static * * @param {String} name The name of the method to add * @param {Function} fn The function that becomes the method * @param {Object} context An optional context to call the method with * (defaults to the Node instance) * @return {any} Depends on what is returned from the DOM node. */ Y_Node.addMethod = function(name, fn, context) { if (name && fn && typeof fn == 'function') { Y_Node.prototype[name] = function() { var args = _slice.call(arguments), node = this, ret; if (args[0] && args[0]._node) { args[0] = args[0]._node; } if (args[1] && args[1]._node) { args[1] = args[1]._node; } args.unshift(node._node); ret = fn.apply(node, args); if (ret) { // scrub truthy ret = Y_Node.scrubVal(ret, node); } (typeof ret != 'undefined') || (ret = node); return ret; }; } else { Y.log('unable to add method: ' + name, 'warn', 'Node'); } }; /** * Imports utility methods to be added as Y.Node methods. * @method importMethod * @static * * @param {Object} host The object that contains the method to import. * @param {String} name The name of the method to import * @param {String} altName An optional name to use in place of the host name * @param {Object} context An optional context to call the method with */ Y_Node.importMethod = function(host, name, altName) { if (typeof name == 'string') { altName = altName || name; Y_Node.addMethod(altName, host[name], host); } else { Y.Array.each(name, function(n) { Y_Node.importMethod(host, n); }); } }; /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for YUI */ /** * Returns a single Node instance bound to the node or the * first element matching the given selector. Returns null if no match found. * <strong>Note:</strong> For chaining purposes you may want to * use <code>Y.all</code>, which returns a NodeList when no match is found. * @method one * @static * @param {String | HTMLElement} node a node or Selector * @return {Node | null} a Node instance or null if no match found. * @for Node */ Y_Node.one = function(node) { var instance = null, cachedNode, uid; if (node) { if (typeof node == 'string') { node = Y_Node._fromString(node); if (!node) { return null; // NOTE: return } } else if (node.getDOMNode) { return node; // NOTE: return } if (node.nodeType || Y.DOM.isWindow(node)) { // avoid bad input (numbers, boolean, etc) uid = (node.uniqueID && node.nodeType !== 9) ? node.uniqueID : node._yuid; instance = Y_Node._instances[uid]; // reuse exising instances cachedNode = instance ? instance._node : null; if (!instance || (cachedNode && node !== cachedNode)) { // new Node when nodes don't match instance = new Y_Node(node); if (node.nodeType != 11) { // dont cache document fragment Y_Node._instances[instance[UID]] = instance; // cache node } } } } return instance; }; /** * The default setter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_SETTER * @static * @param {String} name The attribute/property being set * @param {any} val The value to be set * @return {any} The value */ Y_Node.DEFAULT_SETTER = function(name, val) { var node = this._stateProxy, strPath; if (name.indexOf(DOT) > -1) { strPath = name; name = name.split(DOT); // only allow when defined on node Y.Object.setValue(node, name, val); } else if (typeof node[name] != 'undefined') { // pass thru DOM properties node[name] = val; } return val; }; /** * The default getter for DOM properties * Called with instance context (this === the Node instance) * @method DEFAULT_GETTER * @static * @param {String} name The attribute/property to look up * @return {any} The current value */ Y_Node.DEFAULT_GETTER = function(name) { var node = this._stateProxy, val; if (name.indexOf && name.indexOf(DOT) > -1) { val = Y.Object.getValue(node, name.split(DOT)); } else if (typeof node[name] != 'undefined') { // pass thru from DOM val = node[name]; } return val; }; Y.mix(Y_Node.prototype, { DATA_PREFIX: 'data-', /** * The method called when outputting Node instances as strings * @method toString * @return {String} A string representation of the Node instance */ toString: function() { var str = this[UID] + ': not bound to a node', node = this._node, attrs, id, className; if (node) { attrs = node.attributes; id = (attrs && attrs.id) ? node.getAttribute('id') : null; className = (attrs && attrs.className) ? node.getAttribute('className') : null; str = node[NODE_NAME]; if (id) { str += '#' + id; } if (className) { str += '.' + className.replace(' ', '.'); } // TODO: add yuid? str += ' ' + this[UID]; } return str; }, /** * Returns an attribute value on the Node instance. * Unless pre-configured (via `Node.ATTRS`), get hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be queried. * @method get * @param {String} attr The attribute * @return {any} The current value of the attribute */ get: function(attr) { var val; if (this._getAttr) { // use Attribute imple val = this._getAttr(attr); } else { val = this._get(attr); } if (val) { val = Y_Node.scrubVal(val, this); } else if (val === null) { val = null; // IE: DOM null is not true null (even though they ===) } return val; }, /** * Helper method for get. * @method _get * @private * @param {String} attr The attribute * @return {any} The current value of the attribute */ _get: function(attr) { var attrConfig = Y_Node.ATTRS[attr], val; if (attrConfig && attrConfig.getter) { val = attrConfig.getter.call(this); } else if (Y_Node.re_aria.test(attr)) { val = this._node.getAttribute(attr, 2); } else { val = Y_Node.DEFAULT_GETTER.apply(this, arguments); } return val; }, /** * Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable */ set: function(attr, val) { var attrConfig = Y_Node.ATTRS[attr]; if (this._setAttr) { // use Attribute imple this._setAttr.apply(this, arguments); } else { // use setters inline if (attrConfig && attrConfig.setter) { attrConfig.setter.call(this, val, attr); } else if (Y_Node.re_aria.test(attr)) { // special case Aria this._node.setAttribute(attr, val); } else { Y_Node.DEFAULT_SETTER.apply(this, arguments); } } return this; }, /** * Sets multiple attributes. * @method setAttrs * @param {Object} attrMap an object of name/value pairs to set * @chainable */ setAttrs: function(attrMap) { if (this._setAttrs) { // use Attribute imple this._setAttrs(attrMap); } else { // use setters inline Y.Object.each(attrMap, function(v, n) { this.set(n, v); }, this); } return this; }, /** * Returns an object containing the values for the requested attributes. * @method getAttrs * @param {Array} attrs an array of attributes to get values * @return {Object} An object with attribute name/value pairs. */ getAttrs: function(attrs) { var ret = {}; if (this._getAttrs) { // use Attribute imple this._getAttrs(attrs); } else { // use setters inline Y.Array.each(attrs, function(v, n) { ret[v] = this.get(v); }, this); } return ret; }, /** * Compares nodes to determine if they match. * Node instances can be compared to each other and/or HTMLElements. * @method compareTo * @param {HTMLElement | Node} refNode The reference node to compare to the node. * @return {Boolean} True if the nodes match, false if they do not. */ compareTo: function(refNode) { var node = this._node; if (refNode && refNode._node) { refNode = refNode._node; } return node === refNode; }, /** * Determines whether the node is appended to the document. * @method inDoc * @param {Node|HTMLElement} doc optional An optional document to check against. * Defaults to current document. * @return {Boolean} Whether or not this node is appended to the document. */ inDoc: function(doc) { var node = this._node; doc = (doc) ? doc._node || doc : node[OWNER_DOCUMENT]; if (doc.documentElement) { return Y_DOM.contains(doc.documentElement, node); } }, getById: function(id) { var node = this._node, ret = Y_DOM.byId(id, node[OWNER_DOCUMENT]); if (ret && Y_DOM.contains(node, ret)) { ret = Y.one(ret); } else { ret = null; } return ret; }, /** * Returns the nearest ancestor that passes the test applied by supplied boolean method. * @method ancestor * @param {String | Function} fn A selector string or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * If fn is not passed as an argument, the parent node will be returned. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * @param {String | Function} stopFn optional A selector string or boolean * method to indicate when the search should stop. The search bails when the function * returns true or the selector matches. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} The matching Node instance or null if not found */ ancestor: function(fn, testSelf, stopFn) { // testSelf is optional, check for stopFn as 2nd arg if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.one(Y_DOM.ancestor(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the ancestors that pass the test applied by supplied boolean method. * @method ancestors * @param {String | Function} fn A selector string or boolean method for testing elements. * @param {Boolean} testSelf optional Whether or not to include the element in the scan * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} A NodeList instance containing the matching elements */ ancestors: function(fn, testSelf, stopFn) { if (arguments.length === 2 && (typeof testSelf == 'string' || typeof testSelf == 'function')) { stopFn = testSelf; } return Y.all(Y_DOM.ancestors(this._node, _wrapFn(fn), testSelf, _wrapFn(stopFn))); }, /** * Returns the previous matching sibling. * Returns the nearest element node sibling if no method provided. * @method previous * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ previous: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'previousSibling', _wrapFn(fn), all)); }, /** * Returns the next matching sibling. * Returns the nearest element node sibling if no method provided. * @method next * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {Node} Node instance or null if not found */ next: function(fn, all) { return Y.one(Y_DOM.elementByAxis(this._node, 'nextSibling', _wrapFn(fn), all)); }, /** * Returns all matching siblings. * Returns all siblings if no method provided. * @method siblings * @param {String | Function} fn A selector or boolean method for testing elements. * If a function is used, it receives the current node being tested as the only argument. * @return {NodeList} NodeList instance bound to found siblings */ siblings: function(fn) { return Y.all(Y_DOM.siblings(this._node, _wrapFn(fn))); }, /** * Retrieves a single Node instance, the first element matching the given * CSS selector. * Returns null if no match found. * @method one * * @param {string} selector The CSS selector to test against. * @return {Node | null} A Node instance for the matching HTMLElement or null * if no match found. */ one: function(selector) { return Y.one(Y.Selector.query(selector, this._node, true)); }, /** * Retrieves a NodeList based on the given CSS selector. * @method all * * @param {string} selector The CSS selector to test against. * @return {NodeList} A NodeList instance for the matching HTMLCollection/Array. */ all: function(selector) { var nodelist; if (this._node) { nodelist = Y.all(Y.Selector.query(selector, this._node)); nodelist._query = selector; nodelist._queryRoot = this._node; } return nodelist || Y.all([]); }, // TODO: allow fn test /** * Test if the supplied node matches the supplied selector. * @method test * * @param {string} selector The CSS selector to test against. * @return {boolean} Whether or not the node matches the selector. */ test: function(selector) { return Y.Selector.test(this._node, selector); }, /** * Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * */ remove: function(destroy) { var node = this._node; if (node && node.parentNode) { node.parentNode.removeChild(node); } if (destroy) { this.destroy(); } return this; }, /** * Replace the node with the other node. This is a DOM update only * and does not change the node bound to the Node instance. * Shortcut for myNode.get('parentNode').replaceChild(newNode, myNode); * @method replace * @param {Node | HTMLNode} newNode Node to be inserted * @chainable * */ replace: function(newNode) { var node = this._node; if (typeof newNode == 'string') { newNode = Y_Node.create(newNode); } node.parentNode.replaceChild(Y_Node.getDOMNode(newNode), node); return this; }, /** * @method replaceChild * @for Node * @param {String | HTMLElement | Node} node Node to be inserted * @param {HTMLElement | Node} refNode Node to be replaced * @return {Node} The replaced node */ replaceChild: function(node, refNode) { if (typeof node == 'string') { node = Y_DOM.create(node); } return Y.one(this._node.replaceChild(Y_Node.getDOMNode(node), Y_Node.getDOMNode(refNode))); }, /** * Nulls internal node references, removes any plugins and event listeners. * Note that destroy() will not remove the node from its parent or from the DOM. For that * functionality, call remove(true). * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to remove listeners from the * node's subtree (default is false) * */ destroy: function(recursive) { var UID = Y.config.doc.uniqueID ? 'uniqueID' : '_yuid', instance; this.purge(); // TODO: only remove events add via this Node if (this.unplug) { // may not be a PluginHost this.unplug(); } this.clearData(); if (recursive) { Y.NodeList.each(this.all('*'), function(node) { instance = Y_Node._instances[node[UID]]; if (instance) { instance.destroy(); } else { // purge in case added by other means Y.Event.purgeElement(node); } }); } this._node = null; this._stateProxy = null; delete Y_Node._instances[this._yuid]; }, /** * Invokes a method on the Node instance * @method invoke * @param {String} method The name of the method to invoke * @param {Any} a, b, c, etc. Arguments to invoke the method with. * @return Whatever the underly method returns. * DOM Nodes and Collections return values * are converted to Node/NodeList instances. * */ invoke: function(method, a, b, c, d, e) { var node = this._node, ret; if (a && a._node) { a = a._node; } if (b && b._node) { b = b._node; } ret = node[method](a, b, c, d, e); return Y_Node.scrubVal(ret, this); }, /** * @method swap * @description Swap DOM locations with the given node. * This does not change which DOM node each Node instance refers to. * @param {Node} otherNode The node to swap with * @chainable */ swap: Y.config.doc.documentElement.swapNode ? function(otherNode) { this._node.swapNode(Y_Node.getDOMNode(otherNode)); } : function(otherNode) { otherNode = Y_Node.getDOMNode(otherNode); var node = this._node, parent = otherNode.parentNode, nextSibling = otherNode.nextSibling; if (nextSibling === node) { parent.insertBefore(node, otherNode); } else if (otherNode === node.nextSibling) { parent.insertBefore(otherNode, node); } else { node.parentNode.replaceChild(otherNode, node); Y_DOM.addHTML(parent, node, nextSibling); } return this; }, hasMethod: function(method) { var node = this._node; return !!(node && method in node && typeof node[method] != 'unknown' && (typeof node[method] == 'function' || String(node[method]).indexOf('function') === 1)); // IE reports as object, prepends space }, isFragment: function() { return (this.get('nodeType') === 11); }, /** * Removes and destroys all of the nodes within the node. * @method empty * @chainable */ empty: function() { this.get('childNodes').remove().destroy(true); return this; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNode * @return {DOMNode} */ getDOMNode: function() { return this._node; } }, true); Y.Node = Y_Node; Y.one = Y_Node.one; /** * The NodeList module provides support for managing collections of Nodes. * @module node * @submodule node-core */ /** * The NodeList class provides a wrapper for manipulating DOM NodeLists. * NodeList properties can be accessed via the set/get methods. * Use Y.all() to retrieve NodeList instances. * * @class NodeList * @constructor * @param nodes {String|element|Node|Array} A selector, DOM element, Node, list of DOM elements, or list of Nodes with which to populate this NodeList. */ var NodeList = function(nodes) { var tmp = []; if (nodes) { if (typeof nodes === 'string') { // selector query this._query = nodes; nodes = Y.Selector.query(nodes); } else if (nodes.nodeType || Y_DOM.isWindow(nodes)) { // domNode || window nodes = [nodes]; } else if (nodes._node) { // Y.Node nodes = [nodes._node]; } else if (nodes[0] && nodes[0]._node) { // allow array of Y.Nodes Y.Array.each(nodes, function(node) { if (node._node) { tmp.push(node._node); } }); nodes = tmp; } else { // array of domNodes or domNodeList (no mixed array of Y.Node/domNodes) nodes = Y.Array(nodes, 0, true); } } /** * The underlying array of DOM nodes bound to the Y.NodeList instance * @property _nodes * @private */ this._nodes = nodes || []; }; NodeList.NAME = 'NodeList'; /** * Retrieves the DOM nodes bound to a NodeList instance * @method getDOMNodes * @static * * @param {NodeList} nodelist The NodeList instance * @return {Array} The array of DOM nodes bound to the NodeList */ NodeList.getDOMNodes = function(nodelist) { return (nodelist && nodelist._nodes) ? nodelist._nodes : nodelist; }; NodeList.each = function(instance, fn, context) { var nodes = instance._nodes; if (nodes && nodes.length) { Y.Array.each(nodes, fn, context || instance); } else { Y.log('no nodes bound to ' + this, 'warn', 'NodeList'); } }; NodeList.addMethod = function(name, fn, context) { if (name && fn) { NodeList.prototype[name] = function() { var ret = [], args = arguments; Y.Array.each(this._nodes, function(node) { var UID = (node.uniqueID && node.nodeType !== 9 ) ? 'uniqueID' : '_yuid', instance = Y.Node._instances[node[UID]], ctx, result; if (!instance) { instance = NodeList._getTempNode(node); } ctx = context || instance; result = fn.apply(ctx, args); if (result !== undefined && result !== instance) { ret[ret.length] = result; } }); // TODO: remove tmp pointer return ret.length ? ret : this; }; } else { Y.log('unable to add method: ' + name + ' to NodeList', 'warn', 'node'); } }; NodeList.importMethod = function(host, name, altName) { if (typeof name === 'string') { altName = altName || name; NodeList.addMethod(name, host[name]); } else { Y.Array.each(name, function(n) { NodeList.importMethod(host, n); }); } }; NodeList._getTempNode = function(node) { var tmp = NodeList._tempNode; if (!tmp) { tmp = Y.Node.create('<div></div>'); NodeList._tempNode = tmp; } tmp._node = node; tmp._stateProxy = node; return tmp; }; Y.mix(NodeList.prototype, { _invoke: function(method, args, getter) { var ret = (getter) ? [] : this; this.each(function(node) { var val = node[method].apply(node, args); if (getter) { ret.push(val); } }); return ret; }, /** * Retrieves the Node instance at the given index. * @method item * * @param {Number} index The index of the target Node. * @return {Node} The Node instance at the given index. */ item: function(index) { return Y.one((this._nodes || [])[index]); }, /** * Applies the given function to each Node in the NodeList. * @method each * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to apply the function with * Default context is the current Node instance * @chainable */ each: function(fn, context) { var instance = this; Y.Array.each(this._nodes, function(node, index) { node = Y.one(node); return fn.call(context || node, node, index, instance); }); return instance; }, batch: function(fn, context) { var nodelist = this; Y.Array.each(this._nodes, function(node, index) { var instance = Y.Node._instances[node[UID]]; if (!instance) { instance = NodeList._getTempNode(node); } return fn.call(context || instance, instance, index, nodelist); }); return nodelist; }, /** * Executes the function once for each node until a true value is returned. * @method some * @param {Function} fn The function to apply. It receives 3 arguments: * the current node instance, the node's index, and the NodeList instance * @param {Object} context optional An optional context to execute the function from. * Default context is the current Node instance * @return {Boolean} Whether or not the function returned true for any node. */ some: function(fn, context) { var instance = this; return Y.Array.some(this._nodes, function(node, index) { node = Y.one(node); context = context || node; return fn.call(context, node, index, instance); }); }, /** * Creates a documenFragment from the nodes bound to the NodeList instance * @method toFrag * @return {Node} a Node instance bound to the documentFragment */ toFrag: function() { return Y.one(Y.DOM._nl2frag(this._nodes)); }, /** * Returns the index of the node in the NodeList instance * or -1 if the node isn't found. * @method indexOf * @param {Node | DOMNode} node the node to search for * @return {Int} the index of the node value or -1 if not found */ indexOf: function(node) { return Y.Array.indexOf(this._nodes, Y.Node.getDOMNode(node)); }, /** * Filters the NodeList instance down to only nodes matching the given selector. * @method filter * @param {String} selector The selector to filter against * @return {NodeList} NodeList containing the updated collection * @see Selector */ filter: function(selector) { return Y.all(Y.Selector.filter(this._nodes, selector)); }, /** * Creates a new NodeList containing all nodes at every n indices, where * remainder n % index equals r. * (zero-based index). * @method modulus * @param {Int} n The offset to use (return every nth node) * @param {Int} r An optional remainder to use with the modulus operation (defaults to zero) * @return {NodeList} NodeList containing the updated collection */ modulus: function(n, r) { r = r || 0; var nodes = []; NodeList.each(this, function(node, i) { if (i % n === r) { nodes.push(node); } }); return Y.all(nodes); }, /** * Creates a new NodeList containing all nodes at odd indices * (zero-based index). * @method odd * @return {NodeList} NodeList containing the updated collection */ odd: function() { return this.modulus(2, 1); }, /** * Creates a new NodeList containing all nodes at even indices * (zero-based index), including zero. * @method even * @return {NodeList} NodeList containing the updated collection */ even: function() { return this.modulus(2); }, destructor: function() { }, /** * Reruns the initial query, when created using a selector query * @method refresh * @chainable */ refresh: function() { var doc, nodes = this._nodes, query = this._query, root = this._queryRoot; if (query) { if (!root) { if (nodes && nodes[0] && nodes[0].ownerDocument) { root = nodes[0].ownerDocument; } } this._nodes = Y.Selector.query(query, root); } return this; }, /** * Returns the current number of items in the NodeList. * @method size * @return {Int} The number of items in the NodeList. */ size: function() { return this._nodes.length; }, /** * Determines if the instance is bound to any nodes * @method isEmpty * @return {Boolean} Whether or not the NodeList is bound to any nodes */ isEmpty: function() { return this._nodes.length < 1; }, toString: function() { var str = '', errorMsg = this[UID] + ': not bound to any nodes', nodes = this._nodes, node; if (nodes && nodes[0]) { node = nodes[0]; str += node[NODE_NAME]; if (node.id) { str += '#' + node.id; } if (node.className) { str += '.' + node.className.replace(' ', '.'); } if (nodes.length > 1) { str += '...[' + nodes.length + ' items]'; } } return str || errorMsg; }, /** * Returns the DOM node bound to the Node instance * @method getDOMNodes * @return {Array} */ getDOMNodes: function() { return this._nodes; } }, true); NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance. Nulls internal node references, * removes any plugins and event listeners * @method destroy * @param {Boolean} recursivePurge (optional) Whether or not to * remove listeners from the node's subtree (default is false) * @see Node.destroy */ 'destroy', /** * Called on each Node instance. Removes and destroys all of the nodes * within the node * @method empty * @chainable * @see Node.empty */ 'empty', /** * Called on each Node instance. Removes the node from its parent. * Shortcut for myNode.get('parentNode').removeChild(myNode); * @method remove * @param {Boolean} destroy whether or not to call destroy() on the node * after removal. * @chainable * @see Node.remove */ 'remove', /** * Called on each Node instance. Sets an attribute on the Node instance. * Unless pre-configured (via Node.ATTRS), set hands * off to the underlying DOM node. Only valid * attributes/properties for the node will be set. * To set custom attributes use setAttribute. * @method set * @param {String} attr The attribute to be set. * @param {any} val The value to set the attribute to. * @chainable * @see Node.set */ 'set' ]); // one-off implementation to convert array of Nodes to NodeList // e.g. Y.all('input').get('parentNode'); /** Called on each Node instance * @method get * @see Node */ NodeList.prototype.get = function(attr) { var ret = [], nodes = this._nodes, isNodeList = false, getTemp = NodeList._getTempNode, instance, val; if (nodes[0]) { instance = Y.Node._instances[nodes[0]._yuid] || getTemp(nodes[0]); val = instance._get(attr); if (val && val.nodeType) { isNodeList = true; } } Y.Array.each(nodes, function(node) { instance = Y.Node._instances[node._yuid]; if (!instance) { instance = getTemp(node); } val = instance._get(attr); if (!isNodeList) { // convert array of Nodes to NodeList val = Y.Node.scrubVal(val, instance); } ret.push(val); }); return (isNodeList) ? Y.all(ret) : ret; }; Y.NodeList = NodeList; Y.all = function(nodes) { return new NodeList(nodes); }; Y.Node.all = Y.all; /** * @module node * @submodule node-core */ var Y_NodeList = Y.NodeList, ArrayProto = Array.prototype, ArrayMethods = { /** Returns a new NodeList combining the given NodeList(s) * @for NodeList * @method concat * @param {NodeList | Array} valueN Arrays/NodeLists and/or values to * concatenate to the resulting NodeList * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'concat': 1, /** Removes the last from the NodeList and returns it. * @for NodeList * @method pop * @return {Node | null} The last item in the NodeList, or null if the list is empty. */ 'pop': 0, /** Adds the given Node(s) to the end of the NodeList. * @for NodeList * @method push * @param {Node | DOMNode} nodes One or more nodes to add to the end of the NodeList. */ 'push': 0, /** Removes the first item from the NodeList and returns it. * @for NodeList * @method shift * @return {Node | null} The first item in the NodeList, or null if the NodeList is empty. */ 'shift': 0, /** Returns a new NodeList comprising the Nodes in the given range. * @for NodeList * @method slice * @param {Number} begin Zero-based index at which to begin extraction. As a negative index, start indicates an offset from the end of the sequence. slice(-2) extracts the second-to-last element and the last element in the sequence. * @param {Number} end Zero-based index at which to end extraction. slice extracts up to but not including end. slice(1,4) extracts the second element through the fourth element (elements indexed 1, 2, and 3). As a negative index, end indicates an offset from the end of the sequence. slice(2,-1) extracts the third element through the second-to-last element in the sequence. If end is omitted, slice extracts to the end of the sequence. * @return {NodeList} A new NodeList comprised of this NodeList joined with the input. */ 'slice': 1, /** Changes the content of the NodeList, adding new elements while removing old elements. * @for NodeList * @method splice * @param {Number} index Index at which to start changing the array. If negative, will begin that many elements from the end. * @param {Number} howMany An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed. In this case, you should specify at least one new element. If no howMany parameter is specified (second syntax above, which is a SpiderMonkey extension), all elements after index are removed. * {Node | DOMNode| element1, ..., elementN The elements to add to the array. If you don't specify any elements, splice simply removes elements from the array. * @return {NodeList} The element(s) removed. */ 'splice': 1, /** Adds the given Node(s) to the beginning of the NodeList. * @for NodeList * @method unshift * @param {Node | DOMNode} nodes One or more nodes to add to the NodeList. */ 'unshift': 0 }; Y.Object.each(ArrayMethods, function(returnNodeList, name) { Y_NodeList.prototype[name] = function() { var args = [], i = 0, arg, ret; while (typeof (arg = arguments[i++]) != 'undefined') { // use DOM nodes/nodeLists args.push(arg._node || arg._nodes || arg); } ret = ArrayProto[name].apply(this._nodes, args); if (returnNodeList) { ret = Y.all(ret); } else { ret = Y.Node.scrubVal(ret); } return ret; }; }); /** * @module node * @submodule node-core */ Y.Array.each([ /** * Passes through to DOM method. * @for Node * @method removeChild * @param {HTMLElement | Node} node Node to be removed * @return {Node} The removed node */ 'removeChild', /** * Passes through to DOM method. * @method hasChildNodes * @return {Boolean} Whether or not the node has any childNodes */ 'hasChildNodes', /** * Passes through to DOM method. * @method cloneNode * @param {Boolean} deep Whether or not to perform a deep clone, which includes * subtree and attributes * @return {Node} The clone */ 'cloneNode', /** * Passes through to DOM method. * @method hasAttribute * @param {String} attribute The attribute to test for * @return {Boolean} Whether or not the attribute is present */ 'hasAttribute', /** * Passes through to DOM method. * @method scrollIntoView * @chainable */ 'scrollIntoView', /** * Passes through to DOM method. * @method getElementsByTagName * @param {String} tagName The tagName to collect * @return {NodeList} A NodeList representing the HTMLCollection */ 'getElementsByTagName', /** * Passes through to DOM method. * @method focus * @chainable */ 'focus', /** * Passes through to DOM method. * @method blur * @chainable */ 'blur', /** * Passes through to DOM method. * Only valid on FORM elements * @method submit * @chainable */ 'submit', /** * Passes through to DOM method. * Only valid on FORM elements * @method reset * @chainable */ 'reset', /** * Passes through to DOM method. * @method select * @chainable */ 'select', /** * Passes through to DOM method. * Only valid on TABLE elements * @method createCaption * @chainable */ 'createCaption' ], function(method) { Y.log('adding: ' + method, 'info', 'node'); Y.Node.prototype[method] = function(arg1, arg2, arg3) { var ret = this.invoke(method, arg1, arg2, arg3); return ret; }; }); /** * Passes through to DOM method. * @method removeAttribute * @param {String} attribute The attribute to be removed * @chainable */ // one-off implementation due to IE returning boolean, breaking chaining Y.Node.prototype.removeAttribute = function(attr) { var node = this._node; if (node) { node.removeAttribute(attr, 0); // comma zero for IE < 8 to force case-insensitive } return this; }; Y.Node.importMethod(Y.DOM, [ /** * Determines whether the node is an ancestor of another HTML element in the DOM hierarchy. * @method contains * @param {Node | HTMLElement} needle The possible node or descendent * @return {Boolean} Whether or not this node is the needle its ancestor */ 'contains', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Wraps the given HTML around the node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable * @for Node */ 'wrap', /** * Removes the node's parent node. * @method unwrap * @chainable */ 'unwrap', /** * Applies a unique ID to the node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @see Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute', /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @see Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows for removing attributes on DOM nodes. * This passes through to the DOM node, allowing for custom attributes. * @method removeAttribute * @see Node * @for NodeList * @param {string} name The attribute to remove */ 'removeAttribute', /** * Removes the parent node from node in the list. * @method unwrap * @chainable */ 'unwrap', /** * Wraps the given HTML around each node. * @method wrap * @param {String} html The markup to wrap around the node. * @chainable */ 'wrap', /** * Applies a unique ID to each node if none exists * @method generateID * @return {String} The existing or generated ID */ 'generateID' ]); }, '@VERSION@', {"requires": ["dom-core", "selector"]}); YUI.add('node-base', function (Y, NAME) { /** * @module node * @submodule node-base */ var methods = [ /** * Determines whether each node has the given className. * @method hasClass * @for Node * @param {String} className the class name to search for * @return {Boolean} Whether or not the element has the specified class */ 'hasClass', /** * Adds a class name to each node. * @method addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ 'addClass', /** * Removes a class name from each node. * @method removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ 'removeClass', /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ 'replaceClass', /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @param {String} className the class name to be toggled * @param {Boolean} force Option to force adding or removing the class. * @chainable */ 'toggleClass' ]; Y.Node.importMethod(Y.DOM, methods); /** * Determines whether each node has the given className. * @method hasClass * @see Node.hasClass * @for NodeList * @param {String} className the class name to search for * @return {Array} An array of booleans for each node bound to the NodeList. */ /** * Adds a class name to each node. * @method addClass * @see Node.addClass * @param {String} className the class name to add to the node's class attribute * @chainable */ /** * Removes a class name from each node. * @method removeClass * @see Node.removeClass * @param {String} className the class name to remove from the node's class attribute * @chainable */ /** * Replace a class with another class for each node. * If no oldClassName is present, the newClassName is simply added. * @method replaceClass * @see Node.replaceClass * @param {String} oldClassName the class name to be replaced * @param {String} newClassName the class name that will be replacing the old class name * @chainable */ /** * If the className exists on the node it is removed, if it doesn't exist it is added. * @method toggleClass * @see Node.toggleClass * @param {String} className the class name to be toggled * @chainable */ Y.NodeList.importMethod(Y.Node.prototype, methods); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Returns a new dom node using the provided markup string. * @method create * @static * @param {String} html The markup used to create the element * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment * @for Node */ Y_Node.create = function(html, doc) { if (doc && doc._node) { doc = doc._node; } return Y.one(Y_DOM.create(html, doc)); }; Y.mix(Y_Node.prototype, { /** * Creates a new Node using the provided markup string. * @method create * @param {String} html The markup used to create the element. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {HTMLDocument} doc An optional document context * @return {Node} A Node instance bound to a DOM node or fragment */ create: Y_Node.create, /** * Inserts the content before the reference node. * @method insert * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @param {Int | Node | HTMLElement | String} where The position to insert at. * Possible "where" arguments * <dl> * <dt>Y.Node</dt> * <dd>The Node to insert before</dd> * <dt>HTMLElement</dt> * <dd>The element to insert before</dd> * <dt>Int</dt> * <dd>The index of the child element to insert before</dd> * <dt>"replace"</dt> * <dd>Replaces the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts before the existing HTML</dd> * <dt>"before"</dt> * <dd>Inserts content before the node</dd> * <dt>"after"</dt> * <dd>Inserts content after the node</dd> * </dl> * @chainable */ insert: function(content, where) { this._insert(content, where); return this; }, _insert: function(content, where) { var node = this._node, ret = null; if (typeof where == 'number') { // allow index where = this._node.childNodes[where]; } else if (where && where._node) { // Node where = where._node; } if (content && typeof content != 'string') { // allow Node or NodeList/Array instances content = content._node || content._nodes || content; } ret = Y_DOM.addHTML(node, content, where); return ret; }, /** * Inserts the content as the firstChild of the node. * @method prepend * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ prepend: function(content) { return this.insert(content, 0); }, /** * Inserts the content as the lastChild of the node. * @method append * @param {String | Node | HTMLElement} content The content to insert * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @chainable */ append: function(content) { return this.insert(content, null); }, /** * @method appendChild * @param {String | HTMLElement | Node} node Node to be appended * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The appended node */ appendChild: function(node) { return Y_Node.scrubVal(this._insert(node)); }, /** * @method insertBefore * @param {String | HTMLElement | Node} newNode Node to be appended * @param {HTMLElement | Node} refNode Node to be inserted before * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content. * @return {Node} The inserted node */ insertBefore: function(newNode, refNode) { return Y.Node.scrubVal(this._insert(newNode, refNode)); }, /** * Appends the node to the given node. * @method appendTo * @param {Node | HTMLElement} node The node to append to * @chainable */ appendTo: function(node) { Y.one(node).append(this); return this; }, /** * Replaces the node's current content with the content. * Note that this passes to innerHTML and is not escaped. * Use <a href="../classes/Escape.html#method_html">`Y.Escape.html()`</a> * to escape html content or `set('text')` to add as text. * @method setContent * @deprecated Use setHTML * @param {String | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ setContent: function(content) { this._insert(content, 'replace'); return this; }, /** * Returns the node's current content (e.g. innerHTML) * @method getContent * @deprecated Use getHTML * @return {String} The current content */ getContent: function(content) { return this.get('innerHTML'); } }); /** * Replaces the node's current html content with the content provided. * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @method setHTML * @param {String | HTML | Node | HTMLElement | NodeList | HTMLCollection} content The content to insert * @chainable */ Y.Node.prototype.setHTML = Y.Node.prototype.setContent; /** * Returns the node's current html content (e.g. innerHTML) * @method getHTML * @return {String} The html content */ Y.Node.prototype.getHTML = Y.Node.prototype.getContent; Y.NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @for NodeList * @method append * @see Node.append */ 'append', /** * Called on each Node instance * @for NodeList * @method insert * @see Node.insert */ 'insert', /** * Called on each Node instance * @for NodeList * @method appendChild * @see Node.appendChild */ 'appendChild', /** * Called on each Node instance * @for NodeList * @method insertBefore * @see Node.insertBefore */ 'insertBefore', /** * Called on each Node instance * @for NodeList * @method prepend * @see Node.prepend */ 'prepend', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setContent * @deprecated Use setHTML */ 'setContent', /** * Called on each Node instance * @for NodeList * @method getContent * @deprecated Use getHTML */ 'getContent', /** * Called on each Node instance * Note that this passes to innerHTML and is not escaped. * Use `Y.Escape.html()` to escape HTML, or `set('text')` to add as text. * @for NodeList * @method setHTML * @see Node.setHTML */ 'setHTML', /** * Called on each Node instance * @for NodeList * @method getHTML * @see Node.getHTML */ 'getHTML' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node, Y_DOM = Y.DOM; /** * Static collection of configuration attributes for special handling * @property ATTRS * @static * @type object */ Y_Node.ATTRS = { /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config text * @type String */ text: { getter: function() { return Y_DOM.getText(this._node); }, setter: function(content) { Y_DOM.setText(this._node, content); return content; } }, /** * Allows for getting and setting the text of an element. * Formatting is preserved and special characters are treated literally. * @config for * @type String */ 'for': { getter: function() { return Y_DOM.getAttribute(this._node, 'for'); }, setter: function(val) { Y_DOM.setAttribute(this._node, 'for', val); return val; } }, 'options': { getter: function() { return this._node.getElementsByTagName('option'); } }, /** * Returns a NodeList instance of all HTMLElement children. * @readOnly * @config children * @type NodeList */ 'children': { getter: function() { var node = this._node, children = node.children, childNodes, i, len; if (!children) { childNodes = node.childNodes; children = []; for (i = 0, len = childNodes.length; i < len; ++i) { if (childNodes[i].tagName) { children[children.length] = childNodes[i]; } } } return Y.all(children); } }, value: { getter: function() { return Y_DOM.getValue(this._node); }, setter: function(val) { Y_DOM.setValue(this._node, val); return val; } } }; Y.Node.importMethod(Y.DOM, [ /** * Allows setting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method setAttribute * @for Node * @for NodeList * @chainable * @param {string} name The attribute name * @param {string} value The value to set */ 'setAttribute', /** * Allows getting attributes on DOM nodes, normalizing in some cases. * This passes through to the DOM node, allowing for custom attributes. * @method getAttribute * @for Node * @for NodeList * @param {string} name The attribute name * @return {string} The attribute value */ 'getAttribute' ]); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; var Y_NodeList = Y.NodeList; /** * List of events that route to DOM events * @static * @property DOM_EVENTS * @for Node */ Y_Node.DOM_EVENTS = { abort: 1, beforeunload: 1, blur: 1, change: 1, click: 1, close: 1, command: 1, contextmenu: 1, dblclick: 1, DOMMouseScroll: 1, drag: 1, dragstart: 1, dragenter: 1, dragover: 1, dragleave: 1, dragend: 1, drop: 1, error: 1, focus: 1, key: 1, keydown: 1, keypress: 1, keyup: 1, load: 1, message: 1, mousedown: 1, mouseenter: 1, mouseleave: 1, mousemove: 1, mousemultiwheel: 1, mouseout: 1, mouseover: 1, mouseup: 1, mousewheel: 1, orientationchange: 1, reset: 1, resize: 1, select: 1, selectstart: 1, submit: 1, scroll: 1, textInput: 1, unload: 1 }; // Add custom event adaptors to this list. This will make it so // that delegate, key, available, contentready, etc all will // be available through Node.on Y.mix(Y_Node.DOM_EVENTS, Y.Env.evt.plugins); Y.augment(Y_Node, Y.EventTarget); Y.mix(Y_Node.prototype, { /** * Removes event listeners from the node and (optionally) its subtree * @method purge * @param {Boolean} recurse (optional) Whether or not to remove listeners from the * node's subtree * @param {String} type (optional) Only remove listeners of the specified type * @chainable * */ purge: function(recurse, type) { Y.Event.purgeElement(this._node, recurse, type); return this; } }); Y.mix(Y.NodeList.prototype, { _prepEvtArgs: function(type, fn, context) { // map to Y.on/after signature (type, fn, nodes, context, arg1, arg2, etc) var args = Y.Array(arguments, 0, true); if (args.length < 2) { // type only (event hash) just add nodes args[2] = this._nodes; } else { args.splice(2, 0, this._nodes); } args[3] = context || this; // default to NodeList instance as context return args; }, /** Subscribe a callback function for each `Node` in the collection to execute in response to a DOM event. NOTE: Generally, the `on()` method should be avoided on `NodeLists`, in favor of using event delegation from a parent Node. See the Event user guide for details. Most DOM events are associated with a preventable default behavior, such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. By default, the `this` object will be the `NodeList` that the subscription came from, <em>not the `Node` that received the event</em>. Use `e.currentTarget` to refer to the `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.all(".sku").on("keydown", function (e) { if (e.keyCode === 13) { e.preventDefault(); // Use e.currentTarget to refer to the individual Node var item = Y.MyApp.searchInventory( e.currentTarget.get('value') ); // etc ... } }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for NodeList **/ on: function(type, fn, context) { return Y.on.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList. * @method once * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ once: function(type, fn, context) { return Y.once.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an event listener to each Node bound to the NodeList. * The handler is called only after all on() handlers are called * and the event is not prevented. * @method after * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ after: function(type, fn, context) { return Y.after.apply(Y, this._prepEvtArgs.apply(this, arguments)); }, /** * Applies an one-time event listener to each Node bound to the NodeList * that will be called only after all on() handlers are called and the * event is not prevented. * * @method onceAfter * @param {String} type The event being listened for * @param {Function} fn The handler to call when the event fires * @param {Object} context The context to call the handler with. * Default is the NodeList instance. * @return {EventHandle} A subscription handle capable of detaching that * subscription * @for NodeList */ onceAfter: function(type, fn, context) { return Y.onceAfter.apply(Y, this._prepEvtArgs.apply(this, arguments)); } }); Y_NodeList.importMethod(Y.Node.prototype, [ /** * Called on each Node instance * @method detach * @see Node.detach * @for NodeList */ 'detach', /** Called on each Node instance * @method detachAll * @see Node.detachAll * @for NodeList */ 'detachAll' ]); /** Subscribe a callback function to execute in response to a DOM event or custom event. Most DOM events are associated with a preventable default behavior such as link clicks navigating to a new page. Callbacks are passed a `DOMEventFacade` object as their first argument (usually called `e`) that can be used to prevent this default behavior with `e.preventDefault()`. See the `DOMEventFacade` API for all available properties and methods on the object. If the event name passed as the first parameter is not a whitelisted DOM event, it will be treated as a custom event subscriptions, allowing `node.fire('customEventName')` later in the code. Refer to the Event user guide for the full DOM event whitelist. By default, the `this` object in the callback will refer to the subscribed `Node`. Returning `false` from a callback is supported as an alternative to calling `e.preventDefault(); e.stopPropagation();`. However, it is recommended to use the event methods. @example Y.one("#my-form").on("submit", function (e) { e.preventDefault(); // proceed with ajax form submission instead... }); @method on @param {String} type The name of the event @param {Function} fn The callback to execute in response to the event @param {Object} [context] Override `this` object in callback @param {Any} [arg*] 0..n additional arguments to supply to the subscriber @return {EventHandle} A subscription handle capable of detaching that subscription @for Node **/ Y.mix(Y.Node.ATTRS, { offsetHeight: { setter: function(h) { Y.DOM.setHeight(this._node, h); return h; }, getter: function() { return this._node.offsetHeight; } }, offsetWidth: { setter: function(w) { Y.DOM.setWidth(this._node, w); return w; }, getter: function() { return this._node.offsetWidth; } } }); Y.mix(Y.Node.prototype, { sizeTo: function(w, h) { var node; if (arguments.length < 2) { node = Y.one(w); w = node.get('offsetWidth'); h = node.get('offsetHeight'); } this.setAttrs({ offsetWidth: w, offsetHeight: h }); } }); /** * @module node * @submodule node-base */ var Y_Node = Y.Node; Y.mix(Y_Node.prototype, { /** * Makes the node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @for Node * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ show: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(true, callback); return this; }, /** * The implementation for showing nodes. * Default is to remove the hidden attribute and reset the CSS style.display property. * @method _show * @protected * @chainable */ _show: function() { this.removeAttribute('hidden'); // For back-compat we need to leave this in for browsers that // do not visually hide a node via the hidden attribute // and for users that check visibility based on style display. this.setStyle('display', ''); }, _isHidden: function() { return Y.DOM.getAttribute(this._node, 'hidden') === 'true'; }, /** * Displays or hides the node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the node using given named effect. * @method toggleView * @for Node * @param {String} [name] An optional string value to use as transition effect. * @param {Boolean} [on] An optional boolean value to force the node to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ toggleView: function(on, callback) { this._toggleView.apply(this, arguments); return this; }, _toggleView: function(on, callback) { callback = arguments[arguments.length - 1]; // base on current state if not forcing if (typeof on != 'boolean') { on = (this._isHidden()) ? 1 : 0; } if (on) { this._show(); } else { this._hide(); } if (typeof callback == 'function') { callback.call(this); } return this; }, /** * Hides the node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ hide: function(callback) { callback = arguments[arguments.length - 1]; this.toggleView(false, callback); return this; }, /** * The implementation for hiding nodes. * Default is to set the hidden attribute to true and set the CSS style.display to 'none'. * @method _hide * @protected * @chainable */ _hide: function() { this.setAttribute('hidden', true); // For back-compat we need to leave this in for browsers that // do not visually hide a node via the hidden attribute // and for users that check visibility based on style display. this.setStyle('display', 'none'); } }); Y.NodeList.importMethod(Y.Node.prototype, [ /** * Makes each node visible. * If the "transition" module is loaded, show optionally * animates the showing of the node using either the default * transition effect ('fadeIn'), or the given named effect. * @method show * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @for NodeList * @chainable */ 'show', /** * Hides each node. * If the "transition" module is loaded, hide optionally * animates the hiding of the node using either the default * transition effect ('fadeOut'), or the given named effect. * @method hide * @param {String} name A named Transition effect to use as the show effect. * @param {Object} config Options to use with the transition. * @param {Function} callback An optional function to run after the transition completes. * @chainable */ 'hide', /** * Displays or hides each node. * If the "transition" module is loaded, toggleView optionally * animates the toggling of the nodes using given named effect. * @method toggleView * @param {String} [name] An optional string value to use as transition effect. * @param {Boolean} [on] An optional boolean value to force the nodes to be shown or hidden * @param {Function} [callback] An optional function to run after the transition completes. * @chainable */ 'toggleView' ]); if (!Y.config.doc.documentElement.hasAttribute) { // IE < 8 Y.Node.prototype.hasAttribute = function(attr) { if (attr === 'value') { if (this.get('value') !== "") { // IE < 8 fails to populate specified when set in HTML return true; } } return !!(this._node.attributes[attr] && this._node.attributes[attr].specified); }; } // IE throws an error when calling focus() on an element that's invisible, not // displayed, or disabled. Y.Node.prototype.focus = function () { try { this._node.focus(); } catch (e) { Y.log('error focusing node: ' + e.toString(), 'error', 'node'); } return this; }; // IE throws error when setting input.type = 'hidden', // input.setAttribute('type', 'hidden') and input.attributes.type.value = 'hidden' Y.Node.ATTRS.type = { setter: function(val) { if (val === 'hidden') { try { this._node.type = 'hidden'; } catch(e) { this.setStyle('display', 'none'); this._inputType = 'hidden'; } } else { try { // IE errors when changing the type from "hidden' this._node.type = val; } catch (e) { Y.log('error setting type: ' + val, 'info', 'node'); } } return val; }, getter: function() { return this._inputType || this._node.type; }, _bypassProxy: true // don't update DOM when using with Attribute }; if (Y.config.doc.createElement('form').elements.nodeType) { // IE: elements collection is also FORM node which trips up scrubVal. Y.Node.ATTRS.elements = { getter: function() { return this.all('input, textarea, button, select'); } }; } /** * Provides methods for managing custom Node data. * * @module node * @main node * @submodule node-data */ Y.mix(Y.Node.prototype, { _initData: function() { if (! ('_data' in this)) { this._data = {}; } }, /** * @method getData * @for Node * @description Retrieves arbitrary data stored on a Node instance. * If no data is associated with the Node, it will attempt to retrieve * a value from the corresponding HTML data attribute. (e.g. node.getData('foo') * will check node.getAttribute('data-foo')). * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {any | Object} Whatever is stored at the given field, * or an object hash of all fields. */ getData: function(name) { this._initData(); var data = this._data, ret = data; if (arguments.length) { // single field if (name in data) { ret = data[name]; } else { // initialize from HTML attribute ret = this._getDataAttribute(name); } } else if (typeof data == 'object' && data !== null) { // all fields ret = {}; Y.Object.each(data, function(v, n) { ret[n] = v; }); ret = this._getDataAttributes(ret); } return ret; }, _getDataAttributes: function(ret) { ret = ret || {}; var i = 0, attrs = this._node.attributes, len = attrs.length, prefix = this.DATA_PREFIX, prefixLength = prefix.length, name; while (i < len) { name = attrs[i].name; if (name.indexOf(prefix) === 0) { name = name.substr(prefixLength); if (!(name in ret)) { // only merge if not already stored ret[name] = this._getDataAttribute(name); } } i += 1; } return ret; }, _getDataAttribute: function(name) { name = this.DATA_PREFIX + name; var node = this._node, attrs = node.attributes, data = attrs && attrs[name] && attrs[name].value; return data; }, /** * @method setData * @for Node * @description Stores arbitrary data on a Node instance. * This is not stored with the DOM node. * @param {string} name The name of the field to set. If no val * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { this._initData(); if (arguments.length > 1) { this._data[name] = val; } else { this._data = name; } return this; }, /** * @method clearData * @for Node * @description Clears internally stored data. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { if ('_data' in this) { if (typeof name != 'undefined') { delete this._data[name]; } else { delete this._data; } } return this; } }); Y.mix(Y.NodeList.prototype, { /** * @method getData * @for NodeList * @description Retrieves arbitrary data stored on each Node instance * bound to the NodeList. * @see Node * @param {string} name Optional name of the data field to retrieve. * If no name is given, all data is returned. * @return {Array} An array containing all of the data for each Node instance. * or an object hash of all fields. */ getData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('getData', args, true); }, /** * @method setData * @for NodeList * @description Stores arbitrary data on each Node instance bound to the * NodeList. This is not stored with the DOM node. * @param {string} name The name of the field to set. If no name * is given, name is treated as the data and overrides any existing data. * @param {any} val The value to be assigned to the field. * @chainable */ setData: function(name, val) { var args = (arguments.length > 1) ? [name, val] : [name]; return this._invoke('setData', args); }, /** * @method clearData * @for NodeList * @description Clears data on all Node instances bound to the NodeList. * @param {string} name The name of the field to clear. If no name * is given, all data is cleared. * @chainable */ clearData: function(name) { var args = (arguments.length) ? [name] : []; return this._invoke('clearData', [name]); } }); }, '@VERSION@', {"requires": ["event-base", "node-core", "dom-base"]}); (function () { var GLOBAL_ENV = YUI.Env; if (!GLOBAL_ENV._ready) { GLOBAL_ENV._ready = function() { GLOBAL_ENV.DOMReady = true; GLOBAL_ENV.remove(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); }; GLOBAL_ENV.add(YUI.config.doc, 'DOMContentLoaded', GLOBAL_ENV._ready); } })(); YUI.add('event-base', function (Y, NAME) { /* * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * The domready event fires at the moment the browser's DOM is * usable. In most cases, this is before images are fully * downloaded, allowing you to provide a more responsive user * interface. * * In YUI 3, domready subscribers will be notified immediately if * that moment has already passed when the subscription is created. * * One exception is if the yui.js file is dynamically injected into * the page. If this is done, you must tell the YUI instance that * you did this in order for DOMReady (and window load events) to * fire normally. That configuration option is 'injected' -- set * it to true if the yui.js script is not included inline. * * This method is part of the 'event-ready' module, which is a * submodule of 'event'. * * @event domready * @for YUI */ Y.publish('domready', { fireOnce: true, async: true }); if (YUI.Env.DOMReady) { Y.fire('domready'); } else { Y.Do.before(function() { Y.fire('domready'); }, YUI.Env, '_ready'); } /** * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ /** * Wraps a DOM event, properties requiring browser abstraction are * fixed here. Provids a security layer when required. * @class DOMEventFacade * @param ev {Event} the DOM event * @param currentTarget {HTMLElement} the element the listener was attached to * @param wrapper {Event.Custom} the custom event wrapper for this DOM event */ var ua = Y.UA, EMPTY = {}, /** * webkit key remapping required for Safari < 3.1 * @property webkitKeymap * @private */ webkitKeymap = { 63232: 38, // up 63233: 40, // down 63234: 37, // left 63235: 39, // right 63276: 33, // page up 63277: 34, // page down 25: 9, // SHIFT-TAB (Safari provides a different key code in // this case, even though the shiftKey modifier is set) 63272: 46, // delete 63273: 36, // home 63275: 35 // end }, /** * Returns a wrapped node. Intended to be used on event targets, * so it will return the node's parent if the target is a text * node. * * If accessing a property of the node throws an error, this is * probably the anonymous div wrapper Gecko adds inside text * nodes. This likely will only occur when attempting to access * the relatedTarget. In this case, we now return null because * the anonymous div is completely useless and we do not know * what the related target was because we can't even get to * the element's parent node. * * @method resolve * @private */ resolve = function(n) { if (!n) { return n; } try { if (n && 3 == n.nodeType) { n = n.parentNode; } } catch(e) { return null; } return Y.one(n); }, DOMEventFacade = function(ev, currentTarget, wrapper) { this._event = ev; this._currentTarget = currentTarget; this._wrapper = wrapper || EMPTY; // if not lazy init this.init(); }; Y.extend(DOMEventFacade, Object, { init: function() { var e = this._event, overrides = this._wrapper.overrides, x = e.pageX, y = e.pageY, c, currentTarget = this._currentTarget; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.pageX = x; this.pageY = y; // charCode is unknown in keyup, keydown. keyCode is unknown in keypress. // FF 3.6 - 8+? pass 0 for keyCode in keypress events. // Webkit, FF 3.6-8+?, and IE9+? pass 0 for charCode in keydown, keyup. // Webkit and IE9+? duplicate charCode in keyCode. // Opera never sets charCode, always keyCode (though with the charCode). // IE6-8 don't set charCode or which. // All browsers other than IE6-8 set which=keyCode in keydown, keyup, and // which=charCode in keypress. // // Moral of the story: (e.which || e.keyCode) will always return the // known code for that key event phase. e.keyCode is often different in // keypress from keydown and keyup. c = e.keyCode || e.charCode; if (ua.webkit && (c in webkitKeymap)) { c = webkitKeymap[c]; } this.keyCode = c; this.charCode = c; // Fill in e.which for IE - implementers should always use this over // e.keyCode or e.charCode. this.which = e.which || e.charCode || c; // this.button = e.button; this.button = this.which; this.target = resolve(e.target); this.currentTarget = resolve(currentTarget); this.relatedTarget = resolve(e.relatedTarget); if (e.type == "mousewheel" || e.type == "DOMMouseScroll") { this.wheelDelta = (e.detail) ? (e.detail * -1) : Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } if (this._touch) { this._touch(e, currentTarget, this._wrapper); } }, stopPropagation: function() { this._event.stopPropagation(); this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { var e = this._event; if (e.stopImmediatePropagation) { e.stopImmediatePropagation(); } else { this.stopPropagation(); } this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { var e = this._event; e.preventDefault(); e.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; }, halt: function(immediate) { if (immediate) { this.stopImmediatePropagation(); } else { this.stopPropagation(); } this.preventDefault(); } }); DOMEventFacade.resolve = resolve; Y.DOM2EventFacade = DOMEventFacade; Y.DOMEventFacade = DOMEventFacade; /** * The native event * @property _event * @type {Native DOM Event} * @private */ /** The name of the event (e.g. "click") @property type @type {String} **/ /** `true` if the "alt" or "option" key is pressed. @property altKey @type {Boolean} **/ /** `true` if the shift key is pressed. @property shiftKey @type {Boolean} **/ /** `true` if the "Windows" key on a Windows keyboard, "command" key on an Apple keyboard, or "meta" key on other keyboards is pressed. @property metaKey @type {Boolean} **/ /** `true` if the "Ctrl" or "control" key is pressed. @property ctrlKey @type {Boolean} **/ /** * The X location of the event on the page (including scroll) * @property pageX * @type {Number} */ /** * The Y location of the event on the page (including scroll) * @property pageY * @type {Number} */ /** * The X location of the event in the viewport * @property clientX * @type {Number} */ /** * The Y location of the event in the viewport * @property clientY * @type {Number} */ /** * The keyCode for key events. Uses charCode if keyCode is not available * @property keyCode * @type {Number} */ /** * The charCode for key events. Same as keyCode * @property charCode * @type {Number} */ /** * The button that was pushed. 1 for left click, 2 for middle click, 3 for * right click. This is only reliably populated on `mouseup` events. * @property button * @type {Number} */ /** * The button that was pushed. Same as button. * @property which * @type {Number} */ /** * Node reference for the targeted element * @property target * @type {Node} */ /** * Node reference for the element that the listener was attached to. * @property currentTarget * @type {Node} */ /** * Node reference to the relatedTarget * @property relatedTarget * @type {Node} */ /** * Number representing the direction and velocity of the movement of the mousewheel. * Negative is down, the higher the number, the faster. Applies to the mousewheel event. * @property wheelDelta * @type {Number} */ /** * Stops the propagation to the next bubble target * @method stopPropagation */ /** * Stops the propagation to the next bubble target and * prevents any additional listeners from being exectued * on the current target. * @method stopImmediatePropagation */ /** * Prevents the event's default behavior * @method preventDefault * @param returnValue {string} sets the returnValue of the event to this value * (rather than the default false value). This can be used to add a customized * confirmation query to the beforeunload event). */ /** * Stops the event propagation and prevents the default * event behavior. * @method halt * @param immediate {boolean} if true additional listeners * on the current target will not be executed */ (function() { /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * @module event * @main event * @submodule event-base */ /** * The event utility provides functions to add and remove event listeners, * event cleansing. It also tries to automatically remove listeners it * registers during the unload event. * * @class Event * @static */ Y.Env.evt.dom_wrappers = {}; Y.Env.evt.dom_map = {}; var _eventenv = Y.Env.evt, config = Y.config, win = config.win, add = YUI.Env.add, remove = YUI.Env.remove, onLoad = function() { YUI.Env.windowLoaded = true; Y.Event._load(); remove(win, "load", onLoad); }, onUnload = function() { Y.Event._unload(); }, EVENT_READY = 'domready', COMPAT_ARG = '~yui|2|compat~', shouldIterate = function(o) { try { // TODO: See if there's a more performant way to return true early on this, for the common case return (o && typeof o !== "string" && Y.Lang.isNumber(o.length) && !o.tagName && !Y.DOM.isWindow(o)); } catch(ex) { Y.log("collection check failure", "warn", "event"); return false; } }, // aliases to support DOM event subscription clean up when the last // subscriber is detached. deleteAndClean overrides the DOM event's wrapper // CustomEvent _delete method. _ceProtoDelete = Y.CustomEvent.prototype._delete, _deleteAndClean = function(s) { var ret = _ceProtoDelete.apply(this, arguments); if (!this.hasSubs()) { Y.Event._clean(this); } return ret; }, Event = function() { /** * True after the onload event has fired * @property _loadComplete * @type boolean * @static * @private */ var _loadComplete = false, /** * The number of times to poll after window.onload. This number is * increased if additional late-bound handlers are requested after * the page load. * @property _retryCount * @static * @private */ _retryCount = 0, /** * onAvailable listeners * @property _avail * @static * @private */ _avail = [], /** * Custom event wrappers for DOM events. Key is * 'event:' + Element uid stamp + event type * @property _wrappers * @type Y.Event.Custom * @static * @private */ _wrappers = _eventenv.dom_wrappers, _windowLoadKey = null, /** * Custom event wrapper map DOM events. Key is * Element uid stamp. Each item is a hash of custom event * wrappers as provided in the _wrappers collection. This * provides the infrastructure for getListeners. * @property _el_events * @static * @private */ _el_events = _eventenv.dom_map; return { /** * The number of times we should look for elements that are not * in the DOM at the time the event is requested after the document * has been loaded. The default is 1000@amp;40 ms, so it will poll * for 40 seconds or until all outstanding handlers are bound * (whichever comes first). * @property POLL_RETRYS * @type int * @static * @final */ POLL_RETRYS: 1000, /** * The poll interval in milliseconds * @property POLL_INTERVAL * @type int * @static * @final */ POLL_INTERVAL: 40, /** * addListener/removeListener can throw errors in unexpected scenarios. * These errors are suppressed, the method returns false, and this property * is set * @property lastError * @static * @type Error */ lastError: null, /** * poll handle * @property _interval * @static * @private */ _interval: null, /** * document readystate poll handle * @property _dri * @static * @private */ _dri: null, /** * True when the document is initially usable * @property DOMReady * @type boolean * @static */ DOMReady: false, /** * @method startInterval * @static * @private */ startInterval: function() { if (!Event._interval) { Event._interval = setInterval(Event._poll, Event.POLL_INTERVAL); } }, /** * Executes the supplied callback when the item with the supplied * id is found. This is meant to be used to execute behavior as * soon as possible as the page loads. If you use this after the * initial page load it will poll for a fixed time for the element. * The number of times it will poll and the frequency are * configurable. By default it will poll for 10 seconds. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onAvailable * * @param {string||string[]} id the id of the element, or an array * of ids to look for. * @param {function} fn what to execute when the element is found. * @param {object} p_obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} p_override If set to true, fn will execute * in the context of p_obj, if set to an object it * will execute in the context of that object * @param checkContent {boolean} check child node readiness (onContentReady) * @static * @deprecated Use Y.on("available") */ // @TODO fix arguments onAvailable: function(id, fn, p_obj, p_override, checkContent, compat) { var a = Y.Array(id), i, availHandle; // Y.log('onAvailable registered for: ' + id); for (i=0; i<a.length; i=i+1) { _avail.push({ id: a[i], fn: fn, obj: p_obj, override: p_override, checkReady: checkContent, compat: compat }); } _retryCount = this.POLL_RETRYS; // We want the first test to be immediate, but async setTimeout(Event._poll, 0); availHandle = new Y.EventHandle({ _delete: function() { // set by the event system for lazy DOM listeners if (availHandle.handle) { availHandle.handle.detach(); return; } var i, j; // otherwise try to remove the onAvailable listener(s) for (i = 0; i < a.length; i++) { for (j = 0; j < _avail.length; j++) { if (a[i] === _avail[j].id) { _avail.splice(j, 1); } } } } }); return availHandle; }, /** * Works the same way as onAvailable, but additionally checks the * state of sibling elements to determine if the content of the * available element is safe to modify. * * <p>The callback is executed with a single parameter: * the custom object parameter, if provided.</p> * * @method onContentReady * * @param {string} id the id of the element to look for. * @param {function} fn what to execute when the element is ready. * @param {object} obj an optional object to be passed back as * a parameter to fn. * @param {boolean|object} override If set to true, fn will execute * in the context of p_obj. If an object, fn will * exectute in the context of that object * * @static * @deprecated Use Y.on("contentready") */ // @TODO fix arguments onContentReady: function(id, fn, obj, override, compat) { return Event.onAvailable(id, fn, obj, override, true, compat); }, /** * Adds an event listener * * @method attach * * @param {String} type The type of event to append * @param {Function} fn The method the event invokes * @param {String|HTMLElement|Array|NodeList} el An id, an element * reference, or a collection of ids and/or elements to assign the * listener to. * @param {Object} context optional context object * @param {Boolean|object} args 0..n arguments to pass to the callback * @return {EventHandle} an object to that can be used to detach the listener * * @static */ attach: function(type, fn, el, context) { return Event._attach(Y.Array(arguments, 0, true)); }, _createWrapper: function (el, type, capture, compat, facade) { var cewrapper, ek = Y.stamp(el), key = 'event:' + ek + type; if (false === facade) { key += 'native'; } if (capture) { key += 'capture'; } cewrapper = _wrappers[key]; if (!cewrapper) { // create CE wrapper cewrapper = Y.publish(key, { silent: true, bubbles: false, emitFacade:false, contextFn: function() { if (compat) { return cewrapper.el; } else { cewrapper.nodeRef = cewrapper.nodeRef || Y.one(cewrapper.el); return cewrapper.nodeRef; } } }); cewrapper.overrides = {}; // for later removeListener calls cewrapper.el = el; cewrapper.key = key; cewrapper.domkey = ek; cewrapper.type = type; cewrapper.fn = function(e) { cewrapper.fire(Event.getEvent(e, el, (compat || (false === facade)))); }; cewrapper.capture = capture; if (el == win && type == "load") { // window load happens once cewrapper.fireOnce = true; _windowLoadKey = key; } cewrapper._delete = _deleteAndClean; _wrappers[key] = cewrapper; _el_events[ek] = _el_events[ek] || {}; _el_events[ek][key] = cewrapper; add(el, type, cewrapper.fn, capture); } return cewrapper; }, _attach: function(args, conf) { var compat, handles, oEl, cewrapper, context, fireNow = false, ret, type = args[0], fn = args[1], el = args[2] || win, facade = conf && conf.facade, capture = conf && conf.capture, overrides = conf && conf.overrides; if (args[args.length-1] === COMPAT_ARG) { compat = true; } if (!fn || !fn.call) { // throw new TypeError(type + " attach call failed, callback undefined"); Y.log(type + " attach call failed, invalid callback", "error", "event"); return false; } // The el argument can be an array of elements or element ids. if (shouldIterate(el)) { handles=[]; Y.each(el, function(v, k) { args[2] = v; handles.push(Event._attach(args.slice(), conf)); }); // return (handles.length === 1) ? handles[0] : handles; return new Y.EventHandle(handles); // If the el argument is a string, we assume it is // actually the id of the element. If the page is loaded // we convert el to the actual element, otherwise we // defer attaching the event until the element is // ready } else if (Y.Lang.isString(el)) { // oEl = (compat) ? Y.DOM.byId(el) : Y.Selector.query(el); if (compat) { oEl = Y.DOM.byId(el); } else { oEl = Y.Selector.query(el); switch (oEl.length) { case 0: oEl = null; break; case 1: oEl = oEl[0]; break; default: args[2] = oEl; return Event._attach(args, conf); } } if (oEl) { el = oEl; // Not found = defer adding the event until the element is available } else { // Y.log(el + ' not found'); ret = Event.onAvailable(el, function() { // Y.log('lazy attach: ' + args); ret.handle = Event._attach(args, conf); }, Event, true, false, compat); return ret; } } // Element should be an html element or node if (!el) { Y.log("unable to attach event " + type, "warn", "event"); return false; } if (Y.Node && Y.instanceOf(el, Y.Node)) { el = Y.Node.getDOMNode(el); } cewrapper = Event._createWrapper(el, type, capture, compat, facade); if (overrides) { Y.mix(cewrapper.overrides, overrides); } if (el == win && type == "load") { // if the load is complete, fire immediately. // all subscribers, including the current one // will be notified. if (YUI.Env.windowLoaded) { fireNow = true; } } if (compat) { args.pop(); } context = args[3]; // set context to the Node if not specified // ret = cewrapper.on.apply(cewrapper, trimmedArgs); ret = cewrapper._on(fn, context, (args.length > 4) ? args.slice(4) : null); if (fireNow) { cewrapper.fire(); } return ret; }, /** * Removes an event listener. Supports the signature the event was bound * with, but the preferred way to remove listeners is using the handle * that is returned when using Y.on * * @method detach * * @param {String} type the type of event to remove. * @param {Function} fn the method the event invokes. If fn is * undefined, then all event handlers for the type of event are * removed. * @param {String|HTMLElement|Array|NodeList|EventHandle} el An * event handle, an id, an element reference, or a collection * of ids and/or elements to remove the listener from. * @return {boolean} true if the unbind was successful, false otherwise. * @static */ detach: function(type, fn, el, obj) { var args=Y.Array(arguments, 0, true), compat, l, ok, i, id, ce; if (args[args.length-1] === COMPAT_ARG) { compat = true; // args.pop(); } if (type && type.detach) { return type.detach(); } // The el argument can be a string if (typeof el == "string") { // el = (compat) ? Y.DOM.byId(el) : Y.all(el); if (compat) { el = Y.DOM.byId(el); } else { el = Y.Selector.query(el); l = el.length; if (l < 1) { el = null; } else if (l == 1) { el = el[0]; } } // return Event.detach.apply(Event, args); } if (!el) { return false; } if (el.detach) { args.splice(2, 1); return el.detach.apply(el, args); // The el argument can be an array of elements or element ids. } else if (shouldIterate(el)) { ok = true; for (i=0, l=el.length; i<l; ++i) { args[2] = el[i]; ok = ( Y.Event.detach.apply(Y.Event, args) && ok ); } return ok; } if (!type || !fn || !fn.call) { return Event.purgeElement(el, false, type); } id = 'event:' + Y.stamp(el) + type; ce = _wrappers[id]; if (ce) { return ce.detach(fn); } else { return false; } }, /** * Finds the event in the window object, the caller's arguments, or * in the arguments of another method in the callstack. This is * executed automatically for events registered through the event * manager, so the implementer should not normally need to execute * this function at all. * @method getEvent * @param {Event} e the event parameter from the handler * @param {HTMLElement} el the element the listener was attached to * @return {Event} the event * @static */ getEvent: function(e, el, noFacade) { var ev = e || win.event; return (noFacade) ? ev : new Y.DOMEventFacade(ev, el, _wrappers['event:' + Y.stamp(el) + e.type]); }, /** * Generates an unique ID for the element if it does not already * have one. * @method generateId * @param el the element to create the id for * @return {string} the resulting id of the element * @static */ generateId: function(el) { return Y.DOM.generateID(el); }, /** * We want to be able to use getElementsByTagName as a collection * to attach a group of events to. Unfortunately, different * browsers return different types of collections. This function * tests to determine if the object is array-like. It will also * fail if the object is an array, but is empty. * @method _isValidCollection * @param o the object to test * @return {boolean} true if the object is array-like and populated * @deprecated was not meant to be used directly * @static * @private */ _isValidCollection: shouldIterate, /** * hook up any deferred listeners * @method _load * @static * @private */ _load: function(e) { if (!_loadComplete) { // Y.log('Load Complete', 'info', 'event'); _loadComplete = true; // Just in case DOMReady did not go off for some reason // E._ready(); if (Y.fire) { Y.fire(EVENT_READY); } // Available elements may not have been detected before the // window load event fires. Try to find them now so that the // the user is more likely to get the onAvailable notifications // before the window load notification Event._poll(); } }, /** * Polling function that runs before the onload event fires, * attempting to attach to DOM Nodes as soon as they are * available * @method _poll * @static * @private */ _poll: function() { if (Event.locked) { return; } if (Y.UA.ie && !YUI.Env.DOMReady) { // Hold off if DOMReady has not fired and check current // readyState to protect against the IE operation aborted // issue. Event.startInterval(); return; } Event.locked = true; // Y.log.debug("poll"); // keep trying until after the page is loaded. We need to // check the page load state prior to trying to bind the // elements so that we can be certain all elements have been // tested appropriately var i, len, item, el, notAvail, executeItem, tryAgain = !_loadComplete; if (!tryAgain) { tryAgain = (_retryCount > 0); } // onAvailable notAvail = []; executeItem = function (el, item) { var context, ov = item.override; try { if (item.compat) { if (item.override) { if (ov === true) { context = item.obj; } else { context = ov; } } else { context = el; } item.fn.call(context, item.obj); } else { context = item.obj || Y.one(el); item.fn.apply(context, (Y.Lang.isArray(ov)) ? ov : []); } } catch (e) { Y.log("Error in available or contentReady callback", 'error', 'event'); } }; // onAvailable for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && !item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // Y.log('avail: ' + el); executeItem(el, item); _avail[i] = null; } else { // Y.log('NOT avail: ' + el); notAvail.push(item); } } } // onContentReady for (i=0,len=_avail.length; i<len; ++i) { item = _avail[i]; if (item && item.checkReady) { // el = (item.compat) ? Y.DOM.byId(item.id) : Y.one(item.id); el = (item.compat) ? Y.DOM.byId(item.id) : Y.Selector.query(item.id, null, true); if (el) { // The element is available, but not necessarily ready // @todo should we test parentNode.nextSibling? if (_loadComplete || (el.get && el.get('nextSibling')) || el.nextSibling) { executeItem(el, item); _avail[i] = null; } } else { notAvail.push(item); } } } _retryCount = (notAvail.length === 0) ? 0 : _retryCount - 1; if (tryAgain) { // we may need to strip the nulled out items here Event.startInterval(); } else { clearInterval(Event._interval); Event._interval = null; } Event.locked = false; return; }, /** * Removes all listeners attached to the given element via addListener. * Optionally, the node's children can also be purged. * Optionally, you can specify a specific type of event to remove. * @method purgeElement * @param {HTMLElement} el the element to purge * @param {boolean} recurse recursively purge this element's children * as well. Use with caution. * @param {string} type optional type of listener to purge. If * left out, all listeners will be removed * @static */ purgeElement: function(el, recurse, type) { // var oEl = (Y.Lang.isString(el)) ? Y.one(el) : el, var oEl = (Y.Lang.isString(el)) ? Y.Selector.query(el, null, true) : el, lis = Event.getListeners(oEl, type), i, len, children, child; if (recurse && oEl) { lis = lis || []; children = Y.Selector.query('*', oEl); len = children.length; for (i = 0; i < len; ++i) { child = Event.getListeners(children[i], type); if (child) { lis = lis.concat(child); } } } if (lis) { for (i = 0, len = lis.length; i < len; ++i) { lis[i].detachAll(); } } }, /** * Removes all object references and the DOM proxy subscription for * a given event for a DOM node. * * @method _clean * @param wrapper {CustomEvent} Custom event proxy for the DOM * subscription * @private * @static * @since 3.4.0 */ _clean: function (wrapper) { var key = wrapper.key, domkey = wrapper.domkey; remove(wrapper.el, wrapper.type, wrapper.fn, wrapper.capture); delete _wrappers[key]; delete Y._yuievt.events[key]; if (_el_events[domkey]) { delete _el_events[domkey][key]; if (!Y.Object.size(_el_events[domkey])) { delete _el_events[domkey]; } } }, /** * Returns all listeners attached to the given element via addListener. * Optionally, you can specify a specific type of event to return. * @method getListeners * @param el {HTMLElement|string} the element or element id to inspect * @param type {string} optional type of listener to return. If * left out, all listeners will be returned * @return {CustomEvent} the custom event wrapper for the DOM event(s) * @static */ getListeners: function(el, type) { var ek = Y.stamp(el, true), evts = _el_events[ek], results=[] , key = (type) ? 'event:' + ek + type : null, adapters = _eventenv.plugins; if (!evts) { return null; } if (key) { // look for synthetic events if (adapters[type] && adapters[type].eventDef) { key += '_synth'; } if (evts[key]) { results.push(evts[key]); } // get native events as well key += 'native'; if (evts[key]) { results.push(evts[key]); } } else { Y.each(evts, function(v, k) { results.push(v); }); } return (results.length) ? results : null; }, /** * Removes all listeners registered by pe.event. Called * automatically during the unload event. * @method _unload * @static * @private */ _unload: function(e) { Y.each(_wrappers, function(v, k) { if (v.type == 'unload') { v.fire(e); } v.detachAll(); }); remove(win, "unload", onUnload); }, /** * Adds a DOM event directly without the caching, cleanup, context adj, etc * * @method nativeAdd * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeAdd: add, /** * Basic remove listener * * @method nativeRemove * @param {HTMLElement} el the element to bind the handler to * @param {string} type the type of event handler * @param {function} fn the callback to invoke * @param {boolen} capture capture or bubble phase * @static * @private */ nativeRemove: remove }; }(); Y.Event = Event; if (config.injected || YUI.Env.windowLoaded) { onLoad(); } else { add(win, "load", onLoad); } // Process onAvailable/onContentReady items when when the DOM is ready in IE if (Y.UA.ie) { Y.on(EVENT_READY, Event._poll); } try { add(win, "unload", onUnload); } catch(e) { /*jshint maxlen:300*/ Y.log("Registering unload listener failed. This is known to happen in Chrome Packaged Apps and Extensions, which don't support unload, and don't provide a way to test for support", "warn", "event-base"); } Event.Custom = Y.CustomEvent; Event.Subscriber = Y.Subscriber; Event.Target = Y.EventTarget; Event.Handle = Y.EventHandle; Event.Facade = Y.EventFacade; Event._poll(); }()); /** * DOM event listener abstraction layer * @module event * @submodule event-base */ /** * Executes the callback as soon as the specified element * is detected in the DOM. This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event available * @param type {string} 'available' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.available = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onAvailable.call(Y.Event, id, fn, o, a); } }; /** * Executes the callback as soon as the specified element * is detected in the DOM with a nextSibling property * (indicating that the element's children are available). * This function expects a selector * string for the element(s) to detect. If you already have * an element reference, you don't need this event. * @event contentready * @param type {string} 'contentready' * @param fn {function} the callback function to execute. * @param el {string} an selector for the element(s) to attach. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.Env.evt.plugins.contentready = { on: function(type, fn, id, o) { var a = arguments.length > 4 ? Y.Array(arguments, 4, true) : null; return Y.Event.onContentReady.call(Y.Event, id, fn, o, a); } }; }, '@VERSION@', {"requires": ["event-custom-base"]}); (function() { var stateChangeListener, GLOBAL_ENV = YUI.Env, config = YUI.config, doc = config.doc, docElement = doc && doc.documentElement, EVENT_NAME = 'onreadystatechange', pollInterval = config.pollInterval || 40; if (docElement.doScroll && !GLOBAL_ENV._ieready) { GLOBAL_ENV._ieready = function() { GLOBAL_ENV._ready(); }; /*! DOMReady: based on work by: Dean Edwards/John Resig/Matthias Miller/Diego Perini */ // Internet Explorer: use the doScroll() method on the root element. // This isolates what appears to be a safe moment to manipulate the // DOM prior to when the document's readyState suggests it is safe to do so. if (self !== self.top) { stateChangeListener = function() { if (doc.readyState == 'complete') { GLOBAL_ENV.remove(doc, EVENT_NAME, stateChangeListener); GLOBAL_ENV.ieready(); } }; GLOBAL_ENV.add(doc, EVENT_NAME, stateChangeListener); } else { GLOBAL_ENV._dri = setInterval(function() { try { docElement.doScroll('left'); clearInterval(GLOBAL_ENV._dri); GLOBAL_ENV._dri = null; GLOBAL_ENV._ieready(); } catch (domNotReady) { } }, pollInterval); } } })(); YUI.add('event-base-ie', function (Y, NAME) { /* * Custom event engine, DOM event listener abstraction layer, synthetic DOM * events. * @module event * @submodule event-base */ function IEEventFacade() { // IEEventFacade.superclass.constructor.apply(this, arguments); Y.DOM2EventFacade.apply(this, arguments); } /* * (intentially left out of API docs) * Alternate Facade implementation that is based on Object.defineProperty, which * is partially supported in IE8. Properties that involve setup work are * deferred to temporary getters using the static _define method. */ function IELazyFacade(e) { var proxy = Y.config.doc.createEventObject(e), proto = IELazyFacade.prototype; // TODO: necessary? proxy.hasOwnProperty = function () { return true; }; proxy.init = proto.init; proxy.halt = proto.halt; proxy.preventDefault = proto.preventDefault; proxy.stopPropagation = proto.stopPropagation; proxy.stopImmediatePropagation = proto.stopImmediatePropagation; Y.DOM2EventFacade.apply(proxy, arguments); return proxy; } var imp = Y.config.doc && Y.config.doc.implementation, useLazyFacade = Y.config.lazyEventFacade, buttonMap = { 0: 1, // left click 4: 2, // middle click 2: 3 // right click }, relatedTargetMap = { mouseout: 'toElement', mouseover: 'fromElement' }, resolve = Y.DOM2EventFacade.resolve, proto = { init: function() { IEEventFacade.superclass.init.apply(this, arguments); var e = this._event, x, y, d, b, de, t; this.target = resolve(e.srcElement); if (('clientX' in e) && (!x) && (0 !== x)) { x = e.clientX; y = e.clientY; d = Y.config.doc; b = d.body; de = d.documentElement; x += (de.scrollLeft || (b && b.scrollLeft) || 0); y += (de.scrollTop || (b && b.scrollTop) || 0); this.pageX = x; this.pageY = y; } if (e.type == "mouseout") { t = e.toElement; } else if (e.type == "mouseover") { t = e.fromElement; } // fallback to t.relatedTarget to support simulated events. // IE doesn't support setting toElement or fromElement on generic // events, so Y.Event.simulate sets relatedTarget instead. this.relatedTarget = resolve(t || e.relatedTarget); // which should contain the unicode key code if this is a key event. // For click events, which is normalized for which mouse button was // clicked. this.which = // chained assignment this.button = e.keyCode || buttonMap[e.button] || e.button; }, stopPropagation: function() { this._event.cancelBubble = true; this._wrapper.stopped = 1; this.stopped = 1; }, stopImmediatePropagation: function() { this.stopPropagation(); this._wrapper.stopped = 2; this.stopped = 2; }, preventDefault: function(returnValue) { this._event.returnValue = returnValue || false; this._wrapper.prevented = 1; this.prevented = 1; } }; Y.extend(IEEventFacade, Y.DOM2EventFacade, proto); Y.extend(IELazyFacade, Y.DOM2EventFacade, proto); IELazyFacade.prototype.init = function () { var e = this._event, overrides = this._wrapper.overrides, define = IELazyFacade._define, lazyProperties = IELazyFacade._lazyProperties, prop; this.altKey = e.altKey; this.ctrlKey = e.ctrlKey; this.metaKey = e.metaKey; this.shiftKey = e.shiftKey; this.type = (overrides && overrides.type) || e.type; this.clientX = e.clientX; this.clientY = e.clientY; this.keyCode = // chained assignment this.charCode = e.keyCode; this.which = // chained assignment this.button = e.keyCode || buttonMap[e.button] || e.button; for (prop in lazyProperties) { if (lazyProperties.hasOwnProperty(prop)) { define(this, prop, lazyProperties[prop]); } } if (this._touch) { this._touch(e, this._currentTarget, this._wrapper); } }; IELazyFacade._lazyProperties = { target: function () { return resolve(this._event.srcElement); }, relatedTarget: function () { var e = this._event, targetProp = relatedTargetMap[e.type] || 'relatedTarget'; // fallback to t.relatedTarget to support simulated events. // IE doesn't support setting toElement or fromElement on generic // events, so Y.Event.simulate sets relatedTarget instead. return resolve(e[targetProp] || e.relatedTarget); }, currentTarget: function () { return resolve(this._currentTarget); }, wheelDelta: function () { var e = this._event; if (e.type === "mousewheel" || e.type === "DOMMouseScroll") { return (e.detail) ? (e.detail * -1) : // wheelDelta between -80 and 80 result in -1 or 1 Math.round(e.wheelDelta / 80) || ((e.wheelDelta < 0) ? -1 : 1); } }, pageX: function () { var e = this._event, val = e.pageX, doc, bodyScroll, docScroll; if (val === undefined) { doc = Y.config.doc; bodyScroll = doc.body && doc.body.scrollLeft; docScroll = doc.documentElement.scrollLeft; val = e.clientX + (docScroll || bodyScroll || 0); } return val; }, pageY: function () { var e = this._event, val = e.pageY, doc, bodyScroll, docScroll; if (val === undefined) { doc = Y.config.doc; bodyScroll = doc.body && doc.body.scrollTop; docScroll = doc.documentElement.scrollTop; val = e.clientY + (docScroll || bodyScroll || 0); } return val; } }; /** * Wrapper function for Object.defineProperty that creates a property whose * value will be calulated only when asked for. After calculating the value, * the getter wll be removed, so it will behave as a normal property beyond that * point. A setter is also assigned so assigning to the property will clear * the getter, so foo.prop = 'a'; foo.prop; won't trigger the getter, * overwriting value 'a'. * * Used only by the DOMEventFacades used by IE8 when the YUI configuration * <code>lazyEventFacade</code> is set to true. * * @method _define * @param o {DOMObject} A DOM object to add the property to * @param prop {String} The name of the new property * @param valueFn {Function} The function that will return the initial, default * value for the property. * @static * @private */ IELazyFacade._define = function (o, prop, valueFn) { function val(v) { var ret = (arguments.length) ? v : valueFn.call(this); delete o[prop]; Object.defineProperty(o, prop, { value: ret, configurable: true, writable: true }); return ret; } Object.defineProperty(o, prop, { get: val, set: val, configurable: true }); }; if (imp && (!imp.hasFeature('Events', '2.0'))) { if (useLazyFacade) { // Make sure we can use the lazy facade logic try { Object.defineProperty(Y.config.doc.createEventObject(), 'z', {}); } catch (e) { useLazyFacade = false; } } Y.DOMEventFacade = (useLazyFacade) ? IELazyFacade : IEEventFacade; } }, '@VERSION@', {"requires": ["node-base"]}); YUI.add('pluginhost-base', function (Y, NAME) { /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost */ /** * Provides the augmentable PluginHost interface, which can be added to any class. * @module pluginhost-base */ /** * <p> * An augmentable class, which provides the augmented class with the ability to host plugins. * It adds <a href="#method_plug">plug</a> and <a href="#method_unplug">unplug</a> methods to the augmented class, which can * be used to add or remove plugins from instances of the class. * </p> * * <p>Plugins can also be added through the constructor configuration object passed to the host class' constructor using * the "plugins" property. Supported values for the "plugins" property are those defined by the <a href="#method_plug">plug</a> method. * * For example the following code would add the AnimPlugin and IOPlugin to Overlay (the plugin host): * <xmp> * var o = new Overlay({plugins: [ AnimPlugin, {fn:IOPlugin, cfg:{section:"header"}}]}); * </xmp> * </p> * <p> * Plug.Host's protected <a href="#method_initPlugins">_initPlugins</a> and <a href="#method_destroyPlugins">_destroyPlugins</a> * methods should be invoked by the host class at the appropriate point in the host's lifecyle. * </p> * * @class Plugin.Host */ var L = Y.Lang; function PluginHost() { this._plugins = {}; } PluginHost.prototype = { /** * Adds a plugin to the host object. This will instantiate the * plugin and attach it to the configured namespace on the host object. * * @method plug * @chainable * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @return {Base} A reference to the host object */ plug: function(Plugin, config) { var i, ln, ns; if (L.isArray(Plugin)) { for (i = 0, ln = Plugin.length; i < ln; i++) { this.plug(Plugin[i]); } } else { if (Plugin && !L.isFunction(Plugin)) { config = Plugin.cfg; Plugin = Plugin.fn; } // Plugin should be fn by now if (Plugin && Plugin.NS) { ns = Plugin.NS; config = config || {}; config.host = this; if (this.hasPlugin(ns)) { // Update config if (this[ns].setAttrs) { this[ns].setAttrs(config); } else { Y.log("Attempt to replug an already attached plugin, and we can't setAttrs, because it's not Attribute based: " + ns); } } else { // Create new instance this[ns] = new Plugin(config); this._plugins[ns] = Plugin; } } else { Y.log("Attempt to plug in an invalid plugin. Host:" + this + ", Plugin:" + Plugin); } } return this; }, /** * Removes a plugin from the host object. This will destroy the * plugin instance and delete the namespace from the host object. * * @method unplug * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @return {Base} A reference to the host object * @chainable */ unplug: function(plugin) { var ns = plugin, plugins = this._plugins; if (plugin) { if (L.isFunction(plugin)) { ns = plugin.NS; if (ns && (!plugins[ns] || plugins[ns] !== plugin)) { ns = null; } } if (ns) { if (this[ns]) { if (this[ns].destroy) { this[ns].destroy(); } delete this[ns]; } if (plugins[ns]) { delete plugins[ns]; } } } else { for (ns in this._plugins) { if (this._plugins.hasOwnProperty(ns)) { this.unplug(ns); } } } return this; }, /** * Determines if a plugin has plugged into this host. * * @method hasPlugin * @param {String} ns The plugin's namespace * @return {Plugin} Returns a truthy value (the plugin instance) if present, or undefined if not. */ hasPlugin : function(ns) { return (this._plugins[ns] && this[ns]); }, /** * Initializes static plugins registered on the host (using the * Base.plug static method) and any plugins passed to the * instance through the "plugins" configuration property. * * @method _initPlugins * @param {Config} config The configuration object with property name/value pairs. * @private */ _initPlugins: function(config) { this._plugins = this._plugins || {}; if (this._initConfigPlugins) { this._initConfigPlugins(config); } }, /** * Unplugs and destroys all plugins on the host * @method _destroyPlugins * @private */ _destroyPlugins: function() { this.unplug(); } }; Y.namespace("Plugin").Host = PluginHost; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('pluginhost-config', function (Y, NAME) { /** * Adds pluginhost constructor configuration and static configuration support * @submodule pluginhost-config */ var PluginHost = Y.Plugin.Host, L = Y.Lang; /** * A protected initialization method, used by the host class to initialize * plugin configurations passed the constructor, through the config object. * * Host objects should invoke this method at the appropriate time in their * construction lifecycle. * * @method _initConfigPlugins * @param {Object} config The configuration object passed to the constructor * @protected * @for Plugin.Host */ PluginHost.prototype._initConfigPlugins = function(config) { // Class Configuration var classes = (this._getClasses) ? this._getClasses() : [this.constructor], plug = [], unplug = {}, constructor, i, classPlug, classUnplug, pluginClassName; // TODO: Room for optimization. Can we apply statically/unplug in same pass? for (i = classes.length - 1; i >= 0; i--) { constructor = classes[i]; classUnplug = constructor._UNPLUG; if (classUnplug) { // subclasses over-write Y.mix(unplug, classUnplug, true); } classPlug = constructor._PLUG; if (classPlug) { // subclasses over-write Y.mix(plug, classPlug, true); } } for (pluginClassName in plug) { if (plug.hasOwnProperty(pluginClassName)) { if (!unplug[pluginClassName]) { this.plug(plug[pluginClassName]); } } } // User Configuration if (config && config.plugins) { this.plug(config.plugins); } }; /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of the class by default). * * @method plug * @static * * @param {Function} hostClass The host class on which to register the plugins * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin * @for Plugin.Host */ PluginHost.plug = function(hostClass, plugin, config) { // Cannot plug into Base, since Plugins derive from Base [ will cause infinite recurrsion ] var p, i, l, name; if (hostClass !== Y.Base) { hostClass._PLUG = hostClass._PLUG || {}; if (!L.isArray(plugin)) { if (config) { plugin = {fn:plugin, cfg:config}; } plugin = [plugin]; } for (i = 0, l = plugin.length; i < l;i++) { p = plugin[i]; name = p.NAME || p.fn.NAME; hostClass._PLUG[name] = p; } } }; /** * Unregisters any class level plugins which have been registered by the host class, or any * other class in the hierarchy. * * @method unplug * @static * * @param {Function} hostClass The host class from which to unregister the plugins * @param {Function | Array} plugin The plugin class, or an array of plugin classes * @for Plugin.Host */ PluginHost.unplug = function(hostClass, plugin) { var p, i, l, name; if (hostClass !== Y.Base) { hostClass._UNPLUG = hostClass._UNPLUG || {}; if (!L.isArray(plugin)) { plugin = [plugin]; } for (i = 0, l = plugin.length; i < l; i++) { p = plugin[i]; name = p.NAME; if (!hostClass._PLUG[name]) { hostClass._UNPLUG[name] = p; } else { delete hostClass._PLUG[name]; } } } }; }, '@VERSION@', {"requires": ["pluginhost-base"]}); YUI.add('event-delegate', function (Y, NAME) { /** * Adds event delegation support to the library. * * @module event * @submodule event-delegate */ var toArray = Y.Array, YLang = Y.Lang, isString = YLang.isString, isObject = YLang.isObject, isArray = YLang.isArray, selectorTest = Y.Selector.test, detachCategories = Y.Env.evt.handles; /** * <p>Sets up event delegation on a container element. The delegated event * will use a supplied selector or filtering function to test if the event * references at least one node that should trigger the subscription * callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {String|node} the element that is the delegation container * @param filter {string|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @static * @for Event */ function delegate(type, fn, el, filter) { var args = toArray(arguments, 0, true), query = isString(el) ? el : null, typeBits, synth, container, categories, cat, i, len, handles, handle; // Support Y.delegate({ click: fnA, key: fnB }, el, filter, ...); // and Y.delegate(['click', 'key'], fn, el, filter, ...); if (isObject(type)) { handles = []; if (isArray(type)) { for (i = 0, len = type.length; i < len; ++i) { args[0] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } else { // Y.delegate({'click', fn}, el, filter) => // Y.delegate('click', fn, el, filter) args.unshift(null); // one arg becomes two; need to make space for (i in type) { if (type.hasOwnProperty(i)) { args[0] = i; args[1] = type[i]; handles.push(Y.delegate.apply(Y, args)); } } } return new Y.EventHandle(handles); } typeBits = type.split(/\|/); if (typeBits.length > 1) { cat = typeBits.shift(); args[0] = type = typeBits.shift(); } synth = Y.Node.DOM_EVENTS[type]; if (isObject(synth) && synth.delegate) { handle = synth.delegate.apply(synth, arguments); } if (!handle) { if (!type || !fn || !el || !filter) { Y.log("delegate requires type, callback, parent, & filter", "warn"); return; } container = (query) ? Y.Selector.query(query, null, true) : el; if (!container && isString(el)) { handle = Y.on('available', function () { Y.mix(handle, Y.delegate.apply(Y, args), true); }, el); } if (!handle && container) { args.splice(2, 2, container); // remove the filter handle = Y.Event._attach(args, { facade: false }); handle.sub.filter = filter; handle.sub._notify = delegate.notifySub; } } if (handle && cat) { categories = detachCategories[cat] || (detachCategories[cat] = {}); categories = categories[type] || (categories[type] = []); categories.push(handle); } return handle; } /** Overrides the <code>_notify</code> method on the normal DOM subscription to inject the filtering logic and only proceed in the case of a match. This method is hosted as a private property of the `delegate` method (e.g. `Y.delegate.notifySub`) @method notifySub @param thisObj {Object} default 'this' object for the callback @param args {Array} arguments passed to the event's <code>fire()</code> @param ce {CustomEvent} the custom event managing the DOM subscriptions for the subscribed event on the subscribing node. @return {Boolean} false if the event was stopped @private @static @since 3.2.0 **/ delegate.notifySub = function (thisObj, args, ce) { // Preserve args for other subscribers args = args.slice(); if (this.args) { args.push.apply(args, this.args); } // Only notify subs if the event occurred on a targeted element var currentTarget = delegate._applyFilter(this.filter, args, ce), //container = e.currentTarget, e, i, len, ret; if (currentTarget) { // Support multiple matches up the the container subtree currentTarget = toArray(currentTarget); // The second arg is the currentTarget, but we'll be reusing this // facade, replacing the currentTarget for each use, so it doesn't // matter what element we seed it with. e = args[0] = new Y.DOMEventFacade(args[0], ce.el, ce); e.container = Y.one(ce.el); for (i = 0, len = currentTarget.length; i < len && !e.stopped; ++i) { e.currentTarget = Y.one(currentTarget[i]); ret = this.fn.apply(this.context || e.currentTarget, args); if (ret === false) { // stop further notifications break; } } return ret; } }; /** Compiles a selector string into a filter function to identify whether Nodes along the parent axis of an event's target should trigger event notification. This function is memoized, so previously compiled filter functions are returned if the same selector string is provided. This function may be useful when defining synthetic events for delegate handling. Hosted as a property of the `delegate` method (e.g. `Y.delegate.compileFilter`). @method compileFilter @param selector {String} the selector string to base the filtration on @return {Function} @since 3.2.0 @static **/ delegate.compileFilter = Y.cached(function (selector) { return function (target, e) { return selectorTest(target._node, selector, (e.currentTarget === e.target) ? null : e.currentTarget._node); }; }); /** Regex to test for disabled elements during filtering. This is only relevant to IE to normalize behavior with other browsers, which swallow events that occur to disabled elements. IE fires the event from the parent element instead of the original target, though it does preserve `event.srcElement` as the disabled element. IE also supports disabled on `<a>`, but the event still bubbles, so it acts more like `e.preventDefault()` plus styling. That issue is not handled here because other browsers fire the event on the `<a>`, so delegate is supported in both cases. @property _disabledRE @type {RegExp} @protected @since 3.8.1 **/ delegate._disabledRE = /^(?:button|input|select|textarea)$/i; /** Walks up the parent axis of an event's target, and tests each element against a supplied filter function. If any Nodes, including the container, satisfy the filter, the delegated callback will be triggered for each. Hosted as a protected property of the `delegate` method (e.g. `Y.delegate._applyFilter`). @method _applyFilter @param filter {Function} boolean function to test for inclusion in event notification @param args {Array} the arguments that would be passed to subscribers @param ce {CustomEvent} the DOM event wrapper @return {Node|Node[]|undefined} The Node or Nodes that satisfy the filter @protected **/ delegate._applyFilter = function (filter, args, ce) { var e = args[0], container = ce.el, // facadeless events in IE, have no e.currentTarget target = e.target || e.srcElement, match = [], isContainer = false; // Resolve text nodes to their containing element if (target.nodeType === 3) { target = target.parentNode; } // For IE. IE propagates events from the parent element of disabled // elements, where other browsers swallow the event entirely. To normalize // this in IE, filtering for matching elements should abort if the target // is a disabled form control. if (target.disabled && delegate._disabledRE.test(target.nodeName)) { return match; } // passing target as the first arg rather than leaving well enough alone // making 'this' in the filter function refer to the target. This is to // support bound filter functions. args.unshift(target); if (isString(filter)) { while (target) { isContainer = (target === container); if (selectorTest(target, filter, (isContainer ? null: container))) { match.push(target); } if (isContainer) { break; } target = target.parentNode; } } else { // filter functions are implementer code and should receive wrappers args[0] = Y.one(target); args[1] = new Y.DOMEventFacade(e, container, ce); while (target) { // filter(target, e, extra args...) - this === target if (filter.apply(args[0], args)) { match.push(target); } if (target === container) { break; } target = target.parentNode; args[0] = Y.one(target); } args[1] = e; // restore the raw DOM event } if (match.length <= 1) { match = match[0]; // single match or undefined } // remove the target args.shift(); return match; }; /** * Sets up event delegation on a container element. The delegated event * will use a supplied filter to test if the callback should be executed. * This filter can be either a selector string or a function that returns * a Node to use as the currentTarget for the event. * * The event object for the delegated event is supplied to the callback * function. It is modified slightly in order to support all properties * that may be needed for event delegation. 'currentTarget' is set to * the element that matched the selector string filter or the Node returned * from the filter function. 'container' is set to the element that the * listener is delegated from (this normally would be the 'currentTarget'). * * Filter functions will be called with the arguments that would be passed to * the callback function, including the event object as the first parameter. * The function should return false (or a falsey value) if the success criteria * aren't met, and the Node to use as the event's currentTarget and 'this' * object if they are. * * @method delegate * @param type {string} the event type to delegate * @param fn {function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param el {string|node} the element that is the delegation container * @param filter {string|function} a selector that must match the target of the * event or a function that returns a Node or false. * @param context optional argument that specifies what 'this' refers to. * @param args* 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for YUI */ Y.delegate = Y.Event.delegate = delegate; }, '@VERSION@', {"requires": ["node-base"]}); YUI.add('node-event-delegate', function (Y, NAME) { /** * Functionality to make the node a delegated event container * @module node * @submodule node-event-delegate */ /** * <p>Sets up a delegation listener for an event occurring inside the Node. * The delegated event will be verified against a supplied selector or * filtering function to test if the event references at least one node that * should trigger the subscription callback.</p> * * <p>Selector string filters will trigger the callback if the event originated * from a node that matches it or is contained in a node that matches it. * Function filters are called for each Node up the parent axis to the * subscribing container node, and receive at each level the Node and the event * object. The function should return true (or a truthy value) if that Node * should trigger the subscription callback. Note, it is possible for filters * to match multiple Nodes for a single event. In this case, the delegate * callback will be executed for each matching Node.</p> * * <p>For each matching Node, the callback will be executed with its 'this' * object set to the Node matched by the filter (unless a specific context was * provided during subscription), and the provided event's * <code>currentTarget</code> will also be set to the matching Node. The * containing Node from which the subscription was originally made can be * referenced as <code>e.container</code>. * * @method delegate * @param type {String} the event type to delegate * @param fn {Function} the callback function to execute. This function * will be provided the event object for the delegated event. * @param spec {String|Function} a selector that must match the target of the * event or a function to test target and its parents for a match * @param context {Object} optional argument that specifies what 'this' refers to. * @param args* {any} 0..n additional arguments to pass on to the callback function. * These arguments will be added after the event object. * @return {EventHandle} the detach handle * @for Node */ Y.Node.prototype.delegate = function(type) { var args = Y.Array(arguments, 0, true), index = (Y.Lang.isObject(type) && !Y.Lang.isArray(type)) ? 1 : 2; args.splice(index, 0, this._node); return Y.delegate.apply(Y, args); }; }, '@VERSION@', {"requires": ["node-base", "event-delegate"]}); YUI.add('node-pluginhost', function (Y, NAME) { /** * @module node * @submodule node-pluginhost */ /** * Registers plugins to be instantiated at the class level (plugins * which should be plugged into every instance of Node by default). * * @method plug * @static * @for Node * @param {Function | Array} plugin Either the plugin class, an array of plugin classes or an array of objects (with fn and cfg properties defined) * @param {Object} config (Optional) If plugin is the plugin class, the configuration for the plugin */ Y.Node.plug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.plug.apply(Y.Base, args); return Y.Node; }; /** * Unregisters any class level plugins which have been registered by the Node * * @method unplug * @static * * @param {Function | Array} plugin The plugin class, or an array of plugin classes */ Y.Node.unplug = function() { var args = Y.Array(arguments); args.unshift(Y.Node); Y.Plugin.Host.unplug.apply(Y.Base, args); return Y.Node; }; Y.mix(Y.Node, Y.Plugin.Host, false, null, 1); // allow batching of plug/unplug via NodeList // doesn't use NodeList.importMethod because we need real Nodes (not tmpNode) /** * Adds a plugin to each node in the NodeList. * This will instantiate the plugin and attach it to the configured namespace on each node * @method plug * @for NodeList * @param P {Function | Object |Array} Accepts the plugin class, or an * object with a "fn" property specifying the plugin class and * a "cfg" property specifying the configuration for the Plugin. * <p> * Additionally an Array can also be passed in, with the above function or * object values, allowing the user to add multiple plugins in a single call. * </p> * @param config (Optional) If the first argument is the plugin class, the second argument * can be the configuration for the plugin. * @chainable */ Y.NodeList.prototype.plug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.plug.apply(Y.one(node), args); }); return this; }; /** * Removes a plugin from all nodes in the NodeList. This will destroy the * plugin instance and delete the namespace each node. * @method unplug * @for NodeList * @param {String | Function} plugin The namespace of the plugin, or the plugin class with the static NS namespace property defined. If not provided, * all registered plugins are unplugged. * @chainable */ Y.NodeList.prototype.unplug = function() { var args = arguments; Y.NodeList.each(this, function(node) { Y.Node.prototype.unplug.apply(Y.one(node), args); }); return this; }; }, '@VERSION@', {"requires": ["node-base", "pluginhost"]}); YUI.add('node-screen', function (Y, NAME) { /** * Extended Node interface for managing regions and screen positioning. * Adds support for positioning elements and normalizes window size and scroll detection. * @module node * @submodule node-screen */ // these are all "safe" returns, no wrapping required Y.each([ /** * Returns the inner width of the viewport (exludes scrollbar). * @config winWidth * @for Node * @type {Int} */ 'winWidth', /** * Returns the inner height of the viewport (exludes scrollbar). * @config winHeight * @type {Int} */ 'winHeight', /** * Document width * @config docWidth * @type {Int} */ 'docWidth', /** * Document height * @config docHeight * @type {Int} */ 'docHeight', /** * Pixel distance the page has been scrolled horizontally * @config docScrollX * @type {Int} */ 'docScrollX', /** * Pixel distance the page has been scrolled vertically * @config docScrollY * @type {Int} */ 'docScrollY' ], function(name) { Y.Node.ATTRS[name] = { getter: function() { var args = Array.prototype.slice.call(arguments); args.unshift(Y.Node.getDOMNode(this)); return Y.DOM[name].apply(this, args); } }; } ); Y.Node.ATTRS.scrollLeft = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollLeft' in node) ? node.scrollLeft : Y.DOM.docScrollX(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollLeft' in node) { node.scrollLeft = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(val, Y.DOM.docScrollY(node)); // scroll window if win or doc } } else { Y.log('unable to set scrollLeft for ' + node, 'error', 'Node'); } } }; Y.Node.ATTRS.scrollTop = { getter: function() { var node = Y.Node.getDOMNode(this); return ('scrollTop' in node) ? node.scrollTop : Y.DOM.docScrollY(node); }, setter: function(val) { var node = Y.Node.getDOMNode(this); if (node) { if ('scrollTop' in node) { node.scrollTop = val; } else if (node.document || node.nodeType === 9) { Y.DOM._getWin(node).scrollTo(Y.DOM.docScrollX(node), val); // scroll window if win or doc } } else { Y.log('unable to set scrollTop for ' + node, 'error', 'Node'); } } }; Y.Node.importMethod(Y.DOM, [ /** * Gets the current position of the node in page coordinates. * @method getXY * @for Node * @return {Array} The XY position of the node */ 'getXY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setXY * @param {Array} xy Contains X & Y values for new position (coordinates are page-based) * @chainable */ 'setXY', /** * Gets the current position of the node in page coordinates. * @method getX * @return {Int} The X position of the node */ 'getX', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setX * @param {Int} x X value for new position (coordinates are page-based) * @chainable */ 'setX', /** * Gets the current position of the node in page coordinates. * @method getY * @return {Int} The Y position of the node */ 'getY', /** * Set the position of the node in page coordinates, regardless of how the node is positioned. * @method setY * @param {Int} y Y value for new position (coordinates are page-based) * @chainable */ 'setY', /** * Swaps the XY position of this node with another node. * @method swapXY * @param {Node | HTMLElement} otherNode The node to swap with. * @chainable */ 'swapXY' ]); /** * @module node * @submodule node-screen */ /** * Returns a region object for the node * @config region * @for Node * @type Node */ Y.Node.ATTRS.region = { getter: function() { var node = this.getDOMNode(), region; if (node && !node.tagName) { if (node.nodeType === 9) { // document node = node.documentElement; } } if (Y.DOM.isWindow(node)) { region = Y.DOM.viewportRegion(node); } else { region = Y.DOM.region(node); } return region; } }; /** * Returns a region object for the node's viewport * @config viewportRegion * @type Node */ Y.Node.ATTRS.viewportRegion = { getter: function() { return Y.DOM.viewportRegion(Y.Node.getDOMNode(this)); } }; Y.Node.importMethod(Y.DOM, 'inViewportRegion'); // these need special treatment to extract 2nd node arg /** * Compares the intersection of the node with another node or region * @method intersect * @for Node * @param {Node|Object} node2 The node or region to compare with. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Object} An object representing the intersection of the regions. */ Y.Node.prototype.intersect = function(node2, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.intersect(node1, node2, altRegion); }; /** * Determines whether or not the node is within the giving region. * @method inRegion * @param {Node|Object} node2 The node or region to compare with. * @param {Boolean} all Whether or not all of the node must be in the region. * @param {Object} altRegion An alternate region to use (rather than this node's). * @return {Boolean} True if in region, false if not. */ Y.Node.prototype.inRegion = function(node2, all, altRegion) { var node1 = Y.Node.getDOMNode(this); if (Y.instanceOf(node2, Y.Node)) { // might be a region object node2 = Y.Node.getDOMNode(node2); } return Y.DOM.inRegion(node1, node2, all, altRegion); }; }, '@VERSION@', {"requires": ["dom-screen", "node-base"]}); YUI.add('node-style', function (Y, NAME) { (function(Y) { /** * Extended Node interface for managing node styles. * @module node * @submodule node-style */ Y.mix(Y.Node.prototype, { /** * Sets a style property of the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ setStyle: function(attr, val) { Y.DOM.setStyle(this._node, attr, val); return this; }, /** * Sets multiple style properties on the node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ setStyles: function(hash) { Y.DOM.setStyles(this._node, hash); return this; }, /** * Returns the style's current value. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for Node * @param {String} attr The style attribute to retrieve. * @return {String} The current value of the style property for the element. */ getStyle: function(attr) { return Y.DOM.getStyle(this._node, attr); }, /** * Returns the computed value for the given style property. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {String} The computed value of the style property for the element. */ getComputedStyle: function(attr) { return Y.DOM.getComputedStyle(this._node, attr); } }); /** * Returns an array of values for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getStyle * @for NodeList * @see Node.getStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The current values of the style property for the element. */ /** * Returns an array of the computed value for each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method getComputedStyle * @see Node.getComputedStyle * @param {String} attr The style attribute to retrieve. * @return {Array} The computed values for each node. */ /** * Sets a style property on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyle * @see Node.setStyle * @param {String} attr The style attribute to set. * @param {String|Number} val The value. * @chainable */ /** * Sets multiple style properties on each node. * Use camelCase (e.g. 'backgroundColor') for multi-word properties. * @method setStyles * @see Node.setStyles * @param {Object} hash An object literal of property:value pairs. * @chainable */ // These are broken out to handle undefined return (avoid false positive for // chainable) Y.NodeList.importMethod(Y.Node.prototype, ['getStyle', 'getComputedStyle', 'setStyle', 'setStyles']); })(Y); }, '@VERSION@', {"requires": ["dom-style", "node-base"]}); YUI.add('querystring-stringify-simple', function (Y, NAME) { /*global Y */ /** * <p>Provides Y.QueryString.stringify method for converting objects to Query Strings. * This is a subset implementation of the full querystring-stringify.</p> * <p>This module provides the bare minimum functionality (encoding a hash of simple values), * without the additional support for nested data structures. Every key-value pair is * encoded by encodeURIComponent.</p> * <p>This module provides a minimalistic way for io to handle single-level objects * as transaction data.</p> * * @module querystring * @submodule querystring-stringify-simple */ var QueryString = Y.namespace("QueryString"), EUC = encodeURIComponent; QueryString.stringify = function (obj, c) { var qs = [], // Default behavior is false; standard key notation. s = c && c.arrayKey ? true : false, key, i, l; for (key in obj) { if (obj.hasOwnProperty(key)) { if (Y.Lang.isArray(obj[key])) { for (i = 0, l = obj[key].length; i < l; i++) { qs.push(EUC(s ? key + '[]' : key) + '=' + EUC(obj[key][i])); } } else { qs.push(EUC(key) + '=' + EUC(obj[key])); } } } return qs.join('&'); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('io-base', function (Y, NAME) { /** Base IO functionality. Provides basic XHR transport support. @module io @submodule io-base @for IO **/ var // List of events that comprise the IO event lifecycle. EVENTS = ['start', 'complete', 'end', 'success', 'failure', 'progress'], // Whitelist of used XHR response object properties. XHR_PROPS = ['status', 'statusText', 'responseText', 'responseXML'], win = Y.config.win, uid = 0; /** The IO class is a utility that brokers HTTP requests through a simplified interface. Specifically, it allows JavaScript to make HTTP requests to a resource without a page reload. The underlying transport for making same-domain requests is the XMLHttpRequest object. IO can also use Flash, if specified as a transport, for cross-domain requests. @class IO @constructor @param {Object} config Object of EventTarget's publish method configurations used to configure IO's events. **/ function IO (config) { var io = this; io._uid = 'io:' + uid++; io._init(config); Y.io._map[io._uid] = io; } IO.prototype = { //-------------------------------------- // Properties //-------------------------------------- /** * A counter that increments for each transaction. * * @property _id * @private * @type {Number} */ _id: 0, /** * Object of IO HTTP headers sent with each transaction. * * @property _headers * @private * @type {Object} */ _headers: { 'X-Requested-With' : 'XMLHttpRequest' }, /** * Object that stores timeout values for any transaction with a defined * "timeout" configuration property. * * @property _timeout * @private * @type {Object} */ _timeout: {}, //-------------------------------------- // Methods //-------------------------------------- _init: function(config) { var io = this, i, len; io.cfg = config || {}; Y.augment(io, Y.EventTarget); for (i = 0, len = EVENTS.length; i < len; ++i) { // Publish IO global events with configurations, if any. // IO global events are set to broadcast by default. // These events use the "io:" namespace. io.publish('io:' + EVENTS[i], Y.merge({ broadcast: 1 }, config)); // Publish IO transaction events with configurations, if // any. These events use the "io-trn:" namespace. io.publish('io-trn:' + EVENTS[i], config); } }, /** * Method that creates a unique transaction object for each request. * * @method _create * @private * @param {Object} cfg Configuration object subset to determine if * the transaction is an XDR or file upload, * requiring an alternate transport. * @param {Number} id Transaction id * @return {Object} The transaction object */ _create: function(config, id) { var io = this, transaction = { id : Y.Lang.isNumber(id) ? id : io._id++, uid: io._uid }, alt = config.xdr ? config.xdr.use : null, form = config.form && config.form.upload ? 'iframe' : null, use; if (alt === 'native') { // Non-IE and IE >= 10 can use XHR level 2 and not rely on an // external transport. alt = Y.UA.ie && !SUPPORTS_CORS ? 'xdr' : null; // Prevent "pre-flight" OPTIONS request by removing the // `X-Requested-With` HTTP header from CORS requests. This header // can be added back on a per-request basis, if desired. io.setHeader('X-Requested-With'); } use = alt || form; transaction = use ? Y.merge(Y.IO.customTransport(use), transaction) : Y.merge(Y.IO.defaultTransport(), transaction); if (transaction.notify) { config.notify = function (e, t, c) { io.notify(e, t, c); }; } if (!use) { if (win && win.FormData && config.data instanceof win.FormData) { transaction.c.upload.onprogress = function (e) { io.progress(transaction, e, config); }; transaction.c.onload = function (e) { io.load(transaction, e, config); }; transaction.c.onerror = function (e) { io.error(transaction, e, config); }; transaction.upload = true; } } return transaction; }, _destroy: function(transaction) { if (win && !transaction.notify && !transaction.xdr) { if (XHR && !transaction.upload) { transaction.c.onreadystatechange = null; } else if (transaction.upload) { transaction.c.upload.onprogress = null; transaction.c.onload = null; transaction.c.onerror = null; } else if (Y.UA.ie && !transaction.e) { // IE, when using XMLHttpRequest as an ActiveX Object, will throw // a "Type Mismatch" error if the event handler is set to "null". transaction.c.abort(); } } transaction = transaction.c = null; }, /** * Method for creating and firing events. * * @method _evt * @private * @param {String} eventName Event to be published. * @param {Object} transaction Transaction object. * @param {Object} config Configuration data subset for event subscription. */ _evt: function(eventName, transaction, config) { var io = this, params, args = config['arguments'], emitFacade = io.cfg.emitFacade, globalEvent = "io:" + eventName, trnEvent = "io-trn:" + eventName; // Workaround for #2532107 this.detach(trnEvent); if (transaction.e) { transaction.c = { status: 0, statusText: transaction.e }; } // Fire event with parameters or an Event Facade. params = [ emitFacade ? { id: transaction.id, data: transaction.c, cfg: config, 'arguments': args } : transaction.id ]; if (!emitFacade) { if (eventName === EVENTS[0] || eventName === EVENTS[2]) { if (args) { params.push(args); } } else { if (transaction.evt) { params.push(transaction.evt); } else { params.push(transaction.c); } if (args) { params.push(args); } } } params.unshift(globalEvent); // Fire global events. io.fire.apply(io, params); // Fire transaction events, if receivers are defined. if (config.on) { params[0] = trnEvent; io.once(trnEvent, config.on[eventName], config.context || Y); io.fire.apply(io, params); } }, /** * Fires event "io:start" and creates, fires a transaction-specific * start event, if `config.on.start` is defined. * * @method start * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ start: function(transaction, config) { /** * Signals the start of an IO request. * @event io:start */ this._evt(EVENTS[0], transaction, config); }, /** * Fires event "io:complete" and creates, fires a * transaction-specific "complete" event, if config.on.complete is * defined. * * @method complete * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ complete: function(transaction, config) { /** * Signals the completion of the request-response phase of a * transaction. Response status and data are accessible, if * available, in this event. * @event io:complete */ this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:end" and creates, fires a transaction-specific "end" * event, if config.on.end is defined. * * @method end * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ end: function(transaction, config) { /** * Signals the end of the transaction lifecycle. * @event io:end */ this._evt(EVENTS[2], transaction, config); this._destroy(transaction); }, /** * Fires event "io:success" and creates, fires a transaction-specific * "success" event, if config.on.success is defined. * * @method success * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ success: function(transaction, config) { /** * Signals an HTTP response with status in the 2xx range. * Fires after io:complete. * @event io:success */ this._evt(EVENTS[3], transaction, config); this.end(transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event, if config.on.failure is defined. * * @method failure * @param {Object} transaction Transaction object. * @param {Object} config Configuration object for the transaction. */ failure: function(transaction, config) { /** * Signals an HTTP response with status outside of the 2xx range. * Fires after io:complete. * @event io:failure */ this._evt(EVENTS[4], transaction, config); this.end(transaction, config); }, /** * Fires event "io:progress" and creates, fires a transaction-specific * "progress" event -- for XMLHttpRequest file upload -- if * config.on.progress is defined. * * @method progress * @param {Object} transaction Transaction object. * @param {Object} progress event. * @param {Object} config Configuration object for the transaction. */ progress: function(transaction, e, config) { /** * Signals the interactive state during a file upload transaction. * This event fires after io:start and before io:complete. * @event io:progress */ transaction.evt = e; this._evt(EVENTS[5], transaction, config); }, /** * Fires event "io:complete" and creates, fires a transaction-specific * "complete" event -- for XMLHttpRequest file upload -- if * config.on.complete is defined. * * @method load * @param {Object} transaction Transaction object. * @param {Object} load event. * @param {Object} config Configuration object for the transaction. */ load: function (transaction, e, config) { transaction.evt = e.target; this._evt(EVENTS[1], transaction, config); }, /** * Fires event "io:failure" and creates, fires a transaction-specific * "failure" event -- for XMLHttpRequest file upload -- if * config.on.failure is defined. * * @method error * @param {Object} transaction Transaction object. * @param {Object} error event. * @param {Object} config Configuration object for the transaction. */ error: function (transaction, e, config) { transaction.evt = e; this._evt(EVENTS[4], transaction, config); }, /** * Retry an XDR transaction, using the Flash tranport, if the native * transport fails. * * @method _retry * @private * @param {Object} transaction Transaction object. * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. */ _retry: function(transaction, uri, config) { this._destroy(transaction); config.xdr.use = 'flash'; return this.send(uri, config, transaction.id); }, /** * Method that concatenates string data for HTTP GET transactions. * * @method _concat * @private * @param {String} uri URI or root data. * @param {String} data Data to be concatenated onto URI. * @return {String} */ _concat: function(uri, data) { uri += (uri.indexOf('?') === -1 ? '?' : '&') + data; return uri; }, /** * Stores default client headers for all transactions. If a label is * passed with no value argument, the header will be deleted. * * @method setHeader * @param {String} name HTTP header * @param {String} value HTTP header value */ setHeader: function(name, value) { if (value) { this._headers[name] = value; } else { delete this._headers[name]; } }, /** * Method that sets all HTTP headers to be sent in a transaction. * * @method _setHeaders * @private * @param {Object} transaction - XHR instance for the specific transaction. * @param {Object} headers - HTTP headers for the specific transaction, as * defined in the configuration object passed to YUI.io(). */ _setHeaders: function(transaction, headers) { headers = Y.merge(this._headers, headers); Y.Object.each(headers, function(value, name) { if (value !== 'disable') { transaction.setRequestHeader(name, headers[name]); } }); }, /** * Starts timeout count if the configuration object has a defined * timeout property. * * @method _startTimeout * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} timeout Timeout in milliseconds. */ _startTimeout: function(transaction, timeout) { var io = this; io._timeout[transaction.id] = setTimeout(function() { io._abort(transaction, 'timeout'); }, timeout); }, /** * Clears the timeout interval started by _startTimeout(). * * @method _clearTimeout * @private * @param {Number} id - Transaction id. */ _clearTimeout: function(id) { clearTimeout(this._timeout[id]); delete this._timeout[id]; }, /** * Method that determines if a transaction response qualifies as success * or failure, based on the response HTTP status code, and fires the * appropriate success or failure events. * * @method _result * @private * @static * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to io(). */ _result: function(transaction, config) { var status; // Firefox will throw an exception if attempting to access // an XHR object's status property, after a request is aborted. try { status = transaction.c.status; } catch(e) { status = 0; } // IE reports HTTP 204 as HTTP 1223. if (status >= 200 && status < 300 || status === 304 || status === 1223) { this.success(transaction, config); } else { this.failure(transaction, config); } }, /** * Event handler bound to onreadystatechange. * * @method _rS * @private * @param {Object} transaction Transaction object generated by _create(). * @param {Object} config Configuration object passed to YUI.io(). */ _rS: function(transaction, config) { var io = this; if (transaction.c.readyState === 4) { if (config.timeout) { io._clearTimeout(transaction.id); } // Yield in the event of request timeout or abort. setTimeout(function() { io.complete(transaction, config); io._result(transaction, config); }, 0); } }, /** * Terminates a transaction due to an explicit abort or timeout. * * @method _abort * @private * @param {Object} transaction Transaction object generated by _create(). * @param {String} type Identifies timed out or aborted transaction. */ _abort: function(transaction, type) { if (transaction && transaction.c) { transaction.e = type; transaction.c.abort(); } }, /** * Requests a transaction. `send()` is implemented as `Y.io()`. Each * transaction may include a configuration object. Its properties are: * * <dl> * <dt>method</dt> * <dd>HTTP method verb (e.g., GET or POST). If this property is not * not defined, the default value will be GET.</dd> * * <dt>data</dt> * <dd>This is the name-value string that will be sent as the * transaction data. If the request is HTTP GET, the data become * part of querystring. If HTTP POST, the data are sent in the * message body.</dd> * * <dt>xdr</dt> * <dd>Defines the transport to be used for cross-domain requests. * By setting this property, the transaction will use the specified * transport instead of XMLHttpRequest. The properties of the * transport object are: * <dl> * <dt>use</dt> * <dd>The transport to be used: 'flash' or 'native'</dd> * <dt>dataType</dt> * <dd>Set the value to 'XML' if that is the expected response * content type.</dd> * <dt>credentials</dt> * <dd>Set the value to 'true' to set XHR.withCredentials property to true.</dd> * </dl></dd> * * <dt>form</dt> * <dd>Form serialization configuration object. Its properties are: * <dl> * <dt>id</dt> * <dd>Node object or id of HTML form</dd> * <dt>useDisabled</dt> * <dd>`true` to also serialize disabled form field values * (defaults to `false`)</dd> * </dl></dd> * * <dt>on</dt> * <dd>Assigns transaction event subscriptions. Available events are: * <dl> * <dt>start</dt> * <dd>Fires when a request is sent to a resource.</dd> * <dt>complete</dt> * <dd>Fires when the transaction is complete.</dd> * <dt>success</dt> * <dd>Fires when the HTTP response status is within the 2xx * range.</dd> * <dt>failure</dt> * <dd>Fires when the HTTP response status is outside the 2xx * range, if an exception occurs, if the transation is aborted, * or if the transaction exceeds a configured `timeout`.</dd> * <dt>end</dt> * <dd>Fires at the conclusion of the transaction * lifecycle, after `success` or `failure`.</dd> * </dl> * * <p>Callback functions for `start` and `end` receive the id of the * transaction as a first argument. For `complete`, `success`, and * `failure`, callbacks receive the id and the response object * (usually the XMLHttpRequest instance). If the `arguments` * property was included in the configuration object passed to * `Y.io()`, the configured data will be passed to all callbacks as * the last argument.</p> * </dd> * * <dt>sync</dt> * <dd>Pass `true` to make a same-domain transaction synchronous. * <strong>CAVEAT</strong>: This will negatively impact the user * experience. Have a <em>very</em> good reason if you intend to use * this.</dd> * * <dt>context</dt> * <dd>The "`this'" object for all configured event handlers. If a * specific context is needed for individual callbacks, bind the * callback to a context using `Y.bind()`.</dd> * * <dt>headers</dt> * <dd>Object map of transaction headers to send to the server. The * object keys are the header names and the values are the header * values.</dd> * * <dt>timeout</dt> * <dd>Millisecond threshold for the transaction before being * automatically aborted.</dd> * * <dt>arguments</dt> * <dd>User-defined data passed to all registered event handlers. * This value is available as the second argument in the "start" and * "end" event handlers. It is the third argument in the "complete", * "success", and "failure" event handlers. <strong>Be sure to quote * this property name in the transaction configuration as * "arguments" is a reserved word in JavaScript</strong> (e.g. * `Y.io({ ..., "arguments": stuff })`).</dd> * </dl> * * @method send * @public * @param {String} uri Qualified path to transaction resource. * @param {Object} config Configuration object for the transaction. * @param {Number} id Transaction id, if already set. * @return {Object} */ send: function(uri, config, id) { var transaction, method, i, len, sync, data, io = this, u = uri, response = {}; config = config ? Y.Object(config) : {}; transaction = io._create(config, id); method = config.method ? config.method.toUpperCase() : 'GET'; sync = config.sync; data = config.data; // Serialize a map object into a key-value string using // querystring-stringify-simple. if ((Y.Lang.isObject(data) && !data.nodeType) && !transaction.upload) { if (Y.QueryString && Y.QueryString.stringify) { Y.log('Stringifying config.data for request', 'info', 'io'); config.data = data = Y.QueryString.stringify(data); } else { Y.log('Failed to stringify config.data object, likely because `querystring-stringify-simple` is missing.', 'warn', 'io'); } } if (config.form) { if (config.form.upload) { // This is a file upload transaction, calling // upload() in io-upload-iframe. return io.upload(transaction, uri, config); } else { // Serialize HTML form data into a key-value string. data = io._serialize(config.form, data); } } // Convert falsy values to an empty string. This way IE can't be // rediculous and translate `undefined` to "undefined". data || (data = ''); if (data) { switch (method) { case 'GET': case 'HEAD': case 'DELETE': u = io._concat(u, data); data = ''; Y.log('HTTP' + method + ' with data. The querystring is: ' + u, 'info', 'io'); break; case 'POST': case 'PUT': // If Content-Type is defined in the configuration object, or // or as a default header, it will be used instead of // 'application/x-www-form-urlencoded; charset=UTF-8' config.headers = Y.merge({ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, config.headers); break; } } if (transaction.xdr) { // Route data to io-xdr module for flash and XDomainRequest. return io.xdr(u, transaction, config); } else if (transaction.notify) { // Route data to custom transport return transaction.c.send(transaction, uri, config); } if (!sync && !transaction.upload) { transaction.c.onreadystatechange = function() { io._rS(transaction, config); }; } try { // Determine if request is to be set as // synchronous or asynchronous. transaction.c.open(method, u, !sync, config.username || null, config.password || null); io._setHeaders(transaction.c, config.headers || {}); io.start(transaction, config); // Will work only in browsers that implement the // Cross-Origin Resource Sharing draft. if (config.xdr && config.xdr.credentials && SUPPORTS_CORS) { transaction.c.withCredentials = true; } // Using "null" with HTTP POST will result in a request // with no Content-Length header defined. transaction.c.send(data); if (sync) { // Create a response object for synchronous transactions, // mixing id and arguments properties with the xhr // properties whitelist. for (i = 0, len = XHR_PROPS.length; i < len; ++i) { response[XHR_PROPS[i]] = transaction.c[XHR_PROPS[i]]; } response.getAllResponseHeaders = function() { return transaction.c.getAllResponseHeaders(); }; response.getResponseHeader = function(name) { return transaction.c.getResponseHeader(name); }; io.complete(transaction, config); io._result(transaction, config); return response; } } catch(e) { if (transaction.xdr) { // This exception is usually thrown by browsers // that do not support XMLHttpRequest Level 2. // Retry the request with the XDR transport set // to 'flash'. If the Flash transport is not // initialized or available, the transaction // will resolve to a transport error. return io._retry(transaction, uri, config); } else { io.complete(transaction, config); io._result(transaction, config); } } // If config.timeout is defined, and the request is standard XHR, // initialize timeout polling. if (config.timeout) { io._startTimeout(transaction, config.timeout); Y.log('Configuration timeout set to: ' + config.timeout, 'info', 'io'); } return { id: transaction.id, abort: function() { return transaction.c ? io._abort(transaction, 'abort') : false; }, isInProgress: function() { return transaction.c ? (transaction.c.readyState % 4) : false; }, io: io }; } }; /** Method for initiating an ajax call. The first argument is the url end point for the call. The second argument is an object to configure the transaction and attach event subscriptions. The configuration object supports the following properties: <dl> <dt>method</dt> <dd>HTTP method verb (e.g., GET or POST). If this property is not not defined, the default value will be GET.</dd> <dt>data</dt> <dd>This is the name-value string that will be sent as the transaction data. If the request is HTTP GET, the data become part of querystring. If HTTP POST, the data are sent in the message body.</dd> <dt>xdr</dt> <dd>Defines the transport to be used for cross-domain requests. By setting this property, the transaction will use the specified transport instead of XMLHttpRequest. The properties of the transport object are: <dl> <dt>use</dt> <dd>The transport to be used: 'flash' or 'native'</dd> <dt>dataType</dt> <dd>Set the value to 'XML' if that is the expected response content type.</dd> </dl></dd> <dt>form</dt> <dd>Form serialization configuration object. Its properties are: <dl> <dt>id</dt> <dd>Node object or id of HTML form</dd> <dt>useDisabled</dt> <dd>`true` to also serialize disabled form field values (defaults to `false`)</dd> </dl></dd> <dt>on</dt> <dd>Assigns transaction event subscriptions. Available events are: <dl> <dt>start</dt> <dd>Fires when a request is sent to a resource.</dd> <dt>complete</dt> <dd>Fires when the transaction is complete.</dd> <dt>success</dt> <dd>Fires when the HTTP response status is within the 2xx range.</dd> <dt>failure</dt> <dd>Fires when the HTTP response status is outside the 2xx range, if an exception occurs, if the transation is aborted, or if the transaction exceeds a configured `timeout`.</dd> <dt>end</dt> <dd>Fires at the conclusion of the transaction lifecycle, after `success` or `failure`.</dd> </dl> <p>Callback functions for `start` and `end` receive the id of the transaction as a first argument. For `complete`, `success`, and `failure`, callbacks receive the id and the response object (usually the XMLHttpRequest instance). If the `arguments` property was included in the configuration object passed to `Y.io()`, the configured data will be passed to all callbacks as the last argument.</p> </dd> <dt>sync</dt> <dd>Pass `true` to make a same-domain transaction synchronous. <strong>CAVEAT</strong>: This will negatively impact the user experience. Have a <em>very</em> good reason if you intend to use this.</dd> <dt>context</dt> <dd>The "`this'" object for all configured event handlers. If a specific context is needed for individual callbacks, bind the callback to a context using `Y.bind()`.</dd> <dt>headers</dt> <dd>Object map of transaction headers to send to the server. The object keys are the header names and the values are the header values.</dd> <dt>timeout</dt> <dd>Millisecond threshold for the transaction before being automatically aborted.</dd> <dt>arguments</dt> <dd>User-defined data passed to all registered event handlers. This value is available as the second argument in the "start" and "end" event handlers. It is the third argument in the "complete", "success", and "failure" event handlers. <strong>Be sure to quote this property name in the transaction configuration as "arguments" is a reserved word in JavaScript</strong> (e.g. `Y.io({ ..., "arguments": stuff })`).</dd> </dl> @method io @static @param {String} url qualified path to transaction resource. @param {Object} config configuration object for the transaction. @return {Object} @for YUI **/ Y.io = function(url, config) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); return transaction.send.apply(transaction, [url, config]); }; /** Method for setting and deleting IO HTTP headers to be sent with every request. Hosted as a property on the `io` function (e.g. `Y.io.header`). @method header @param {String} name HTTP header @param {String} value HTTP header value @static **/ Y.io.header = function(name, value) { // Calling IO through the static interface will use and reuse // an instance of IO. var transaction = Y.io._map['io:0'] || new IO(); transaction.setHeader(name, value); }; Y.IO = IO; // Map of all IO instances created. Y.io._map = {}; var XHR = win && win.XMLHttpRequest, XDR = win && win.XDomainRequest, AX = win && win.ActiveXObject, // Checks for the presence of the `withCredentials` in an XHR instance // object, which will be present if the environment supports CORS. SUPPORTS_CORS = XHR && 'withCredentials' in (new XMLHttpRequest()); Y.mix(Y.IO, { /** * The ID of the default IO transport, defaults to `xhr` * @property _default * @type {String} * @static */ _default: 'xhr', /** * * @method defaultTransport * @static * @param {String} [id] The transport to set as the default, if empty a new transport is created. * @return {Object} The transport object with a `send` method */ defaultTransport: function(id) { if (id) { Y.log('Setting default IO to: ' + id, 'info', 'io'); Y.IO._default = id; } else { var o = { c: Y.IO.transports[Y.IO._default](), notify: Y.IO._default === 'xhr' ? false : true }; Y.log('Creating default transport: ' + Y.IO._default, 'info', 'io'); return o; } }, /** * An object hash of custom transports available to IO * @property transports * @type {Object} * @static */ transports: { xhr: function () { return XHR ? new XMLHttpRequest() : AX ? new ActiveXObject('Microsoft.XMLHTTP') : null; }, xdr: function () { return XDR ? new XDomainRequest() : null; }, iframe: function () { return {}; }, flash: null, nodejs: null }, /** * Create a custom transport of type and return it's object * @method customTransport * @param {String} id The id of the transport to create. * @static */ customTransport: function(id) { var o = { c: Y.IO.transports[id]() }; o[(id === 'xdr' || id === 'flash') ? 'xdr' : 'notify'] = true; return o; } }); Y.mix(Y.IO.prototype, { /** * Fired from the notify method of the transport which in turn fires * the event on the IO object. * @method notify * @param {String} event The name of the event * @param {Object} transaction The transaction object * @param {Object} config The configuration object for this transaction */ notify: function(event, transaction, config) { var io = this; switch (event) { case 'timeout': case 'abort': case 'transport error': transaction.c = { status: 0, statusText: event }; event = 'failure'; default: io[event].apply(io, [transaction, config]); } } }); }, '@VERSION@', {"requires": ["event-custom-base", "querystring-stringify-simple"]}); YUI.add('json-parse', function (Y, NAME) { var _JSON = Y.config.global.JSON; Y.namespace('JSON').parse = function (obj, reviver, space) { return _JSON.parse((typeof obj === 'string' ? obj : obj + ''), reviver, space); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition', function (Y, NAME) { /** * Provides the transition method for Node. * Transition has no API of its own, but adds the transition method to Node. * * @module transition * @requires node-style */ var CAMEL_VENDOR_PREFIX = '', VENDOR_PREFIX = '', DOCUMENT = Y.config.doc, DOCUMENT_ELEMENT = 'documentElement', DOCUMENT_STYLE = DOCUMENT[DOCUMENT_ELEMENT].style, TRANSITION_CAMEL = 'transition', TRANSITION_PROPERTY_CAMEL = 'transitionProperty', TRANSITION_PROPERTY, TRANSITION_DURATION, TRANSITION_TIMING_FUNCTION, TRANSITION_DELAY, TRANSITION_END, ON_TRANSITION_END, EMPTY_OBJ = {}, VENDORS = [ 'Webkit', 'Moz' ], VENDOR_TRANSITION_END = { Webkit: 'webkitTransitionEnd' }, /** * A class for constructing transition instances. * Adds the "transition" method to Node. * @class Transition * @constructor */ Transition = function() { this.init.apply(this, arguments); }; // One off handling of transform-prefixing. Transition._TRANSFORM = 'transform'; Transition._toCamel = function(property) { property = property.replace(/-([a-z])/gi, function(m0, m1) { return m1.toUpperCase(); }); return property; }; Transition._toHyphen = function(property) { property = property.replace(/([A-Z]?)([a-z]+)([A-Z]?)/g, function(m0, m1, m2, m3) { var str = ((m1) ? '-' + m1.toLowerCase() : '') + m2; if (m3) { str += '-' + m3.toLowerCase(); } return str; }); return property; }; Transition.SHOW_TRANSITION = 'fadeIn'; Transition.HIDE_TRANSITION = 'fadeOut'; Transition.useNative = false; // Map transition properties to vendor-specific versions. if ('transition' in DOCUMENT_STYLE && 'transitionProperty' in DOCUMENT_STYLE && 'transitionDuration' in DOCUMENT_STYLE && 'transitionTimingFunction' in DOCUMENT_STYLE && 'transitionDelay' in DOCUMENT_STYLE) { Transition.useNative = true; Transition.supported = true; // TODO: remove } else { Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + 'Transition'; if (property in DOCUMENT[DOCUMENT_ELEMENT].style) { CAMEL_VENDOR_PREFIX = val; VENDOR_PREFIX = Transition._toHyphen(val) + '-'; Transition.useNative = true; Transition.supported = true; // TODO: remove Transition._VENDOR_PREFIX = val; } }); } // Map transform property to vendor-specific versions. // One-off required for cssText injection. if (typeof DOCUMENT_STYLE.transform === 'undefined') { Y.Array.each(VENDORS, function(val) { // then vendor specific var property = val + 'Transform'; if (typeof DOCUMENT_STYLE[property] !== 'undefined') { Transition._TRANSFORM = property; } }); } if (CAMEL_VENDOR_PREFIX) { TRANSITION_CAMEL = CAMEL_VENDOR_PREFIX + 'Transition'; TRANSITION_PROPERTY_CAMEL = CAMEL_VENDOR_PREFIX + 'TransitionProperty'; } TRANSITION_PROPERTY = VENDOR_PREFIX + 'transition-property'; TRANSITION_DURATION = VENDOR_PREFIX + 'transition-duration'; TRANSITION_TIMING_FUNCTION = VENDOR_PREFIX + 'transition-timing-function'; TRANSITION_DELAY = VENDOR_PREFIX + 'transition-delay'; TRANSITION_END = 'transitionend'; ON_TRANSITION_END = 'on' + CAMEL_VENDOR_PREFIX.toLowerCase() + 'transitionend'; TRANSITION_END = VENDOR_TRANSITION_END[CAMEL_VENDOR_PREFIX] || TRANSITION_END; Transition.fx = {}; Transition.toggles = {}; Transition._hasEnd = {}; Transition._reKeywords = /^(?:node|duration|iterations|easing|delay|on|onstart|onend)$/i; Y.Node.DOM_EVENTS[TRANSITION_END] = 1; Transition.NAME = 'transition'; Transition.DEFAULT_EASING = 'ease'; Transition.DEFAULT_DURATION = 0.5; Transition.DEFAULT_DELAY = 0; Transition._nodeAttrs = {}; Transition.prototype = { constructor: Transition, init: function(node, config) { var anim = this; anim._node = node; if (!anim._running && config) { anim._config = config; node._transition = anim; // cache for reuse anim._duration = ('duration' in config) ? config.duration: anim.constructor.DEFAULT_DURATION; anim._delay = ('delay' in config) ? config.delay: anim.constructor.DEFAULT_DELAY; anim._easing = config.easing || anim.constructor.DEFAULT_EASING; anim._count = 0; // track number of animated properties anim._running = false; } return anim; }, addProperty: function(prop, config) { var anim = this, node = this._node, uid = Y.stamp(node), nodeInstance = Y.one(node), attrs = Transition._nodeAttrs[uid], computed, compareVal, dur, attr, val; if (!attrs) { attrs = Transition._nodeAttrs[uid] = {}; } attr = attrs[prop]; // might just be a value if (config && config.value !== undefined) { val = config.value; } else if (config !== undefined) { val = config; config = EMPTY_OBJ; } if (typeof val === 'function') { val = val.call(nodeInstance, nodeInstance); } if (attr && attr.transition) { // take control if another transition owns this property if (attr.transition !== anim) { attr.transition._count--; // remapping attr to this transition } } anim._count++; // properties per transition // make 0 async and fire events dur = ((typeof config.duration !== 'undefined') ? config.duration : anim._duration) || 0.0001; attrs[prop] = { value: val, duration: dur, delay: (typeof config.delay !== 'undefined') ? config.delay : anim._delay, easing: config.easing || anim._easing, transition: anim }; // native end event doesnt fire when setting to same value // supplementing with timer // val may be a string or number (height: 0, etc), but computedStyle is always string computed = Y.DOM.getComputedStyle(node, prop); compareVal = (typeof val === 'string') ? computed : parseFloat(computed); if (Transition.useNative && compareVal === val) { setTimeout(function() { anim._onNativeEnd.call(node, { propertyName: prop, elapsedTime: dur }); }, dur * 1000); } }, removeProperty: function(prop) { var anim = this, attrs = Transition._nodeAttrs[Y.stamp(anim._node)]; if (attrs && attrs[prop]) { delete attrs[prop]; anim._count--; } }, initAttrs: function(config) { var attr, node = this._node; if (config.transform && !config[Transition._TRANSFORM]) { config[Transition._TRANSFORM] = config.transform; delete config.transform; // TODO: copy } for (attr in config) { if (config.hasOwnProperty(attr) && !Transition._reKeywords.test(attr)) { this.addProperty(attr, config[attr]); // when size is auto or % webkit starts from zero instead of computed // (https://bugs.webkit.org/show_bug.cgi?id=16020) // TODO: selective set if (node.style[attr] === '') { Y.DOM.setStyle(node, attr, Y.DOM.getComputedStyle(node, attr)); } } } }, /** * Starts or an animation. * @method run * @chainable * @private */ run: function(callback) { var anim = this, node = anim._node, config = anim._config, data = { type: 'transition:start', config: config }; if (!anim._running) { anim._running = true; if (config.on && config.on.start) { config.on.start.call(Y.one(node), data); } anim.initAttrs(anim._config); anim._callback = callback; anim._start(); } return anim; }, _start: function() { this._runNative(); }, _prepDur: function(dur) { dur = parseFloat(dur) * 1000; return dur + 'ms'; }, _runNative: function() { var anim = this, node = anim._node, uid = Y.stamp(node), style = node.style, computed = node.ownerDocument.defaultView.getComputedStyle(node), attrs = Transition._nodeAttrs[uid], cssText = '', cssTransition = computed[Transition._toCamel(TRANSITION_PROPERTY)], transitionText = TRANSITION_PROPERTY + ': ', duration = TRANSITION_DURATION + ': ', easing = TRANSITION_TIMING_FUNCTION + ': ', delay = TRANSITION_DELAY + ': ', hyphy, attr, name; // preserve existing transitions if (cssTransition !== 'all') { transitionText += cssTransition + ','; duration += computed[Transition._toCamel(TRANSITION_DURATION)] + ','; easing += computed[Transition._toCamel(TRANSITION_TIMING_FUNCTION)] + ','; delay += computed[Transition._toCamel(TRANSITION_DELAY)] + ','; } // run transitions mapped to this instance for (name in attrs) { hyphy = Transition._toHyphen(name); attr = attrs[name]; if ((attr = attrs[name]) && attr.transition === anim) { if (name in node.style) { // only native styles allowed duration += anim._prepDur(attr.duration) + ','; delay += anim._prepDur(attr.delay) + ','; easing += (attr.easing) + ','; transitionText += hyphy + ','; cssText += hyphy + ': ' + attr.value + '; '; } else { this.removeProperty(name); } } } transitionText = transitionText.replace(/,$/, ';'); duration = duration.replace(/,$/, ';'); easing = easing.replace(/,$/, ';'); delay = delay.replace(/,$/, ';'); // only one native end event per node if (!Transition._hasEnd[uid]) { node.addEventListener(TRANSITION_END, anim._onNativeEnd, ''); Transition._hasEnd[uid] = true; } style.cssText += transitionText + duration + easing + delay + cssText; }, _end: function(elapsed) { var anim = this, node = anim._node, callback = anim._callback, config = anim._config, data = { type: 'transition:end', config: config, elapsedTime: elapsed }, nodeInstance = Y.one(node); anim._running = false; anim._callback = null; if (node) { if (config.on && config.on.end) { setTimeout(function() { // IE: allow previous update to finish config.on.end.call(nodeInstance, data); // nested to ensure proper fire order if (callback) { callback.call(nodeInstance, data); } }, 1); } else if (callback) { setTimeout(function() { // IE: allow previous update to finish callback.call(nodeInstance, data); }, 1); } } }, _endNative: function(name) { var node = this._node, value = node.ownerDocument.defaultView.getComputedStyle(node, '')[Transition._toCamel(TRANSITION_PROPERTY)]; name = Transition._toHyphen(name); if (typeof value === 'string') { value = value.replace(new RegExp('(?:^|,\\s)' + name + ',?'), ','); value = value.replace(/^,|,$/, ''); node.style[TRANSITION_CAMEL] = value; } }, _onNativeEnd: function(e) { var node = this, uid = Y.stamp(node), event = e,//e._event, name = Transition._toCamel(event.propertyName), elapsed = event.elapsedTime, attrs = Transition._nodeAttrs[uid], attr = attrs[name], anim = (attr) ? attr.transition : null, data, config; if (anim) { anim.removeProperty(name); anim._endNative(name); config = anim._config[name]; data = { type: 'propertyEnd', propertyName: name, elapsedTime: elapsed, config: config }; if (config && config.on && config.on.end) { config.on.end.call(Y.one(node), data); } if (anim._count <= 0) { // after propertyEnd fires anim._end(elapsed); node.style[TRANSITION_PROPERTY_CAMEL] = ''; // clean up style } } }, destroy: function() { var anim = this, node = anim._node; if (node) { node.removeEventListener(TRANSITION_END, anim._onNativeEnd, false); anim._node = null; } } }; Y.Transition = Transition; Y.TransitionNative = Transition; // TODO: remove /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.one('#demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for Node * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. * @chainable */ Y.Node.prototype.transition = function(name, config, callback) { var transitionAttrs = Transition._nodeAttrs[Y.stamp(this._node)], anim = (transitionAttrs) ? transitionAttrs.transition || null : null, fxConfig, prop; if (typeof name === 'string') { // named effect, pull config from registry if (typeof config === 'function') { callback = config; config = null; } fxConfig = Transition.fx[name]; if (config && typeof config !== 'boolean') { config = Y.clone(config); for (prop in fxConfig) { if (fxConfig.hasOwnProperty(prop)) { if (! (prop in config)) { config[prop] = fxConfig[prop]; } } } } else { config = fxConfig; } } else { // name is a config, config is a callback or undefined callback = config; config = name; } if (anim && !anim._running) { anim.init(this, config); } else { anim = new Transition(this._node, config); } anim.run(callback); return this; }; Y.Node.prototype.show = function(name, config, callback) { this._show(); // show prior to transition if (name && Y.Transition) { if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.SHOW_TRANSITION; } this.transition(name, config, callback); } else if (name && !Y.Transition) { Y.log('unable to transition show; missing transition module', 'warn', 'node'); } return this; }; Y.NodeList.prototype.show = function(name, config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).show(name, config, callback); } return this; }; var _wrapCallBack = function(anim, fn, callback) { return function() { if (fn) { fn.call(anim); } if (callback && typeof callback === 'function') { callback.apply(anim._node, arguments); } }; }; Y.Node.prototype.hide = function(name, config, callback) { if (name && Y.Transition) { if (typeof config === 'function') { callback = config; config = null; } callback = _wrapCallBack(this, this._hide, callback); // wrap with existing callback if (typeof name !== 'string' && !name.push) { // named effect or array of effects supercedes default if (typeof config === 'function') { callback = config; config = name; } name = Transition.HIDE_TRANSITION; } this.transition(name, config, callback); } else if (name && !Y.Transition) { Y.log('unable to transition hide; missing transition module', 'warn', 'node'); } else { this._hide(); } return this; }; Y.NodeList.prototype.hide = function(name, config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).hide(name, config, callback); } return this; }; /** * Animate one or more css properties to a given value. Requires the "transition" module. * <pre>example usage: * Y.all('.demo').transition({ * duration: 1, // in seconds, default is 0.5 * easing: 'ease-out', // default is 'ease' * delay: '1', // delay start for 1 second, default is 0 * * height: '10px', * width: '10px', * * opacity: { // per property * value: 0, * duration: 2, * delay: 2, * easing: 'ease-in' * } * }); * </pre> * @for NodeList * @method transition * @param {Object} config An object containing one or more style properties, a duration and an easing. * @param {Function} callback A function to run after the transition has completed. The callback fires * once per item in the NodeList. * @chainable */ Y.NodeList.prototype.transition = function(config, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { Y.one(node).transition(config, callback); } return this; }; Y.Node.prototype.toggleView = function(name, on, callback) { this._toggles = this._toggles || []; callback = arguments[arguments.length - 1]; if (typeof name !== 'string') { // no transition, just toggle on = name; this._toggleView(on, callback); // call original _toggleView in Y.Node return; } if (typeof on === 'function') { // Ignore "on" if used for callback argument. on = undefined; } if (typeof on === 'undefined' && name in this._toggles) { // reverse current toggle on = ! this._toggles[name]; } on = (on) ? 1 : 0; if (on) { this._show(); } else { callback = _wrapCallBack(this, this._hide, callback); } this._toggles[name] = on; this.transition(Y.Transition.toggles[name][on], callback); return this; }; Y.NodeList.prototype.toggleView = function(name, on, callback) { var nodes = this._nodes, i = 0, node; while ((node = nodes[i++])) { node = Y.one(node); node.toggleView.apply(node, arguments); } return this; }; Y.mix(Transition.fx, { fadeOut: { opacity: 0, duration: 0.5, easing: 'ease-out' }, fadeIn: { opacity: 1, duration: 0.5, easing: 'ease-in' }, sizeOut: { height: 0, width: 0, duration: 0.75, easing: 'ease-out' }, sizeIn: { height: function(node) { return node.get('scrollHeight') + 'px'; }, width: function(node) { return node.get('scrollWidth') + 'px'; }, duration: 0.5, easing: 'ease-in', on: { start: function() { var overflow = this.getStyle('overflow'); if (overflow !== 'hidden') { // enable scrollHeight/Width this.setStyle('overflow', 'hidden'); this._transitionOverflow = overflow; } }, end: function() { if (this._transitionOverflow) { // revert overridden value this.setStyle('overflow', this._transitionOverflow); delete this._transitionOverflow; } } } } }); Y.mix(Transition.toggles, { size: ['sizeOut', 'sizeIn'], fade: ['fadeOut', 'fadeIn'] }); }, '@VERSION@', {"requires": ["node-style"]}); YUI.add('selector-css2', function (Y, NAME) { /** * The selector module provides helper methods allowing CSS2 Selectors to be used with DOM elements. * @module dom * @submodule selector-css2 * @for Selector */ /* * Provides helper methods for collecting and filtering DOM elements. */ var PARENT_NODE = 'parentNode', TAG_NAME = 'tagName', ATTRIBUTES = 'attributes', COMBINATOR = 'combinator', PSEUDOS = 'pseudos', Selector = Y.Selector, SelectorCSS2 = { _reRegExpTokens: /([\^\$\?\[\]\*\+\-\.\(\)\|\\])/, SORT_RESULTS: true, // TODO: better detection, document specific _isXML: (function() { var isXML = (Y.config.doc.createElement('div').tagName !== 'DIV'); return isXML; }()), /** * Mapping of shorthand tokens to corresponding attribute selector * @property shorthand * @type object */ shorthand: { '\\#(-?[_a-z0-9]+[-\\w\\uE000]*)': '[id=$1]', '\\.(-?[_a-z]+[-\\w\\uE000]*)': '[className~=$1]' }, /** * List of operators and corresponding boolean functions. * These functions are passed the attribute and the current node's value of the attribute. * @property operators * @type object */ operators: { '': function(node, attr) { return Y.DOM.getAttribute(node, attr) !== ''; }, // Just test for existence of attribute '~=': '(?:^|\\s+){val}(?:\\s+|$)', // space-delimited '|=': '^{val}-?' // optional hyphen-delimited }, pseudos: { 'first-child': function(node) { return Y.DOM._children(node[PARENT_NODE])[0] === node; } }, _bruteQuery: function(selector, root, firstOnly) { var ret = [], nodes = [], tokens = Selector._tokenize(selector), token = tokens[tokens.length - 1], rootDoc = Y.DOM._getDoc(root), child, id, className, tagName; if (token) { // prefilter nodes id = token.id; className = token.className; tagName = token.tagName || '*'; if (root.getElementsByTagName) { // non-IE lacks DOM api on doc frags // try ID first, unless no root.all && root not in document // (root.all works off document, but not getElementById) if (id && (root.all || (root.nodeType === 9 || Y.DOM.inDoc(root)))) { nodes = Y.DOM.allById(id, root); // try className } else if (className) { nodes = root.getElementsByClassName(className); } else { // default to tagName nodes = root.getElementsByTagName(tagName); } } else { // brute getElementsByTagName() child = root.firstChild; while (child) { // only collect HTMLElements // match tag to supplement missing getElementsByTagName if (child.tagName && (tagName === '*' || child.tagName === tagName)) { nodes.push(child); } child = child.nextSibling || child.firstChild; } } if (nodes.length) { ret = Selector._filterNodes(nodes, tokens, firstOnly); } } return ret; }, _filterNodes: function(nodes, tokens, firstOnly) { var i = 0, j, len = tokens.length, n = len - 1, result = [], node = nodes[0], tmpNode = node, getters = Y.Selector.getters, operator, combinator, token, path, pass, value, tests, test; for (i = 0; (tmpNode = node = nodes[i++]);) { n = len - 1; path = null; testLoop: while (tmpNode && tmpNode.tagName) { token = tokens[n]; tests = token.tests; j = tests.length; if (j && !pass) { while ((test = tests[--j])) { operator = test[1]; if (getters[test[0]]) { value = getters[test[0]](tmpNode, test[0]); } else { value = tmpNode[test[0]]; if (test[0] === 'tagName' && !Selector._isXML) { value = value.toUpperCase(); } if (typeof value != 'string' && value !== undefined && value.toString) { value = value.toString(); // coerce for comparison } else if (value === undefined && tmpNode.getAttribute) { // use getAttribute for non-standard attributes value = tmpNode.getAttribute(test[0], 2); // 2 === force string for IE } } if ((operator === '=' && value !== test[2]) || // fast path for equality (typeof operator !== 'string' && // protect against String.test monkey-patch (Moo) operator.test && !operator.test(value)) || // regex test (!operator.test && // protect against RegExp as function (webkit) typeof operator === 'function' && !operator(tmpNode, test[0], test[2]))) { // function test // skip non element nodes or non-matching tags if ((tmpNode = tmpNode[path])) { while (tmpNode && (!tmpNode.tagName || (token.tagName && token.tagName !== tmpNode.tagName)) ) { tmpNode = tmpNode[path]; } } continue testLoop; } } } n--; // move to next token // now that we've passed the test, move up the tree by combinator if (!pass && (combinator = token.combinator)) { path = combinator.axis; tmpNode = tmpNode[path]; // skip non element nodes while (tmpNode && !tmpNode.tagName) { tmpNode = tmpNode[path]; } if (combinator.direct) { // one pass only path = null; } } else { // success if we made it this far result.push(node); if (firstOnly) { return result; } break; } } } node = tmpNode = null; return result; }, combinators: { ' ': { axis: 'parentNode' }, '>': { axis: 'parentNode', direct: true }, '+': { axis: 'previousSibling', direct: true } }, _parsers: [ { name: ATTRIBUTES, re: /^\uE003(-?[a-z]+[\w\-]*)+([~\|\^\$\*!=]=?)?['"]?([^\uE004'"]*)['"]?\uE004/i, fn: function(match, token) { var operator = match[2] || '', operators = Selector.operators, escVal = (match[3]) ? match[3].replace(/\\/g, '') : '', test; // add prefiltering for ID and CLASS if ((match[1] === 'id' && operator === '=') || (match[1] === 'className' && Y.config.doc.documentElement.getElementsByClassName && (operator === '~=' || operator === '='))) { token.prefilter = match[1]; match[3] = escVal; // escape all but ID for prefilter, which may run through QSA (via Dom.allById) token[match[1]] = (match[1] === 'id') ? match[3] : escVal; } // add tests if (operator in operators) { test = operators[operator]; if (typeof test === 'string') { match[3] = escVal.replace(Selector._reRegExpTokens, '\\$1'); test = new RegExp(test.replace('{val}', match[3])); } match[2] = test; } if (!token.last || token.prefilter !== match[1]) { return match.slice(1); } } }, { name: TAG_NAME, re: /^((?:-?[_a-z]+[\w-]*)|\*)/i, fn: function(match, token) { var tag = match[1]; if (!Selector._isXML) { tag = tag.toUpperCase(); } token.tagName = tag; if (tag !== '*' && (!token.last || token.prefilter)) { return [TAG_NAME, '=', tag]; } if (!token.prefilter) { token.prefilter = 'tagName'; } } }, { name: COMBINATOR, re: /^\s*([>+~]|\s)\s*/, fn: function(match, token) { } }, { name: PSEUDOS, re: /^:([\-\w]+)(?:\uE005['"]?([^\uE005]*)['"]?\uE006)*/i, fn: function(match, token) { var test = Selector[PSEUDOS][match[1]]; if (test) { // reorder match array and unescape special chars for tests if (match[2]) { match[2] = match[2].replace(/\\/g, ''); } return [match[2], test]; } else { // selector token not supported (possibly missing CSS3 module) return false; } } } ], _getToken: function(token) { return { tagName: null, id: null, className: null, attributes: {}, combinator: null, tests: [] }; }, /* Break selector into token units per simple selector. Combinator is attached to the previous token. */ _tokenize: function(selector) { selector = selector || ''; selector = Selector._parseSelector(Y.Lang.trim(selector)); var token = Selector._getToken(), // one token per simple selector (left selector holds combinator) query = selector, // original query for debug report tokens = [], // array of tokens found = false, // whether or not any matches were found this pass match, // the regex match test, i, parser; /* Search for selector patterns, store, and strip them from the selector string until no patterns match (invalid selector) or we run out of chars. Multiple attributes and pseudos are allowed, in any order. for example: 'form:first-child[type=button]:not(button)[lang|=en]' */ outer: do { found = false; // reset after full pass for (i = 0; (parser = Selector._parsers[i++]);) { if ( (match = parser.re.exec(selector)) ) { // note assignment if (parser.name !== COMBINATOR ) { token.selector = selector; } selector = selector.replace(match[0], ''); // strip current match from selector if (!selector.length) { token.last = true; } if (Selector._attrFilters[match[1]]) { // convert class to className, etc. match[1] = Selector._attrFilters[match[1]]; } test = parser.fn(match, token); if (test === false) { // selector not supported found = false; break outer; } else if (test) { token.tests.push(test); } if (!selector.length || parser.name === COMBINATOR) { tokens.push(token); token = Selector._getToken(token); if (parser.name === COMBINATOR) { token.combinator = Y.Selector.combinators[match[1]]; } } found = true; } } } while (found && selector.length); if (!found || selector.length) { // not fully parsed Y.log('query: ' + query + ' contains unsupported token in: ' + selector, 'warn', 'Selector'); tokens = []; } return tokens; }, _replaceMarkers: function(selector) { selector = selector.replace(/\[/g, '\uE003'); selector = selector.replace(/\]/g, '\uE004'); selector = selector.replace(/\(/g, '\uE005'); selector = selector.replace(/\)/g, '\uE006'); return selector; }, _replaceShorthand: function(selector) { var shorthand = Y.Selector.shorthand, re; for (re in shorthand) { if (shorthand.hasOwnProperty(re)) { selector = selector.replace(new RegExp(re, 'gi'), shorthand[re]); } } return selector; }, _parseSelector: function(selector) { var replaced = Y.Selector._replaceSelector(selector), selector = replaced.selector; // replace shorthand (".foo, #bar") after pseudos and attrs // to avoid replacing unescaped chars selector = Y.Selector._replaceShorthand(selector); selector = Y.Selector._restore('attr', selector, replaced.attrs); selector = Y.Selector._restore('pseudo', selector, replaced.pseudos); // replace braces and parens before restoring escaped chars // to avoid replacing ecaped markers selector = Y.Selector._replaceMarkers(selector); selector = Y.Selector._restore('esc', selector, replaced.esc); return selector; }, _attrFilters: { 'class': 'className', 'for': 'htmlFor' }, getters: { href: function(node, attr) { return Y.DOM.getAttribute(node, attr); }, id: function(node, attr) { return Y.DOM.getId(node); } } }; Y.mix(Y.Selector, SelectorCSS2, true); Y.Selector.getters.src = Y.Selector.getters.rel = Y.Selector.getters.href; // IE wants class with native queries if (Y.Selector.useNative && Y.config.doc.querySelector) { Y.Selector.shorthand['\\.(-?[_a-z]+[-\\w]*)'] = '[class~=$1]'; } }, '@VERSION@', {"requires": ["selector-native"]}); YUI.add('selector-css3', function (Y, NAME) { /** * The selector css3 module provides support for css3 selectors. * @module dom * @submodule selector-css3 * @for Selector */ /* an+b = get every _a_th node starting at the _b_th 0n+b = no repeat ("0" and "n" may both be omitted (together) , e.g. "0n+1" or "1", not "0+1"), return only the _b_th element 1n+b = get every element starting from b ("1" may may be omitted, e.g. "1n+0" or "n+0" or "n") an+0 = get every _a_th element, "0" may be omitted */ Y.Selector._reNth = /^(?:([\-]?\d*)(n){1}|(odd|even)$)*([\-+]?\d*)$/; Y.Selector._getNth = function(node, expr, tag, reverse) { Y.Selector._reNth.test(expr); var a = parseInt(RegExp.$1, 10), // include every _a_ elements (zero means no repeat, just first _a_) n = RegExp.$2, // "n" oddeven = RegExp.$3, // "odd" or "even" b = parseInt(RegExp.$4, 10) || 0, // start scan from element _b_ result = [], siblings = Y.DOM._children(node.parentNode, tag), op; if (oddeven) { a = 2; // always every other op = '+'; n = 'n'; b = (oddeven === 'odd') ? 1 : 0; } else if ( isNaN(a) ) { a = (n) ? 1 : 0; // start from the first or no repeat } if (a === 0) { // just the first if (reverse) { b = siblings.length - b + 1; } if (siblings[b - 1] === node) { return true; } else { return false; } } else if (a < 0) { reverse = !!reverse; a = Math.abs(a); } if (!reverse) { for (var i = b - 1, len = siblings.length; i < len; i += a) { if ( i >= 0 && siblings[i] === node ) { return true; } } } else { for (var i = siblings.length - b, len = siblings.length; i >= 0; i -= a) { if ( i < len && siblings[i] === node ) { return true; } } } return false; }; Y.mix(Y.Selector.pseudos, { 'root': function(node) { return node === node.ownerDocument.documentElement; }, 'nth-child': function(node, expr) { return Y.Selector._getNth(node, expr); }, 'nth-last-child': function(node, expr) { return Y.Selector._getNth(node, expr, null, true); }, 'nth-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName); }, 'nth-last-of-type': function(node, expr) { return Y.Selector._getNth(node, expr, node.tagName, true); }, 'last-child': function(node) { var children = Y.DOM._children(node.parentNode); return children[children.length - 1] === node; }, 'first-of-type': function(node) { return Y.DOM._children(node.parentNode, node.tagName)[0] === node; }, 'last-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children[children.length - 1] === node; }, 'only-child': function(node) { var children = Y.DOM._children(node.parentNode); return children.length === 1 && children[0] === node; }, 'only-of-type': function(node) { var children = Y.DOM._children(node.parentNode, node.tagName); return children.length === 1 && children[0] === node; }, 'empty': function(node) { return node.childNodes.length === 0; }, 'not': function(node, expr) { return !Y.Selector.test(node, expr); }, 'contains': function(node, expr) { var text = node.innerText || node.textContent || ''; return text.indexOf(expr) > -1; }, 'checked': function(node) { return (node.checked === true || node.selected === true); }, enabled: function(node) { return (node.disabled !== undefined && !node.disabled); }, disabled: function(node) { return (node.disabled); } }); Y.mix(Y.Selector.operators, { '^=': '^{val}', // Match starts with value '$=': '{val}$', // Match ends with value '*=': '{val}' // Match contains value as substring }); Y.Selector.combinators['~'] = { axis: 'previousSibling' }; }, '@VERSION@', {"requires": ["selector-native", "selector-css2"]}); YUI.add('yui-log', function (Y, NAME) { /** * Provides console log capability and exposes a custom event for * console implementations. This module is a `core` YUI module, * <a href="../classes/YUI.html#method_log">it's documentation is located under the YUI class</a>. * * @module yui * @submodule yui-log */ var INSTANCE = Y, LOGEVENT = 'yui:log', UNDEFINED = 'undefined', LEVELS = { debug: 1, info: 2, warn: 4, error: 8 }; /** * If the 'debug' config is true, a 'yui:log' event will be * dispatched, which the Console widget and anything else * can consume. If the 'useBrowserConsole' config is true, it will * write to the browser console if available. YUI-specific log * messages will only be present in the -debug versions of the * JS files. The build system is supposed to remove log statements * from the raw and minified versions of the files. * * @method log * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.log = function(msg, cat, src, silent) { var bail, excl, incl, m, f, minlevel, Y = INSTANCE, c = Y.config, publisher = (Y.fire) ? Y : YUI.Env.globalEvents; // suppress log message if the config is off or the event stack // or the event call stack contains a consumer of the yui:log event if (c.debug) { // apply source filters src = src || ""; if (typeof src !== "undefined") { excl = c.logExclude; incl = c.logInclude; if (incl && !(src in incl)) { bail = 1; } else if (incl && (src in incl)) { bail = !incl[src]; } else if (excl && (src in excl)) { bail = excl[src]; } // Determine the current minlevel as defined in configuration Y.config.logLevel = Y.config.logLevel || 'debug'; minlevel = LEVELS[Y.config.logLevel.toLowerCase()]; if (cat in LEVELS && LEVELS[cat] < minlevel) { // Skip this message if the we don't meet the defined minlevel bail = 1; } } if (!bail) { if (c.useBrowserConsole) { m = (src) ? src + ': ' + msg : msg; if (Y.Lang.isFunction(c.logFn)) { c.logFn.call(Y, msg, cat, src); } else if (typeof console !== UNDEFINED && console.log) { f = (cat && console[cat] && (cat in LEVELS)) ? cat : 'log'; console[f](m); } else if (typeof opera !== UNDEFINED) { opera.postError(m); } } if (publisher && !silent) { if (publisher === Y && (!publisher.getEvent(LOGEVENT))) { publisher.publish(LOGEVENT, { broadcast: 2 }); } publisher.fire(LOGEVENT, { msg: msg, cat: cat, src: src }); } } } return Y; }; /** * Write a system message. This message will be preserved in the * minified and raw versions of the YUI files, unlike log statements. * @method message * @for YUI * @param {String} msg The message to log. * @param {String} cat The log category for the message. Default * categories are "info", "warn", "error", time". * Custom categories can be used as well. (opt). * @param {String} src The source of the the message (opt). * @param {boolean} silent If true, the log event won't fire. * @return {YUI} YUI instance. */ INSTANCE.message = function() { return INSTANCE.log.apply(INSTANCE, arguments); }; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('dump', function (Y, NAME) { /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. Use object notation for * associative arrays. * * If included, the dump method is added to the YUI instance. * * @module dump */ var L = Y.Lang, OBJ = '{...}', FUN = 'f(){...}', COMMA = ', ', ARROW = ' => ', /** * Returns a simple string representation of the object or array. * Other types of objects will be returned unprocessed. Arrays * are expected to be indexed. * * @method dump * @param {Object} o The object to dump. * @param {Number} d How deep to recurse child objects, default 3. * @return {String} the dump result. * @for YUI */ dump = function(o, d) { var i, len, s = [], type = L.type(o); // Cast non-objects to string // Skip dates because the std toString is what we want // Skip HTMLElement-like objects because trying to dump // an element will cause an unhandled exception in FF 2.x if (!L.isObject(o)) { return o + ''; } else if (type == 'date') { return o; } else if (o.nodeType && o.tagName) { return o.tagName + '#' + o.id; } else if (o.document && o.navigator) { return 'window'; } else if (o.location && o.body) { return 'document'; } else if (type == 'function') { return FUN; } // dig into child objects the depth specifed. Default 3 d = (L.isNumber(d)) ? d : 3; // arrays [1, 2, 3] if (type == 'array') { s.push('['); for (i = 0, len = o.length; i < len; i = i + 1) { if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } if (s.length > 1) { s.pop(); } s.push(']'); // regexp /foo/ } else if (type == 'regexp') { s.push(o.toString()); // objects {k1 => v1, k2 => v2} } else { s.push('{'); for (i in o) { if (o.hasOwnProperty(i)) { try { s.push(i + ARROW); if (L.isObject(o[i])) { s.push((d > 0) ? L.dump(o[i], d - 1) : OBJ); } else { s.push(o[i]); } s.push(COMMA); } catch (e) { s.push('Error: ' + e.message); } } } if (s.length > 1) { s.pop(); } s.push('}'); } return s.join(''); }; Y.dump = dump; L.dump = dump; }, '@VERSION@', {"requires": ["yui-base"]}); YUI.add('transition-timer', function (Y, NAME) { /** * Provides the base Transition class, for animating numeric properties. * * @module transition * @submodule transition-timer */ var Transition = Y.Transition; Y.mix(Transition.prototype, { _start: function() { if (Transition.useNative) { this._runNative(); } else { this._runTimer(); } }, _runTimer: function() { var anim = this; anim._initAttrs(); Transition._running[Y.stamp(anim)] = anim; anim._startTime = new Date(); Transition._startTimer(); }, _endTimer: function() { var anim = this; delete Transition._running[Y.stamp(anim)]; anim._startTime = null; }, _runFrame: function() { var t = new Date() - this._startTime; this._runAttrs(t); }, _runAttrs: function(time) { var anim = this, node = anim._node, config = anim._config, uid = Y.stamp(node), attrs = Transition._nodeAttrs[uid], customAttr = Transition.behaviors, done = false, allDone = false, data, name, attribute, setter, elapsed, delay, d, t, i; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { d = attribute.duration; delay = attribute.delay; elapsed = (time - delay) / 1000; t = time; data = { type: 'propertyEnd', propertyName: name, config: config, elapsedTime: elapsed }; setter = (i in customAttr && 'set' in customAttr[i]) ? customAttr[i].set : Transition.DEFAULT_SETTER; done = (t >= d); if (t > d) { t = d; } if (!delay || time >= delay) { setter(anim, name, attribute.from, attribute.to, t - delay, d - delay, attribute.easing, attribute.unit); if (done) { delete attrs[name]; anim._count--; if (config[name] && config[name].on && config[name].on.end) { config[name].on.end.call(Y.one(node), data); } //node.fire('transition:propertyEnd', data); if (!allDone && anim._count <= 0) { allDone = true; anim._end(elapsed); anim._endTimer(); } } } } } }, _initAttrs: function() { var anim = this, customAttr = Transition.behaviors, uid = Y.stamp(anim._node), attrs = Transition._nodeAttrs[uid], attribute, duration, delay, easing, val, name, mTo, mFrom, unit, begin, end; for (name in attrs) { if ((attribute = attrs[name]) && attribute.transition === anim) { duration = attribute.duration * 1000; delay = attribute.delay * 1000; easing = attribute.easing; val = attribute.value; // only allow supported properties if (name in anim._node.style || name in Y.DOM.CUSTOM_STYLES) { begin = (name in customAttr && 'get' in customAttr[name]) ? customAttr[name].get(anim, name) : Transition.DEFAULT_GETTER(anim, name); mFrom = Transition.RE_UNITS.exec(begin); mTo = Transition.RE_UNITS.exec(val); begin = mFrom ? mFrom[1] : begin; end = mTo ? mTo[1] : val; unit = mTo ? mTo[2] : mFrom ? mFrom[2] : ''; // one might be zero TODO: mixed units if (!unit && Transition.RE_DEFAULT_UNIT.test(name)) { unit = Transition.DEFAULT_UNIT; } if (typeof easing === 'string') { if (easing.indexOf('cubic-bezier') > -1) { easing = easing.substring(13, easing.length - 1).split(','); } else if (Transition.easings[easing]) { easing = Transition.easings[easing]; } } attribute.from = Number(begin); attribute.to = Number(end); attribute.unit = unit; attribute.easing = easing; attribute.duration = duration + delay; attribute.delay = delay; } else { delete attrs[name]; anim._count--; } } } }, destroy: function() { this.detachAll(); this._node = null; } }, true); Y.mix(Y.Transition, { _runtimeAttrs: {}, /* * Regex of properties that should use the default unit. * * @property RE_DEFAULT_UNIT * @static */ RE_DEFAULT_UNIT: /^width|height|top|right|bottom|left|margin.*|padding.*|border.*$/i, /* * The default unit to use with properties that pass the RE_DEFAULT_UNIT test. * * @property DEFAULT_UNIT * @static */ DEFAULT_UNIT: 'px', /* * Time in milliseconds passed to setInterval for frame processing * * @property intervalTime * @default 20 * @static */ intervalTime: 20, /* * Bucket for custom getters and setters * * @property behaviors * @static */ behaviors: { left: { get: function(anim, attr) { return Y.DOM._getAttrOffset(anim._node, attr); } } }, /* * The default setter to use when setting object properties. * * @property DEFAULT_SETTER * @static */ DEFAULT_SETTER: function(anim, att, from, to, elapsed, duration, fn, unit) { from = Number(from); to = Number(to); var node = anim._node, val = Transition.cubicBezier(fn, elapsed / duration); val = from + val[0] * (to - from); if (node) { if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { unit = unit || ''; Y.DOM.setStyle(node, att, val + unit); } } else { anim._end(); } }, /* * The default getter to use when getting object properties. * * @property DEFAULT_GETTER * @static */ DEFAULT_GETTER: function(anim, att) { var node = anim._node, val = ''; if (att in node.style || att in Y.DOM.CUSTOM_STYLES) { val = Y.DOM.getComputedStyle(node, att); } return val; }, _startTimer: function() { if (!Transition._timer) { Transition._timer = setInterval(Transition._runFrame, Transition.intervalTime); } }, _stopTimer: function() { clearInterval(Transition._timer); Transition._timer = null; }, /* * Called per Interval to handle each animation frame. * @method _runFrame * @private * @static */ _runFrame: function() { var done = true, anim; for (anim in Transition._running) { if (Transition._running[anim]._runFrame) { done = false; Transition._running[anim]._runFrame(); } } if (done) { Transition._stopTimer(); } }, cubicBezier: function(p, t) { var x0 = 0, y0 = 0, x1 = p[0], y1 = p[1], x2 = p[2], y2 = p[3], x3 = 1, y3 = 0, A = x3 - 3 * x2 + 3 * x1 - x0, B = 3 * x2 - 6 * x1 + 3 * x0, C = 3 * x1 - 3 * x0, D = x0, E = y3 - 3 * y2 + 3 * y1 - y0, F = 3 * y2 - 6 * y1 + 3 * y0, G = 3 * y1 - 3 * y0, H = y0, x = (((A*t) + B)*t + C)*t + D, y = (((E*t) + F)*t + G)*t + H; return [x, y]; }, easings: { ease: [0.25, 0, 1, 0.25], linear: [0, 0, 1, 1], 'ease-in': [0.42, 0, 1, 1], 'ease-out': [0, 0, 0.58, 1], 'ease-in-out': [0.42, 0, 0.58, 1] }, _running: {}, _timer: null, RE_UNITS: /^(-?\d*\.?\d*){1}(em|ex|px|in|cm|mm|pt|pc|%)*$/ }, true); Transition.behaviors.top = Transition.behaviors.bottom = Transition.behaviors.right = Transition.behaviors.left; Y.Transition = Transition; }, '@VERSION@', {"requires": ["transition"]}); YUI.add('yui', function (Y, NAME) { // empty }, '@VERSION@', { "use": [ "yui", "oop", "dom", "event-custom-base", "event-base", "pluginhost", "node", "event-delegate", "io-base", "json-parse", "transition", "selector-css3", "dom-style-ie", "querystring-stringify-simple" ] }); var Y = YUI().use('*');
ext-4.2.1/docs/output/Ext.Component.js
crysfel/fundamentos-extjs
Ext.data.JsonP.Ext_Component({"alternateClassNames":[],"aliases":{"widget":["component","box"]},"enum":null,"parentMixins":["Ext.state.Stateful","Ext.util.Animate","Ext.util.ElementContainer","Ext.util.Observable","Ext.util.Positionable","Ext.util.Renderable"],"tagname":"class","subclasses":["Ext.Img","Ext.LoadMask","Ext.ProgressBar","Ext.button.Button","Ext.chart.MaskLayer","Ext.container.AbstractContainer","Ext.dd.StatusProxy","Ext.draw.Component","Ext.flash.Component","Ext.form.Label","Ext.form.field.Base","Ext.menu.Item","Ext.panel.Tool","Ext.picker.Color","Ext.picker.Date","Ext.picker.Month","Ext.resizer.Handle","Ext.resizer.Splitter","Ext.toolbar.Fill","Ext.toolbar.Item","Ext.toolbar.Spacer","Ext.ux.IFrame","Ext.ux.statusbar.ValidationStatus","Ext.view.AbstractView"],"extends":"Ext.AbstractComponent","uses":["Ext.dom.Layer","Ext.resizer.Resizer","Ext.util.ComponentDragger","Ext.util.DelayedTask"],"html":"<div><pre class=\"hierarchy\"><h4>Hierarchy</h4><div class='subclass first-child'><a href='#!/api/Ext.Base' rel='Ext.Base' class='docClass'>Ext.Base</a><div class='subclass '><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='docClass'>Ext.AbstractComponent</a><div class='subclass '><strong>Ext.Component</strong></div></div></div><h4>Mixins</h4><div class='dependency'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='docClass'>Ext.util.Floating</a></div><h4>Inherited mixins</h4><div class='dependency'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='docClass'>Ext.state.Stateful</a></div><div class='dependency'><a href='#!/api/Ext.util.Animate' rel='Ext.util.Animate' class='docClass'>Ext.util.Animate</a></div><div class='dependency'><a href='#!/api/Ext.util.ElementContainer' rel='Ext.util.ElementContainer' class='docClass'>Ext.util.ElementContainer</a></div><div class='dependency'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='docClass'>Ext.util.Observable</a></div><div class='dependency'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='docClass'>Ext.util.Positionable</a></div><div class='dependency'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='docClass'>Ext.util.Renderable</a></div><h4>Subclasses</h4><div class='dependency'><a href='#!/api/Ext.Img' rel='Ext.Img' class='docClass'>Ext.Img</a></div><div class='dependency'><a href='#!/api/Ext.LoadMask' rel='Ext.LoadMask' class='docClass'>Ext.LoadMask</a></div><div class='dependency'><a href='#!/api/Ext.ProgressBar' rel='Ext.ProgressBar' class='docClass'>Ext.ProgressBar</a></div><div class='dependency'><a href='#!/api/Ext.button.Button' rel='Ext.button.Button' class='docClass'>Ext.button.Button</a></div><div class='dependency'><a href='#!/api/Ext.chart.MaskLayer' rel='Ext.chart.MaskLayer' class='docClass'>Ext.chart.MaskLayer</a></div><div class='dependency'><a href='#!/api/Ext.container.AbstractContainer' rel='Ext.container.AbstractContainer' class='docClass'>Ext.container.AbstractContainer</a></div><div class='dependency'><a href='#!/api/Ext.dd.StatusProxy' rel='Ext.dd.StatusProxy' class='docClass'>Ext.dd.StatusProxy</a></div><div class='dependency'><a href='#!/api/Ext.draw.Component' rel='Ext.draw.Component' class='docClass'>Ext.draw.Component</a></div><div class='dependency'><a href='#!/api/Ext.flash.Component' rel='Ext.flash.Component' class='docClass'>Ext.flash.Component</a></div><div class='dependency'><a href='#!/api/Ext.form.Label' rel='Ext.form.Label' class='docClass'>Ext.form.Label</a></div><div class='dependency'><a href='#!/api/Ext.form.field.Base' rel='Ext.form.field.Base' class='docClass'>Ext.form.field.Base</a></div><div class='dependency'><a href='#!/api/Ext.menu.Item' rel='Ext.menu.Item' class='docClass'>Ext.menu.Item</a></div><div class='dependency'><a href='#!/api/Ext.panel.Tool' rel='Ext.panel.Tool' class='docClass'>Ext.panel.Tool</a></div><div class='dependency'><a href='#!/api/Ext.picker.Color' rel='Ext.picker.Color' class='docClass'>Ext.picker.Color</a></div><div class='dependency'><a href='#!/api/Ext.picker.Date' rel='Ext.picker.Date' class='docClass'>Ext.picker.Date</a></div><div class='dependency'><a href='#!/api/Ext.picker.Month' rel='Ext.picker.Month' class='docClass'>Ext.picker.Month</a></div><div class='dependency'><a href='#!/api/Ext.resizer.Handle' rel='Ext.resizer.Handle' class='docClass'>Ext.resizer.Handle</a></div><div class='dependency'><a href='#!/api/Ext.resizer.Splitter' rel='Ext.resizer.Splitter' class='docClass'>Ext.resizer.Splitter</a></div><div class='dependency'><a href='#!/api/Ext.toolbar.Fill' rel='Ext.toolbar.Fill' class='docClass'>Ext.toolbar.Fill</a></div><div class='dependency'><a href='#!/api/Ext.toolbar.Item' rel='Ext.toolbar.Item' class='docClass'>Ext.toolbar.Item</a></div><div class='dependency'><a href='#!/api/Ext.toolbar.Spacer' rel='Ext.toolbar.Spacer' class='docClass'>Ext.toolbar.Spacer</a></div><div class='dependency'><a href='#!/api/Ext.ux.IFrame' rel='Ext.ux.IFrame' class='docClass'>Ext.ux.IFrame</a></div><div class='dependency'><a href='#!/api/Ext.ux.statusbar.ValidationStatus' rel='Ext.ux.statusbar.ValidationStatus' class='docClass'>Ext.ux.statusbar.ValidationStatus</a></div><div class='dependency'><a href='#!/api/Ext.view.AbstractView' rel='Ext.view.AbstractView' class='docClass'>Ext.view.AbstractView</a></div><h4>Uses</h4><div class='dependency'><a href='#!/api/Ext.dom.Layer' rel='Ext.dom.Layer' class='docClass'>Ext.dom.Layer</a></div><div class='dependency'><a href='#!/api/Ext.resizer.Resizer' rel='Ext.resizer.Resizer' class='docClass'>Ext.resizer.Resizer</a></div><div class='dependency'><a href='#!/api/Ext.util.ComponentDragger' rel='Ext.util.ComponentDragger' class='docClass'>Ext.util.ComponentDragger</a></div><div class='dependency'><a href='#!/api/Ext.util.DelayedTask' rel='Ext.util.DelayedTask' class='docClass'>Ext.util.DelayedTask</a></div><h4>Files</h4><div class='dependency'><a href='source/Component5.html#Ext-Component' target='_blank'>Component.js</a></div><div class='dependency'><a href='source/Region2.html#Ext-layout-container-border-Region' target='_blank'>Region.js</a></div></pre><div class='doc-contents'><p>Base class for all Ext components.</p>\n\n<p>The Component base class has built-in support for basic hide/show and enable/disable and size control behavior.</p>\n\n<h2>xtypes</h2>\n\n<p>Every component has a specific xtype, which is its Ext-specific type name, along with methods for checking the xtype\nlike <a href=\"#!/api/Ext.Component-method-getXType\" rel=\"Ext.Component-method-getXType\" class=\"docClass\">getXType</a> and <a href=\"#!/api/Ext.Component-method-isXType\" rel=\"Ext.Component-method-isXType\" class=\"docClass\">isXType</a>. See the <a href=\"#!/guide/components\">Component Guide</a> for more information on xtypes and the\nComponent hierarchy.</p>\n\n<h2>Finding components</h2>\n\n<p>All Components are registered with the <a href=\"#!/api/Ext.ComponentManager\" rel=\"Ext.ComponentManager\" class=\"docClass\">Ext.ComponentManager</a> on construction so that they can be referenced at\nany time via <a href=\"#!/api/Ext-method-getCmp\" rel=\"Ext-method-getCmp\" class=\"docClass\">Ext.getCmp</a>, passing the <a href=\"#!/api/Ext.Component-cfg-id\" rel=\"Ext.Component-cfg-id\" class=\"docClass\">id</a>.</p>\n\n<p>Additionally the <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">Ext.ComponentQuery</a> provides a CSS-selectors-like way to look up components by their xtype\nand many other attributes. For example the following code will find all textfield components inside component with\n<code>id: 'myform'</code>:</p>\n\n<pre><code><a href=\"#!/api/Ext.ComponentQuery-method-query\" rel=\"Ext.ComponentQuery-method-query\" class=\"docClass\">Ext.ComponentQuery.query</a>('#myform textfield');\n</code></pre>\n\n<h2>Extending <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></h2>\n\n<p>All subclasses of Component may participate in the automated Ext component\nlifecycle of creation, rendering and destruction which is provided by the <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Container</a>\nclass. Components may be added to a Container through the <a href=\"#!/api/Ext.container.Container-cfg-items\" rel=\"Ext.container.Container-cfg-items\" class=\"docClass\">items</a> config option\nat the time the Container is created, or they may be added dynamically via the\n<a href=\"#!/api/Ext.container.Container-method-add\" rel=\"Ext.container.Container-method-add\" class=\"docClass\">add</a> method.</p>\n\n<p>All user-developed visual widgets that are required to participate in automated lifecycle and size management should\nsubclass Component.</p>\n\n<p>See the Creating new UI controls chapter in <a href=\"#!/guide/components\">Component Guide</a> for details on how and to either extend\nor augment Ext JS base classes to create custom Components.</p>\n\n<h2>The <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> class by itself</h2>\n\n<p>Usually one doesn't need to instantiate the <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> class. There are subclasses which implement\nspecialized use cases, covering most application needs. However it is possible to instantiate a base\nComponent, and it can be rendered to document, or handled by layouts as the child item of a Container:</p>\n\n<pre class='inline-example '><code><a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>', {\n html: 'Hello world!',\n width: 300,\n height: 200,\n padding: 20,\n style: {\n color: '#FFFFFF',\n backgroundColor:'#000000'\n },\n renderTo: <a href=\"#!/api/Ext-method-getBody\" rel=\"Ext-method-getBody\" class=\"docClass\">Ext.getBody</a>()\n});\n</code></pre>\n\n<p>The Component above creates its encapsulating <code>div</code> upon render, and use the configured HTML as content. More complex\ninternal structure may be created using the <a href=\"#!/api/Ext.Component-cfg-renderTpl\" rel=\"Ext.Component-cfg-renderTpl\" class=\"docClass\">renderTpl</a> configuration, although to display database-derived\nmass data, it is recommended that an ExtJS data-backed Component such as a <a href=\"#!/api/Ext.view.View\" rel=\"Ext.view.View\" class=\"docClass\">View</a>,\n<a href=\"#!/api/Ext.grid.Panel\" rel=\"Ext.grid.Panel\" class=\"docClass\">GridPanel</a>, or <a href=\"#!/api/Ext.tree.Panel\" rel=\"Ext.tree.Panel\" class=\"docClass\">TreePanel</a> be used.</p>\n\n<p><strong>From override Ext.layout.container.border.Region:</strong> This override provides extra, border layout specific methods for <code><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></code>. The\n<code><a href=\"#!/api/Ext.layout.container.Border\" rel=\"Ext.layout.container.Border\" class=\"docClass\">Ext.layout.container.Border</a></code> class requires this override so that the added functions\nare only included in a build when <code>border</code> layout is used.</p>\n</div><div class='members'><div class='members-section'><div class='definedBy'>Defined By</div><h3 class='members-title icon-cfg'>Config options</h3><div class='subsection'><div id='cfg-autoEl' class='member first-child inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-autoEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-autoEl' class='name expandable'>autoEl</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span></div><div class='description'><div class='short'>A tag name or DomHelper spec used to create the Element which will\nencapsulate this Component. ...</div><div class='long'><p>A tag name or <a href=\"#!/api/Ext.DomHelper\" rel=\"Ext.DomHelper\" class=\"docClass\">DomHelper</a> spec used to create the <a href=\"#!/api/Ext.AbstractComponent-method-getEl\" rel=\"Ext.AbstractComponent-method-getEl\" class=\"docClass\">Element</a> which will\nencapsulate this Component.</p>\n\n<p>You do not normally need to specify this. For the base classes <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> and\n<a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a>, this defaults to <strong>'div'</strong>. The more complex Sencha classes use a more\ncomplex DOM structure specified by their own <a href=\"#!/api/Ext.AbstractComponent-cfg-renderTpl\" rel=\"Ext.AbstractComponent-cfg-renderTpl\" class=\"docClass\">renderTpl</a>s.</p>\n\n<p>This is intended to allow the developer to create application-specific utility Components encapsulated by\ndifferent DOM elements. Example usage:</p>\n\n<pre><code>{\n xtype: 'component',\n autoEl: {\n tag: 'img',\n src: 'http://www.example.com/example.jpg'\n }\n}, {\n xtype: 'component',\n autoEl: {\n tag: 'blockquote',\n html: 'autoEl is cool!'\n }\n}, {\n xtype: 'container',\n autoEl: 'ul',\n cls: 'ux-unordered-list',\n items: {\n xtype: 'component',\n autoEl: 'li',\n html: 'First list item'\n }\n}\n</code></pre>\n <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='cfg-autoLoad' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-autoLoad' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-autoLoad' class='name expandable'>autoLoad</a><span> : <a href=\"#!/api/Ext.ComponentLoader\" rel=\"Ext.ComponentLoader\" class=\"docClass\">Ext.ComponentLoader</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><strong class='deprecated signature' >deprecated</strong></div><div class='description'><div class='short'>An alias for loader config which also allows to specify just a string which will be\nused as the url that's automatica...</div><div class='long'><p>An alias for <a href=\"#!/api/Ext.AbstractComponent-cfg-loader\" rel=\"Ext.AbstractComponent-cfg-loader\" class=\"docClass\">loader</a> config which also allows to specify just a string which will be\nused as the url that's automatically loaded:</p>\n\n<pre><code><a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>', {\n autoLoad: 'content.html',\n renderTo: <a href=\"#!/api/Ext-method-getBody\" rel=\"Ext-method-getBody\" class=\"docClass\">Ext.getBody</a>()\n});\n</code></pre>\n\n<p>The above is the same as:</p>\n\n<pre><code><a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>', {\n loader: {\n url: 'content.html',\n autoLoad: true\n },\n renderTo: <a href=\"#!/api/Ext-method-getBody\" rel=\"Ext-method-getBody\" class=\"docClass\">Ext.getBody</a>()\n});\n</code></pre>\n\n<p>Don't use it together with <a href=\"#!/api/Ext.AbstractComponent-cfg-loader\" rel=\"Ext.AbstractComponent-cfg-loader\" class=\"docClass\">loader</a> config.</p>\n <div class='signature-box deprecated'>\n <p>This cfg has been <strong>deprecated</strong> since 4.1.1</p>\n <p>Use <a href=\"#!/api/Ext.AbstractComponent-cfg-loader\" rel=\"Ext.AbstractComponent-cfg-loader\" class=\"docClass\">loader</a> config instead.</p>\n\n </div>\n</div></div></div><div id='cfg-autoRender' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-autoRender' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-autoRender' class='name expandable'>autoRender</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/HTMLElement/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a></span></div><div class='description'><div class='short'>This config is intended mainly for non-floating Components which may or may not be shown. ...</div><div class='long'><p>This config is intended mainly for non-<a href=\"#!/api/Ext.AbstractComponent-cfg-floating\" rel=\"Ext.AbstractComponent-cfg-floating\" class=\"docClass\">floating</a> Components which may or may not be shown. Instead of using\n<a href=\"#!/api/Ext.AbstractComponent-cfg-renderTo\" rel=\"Ext.AbstractComponent-cfg-renderTo\" class=\"docClass\">renderTo</a> in the configuration, and rendering upon construction, this allows a Component to render itself\nupon first <em><a href=\"#!/api/Ext.Component-method-show\" rel=\"Ext.Component-method-show\" class=\"docClass\">show</a></em>. If <a href=\"#!/api/Ext.AbstractComponent-cfg-floating\" rel=\"Ext.AbstractComponent-cfg-floating\" class=\"docClass\">floating</a> is <code>true</code>, the value of this config is omitted as if it is <code>true</code>.</p>\n\n<p>Specify as <code>true</code> to have this Component render to the document body upon first show.</p>\n\n<p>Specify as an element, or the ID of an element to have this Component render to a specific element upon first\nshow.</p>\n<p>Defaults to: <code>false</code></p></div></div></div><div id='cfg-autoScroll' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-autoScroll' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-autoScroll' class='name expandable'>autoScroll</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>true to use overflow:'auto' on the components layout element and show scroll bars automatically when necessary,\nfalse...</div><div class='long'><p><code>true</code> to use overflow:'auto' on the components layout element and show scroll bars automatically when necessary,\n<code>false</code> to clip any overflowing content.\nThis should not be combined with <a href=\"#!/api/Ext.Component-cfg-overflowX\" rel=\"Ext.Component-cfg-overflowX\" class=\"docClass\">overflowX</a> or <a href=\"#!/api/Ext.Component-cfg-overflowY\" rel=\"Ext.Component-cfg-overflowY\" class=\"docClass\">overflowY</a>.</p>\n<p>Defaults to: <code>false</code></p></div></div></div><div id='cfg-autoShow' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-autoShow' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-autoShow' class='name expandable'>autoShow</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>true to automatically show the component upon creation. ...</div><div class='long'><p><code>true</code> to automatically show the component upon creation. This config option may only be used for\n<a href=\"#!/api/Ext.AbstractComponent-cfg-floating\" rel=\"Ext.AbstractComponent-cfg-floating\" class=\"docClass\">floating</a> components or components that use <a href=\"#!/api/Ext.AbstractComponent-cfg-autoRender\" rel=\"Ext.AbstractComponent-cfg-autoRender\" class=\"docClass\">autoRender</a>.</p>\n<p>Defaults to: <code>false</code></p> <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='cfg-baseCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-baseCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-baseCls' class='name expandable'>baseCls</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>The base CSS class to apply to this component's element. ...</div><div class='long'><p>The base CSS class to apply to this component's element. This will also be prepended to elements within this\ncomponent like Panel's body will get a class <code>x-panel-body</code>. This means that if you create a subclass of Panel, and\nyou want it to get all the Panels styling for the element and the body, you leave the <code>baseCls</code> <code>x-panel</code> and use\n<code>componentCls</code> to add specific styling for this component.</p>\n<p>Defaults to: <code>'x-component'</code></p></div></div></div><div id='cfg-border' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-border' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-border' class='name expandable'>border</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>Specifies the border size for this component. ...</div><div class='long'><p>Specifies the border size for this component. The border can be a single numeric value to apply to all sides or it can\nbe a CSS style specification for each style, for example: '10 5 3 10' (top, right, bottom, left).</p>\n\n<p>For components that have no border by default, setting this won't make the border appear by itself.\nYou also need to specify border color and style:</p>\n\n<pre><code>border: 5,\nstyle: {\n borderColor: 'red',\n borderStyle: 'solid'\n}\n</code></pre>\n\n<p>To turn off the border, use <code>border: false</code>.</p>\n</div></div></div><div id='cfg-childEls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-childEls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-childEls' class='name expandable'>childEls</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>[]</span></div><div class='description'><div class='short'>An array describing the child elements of the Component. ...</div><div class='long'><p>An array describing the child elements of the Component. Each member of the array\nis an object with these properties:</p>\n\n<ul>\n<li><code>name</code> - The property name on the Component for the child element.</li>\n<li><code>itemId</code> - The id to combine with the Component's id that is the id of the child element.</li>\n<li><code>id</code> - The id of the child element.</li>\n</ul>\n\n\n<p>If the array member is a string, it is equivalent to <code>{ name: m, itemId: m }</code>.</p>\n\n<p>For example, a Component which renders a title and body text:</p>\n\n<pre class='inline-example '><code><a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>', {\n renderTo: <a href=\"#!/api/Ext-method-getBody\" rel=\"Ext-method-getBody\" class=\"docClass\">Ext.getBody</a>(),\n renderTpl: [\n '&lt;h1 id=\"{id}-title\"&gt;{title}&lt;/h1&gt;',\n '&lt;p&gt;{msg}&lt;/p&gt;',\n ],\n renderData: {\n title: \"Error\",\n msg: \"Something went wrong\"\n },\n childEls: [\"title\"],\n listeners: {\n afterrender: function(cmp){\n // After rendering the component will have a title property\n cmp.title.setStyle({color: \"red\"});\n }\n }\n});\n</code></pre>\n\n<p>A more flexible, but somewhat slower, approach is <a href=\"#!/api/Ext.AbstractComponent-cfg-renderSelectors\" rel=\"Ext.AbstractComponent-cfg-renderSelectors\" class=\"docClass\">renderSelectors</a>.</p>\n</div></div></div><div id='cfg-cls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-cls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-cls' class='name expandable'>cls</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>An optional extra CSS class that will be added to this component's Element. ...</div><div class='long'><p>An optional extra CSS class that will be added to this component's Element. This can be useful\nfor adding customized styles to the component or any of its children using standard CSS rules.</p>\n<p>Defaults to: <code>''</code></p> <p>Available since: <b>1.1.0</b></p>\n</div></div></div><div id='cfg-columnWidth' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-columnWidth' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-columnWidth' class='name expandable'>columnWidth</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>Defines the column width inside column layout. ...</div><div class='long'><p>Defines the column width inside <a href=\"#!/api/Ext.layout.container.Column\" rel=\"Ext.layout.container.Column\" class=\"docClass\">column layout</a>.</p>\n\n<p>Can be specified as a number or as a percentage.</p>\n</div></div></div><div id='cfg-componentCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-componentCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-componentCls' class='name not-expandable'>componentCls</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'><p>CSS Class to be added to a components root level element to give distinction to it via styling.</p>\n</div><div class='long'><p>CSS Class to be added to a components root level element to give distinction to it via styling.</p>\n</div></div></div><div id='cfg-componentLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-componentLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-componentLayout' class='name expandable'>componentLayout</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span></div><div class='description'><div class='short'>The sizing and positioning of a Component's internal Elements is the responsibility of the Component's layout\nmanager...</div><div class='long'><p>The sizing and positioning of a Component's internal Elements is the responsibility of the Component's layout\nmanager which sizes a Component's internal structure in response to the Component being sized.</p>\n\n<p>Generally, developers will not use this configuration as all provided Components which need their internal\nelements sizing (Such as <a href=\"#!/api/Ext.form.field.Base\" rel=\"Ext.form.field.Base\" class=\"docClass\">input fields</a>) come with their own componentLayout managers.</p>\n\n<p>The <a href=\"#!/api/Ext.layout.container.Auto\" rel=\"Ext.layout.container.Auto\" class=\"docClass\">default layout manager</a> will be used on instances of the base <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>\nclass which simply sizes the Component's encapsulating element to the height and width specified in the\n<a href=\"#!/api/Ext.AbstractComponent-method-setSize\" rel=\"Ext.AbstractComponent-method-setSize\" class=\"docClass\">setSize</a> method.</p>\n</div></div></div><div id='cfg-constrain' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-cfg-constrain' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-cfg-constrain' class='name expandable'>constrain</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>True to constrain this Components within its containing element, false to allow it to fall outside of its containing\n...</div><div class='long'><p>True to constrain this Components within its containing element, false to allow it to fall outside of its containing\nelement. By default this Component will be rendered to <code>document.body</code>. To render and constrain this Component within\nanother element specify <a href=\"#!/api/Ext.AbstractComponent-cfg-renderTo\" rel=\"Ext.AbstractComponent-cfg-renderTo\" class=\"docClass\">renderTo</a>.</p>\n<p>Defaults to: <code>false</code></p></div></div></div><div id='cfg-constrainTo' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-constrainTo' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-constrainTo' class='name expandable'>constrainTo</a><span> : <a href=\"#!/api/Ext.util.Region\" rel=\"Ext.util.Region\" class=\"docClass\">Ext.util.Region</a>/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a></span></div><div class='description'><div class='short'>A Region (or an element from which a Region measurement will be read) which is used\nto constrain the component. ...</div><div class='long'><p>A <a href=\"#!/api/Ext.util.Region\" rel=\"Ext.util.Region\" class=\"docClass\">Region</a> (or an element from which a Region measurement will be read) which is used\nto constrain the component. Only applies when the component is floating.</p>\n</div></div></div><div id='cfg-constraintInsets' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-constraintInsets' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-constraintInsets' class='name expandable'>constraintInsets</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>An object or a string (in TRBL order) specifying insets from the configured constrain region\nwithin which this compon...</div><div class='long'><p>An object or a string (in TRBL order) specifying insets from the configured <a href=\"#!/api/Ext.Component-cfg-constrainTo\" rel=\"Ext.Component-cfg-constrainTo\" class=\"docClass\">constrain region</a>\nwithin which this component must be constrained when positioning or sizing.\nexample:</p>\n\n<p> constraintInsets: '10 10 10 10' // Constrain with 10px insets from parent</p>\n</div></div></div><div id='cfg-contentEl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-contentEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-contentEl' class='name expandable'>contentEl</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>Specify an existing HTML element, or the id of an existing HTML element to use as the content for this component. ...</div><div class='long'><p>Specify an existing HTML element, or the <code>id</code> of an existing HTML element to use as the content for this component.</p>\n\n<p>This config option is used to take an existing HTML element and place it in the layout element of a new component\n(it simply moves the specified DOM element <em>after the Component is rendered</em> to use as the content.</p>\n\n<p><strong>Notes:</strong></p>\n\n<p>The specified HTML element is appended to the layout element of the component <em>after any configured\n<a href=\"#!/api/Ext.AbstractComponent-cfg-html\" rel=\"Ext.AbstractComponent-cfg-html\" class=\"docClass\">HTML</a> has been inserted</em>, and so the document will not contain this element at the time\nthe <a href=\"#!/api/Ext.AbstractComponent-event-render\" rel=\"Ext.AbstractComponent-event-render\" class=\"docClass\">render</a> event is fired.</p>\n\n<p>The specified HTML element used will not participate in any <strong><code><a href=\"#!/api/Ext.container.Container-cfg-layout\" rel=\"Ext.container.Container-cfg-layout\" class=\"docClass\">layout</a></code></strong>\nscheme that the Component may use. It is just HTML. Layouts operate on child\n<strong><code><a href=\"#!/api/Ext.container.Container-cfg-items\" rel=\"Ext.container.Container-cfg-items\" class=\"docClass\">items</a></code></strong>.</p>\n\n<p>Add either the <code>x-hidden</code> or the <code>x-hide-display</code> CSS class to prevent a brief flicker of the content before it\nis rendered to the panel.</p>\n <p>Available since: <b>3.4.0</b></p>\n</div></div></div><div id='cfg-data' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-data' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-data' class='name not-expandable'>data</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span></div><div class='description'><div class='short'><p>The initial set of data to apply to the <code><a href=\"#!/api/Ext.AbstractComponent-cfg-tpl\" rel=\"Ext.AbstractComponent-cfg-tpl\" class=\"docClass\">tpl</a></code> to update the content area of the Component.</p>\n</div><div class='long'><p>The initial set of data to apply to the <code><a href=\"#!/api/Ext.AbstractComponent-cfg-tpl\" rel=\"Ext.AbstractComponent-cfg-tpl\" class=\"docClass\">tpl</a></code> to update the content area of the Component.</p>\n <p>Available since: <b>3.4.0</b></p>\n</div></div></div><div id='cfg-defaultAlign' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-defaultAlign' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-defaultAlign' class='name expandable'>defaultAlign</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>The default Ext.Element#getAlignToXY anchor position value for this menu\nrelative to its element of origin. ...</div><div class='long'><p>The default <a href=\"#!/api/Ext.util.Positionable-method-getAlignToXY\" rel=\"Ext.util.Positionable-method-getAlignToXY\" class=\"docClass\">Ext.Element#getAlignToXY</a> anchor position value for this menu\nrelative to its element of origin. Used in conjunction with <a href=\"#!/api/Ext.Component-method-showBy\" rel=\"Ext.Component-method-showBy\" class=\"docClass\">showBy</a>.</p>\n<p>Defaults to: <code>&quot;tl-bl?&quot;</code></p></div></div></div><div id='cfg-disabled' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-disabled' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-disabled' class='name expandable'>disabled</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>true to disable the component. ...</div><div class='long'><p><code>true</code> to disable the component.</p>\n<p>Defaults to: <code>false</code></p> <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='cfg-disabledCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-disabledCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-disabledCls' class='name expandable'>disabledCls</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>CSS class to add when the Component is disabled. ...</div><div class='long'><p>CSS class to add when the Component is disabled.</p>\n<p>Defaults to: <code>'x-item-disabled'</code></p></div></div></div><div id='cfg-draggable' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-draggable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-draggable' class='name expandable'>draggable</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span></div><div class='description'><div class='short'>Specify as true to make a floating Component draggable using the Component's encapsulating element as\nthe drag handle. ...</div><div class='long'><p>Specify as true to make a <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a> Component draggable using the Component's encapsulating element as\nthe drag handle.</p>\n\n<p>This may also be specified as a config object for the <a href=\"#!/api/Ext.util.ComponentDragger\" rel=\"Ext.util.ComponentDragger\" class=\"docClass\">ComponentDragger</a> which is\ninstantiated to perform dragging.</p>\n\n<p>For example to create a Component which may only be dragged around using a certain internal element as the drag\nhandle, use the delegate option:</p>\n\n<pre><code>new <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>({\n constrain: true,\n floating: true,\n style: {\n backgroundColor: '#fff',\n border: '1px solid black'\n },\n html: '&lt;h1 style=\"cursor:move\"&gt;The title&lt;/h1&gt;&lt;p&gt;The content&lt;/p&gt;',\n draggable: {\n delegate: 'h1'\n }\n}).show();\n</code></pre>\n<p>Defaults to: <code>false</code></p><p>Overrides: <a href='#!/api/Ext.AbstractComponent-cfg-draggable' rel='Ext.AbstractComponent-cfg-draggable' class='docClass'>Ext.AbstractComponent.draggable</a></p></div></div></div><div id='cfg-fixed' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-cfg-fixed' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-cfg-fixed' class='name expandable'>fixed</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>Configure as true to have this Component fixed at its X, Y coordinates in the browser viewport, immune\nto scrolling t...</div><div class='long'><p>Configure as <code>true</code> to have this Component fixed at its <code>X, Y</code> coordinates in the browser viewport, immune\nto scrolling the document.</p>\n\n<p><em>Only in browsers that support <code>position:fixed</code></em></p>\n\n<p><em>IE6 and IE7, 8 and 9 quirks do not support <code>position: fixed</code></em></p>\n<p>Defaults to: <code>false</code></p></div></div></div><div id='cfg-floating' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-floating' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-floating' class='name expandable'>floating</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>Specify as true to float the Component outside of the document flow using CSS absolute positioning. ...</div><div class='long'><p>Specify as true to float the Component outside of the document flow using CSS absolute positioning.</p>\n\n<p>Components such as <a href=\"#!/api/Ext.window.Window\" rel=\"Ext.window.Window\" class=\"docClass\">Window</a>s and <a href=\"#!/api/Ext.menu.Menu\" rel=\"Ext.menu.Menu\" class=\"docClass\">Menu</a>s are floating by default.</p>\n\n<p>Floating Components that are programatically <a href=\"#!/api/Ext.Component-method-render\" rel=\"Ext.Component-method-render\" class=\"docClass\">rendered</a> will register\nthemselves with the global <a href=\"#!/api/Ext.WindowManager\" rel=\"Ext.WindowManager\" class=\"docClass\">ZIndexManager</a></p>\n\n<h3>Floating Components as child items of a Container</h3>\n\n<p>A floating Component may be used as a child item of a Container. This just allows the floating Component to seek\na ZIndexManager by examining the ownerCt chain.</p>\n\n<p>When configured as floating, Components acquire, at render time, a <a href=\"#!/api/Ext.ZIndexManager\" rel=\"Ext.ZIndexManager\" class=\"docClass\">ZIndexManager</a> which\nmanages a stack of related floating Components. The ZIndexManager brings a single floating Component to the top\nof its stack when the Component's <a href=\"#!/api/Ext.Component-method-toFront\" rel=\"Ext.Component-method-toFront\" class=\"docClass\">toFront</a> method is called.</p>\n\n<p>The ZIndexManager is found by traversing up the <a href=\"#!/api/Ext.Component-property-ownerCt\" rel=\"Ext.Component-property-ownerCt\" class=\"docClass\">ownerCt</a> chain to find an ancestor which itself is\nfloating. This is so that descendant floating Components of floating <em>Containers</em> (Such as a ComboBox dropdown\nwithin a Window) can have its zIndex managed relative to any siblings, but always <strong>above</strong> that floating\nancestor Container.</p>\n\n<p>If no floating ancestor is found, a floating Component registers itself with the default <a href=\"#!/api/Ext.WindowManager\" rel=\"Ext.WindowManager\" class=\"docClass\">ZIndexManager</a>.</p>\n\n<p>Floating components <em>do not participate in the Container's layout</em>. Because of this, they are not rendered until\nyou explicitly <a href=\"#!/api/Ext.Component-method-show\" rel=\"Ext.Component-method-show\" class=\"docClass\">show</a> them.</p>\n\n<p>After rendering, the ownerCt reference is deleted, and the <a href=\"#!/api/Ext.Component-property-floatParent\" rel=\"Ext.Component-property-floatParent\" class=\"docClass\">floatParent</a> property is set to the found\nfloating ancestor Container. If no floating ancestor Container was found the <a href=\"#!/api/Ext.Component-property-floatParent\" rel=\"Ext.Component-property-floatParent\" class=\"docClass\">floatParent</a> property will\nnot be set.</p>\n<p>Defaults to: <code>false</code></p><p>Overrides: <a href='#!/api/Ext.AbstractComponent-cfg-floating' rel='Ext.AbstractComponent-cfg-floating' class='docClass'>Ext.AbstractComponent.floating</a></p></div></div></div><div id='cfg-focusOnToFront' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-cfg-focusOnToFront' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-cfg-focusOnToFront' class='name expandable'>focusOnToFront</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>Specifies whether the floated component should be automatically focused when\nit is brought to the front. ...</div><div class='long'><p>Specifies whether the floated component should be automatically <a href=\"#!/api/Ext.Component-method-focus\" rel=\"Ext.Component-method-focus\" class=\"docClass\">focused</a> when\nit is <a href=\"#!/api/Ext.util.Floating-method-toFront\" rel=\"Ext.util.Floating-method-toFront\" class=\"docClass\">brought to the front</a>.</p>\n<p>Defaults to: <code>true</code></p></div></div></div><div id='cfg-formBind' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-formBind' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-formBind' class='name expandable'>formBind</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>When inside FormPanel, any component configured with formBind: true will\nbe enabled/disabled depending on the validit...</div><div class='long'><p>When inside FormPanel, any component configured with <code>formBind: true</code> will\nbe enabled/disabled depending on the validity state of the form.\nSee <a href=\"#!/api/Ext.form.Panel\" rel=\"Ext.form.Panel\" class=\"docClass\">Ext.form.Panel</a> for more information and example.</p>\n<p>Defaults to: <code>false</code></p></div></div></div><div id='cfg-frame' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-frame' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-frame' class='name expandable'>frame</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>Specify as true to have the Component inject framing elements within the Component at render time to provide a\ngraphi...</div><div class='long'><p>Specify as <code>true</code> to have the Component inject framing elements within the Component at render time to provide a\ngraphical rounded frame around the Component content.</p>\n\n<p>This is only necessary when running on outdated, or non standard-compliant browsers such as Microsoft's Internet\nExplorer prior to version 9 which do not support rounded corners natively.</p>\n\n<p>The extra space taken up by this framing is available from the read only property <a href=\"#!/api/Ext.AbstractComponent-property-frameSize\" rel=\"Ext.AbstractComponent-property-frameSize\" class=\"docClass\">frameSize</a>.</p>\n</div></div></div><div id='cfg-height' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-height' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-height' class='name not-expandable'>height</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span></div><div class='description'><div class='short'><p>The height of this component in pixels.</p>\n</div><div class='long'><p>The height of this component in pixels.</p>\n</div></div></div><div id='cfg-hidden' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-hidden' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-hidden' class='name expandable'>hidden</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>true to hide the component. ...</div><div class='long'><p><code>true</code> to hide the component.</p>\n<p>Defaults to: <code>false</code></p> <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='cfg-hideMode' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-hideMode' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-hideMode' class='name expandable'>hideMode</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>A String which specifies how this Component's encapsulating DOM element will be hidden. ...</div><div class='long'><p>A String which specifies how this Component's encapsulating DOM element will be hidden. Values may be:</p>\n\n<ul>\n<li><code>'display'</code> : The Component will be hidden using the <code>display: none</code> style.</li>\n<li><code>'visibility'</code> : The Component will be hidden using the <code>visibility: hidden</code> style.</li>\n<li><code>'offsets'</code> : The Component will be hidden by absolutely positioning it out of the visible area of the document.\nThis is useful when a hidden Component must maintain measurable dimensions. Hiding using <code>display</code> results in a\nComponent having zero dimensions.</li>\n</ul>\n\n<p>Defaults to: <code>'display'</code></p> <p>Available since: <b>1.1.0</b></p>\n</div></div></div><div id='cfg-html' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-html' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-html' class='name expandable'>html</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span></div><div class='description'><div class='short'>An HTML fragment, or a DomHelper specification to use as the layout element content. ...</div><div class='long'><p>An HTML fragment, or a <a href=\"#!/api/Ext.DomHelper\" rel=\"Ext.DomHelper\" class=\"docClass\">DomHelper</a> specification to use as the layout element content.\nThe HTML content is added after the component is rendered, so the document will not contain this HTML at the time\nthe <a href=\"#!/api/Ext.AbstractComponent-event-render\" rel=\"Ext.AbstractComponent-event-render\" class=\"docClass\">render</a> event is fired. This content is inserted into the body <em>before</em> any configured <a href=\"#!/api/Ext.AbstractComponent-cfg-contentEl\" rel=\"Ext.AbstractComponent-cfg-contentEl\" class=\"docClass\">contentEl</a>\nis appended.</p>\n<p>Defaults to: <code>''</code></p> <p>Available since: <b>3.4.0</b></p>\n</div></div></div><div id='cfg-id' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-id' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-id' class='name expandable'>id</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>The unique id of this component instance. ...</div><div class='long'><p>The <strong>unique id of this component instance.</strong></p>\n\n<p>It should not be necessary to use this configuration except for singleton objects in your application. Components\ncreated with an <code>id</code> may be accessed globally using <a href=\"#!/api/Ext-method-getCmp\" rel=\"Ext-method-getCmp\" class=\"docClass\">Ext.getCmp</a>.</p>\n\n<p>Instead of using assigned ids, use the <a href=\"#!/api/Ext.AbstractComponent-cfg-itemId\" rel=\"Ext.AbstractComponent-cfg-itemId\" class=\"docClass\">itemId</a> config, and <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">ComponentQuery</a>\nwhich provides selector-based searching for Sencha Components analogous to DOM querying. The <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Container</a> class contains <a href=\"#!/api/Ext.container.Container-method-down\" rel=\"Ext.container.Container-method-down\" class=\"docClass\">shortcut methods</a> to query\nits descendant Components by selector.</p>\n\n<p>Note that this <code>id</code> will also be used as the element id for the containing HTML element that is rendered to the\npage for this component. This allows you to write id-based CSS rules to style the specific instance of this\ncomponent uniquely, and also to select sub-elements using this component's <code>id</code> as the parent.</p>\n\n<p><strong>Note:</strong> To avoid complications imposed by a unique <code>id</code> also see <code><a href=\"#!/api/Ext.AbstractComponent-cfg-itemId\" rel=\"Ext.AbstractComponent-cfg-itemId\" class=\"docClass\">itemId</a></code>.</p>\n\n<p><strong>Note:</strong> To access the container of a Component see <code><a href=\"#!/api/Ext.AbstractComponent-property-ownerCt\" rel=\"Ext.AbstractComponent-property-ownerCt\" class=\"docClass\">ownerCt</a></code>.</p>\n\n<p>Defaults to an <a href=\"#!/api/Ext.AbstractComponent-method-getId\" rel=\"Ext.AbstractComponent-method-getId\" class=\"docClass\">auto-assigned id</a>.</p>\n <p>Available since: <b>1.1.0</b></p>\n</div></div></div><div id='cfg-itemId' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-itemId' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-itemId' class='name expandable'>itemId</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>An itemId can be used as an alternative way to get a reference to a component when no object reference is\navailable. ...</div><div class='long'><p>An <code>itemId</code> can be used as an alternative way to get a reference to a component when no object reference is\navailable. Instead of using an <code><a href=\"#!/api/Ext.AbstractComponent-cfg-id\" rel=\"Ext.AbstractComponent-cfg-id\" class=\"docClass\">id</a></code> with <a href=\"#!/api/Ext\" rel=\"Ext\" class=\"docClass\">Ext</a>.<a href=\"#!/api/Ext-method-getCmp\" rel=\"Ext-method-getCmp\" class=\"docClass\">getCmp</a>, use <code>itemId</code> with\n<a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a>.<a href=\"#!/api/Ext.container.Container-method-getComponent\" rel=\"Ext.container.Container-method-getComponent\" class=\"docClass\">getComponent</a> which will retrieve\n<code>itemId</code>'s or <a href=\"#!/api/Ext.AbstractComponent-cfg-id\" rel=\"Ext.AbstractComponent-cfg-id\" class=\"docClass\">id</a>'s. Since <code>itemId</code>'s are an index to the container's internal MixedCollection, the\n<code>itemId</code> is scoped locally to the container -- avoiding potential conflicts with <a href=\"#!/api/Ext.ComponentManager\" rel=\"Ext.ComponentManager\" class=\"docClass\">Ext.ComponentManager</a>\nwhich requires a <strong>unique</strong> <code><a href=\"#!/api/Ext.AbstractComponent-cfg-id\" rel=\"Ext.AbstractComponent-cfg-id\" class=\"docClass\">id</a></code>.</p>\n\n<pre><code>var c = new <a href=\"#!/api/Ext.panel.Panel\" rel=\"Ext.panel.Panel\" class=\"docClass\">Ext.panel.Panel</a>({ //\n <a href=\"#!/api/Ext.Component-cfg-height\" rel=\"Ext.Component-cfg-height\" class=\"docClass\">height</a>: 300,\n <a href=\"#!/api/Ext.AbstractComponent-cfg-renderTo\" rel=\"Ext.AbstractComponent-cfg-renderTo\" class=\"docClass\">renderTo</a>: document.body,\n <a href=\"#!/api/Ext.container.Container-cfg-layout\" rel=\"Ext.container.Container-cfg-layout\" class=\"docClass\">layout</a>: 'auto',\n <a href=\"#!/api/Ext.container.Container-cfg-items\" rel=\"Ext.container.Container-cfg-items\" class=\"docClass\">items</a>: [\n {\n itemId: 'p1',\n <a href=\"#!/api/Ext.panel.Panel-cfg-title\" rel=\"Ext.panel.Panel-cfg-title\" class=\"docClass\">title</a>: 'Panel 1',\n <a href=\"#!/api/Ext.Component-cfg-height\" rel=\"Ext.Component-cfg-height\" class=\"docClass\">height</a>: 150\n },\n {\n itemId: 'p2',\n <a href=\"#!/api/Ext.panel.Panel-cfg-title\" rel=\"Ext.panel.Panel-cfg-title\" class=\"docClass\">title</a>: 'Panel 2',\n <a href=\"#!/api/Ext.Component-cfg-height\" rel=\"Ext.Component-cfg-height\" class=\"docClass\">height</a>: 150\n }\n ]\n})\np1 = c.<a href=\"#!/api/Ext.container.Container-method-getComponent\" rel=\"Ext.container.Container-method-getComponent\" class=\"docClass\">getComponent</a>('p1'); // not the same as <a href=\"#!/api/Ext-method-getCmp\" rel=\"Ext-method-getCmp\" class=\"docClass\">Ext.getCmp()</a>\np2 = p1.<a href=\"#!/api/Ext.AbstractComponent-property-ownerCt\" rel=\"Ext.AbstractComponent-property-ownerCt\" class=\"docClass\">ownerCt</a>.<a href=\"#!/api/Ext.container.Container-method-getComponent\" rel=\"Ext.container.Container-method-getComponent\" class=\"docClass\">getComponent</a>('p2'); // reference via a sibling\n</code></pre>\n\n<p>Also see <a href=\"#!/api/Ext.AbstractComponent-cfg-id\" rel=\"Ext.AbstractComponent-cfg-id\" class=\"docClass\">id</a>, <code><a href=\"#!/api/Ext.container.Container-method-query\" rel=\"Ext.container.Container-method-query\" class=\"docClass\">Ext.container.Container.query</a></code>, <code><a href=\"#!/api/Ext.container.Container-method-down\" rel=\"Ext.container.Container-method-down\" class=\"docClass\">Ext.container.Container.down</a></code> and\n<code><a href=\"#!/api/Ext.container.Container-method-child\" rel=\"Ext.container.Container-method-child\" class=\"docClass\">Ext.container.Container.child</a></code>.</p>\n\n<p><strong>Note</strong>: to access the container of an item see <a href=\"#!/api/Ext.AbstractComponent-property-ownerCt\" rel=\"Ext.AbstractComponent-property-ownerCt\" class=\"docClass\">ownerCt</a>.</p>\n <p>Available since: <b>3.4.0</b></p>\n</div></div></div><div id='cfg-listeners' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-cfg-listeners' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-cfg-listeners' class='name expandable'>listeners</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span></div><div class='description'><div class='short'>A config object containing one or more event handlers to be added to this object during initialization. ...</div><div class='long'><p>A config object containing one or more event handlers to be added to this object during initialization. This\nshould be a valid listeners config object as specified in the <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">addListener</a> example for attaching multiple\nhandlers at once.</p>\n\n<p><strong>DOM events from Ext JS <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Components</a></strong></p>\n\n<p>While <em>some</em> Ext JS Component classes export selected DOM events (e.g. \"click\", \"mouseover\" etc), this is usually\nonly done when extra value can be added. For example the <a href=\"#!/api/Ext.view.View\" rel=\"Ext.view.View\" class=\"docClass\">DataView</a>'s <strong><code><a href=\"#!/api/Ext.view.View-event-itemclick\" rel=\"Ext.view.View-event-itemclick\" class=\"docClass\">itemclick</a></code></strong> event passing the node clicked on. To access DOM events directly from a\nchild element of a Component, we need to specify the <code>element</code> option to identify the Component property to add a\nDOM listener to:</p>\n\n<pre><code>new <a href=\"#!/api/Ext.panel.Panel\" rel=\"Ext.panel.Panel\" class=\"docClass\">Ext.panel.Panel</a>({\n width: 400,\n height: 200,\n dockedItems: [{\n xtype: 'toolbar'\n }],\n listeners: {\n click: {\n element: 'el', //bind to the underlying el property on the panel\n fn: function(){ console.log('click el'); }\n },\n dblclick: {\n element: 'body', //bind to the underlying body property on the panel\n fn: function(){ console.log('dblclick body'); }\n }\n }\n});\n</code></pre>\n</div></div></div><div id='cfg-loader' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-loader' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-loader' class='name expandable'>loader</a><span> : <a href=\"#!/api/Ext.ComponentLoader\" rel=\"Ext.ComponentLoader\" class=\"docClass\">Ext.ComponentLoader</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span></div><div class='description'><div class='short'>A configuration object or an instance of a Ext.ComponentLoader to load remote content\nfor this Component. ...</div><div class='long'><p>A configuration object or an instance of a <a href=\"#!/api/Ext.ComponentLoader\" rel=\"Ext.ComponentLoader\" class=\"docClass\">Ext.ComponentLoader</a> to load remote content\nfor this Component.</p>\n\n<pre><code><a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>', {\n loader: {\n url: 'content.html',\n autoLoad: true\n },\n renderTo: <a href=\"#!/api/Ext-method-getBody\" rel=\"Ext-method-getBody\" class=\"docClass\">Ext.getBody</a>()\n});\n</code></pre>\n</div></div></div><div id='cfg-margin' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-margin' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-margin' class='name expandable'>margin</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>Specifies the margin for this component. ...</div><div class='long'><p>Specifies the margin for this component. The margin can be a single numeric value to apply to all sides or it can\nbe a CSS style specification for each style, for example: '10 5 3 10' (top, right, bottom, left).</p>\n</div></div></div><div id='cfg-maxHeight' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-maxHeight' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-maxHeight' class='name expandable'>maxHeight</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span></div><div class='description'><div class='short'>The maximum value in pixels which this Component will set its height to. ...</div><div class='long'><p>The maximum value in pixels which this Component will set its height to.</p>\n\n<p><strong>Warning:</strong> This will override any size management applied by layout managers.</p>\n</div></div></div><div id='cfg-maxWidth' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-maxWidth' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-maxWidth' class='name expandable'>maxWidth</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span></div><div class='description'><div class='short'>The maximum value in pixels which this Component will set its width to. ...</div><div class='long'><p>The maximum value in pixels which this Component will set its width to.</p>\n\n<p><strong>Warning:</strong> This will override any size management applied by layout managers.</p>\n</div></div></div><div id='cfg-minHeight' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-minHeight' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-minHeight' class='name expandable'>minHeight</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span></div><div class='description'><div class='short'>The minimum value in pixels which this Component will set its height to. ...</div><div class='long'><p>The minimum value in pixels which this Component will set its height to.</p>\n\n<p><strong>Warning:</strong> This will override any size management applied by layout managers.</p>\n</div></div></div><div id='cfg-minWidth' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-minWidth' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-minWidth' class='name expandable'>minWidth</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span></div><div class='description'><div class='short'>The minimum value in pixels which this Component will set its width to. ...</div><div class='long'><p>The minimum value in pixels which this Component will set its width to.</p>\n\n<p><strong>Warning:</strong> This will override any size management applied by layout managers.</p>\n</div></div></div><div id='cfg-overCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-overCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-overCls' class='name expandable'>overCls</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>An optional extra CSS class that will be added to this component's Element when the mouse moves over the Element,\nand...</div><div class='long'><p>An optional extra CSS class that will be added to this component's Element when the mouse moves over the Element,\nand removed when the mouse moves out. This can be useful for adding customized 'active' or 'hover' styles to the\ncomponent or any of its children using standard CSS rules.</p>\n<p>Defaults to: <code>''</code></p> <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='cfg-overflowX' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-overflowX' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-overflowX' class='name expandable'>overflowX</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>Possible values are:\n * 'auto' to enable automatic horizontal scrollbar (overflow-x: 'auto'). ...</div><div class='long'><p>Possible values are:\n * <code>'auto'</code> to enable automatic horizontal scrollbar (overflow-x: 'auto').\n * <code>'scroll'</code> to always enable horizontal scrollbar (overflow-x: 'scroll').\nThe default is overflow-x: 'hidden'. This should not be combined with <a href=\"#!/api/Ext.Component-cfg-autoScroll\" rel=\"Ext.Component-cfg-autoScroll\" class=\"docClass\">autoScroll</a>.</p>\n</div></div></div><div id='cfg-overflowY' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-overflowY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-overflowY' class='name expandable'>overflowY</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>Possible values are:\n * 'auto' to enable automatic vertical scrollbar (overflow-y: 'auto'). ...</div><div class='long'><p>Possible values are:\n * <code>'auto'</code> to enable automatic vertical scrollbar (overflow-y: 'auto').\n * <code>'scroll'</code> to always enable vertical scrollbar (overflow-y: 'scroll').\nThe default is overflow-y: 'hidden'. This should not be combined with <a href=\"#!/api/Ext.Component-cfg-autoScroll\" rel=\"Ext.Component-cfg-autoScroll\" class=\"docClass\">autoScroll</a>.</p>\n</div></div></div><div id='cfg-padding' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-padding' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-padding' class='name expandable'>padding</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>Specifies the padding for this component. ...</div><div class='long'><p>Specifies the padding for this component. The padding can be a single numeric value to apply to all sides or it\ncan be a CSS style specification for each style, for example: '10 5 3 10' (top, right, bottom, left).</p>\n</div></div></div><div id='cfg-plugins' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-plugins' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-plugins' class='name expandable'>plugins</a><span> : <a href=\"#!/api/Ext.AbstractPlugin\" rel=\"Ext.AbstractPlugin\" class=\"docClass\">Ext.AbstractPlugin</a>[]/<a href=\"#!/api/Ext.AbstractPlugin\" rel=\"Ext.AbstractPlugin\" class=\"docClass\">Ext.AbstractPlugin</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>[]/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>/<a href=\"#!/api/Ext.enums.Plugin\" rel=\"Ext.enums.Plugin\" class=\"docClass\">Ext.enums.Plugin</a>[]/<a href=\"#!/api/Ext.enums.Plugin\" rel=\"Ext.enums.Plugin\" class=\"docClass\">Ext.enums.Plugin</a></span></div><div class='description'><div class='short'>An array of plugins to be added to this component. ...</div><div class='long'><p>An array of plugins to be added to this component. Can also be just a single plugin instead of array.</p>\n\n<p>Plugins provide custom functionality for a component. The only requirement for\na valid plugin is that it contain an <code>init</code> method that accepts a reference of type <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>. When a component\nis created, if any plugins are available, the component will call the init method on each plugin, passing a\nreference to itself. Each plugin can then call methods or respond to events on the component as needed to provide\nits functionality.</p>\n\n<p>Plugins can be added to component by either directly referencing the plugin instance:</p>\n\n<pre><code>plugins: [<a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.grid.plugin.CellEditing\" rel=\"Ext.grid.plugin.CellEditing\" class=\"docClass\">Ext.grid.plugin.CellEditing</a>', {clicksToEdit: 1})],\n</code></pre>\n\n<p>By using config object with ptype:</p>\n\n<pre><code>plugins: [{ptype: 'cellediting', clicksToEdit: 1}],\n</code></pre>\n\n<p>Or with just a ptype:</p>\n\n<pre><code>plugins: ['cellediting', 'gridviewdragdrop'],\n</code></pre>\n\n<p>See <a href=\"#!/api/Ext.enums.Plugin\" rel=\"Ext.enums.Plugin\" class=\"docClass\">Ext.enums.Plugin</a> for list of all ptypes.</p>\n <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='cfg-region' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-region' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-region' class='name expandable'>region</a><span> : \"north\"/\"south\"/\"east\"/\"west\"/\"center\"</span></div><div class='description'><div class='short'>Defines the region inside border layout. ...</div><div class='long'><p>Defines the region inside <a href=\"#!/api/Ext.layout.container.Border\" rel=\"Ext.layout.container.Border\" class=\"docClass\">border layout</a>.</p>\n\n<p>Possible values:</p>\n\n<ul>\n<li>north - Positions component at top.</li>\n<li>south - Positions component at bottom.</li>\n<li>east - Positions component at right.</li>\n<li>west - Positions component at left.</li>\n<li>center - Positions component at the remaining space.\nThere <strong>must</strong> be a component with <code>region: \"center\"</code> in every border layout.</li>\n</ul>\n\n</div></div></div><div id='cfg-renderData' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-renderData' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-renderData' class='name expandable'>renderData</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span></div><div class='description'><div class='short'>The data used by renderTpl in addition to the following property values of the component:\n\n\nid\nui\nuiCls\nbaseCls\ncompo...</div><div class='long'><p>The data used by <a href=\"#!/api/Ext.AbstractComponent-cfg-renderTpl\" rel=\"Ext.AbstractComponent-cfg-renderTpl\" class=\"docClass\">renderTpl</a> in addition to the following property values of the component:</p>\n\n<ul>\n<li>id</li>\n<li>ui</li>\n<li>uiCls</li>\n<li>baseCls</li>\n<li>componentCls</li>\n<li>frame</li>\n</ul>\n\n\n<p>See <a href=\"#!/api/Ext.AbstractComponent-cfg-renderSelectors\" rel=\"Ext.AbstractComponent-cfg-renderSelectors\" class=\"docClass\">renderSelectors</a> and <a href=\"#!/api/Ext.AbstractComponent-cfg-childEls\" rel=\"Ext.AbstractComponent-cfg-childEls\" class=\"docClass\">childEls</a> for usage examples.</p>\n</div></div></div><div id='cfg-renderSelectors' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-renderSelectors' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-renderSelectors' class='name expandable'>renderSelectors</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span></div><div class='description'><div class='short'>An object containing properties specifying DomQuery selectors which identify child elements\ncreated by the render pro...</div><div class='long'><p>An object containing properties specifying <a href=\"#!/api/Ext.dom.Query\" rel=\"Ext.dom.Query\" class=\"docClass\">DomQuery</a> selectors which identify child elements\ncreated by the render process.</p>\n\n<p>After the Component's internal structure is rendered according to the <a href=\"#!/api/Ext.AbstractComponent-cfg-renderTpl\" rel=\"Ext.AbstractComponent-cfg-renderTpl\" class=\"docClass\">renderTpl</a>, this object is iterated through,\nand the found Elements are added as properties to the Component using the <code>renderSelector</code> property name.</p>\n\n<p>For example, a Component which renders a title and description into its element:</p>\n\n<pre><code><a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>', {\n renderTo: <a href=\"#!/api/Ext-method-getBody\" rel=\"Ext-method-getBody\" class=\"docClass\">Ext.getBody</a>(),\n renderTpl: [\n '&lt;h1 class=\"title\"&gt;{title}&lt;/h1&gt;',\n '&lt;p&gt;{desc}&lt;/p&gt;'\n ],\n renderData: {\n title: \"Error\",\n desc: \"Something went wrong\"\n },\n renderSelectors: {\n titleEl: 'h1.title',\n descEl: 'p'\n },\n listeners: {\n afterrender: function(cmp){\n // After rendering the component will have a titleEl and descEl properties\n cmp.titleEl.setStyle({color: \"red\"});\n }\n }\n});\n</code></pre>\n\n<p>For a faster, but less flexible, alternative that achieves the same end result (properties for child elements on the\nComponent after render), see <a href=\"#!/api/Ext.AbstractComponent-cfg-childEls\" rel=\"Ext.AbstractComponent-cfg-childEls\" class=\"docClass\">childEls</a> and <a href=\"#!/api/Ext.AbstractComponent-method-addChildEls\" rel=\"Ext.AbstractComponent-method-addChildEls\" class=\"docClass\">addChildEls</a>.</p>\n</div></div></div><div id='cfg-renderTo' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-renderTo' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-renderTo' class='name expandable'>renderTo</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/HTMLElement/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a></span></div><div class='description'><div class='short'>Specify the id of the element, a DOM element or an existing Element that this component will be rendered into. ...</div><div class='long'><p>Specify the <code>id</code> of the element, a DOM element or an existing Element that this component will be rendered into.</p>\n\n<p><strong>Notes:</strong></p>\n\n<p>Do <em>not</em> use this option if the Component is to be a child item of a <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Container</a>.\nIt is the responsibility of the <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Container</a>'s\n<a href=\"#!/api/Ext.container.Container-cfg-layout\" rel=\"Ext.container.Container-cfg-layout\" class=\"docClass\">layout manager</a> to render and manage its child items.</p>\n\n<p>When using this config, a call to <code>render()</code> is not required.</p>\n\n<p>See also: <a href=\"#!/api/Ext.AbstractComponent-method-render\" rel=\"Ext.AbstractComponent-method-render\" class=\"docClass\">render</a>.</p>\n <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='cfg-renderTpl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-renderTpl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-renderTpl' class='name expandable'>renderTpl</a><span> : <a href=\"#!/api/Ext.XTemplate\" rel=\"Ext.XTemplate\" class=\"docClass\">Ext.XTemplate</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>[]</span><strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>An XTemplate used to create the internal structure inside this Component's encapsulating\nElement. ...</div><div class='long'><p>An <a href=\"#!/api/Ext.XTemplate\" rel=\"Ext.XTemplate\" class=\"docClass\">XTemplate</a> used to create the internal structure inside this Component's encapsulating\n<a href=\"#!/api/Ext.AbstractComponent-method-getEl\" rel=\"Ext.AbstractComponent-method-getEl\" class=\"docClass\">Element</a>.</p>\n\n<p>You do not normally need to specify this. For the base classes <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> and\n<a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a>, this defaults to <strong><code>null</code></strong> which means that they will be initially rendered\nwith no internal structure; they render their <a href=\"#!/api/Ext.AbstractComponent-method-getEl\" rel=\"Ext.AbstractComponent-method-getEl\" class=\"docClass\">Element</a> empty. The more specialized Ext JS and Sencha Touch\nclasses which use a more complex DOM structure, provide their own template definitions.</p>\n\n<p>This is intended to allow the developer to create application-specific utility Components with customized\ninternal structure.</p>\n\n<p>Upon rendering, any created child elements may be automatically imported into object properties using the\n<a href=\"#!/api/Ext.AbstractComponent-cfg-renderSelectors\" rel=\"Ext.AbstractComponent-cfg-renderSelectors\" class=\"docClass\">renderSelectors</a> and <a href=\"#!/api/Ext.AbstractComponent-cfg-childEls\" rel=\"Ext.AbstractComponent-cfg-childEls\" class=\"docClass\">childEls</a> options.</p>\n<p>Defaults to: <code>'{%this.renderContent(out,values)%}'</code></p></div></div></div><div id='cfg-resizable' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-resizable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-resizable' class='name expandable'>resizable</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span></div><div class='description'><div class='short'>Specify as true to apply a Resizer to this Component after rendering. ...</div><div class='long'><p>Specify as <code>true</code> to apply a <a href=\"#!/api/Ext.resizer.Resizer\" rel=\"Ext.resizer.Resizer\" class=\"docClass\">Resizer</a> to this Component after rendering.</p>\n\n<p>May also be specified as a config object to be passed to the constructor of <a href=\"#!/api/Ext.resizer.Resizer\" rel=\"Ext.resizer.Resizer\" class=\"docClass\">Resizer</a>\nto override any defaults. By default the Component passes its minimum and maximum size, and uses\n<code><a href=\"#!/api/Ext.resizer.Resizer-cfg-dynamic\" rel=\"Ext.resizer.Resizer-cfg-dynamic\" class=\"docClass\">Ext.resizer.Resizer.dynamic</a>: false</code></p>\n</div></div></div><div id='cfg-resizeHandles' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-resizeHandles' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-resizeHandles' class='name expandable'>resizeHandles</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>A valid Ext.resizer.Resizer handles config string. ...</div><div class='long'><p>A valid <a href=\"#!/api/Ext.resizer.Resizer\" rel=\"Ext.resizer.Resizer\" class=\"docClass\">Ext.resizer.Resizer</a> handles config string. Only applies when resizable = true.</p>\n<p>Defaults to: <code>'all'</code></p></div></div></div><div id='cfg-rtl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent2.html#Ext-AbstractComponent-cfg-rtl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-rtl' class='name expandable'>rtl</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>True to layout this component and its descendants in \"rtl\" (right-to-left) mode. ...</div><div class='long'><p>True to layout this component and its descendants in \"rtl\" (right-to-left) mode.\nCan be explicitly set to false to override a true value inherited from an ancestor.</p>\n\n<p><strong>Defined in override Ext.rtl.AbstractComponent.</strong></p>\n</div></div></div><div id='cfg-saveDelay' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-cfg-saveDelay' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-cfg-saveDelay' class='name expandable'>saveDelay</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span></div><div class='description'><div class='short'>A buffer to be applied if many state events are fired within a short period. ...</div><div class='long'><p>A buffer to be applied if many state events are fired within a short period.</p>\n<p>Defaults to: <code>100</code></p></div></div></div><div id='cfg-shadow' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-cfg-shadow' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-cfg-shadow' class='name expandable'>shadow</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>Specifies whether the floating component should be given a shadow. ...</div><div class='long'><p>Specifies whether the floating component should be given a shadow. Set to true to automatically create an\n<a href=\"#!/api/Ext.Shadow\" rel=\"Ext.Shadow\" class=\"docClass\">Ext.Shadow</a>, or a string indicating the shadow's display <a href=\"#!/api/Ext.Shadow-cfg-mode\" rel=\"Ext.Shadow-cfg-mode\" class=\"docClass\">Ext.Shadow.mode</a>. Set to false to\ndisable the shadow.</p>\n<p>Defaults to: <code>'sides'</code></p></div></div></div><div id='cfg-shadowOffset' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-cfg-shadowOffset' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-cfg-shadowOffset' class='name not-expandable'>shadowOffset</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span></div><div class='description'><div class='short'><p>Number of pixels to offset the shadow.</p>\n</div><div class='long'><p>Number of pixels to offset the shadow.</p>\n</div></div></div><div id='cfg-shrinkWrap' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-shrinkWrap' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-shrinkWrap' class='name expandable'>shrinkWrap</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span></div><div class='description'><div class='short'>If this property is a number, it is interpreted as follows:\n\n\n0: Neither width nor height depend on content. ...</div><div class='long'><p>If this property is a number, it is interpreted as follows:</p>\n\n<ul>\n<li>0: Neither width nor height depend on content. This is equivalent to <code>false</code>.</li>\n<li>1: Width depends on content (shrink wraps), but height does not.</li>\n<li>2: Height depends on content (shrink wraps), but width does not. The default.</li>\n<li>3: Both width and height depend on content (shrink wrap). This is equivalent to <code>true</code>.</li>\n</ul>\n\n\n<p>In CSS terms, shrink-wrap width is analogous to an inline-block element as opposed\nto a block-level element. Some container layouts always shrink-wrap their children,\neffectively ignoring this property (e.g., <a href=\"#!/api/Ext.layout.container.HBox\" rel=\"Ext.layout.container.HBox\" class=\"docClass\">Ext.layout.container.HBox</a>,\n<a href=\"#!/api/Ext.layout.container.VBox\" rel=\"Ext.layout.container.VBox\" class=\"docClass\">Ext.layout.container.VBox</a>, <a href=\"#!/api/Ext.layout.component.Dock\" rel=\"Ext.layout.component.Dock\" class=\"docClass\">Ext.layout.component.Dock</a>).</p>\n<p>Defaults to: <code>2</code></p></div></div></div><div id='cfg-stateEvents' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-cfg-stateEvents' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-cfg-stateEvents' class='name expandable'>stateEvents</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>[]</span></div><div class='description'><div class='short'>An array of events that, when fired, should trigger this object to\nsave its state. ...</div><div class='long'><p>An array of events that, when fired, should trigger this object to\nsave its state. Defaults to none. <code>stateEvents</code> may be any type\nof event supported by this object, including browser or custom events\n(e.g., <tt>['click', 'customerchange']</tt>).</p>\n\n\n<p>See <code><a href=\"#!/api/Ext.state.Stateful-cfg-stateful\" rel=\"Ext.state.Stateful-cfg-stateful\" class=\"docClass\">stateful</a></code> for an explanation of saving and\nrestoring object state.</p>\n\n</div></div></div><div id='cfg-stateId' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-cfg-stateId' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-cfg-stateId' class='name expandable'>stateId</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>The unique id for this object to use for state management purposes. ...</div><div class='long'><p>The unique id for this object to use for state management purposes.</p>\n\n<p>See <a href=\"#!/api/Ext.state.Stateful-cfg-stateful\" rel=\"Ext.state.Stateful-cfg-stateful\" class=\"docClass\">stateful</a> for an explanation of saving and restoring state.</p>\n\n</div></div></div><div id='cfg-stateful' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-cfg-stateful' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-cfg-stateful' class='name expandable'>stateful</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>A flag which causes the object to attempt to restore the state of\ninternal properties from a saved state on startup. ...</div><div class='long'><p>A flag which causes the object to attempt to restore the state of\ninternal properties from a saved state on startup. The object must have\na <a href=\"#!/api/Ext.state.Stateful-cfg-stateId\" rel=\"Ext.state.Stateful-cfg-stateId\" class=\"docClass\">stateId</a> for state to be managed.</p>\n\n<p>Auto-generated ids are not guaranteed to be stable across page loads and\ncannot be relied upon to save and restore the same state for a object.</p>\n\n<p>For state saving to work, the state manager's provider must have been\nset to an implementation of <a href=\"#!/api/Ext.state.Provider\" rel=\"Ext.state.Provider\" class=\"docClass\">Ext.state.Provider</a> which overrides the\n<a href=\"#!/api/Ext.state.Provider-method-set\" rel=\"Ext.state.Provider-method-set\" class=\"docClass\">set</a> and <a href=\"#!/api/Ext.state.Provider-method-get\" rel=\"Ext.state.Provider-method-get\" class=\"docClass\">get</a>\nmethods to save and recall name/value pairs. A built-in implementation,\n<a href=\"#!/api/Ext.state.CookieProvider\" rel=\"Ext.state.CookieProvider\" class=\"docClass\">Ext.state.CookieProvider</a> is available.</p>\n\n<p>To set the state provider for the current page:</p>\n\n<p> <a href=\"#!/api/Ext.state.Manager-method-setProvider\" rel=\"Ext.state.Manager-method-setProvider\" class=\"docClass\">Ext.state.Manager.setProvider</a>(new <a href=\"#!/api/Ext.state.CookieProvider\" rel=\"Ext.state.CookieProvider\" class=\"docClass\">Ext.state.CookieProvider</a>({</p>\n\n<pre><code> expires: new Date(new Date().getTime()+(1000*60*60*24*7)), //7 days from now\n</code></pre>\n\n<p> }));</p>\n\n<p>A stateful object attempts to save state when one of the events\nlisted in the <a href=\"#!/api/Ext.state.Stateful-cfg-stateEvents\" rel=\"Ext.state.Stateful-cfg-stateEvents\" class=\"docClass\">stateEvents</a> configuration fires.</p>\n\n<p>To save state, a stateful object first serializes its state by\ncalling <em><a href=\"#!/api/Ext.state.Stateful-method-getState\" rel=\"Ext.state.Stateful-method-getState\" class=\"docClass\">getState</a></em>.</p>\n\n<p>The Component base class implements <a href=\"#!/api/Ext.state.Stateful-method-getState\" rel=\"Ext.state.Stateful-method-getState\" class=\"docClass\">getState</a> to save its width and height within the state\nonly if they were initially configured, and have changed from the configured value.</p>\n\n<p>The Panel class saves its collapsed state in addition to that.</p>\n\n<p>The Grid class saves its column state in addition to its superclass state.</p>\n\n<p>If there is more application state to be save, the developer must provide an implementation which\nfirst calls the superclass method to inherit the above behaviour, and then injects new properties\ninto the returned object.</p>\n\n<p>The value yielded by getState is passed to <a href=\"#!/api/Ext.state.Manager-method-set\" rel=\"Ext.state.Manager-method-set\" class=\"docClass\">Ext.state.Manager.set</a>\nwhich uses the configured <a href=\"#!/api/Ext.state.Provider\" rel=\"Ext.state.Provider\" class=\"docClass\">Ext.state.Provider</a> to save the object\nkeyed by the <a href=\"#!/api/Ext.state.Stateful-cfg-stateId\" rel=\"Ext.state.Stateful-cfg-stateId\" class=\"docClass\">stateId</a>.</p>\n\n<p>During construction, a stateful object attempts to <em>restore</em> its state by calling\n<a href=\"#!/api/Ext.state.Manager-method-get\" rel=\"Ext.state.Manager-method-get\" class=\"docClass\">Ext.state.Manager.get</a> passing the <a href=\"#!/api/Ext.state.Stateful-cfg-stateId\" rel=\"Ext.state.Stateful-cfg-stateId\" class=\"docClass\">stateId</a></p>\n\n<p>The resulting object is passed to <a href=\"#!/api/Ext.state.Stateful-method-applyState\" rel=\"Ext.state.Stateful-method-applyState\" class=\"docClass\">applyState</a>*. The default implementation of\n<a href=\"#!/api/Ext.state.Stateful-method-applyState\" rel=\"Ext.state.Stateful-method-applyState\" class=\"docClass\">applyState</a> simply copies properties into the object, but a developer may\noverride this to support restoration of more complex application state.</p>\n\n<p>You can perform extra processing on state save and restore by attaching\nhandlers to the <a href=\"#!/api/Ext.state.Stateful-event-beforestaterestore\" rel=\"Ext.state.Stateful-event-beforestaterestore\" class=\"docClass\">beforestaterestore</a>, <a href=\"#!/api/Ext.state.Stateful-event-staterestore\" rel=\"Ext.state.Stateful-event-staterestore\" class=\"docClass\">staterestore</a>,\n<a href=\"#!/api/Ext.state.Stateful-event-beforestatesave\" rel=\"Ext.state.Stateful-event-beforestatesave\" class=\"docClass\">beforestatesave</a> and <a href=\"#!/api/Ext.state.Stateful-event-statesave\" rel=\"Ext.state.Stateful-event-statesave\" class=\"docClass\">statesave</a> events.</p>\n<p>Defaults to: <code>false</code></p></div></div></div><div id='cfg-style' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-style' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-style' class='name expandable'>style</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span></div><div class='description'><div class='short'>A custom style specification to be applied to this component's Element. ...</div><div class='long'><p>A custom style specification to be applied to this component's Element. Should be a valid argument to\n<a href=\"#!/api/Ext.dom.Element-method-applyStyles\" rel=\"Ext.dom.Element-method-applyStyles\" class=\"docClass\">Ext.Element.applyStyles</a>.</p>\n\n<pre><code>new <a href=\"#!/api/Ext.panel.Panel\" rel=\"Ext.panel.Panel\" class=\"docClass\">Ext.panel.Panel</a>({\n title: 'Some Title',\n renderTo: <a href=\"#!/api/Ext-method-getBody\" rel=\"Ext-method-getBody\" class=\"docClass\">Ext.getBody</a>(),\n width: 400, height: 300,\n layout: 'form',\n items: [{\n xtype: 'textarea',\n style: {\n width: '95%',\n marginBottom: '10px'\n }\n },\n new <a href=\"#!/api/Ext.button.Button\" rel=\"Ext.button.Button\" class=\"docClass\">Ext.button.Button</a>({\n text: 'Send',\n minWidth: '100',\n style: {\n marginBottom: '10px'\n }\n })\n ]\n});\n</code></pre>\n <p>Available since: <b>1.1.0</b></p>\n</div></div></div><div id='cfg-toFrontOnShow' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-cfg-toFrontOnShow' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-cfg-toFrontOnShow' class='name expandable'>toFrontOnShow</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>True to automatically call toFront when the show method is called on an already visible,\nfloating component. ...</div><div class='long'><p>True to automatically call <a href=\"#!/api/Ext.Component-method-toFront\" rel=\"Ext.Component-method-toFront\" class=\"docClass\">toFront</a> when the <a href=\"#!/api/Ext.Component-method-show\" rel=\"Ext.Component-method-show\" class=\"docClass\">show</a> method is called on an already visible,\nfloating component.</p>\n<p>Defaults to: <code>true</code></p></div></div></div><div id='cfg-tpl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-tpl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-tpl' class='name expandable'>tpl</a><span> : <a href=\"#!/api/Ext.XTemplate\" rel=\"Ext.XTemplate\" class=\"docClass\">Ext.XTemplate</a>/<a href=\"#!/api/Ext.Template\" rel=\"Ext.Template\" class=\"docClass\">Ext.Template</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>[]</span></div><div class='description'><div class='short'>An Ext.Template, Ext.XTemplate or an array of strings to form an Ext.XTemplate. ...</div><div class='long'><p>An <a href=\"#!/api/Ext.Template\" rel=\"Ext.Template\" class=\"docClass\">Ext.Template</a>, <a href=\"#!/api/Ext.XTemplate\" rel=\"Ext.XTemplate\" class=\"docClass\">Ext.XTemplate</a> or an array of strings to form an <a href=\"#!/api/Ext.XTemplate\" rel=\"Ext.XTemplate\" class=\"docClass\">Ext.XTemplate</a>. Used in\nconjunction with the <code><a href=\"#!/api/Ext.AbstractComponent-cfg-data\" rel=\"Ext.AbstractComponent-cfg-data\" class=\"docClass\">data</a></code> and <code><a href=\"#!/api/Ext.AbstractComponent-cfg-tplWriteMode\" rel=\"Ext.AbstractComponent-cfg-tplWriteMode\" class=\"docClass\">tplWriteMode</a></code> configurations.</p>\n <p>Available since: <b>3.4.0</b></p>\n</div></div></div><div id='cfg-tplWriteMode' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-tplWriteMode' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-tplWriteMode' class='name expandable'>tplWriteMode</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>The Ext.(X)Template method to use when updating the content area of the Component. ...</div><div class='long'><p>The Ext.(X)Template method to use when updating the content area of the Component.\nSee <code><a href=\"#!/api/Ext.XTemplate-method-overwrite\" rel=\"Ext.XTemplate-method-overwrite\" class=\"docClass\">Ext.XTemplate.overwrite</a></code> for information on default mode.</p>\n<p>Defaults to: <code>'overwrite'</code></p> <p>Available since: <b>3.4.0</b></p>\n</div></div></div><div id='cfg-ui' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-ui' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-ui' class='name expandable'>ui</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>A UI style for a component. ...</div><div class='long'><p>A UI style for a component.</p>\n<p>Defaults to: <code>'default'</code></p></div></div></div><div id='cfg-uiCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-uiCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-uiCls' class='name expandable'>uiCls</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>[]</span><strong class='private signature' >private</strong></div><div class='description'><div class='short'>An array of of classNames which are currently applied to this component. ...</div><div class='long'><p>An array of of <code>classNames</code> which are currently applied to this component.</p>\n<p>Defaults to: <code>[]</code></p></div></div></div><div id='cfg-width' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-width' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-width' class='name not-expandable'>width</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span></div><div class='description'><div class='short'><p>The width of this component in pixels.</p>\n</div><div class='long'><p>The width of this component in pixels.</p>\n</div></div></div><div id='cfg-xtype' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-cfg-xtype' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-cfg-xtype' class='name expandable'>xtype</a><span> : <a href=\"#!/api/Ext.enums.Widget\" rel=\"Ext.enums.Widget\" class=\"docClass\">Ext.enums.Widget</a></span></div><div class='description'><div class='short'>This property provides a shorter alternative to creating objects than using a full\nclass name. ...</div><div class='long'><p>This property provides a shorter alternative to creating objects than using a full\nclass name. Using <code>xtype</code> is the most common way to define component instances,\nespecially in a container. For example, the items in a form containing text fields\ncould be created explicitly like so:</p>\n\n<pre><code> items: [\n <a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.form.field.Text\" rel=\"Ext.form.field.Text\" class=\"docClass\">Ext.form.field.Text</a>', {\n fieldLabel: 'Foo'\n }),\n <a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.form.field.Text\" rel=\"Ext.form.field.Text\" class=\"docClass\">Ext.form.field.Text</a>', {\n fieldLabel: 'Bar'\n }),\n <a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.form.field.Number\" rel=\"Ext.form.field.Number\" class=\"docClass\">Ext.form.field.Number</a>', {\n fieldLabel: 'Num'\n })\n ]\n</code></pre>\n\n<p>But by using <code>xtype</code>, the above becomes:</p>\n\n<pre><code> items: [\n {\n xtype: 'textfield',\n fieldLabel: 'Foo'\n },\n {\n xtype: 'textfield',\n fieldLabel: 'Bar'\n },\n {\n xtype: 'numberfield',\n fieldLabel: 'Num'\n }\n ]\n</code></pre>\n\n<p>When the <code>xtype</code> is common to many items, <a href=\"#!/api/Ext.container.AbstractContainer-cfg-defaultType\" rel=\"Ext.container.AbstractContainer-cfg-defaultType\" class=\"docClass\">Ext.container.AbstractContainer.defaultType</a>\nis another way to specify the <code>xtype</code> for all items that don't have an explicit <code>xtype</code>:</p>\n\n<pre><code> defaultType: 'textfield',\n items: [\n { fieldLabel: 'Foo' },\n { fieldLabel: 'Bar' },\n { fieldLabel: 'Num', xtype: 'numberfield' }\n ]\n</code></pre>\n\n<p>Each member of the <code>items</code> array is now just a \"configuration object\". These objects\nare used to create and configure component instances. A configuration object can be\nmanually used to instantiate a component using <a href=\"#!/api/Ext-method-widget\" rel=\"Ext-method-widget\" class=\"docClass\">Ext.widget</a>:</p>\n\n<pre><code> var text1 = <a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.form.field.Text\" rel=\"Ext.form.field.Text\" class=\"docClass\">Ext.form.field.Text</a>', {\n fieldLabel: 'Foo'\n });\n\n // or alternatively:\n\n var text1 = <a href=\"#!/api/Ext-method-widget\" rel=\"Ext-method-widget\" class=\"docClass\">Ext.widget</a>({\n xtype: 'textfield',\n fieldLabel: 'Foo'\n });\n</code></pre>\n\n<p>This conversion of configuration objects into instantiated components is done when\na container is created as part of its {<a href=\"#!/api/Ext.container.AbstractContainer-method-initComponent\" rel=\"Ext.container.AbstractContainer-method-initComponent\" class=\"docClass\">Ext.container.AbstractContainer.initComponent</a>}\nprocess. As part of the same process, the <code>items</code> array is converted from its raw\narray form into a <a href=\"#!/api/Ext.util.MixedCollection\" rel=\"Ext.util.MixedCollection\" class=\"docClass\">Ext.util.MixedCollection</a> instance.</p>\n\n<p>You can define your own <code>xtype</code> on a custom <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">component</a> by specifying\nthe <code>xtype</code> property in <a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>. For example:</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('MyApp.PressMeButton', {\n extend: '<a href=\"#!/api/Ext.button.Button\" rel=\"Ext.button.Button\" class=\"docClass\">Ext.button.Button</a>',\n xtype: 'pressmebutton',\n text: 'Press Me'\n});\n</code></pre>\n\n<p>Care should be taken when naming an <code>xtype</code> in a custom component because there is\na single, shared scope for all xtypes. Third part components should consider using\na prefix to avoid collisions.</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('Foo.form.CoolButton', {\n extend: '<a href=\"#!/api/Ext.button.Button\" rel=\"Ext.button.Button\" class=\"docClass\">Ext.button.Button</a>',\n xtype: 'ux-coolbutton',\n text: 'Cool!'\n});\n</code></pre>\n\n<p>See <a href=\"#!/api/Ext.enums.Widget\" rel=\"Ext.enums.Widget\" class=\"docClass\">Ext.enums.Widget</a> for list of all available xtypes.</p>\n <p>Available since: <b>2.3.0</b></p>\n</div></div></div></div></div><div class='members-section'><h3 class='members-title icon-property'>Properties</h3><div class='subsection'><div class='definedBy'>Defined By</div><h4 class='members-subtitle'>Instance Properties</h3><div id='property-S-className' class='member first-child inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-property-S-className' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-property-S-className' class='name expandable'>$className</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>'Ext.Base'</code></p></div></div></div><div id='property-_alignRe' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-property-_alignRe' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-property-_alignRe' class='name expandable'>_alignRe</a><span> : <a href=\"#!/api/RegExp\" rel=\"RegExp\" class=\"docClass\">RegExp</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>/^([a-z]+)-([a-z]+)(\\?)?$/</code></p></div></div></div><div id='property-_isLayoutRoot' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-_isLayoutRoot' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-_isLayoutRoot' class='name expandable'>_isLayoutRoot</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Setting this property to true causes the isLayoutRoot method to return\ntrue and stop the search for the top-most comp...</div><div class='long'><p>Setting this property to <code>true</code> causes the <a href=\"#!/api/Ext.AbstractComponent-method-isLayoutRoot\" rel=\"Ext.AbstractComponent-method-isLayoutRoot\" class=\"docClass\">isLayoutRoot</a> method to return\n<code>true</code> and stop the search for the top-most component for a layout.</p>\n<p>Defaults to: <code>false</code></p></div></div></div><div id='property-_positionTopLeft' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-property-_positionTopLeft' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-property-_positionTopLeft' class='name expandable'>_positionTopLeft</a><span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>['position', 'top', 'left']</code></p></div></div></div><div id='property-allowDomMove' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-allowDomMove' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-allowDomMove' class='name expandable'>allowDomMove</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>true</code></p></div></div></div><div id='property-autoGenId' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-autoGenId' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-autoGenId' class='name expandable'>autoGenId</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'>true indicates an id was auto-generated rather than provided by configuration. ...</div><div class='long'><p><code>true</code> indicates an <code>id</code> was auto-generated rather than provided by configuration.</p>\n<p>Defaults to: <code>false</code></p></div></div></div><div id='property-borderBoxCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-borderBoxCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-borderBoxCls' class='name expandable'>borderBoxCls</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'>private ...</div><div class='long'><p>private</p>\n<p>Defaults to: <code>Ext.baseCSSPrefix + 'border-box'</code></p></div></div></div><div id='property-bubbleEvents' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-property-bubbleEvents' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-property-bubbleEvents' class='name expandable'>bubbleEvents</a><span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>[]</code></p></div></div></div><div id='property-childEls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.ElementContainer' rel='Ext.util.ElementContainer' class='defined-in docClass'>Ext.util.ElementContainer</a><br/><a href='source/ElementContainer.html#Ext-util-ElementContainer-property-childEls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.ElementContainer-property-childEls' class='name expandable'>childEls</a><span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>[]</code></p></div></div></div><div id='property-componentLayoutCounter' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-componentLayoutCounter' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-componentLayoutCounter' class='name expandable'>componentLayoutCounter</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'>The number of component layout calls made on this object. ...</div><div class='long'><p>The number of component layout calls made on this object.</p>\n<p>Defaults to: <code>0</code></p></div></div></div><div id='property-configMap' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-property-configMap' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-property-configMap' class='name expandable'>configMap</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>{}</code></p></div></div></div><div id='property-contentPaddingProperty' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-contentPaddingProperty' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-contentPaddingProperty' class='name expandable'>contentPaddingProperty</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span></div><div class='description'><div class='short'>The name of the padding property that is used by the layout to manage\npadding. ...</div><div class='long'><p>The name of the padding property that is used by the layout to manage\npadding. See <a href=\"#!/api/Ext.layout.container.Auto-property-managePadding\" rel=\"Ext.layout.container.Auto-property-managePadding\" class=\"docClass\">managePadding</a></p>\n<p>Defaults to: <code>'padding'</code></p></div></div></div><div id='property-convertPositionSpec' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-property-convertPositionSpec' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-property-convertPositionSpec' class='name expandable'>convertPositionSpec</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'>By default this method does nothing but return the position spec passed to it. ...</div><div class='long'><p>By default this method does nothing but return the position spec passed to it. In\nrtl mode it is overridden to convert \"l\" to \"r\" and vice versa when required.</p>\n</div></div></div><div id='property-defaultComponentLayoutType' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-property-defaultComponentLayoutType' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-property-defaultComponentLayoutType' class='name expandable'>defaultComponentLayoutType</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>'autocomponent'</code></p></div></div></div><div id='property-deferLayouts' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-deferLayouts' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-deferLayouts' class='name expandable'>deferLayouts</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>false</code></p></div></div></div><div id='property-draggable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-draggable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-draggable' class='name expandable'>draggable</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><strong class='readonly signature' >readonly</strong></div><div class='description'><div class='short'>Indicates whether or not the component can be dragged. ...</div><div class='long'><p>Indicates whether or not the component can be dragged.</p>\n<p>Defaults to: <code>false</code></p></div></div></div><div id='property-eventsSuspended' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-property-eventsSuspended' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-property-eventsSuspended' class='name expandable'>eventsSuspended</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Initial suspended call count. ...</div><div class='long'><p>Initial suspended call count. Incremented when <a href=\"#!/api/Ext.util.Observable-method-suspendEvents\" rel=\"Ext.util.Observable-method-suspendEvents\" class=\"docClass\">suspendEvents</a> is called, decremented when <a href=\"#!/api/Ext.util.Observable-method-resumeEvents\" rel=\"Ext.util.Observable-method-resumeEvents\" class=\"docClass\">resumeEvents</a> is called.</p>\n<p>Defaults to: <code>0</code></p></div></div></div><div id='property-floatParent' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-property-floatParent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-property-floatParent' class='name expandable'>floatParent</a><span> : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.Container</a></span><strong class='readonly signature' >readonly</strong></div><div class='description'><div class='short'>Only present for floating Components which were inserted as child items of Containers. ...</div><div class='long'><p><strong>Only present for <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a> Components which were inserted as child items of Containers.</strong></p>\n\n<p>There are other similar relationships such as the <a href=\"#!/api/Ext.button.Button\" rel=\"Ext.button.Button\" class=\"docClass\">button</a> which activates a <a href=\"#!/api/Ext.button.Button-cfg-menu\" rel=\"Ext.button.Button-cfg-menu\" class=\"docClass\">menu</a>, or the\n<a href=\"#!/api/Ext.menu.Item\" rel=\"Ext.menu.Item\" class=\"docClass\">menu item</a> which activated a <a href=\"#!/api/Ext.menu.Item-cfg-menu\" rel=\"Ext.menu.Item-cfg-menu\" class=\"docClass\">submenu</a>, or the\n<a href=\"#!/api/Ext.grid.column.Column\" rel=\"Ext.grid.column.Column\" class=\"docClass\">column header</a> which activated the column menu.</p>\n\n<p>These differences are abstracted away by the <a href=\"#!/api/Ext.Component-method-up\" rel=\"Ext.Component-method-up\" class=\"docClass\">up</a> method.</p>\n\n<p>Floating Components that are programatically <a href=\"#!/api/Ext.Component-method-render\" rel=\"Ext.Component-method-render\" class=\"docClass\">rendered</a> will not have a <code>floatParent</code>\nproperty.</p>\n\n<p>See <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a> and <a href=\"#!/api/Ext.Component-property-zIndexManager\" rel=\"Ext.Component-property-zIndexManager\" class=\"docClass\">zIndexManager</a></p>\n</div></div></div><div id='property-frameCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-property-frameCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-property-frameCls' class='name expandable'>frameCls</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>Ext.baseCSSPrefix + 'frame'</code></p></div></div></div><div id='property-frameElNames' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-property-frameElNames' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-property-frameElNames' class='name expandable'>frameElNames</a><span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>['TL', 'TC', 'TR', 'ML', 'MC', 'MR', 'BL', 'BC', 'BR']</code></p></div></div></div><div id='property-frameElementsArray' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-frameElementsArray' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-frameElementsArray' class='name expandable'>frameElementsArray</a><span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>['tl', 'tc', 'tr', 'ml', 'mc', 'mr', 'bl', 'bc', 'br']</code></p></div></div></div><div id='property-frameIdRegex' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-property-frameIdRegex' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-property-frameIdRegex' class='name expandable'>frameIdRegex</a><span> : <a href=\"#!/api/RegExp\" rel=\"RegExp\" class=\"docClass\">RegExp</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>/[\\-]frame\\d+[TMB][LCR]$/</code></p></div></div></div><div id='property-frameInfoCache' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-property-frameInfoCache' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-property-frameInfoCache' class='name expandable'>frameInfoCache</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Cache the frame information object so as not to cause style recalculations ...</div><div class='long'><p>Cache the frame information object so as not to cause style recalculations</p>\n<p>Defaults to: <code>{}</code></p></div></div></div><div id='property-frameSize' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-frameSize' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-frameSize' class='name expandable'>frameSize</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><strong class='readonly signature' >readonly</strong></div><div class='description'><div class='short'>Indicates the width of any framing elements which were added within the encapsulating\nelement to provide graphical, r...</div><div class='long'><p>Indicates the width of any framing elements which were added within the encapsulating\nelement to provide graphical, rounded borders. See the <a href=\"#!/api/Ext.AbstractComponent-cfg-frame\" rel=\"Ext.AbstractComponent-cfg-frame\" class=\"docClass\">frame</a> config. This\nproperty is <code>null</code> if the component is not framed.</p>\n\n<p>This is an object containing the frame width in pixels for all four sides of the\nComponent containing the following properties:</p>\n<ul><li><span class='pre'>top</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>The width of the top framing element in pixels.</p>\n<p>Defaults to: <code>0</code></p></div></li><li><span class='pre'>right</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>The width of the right framing element in pixels.</p>\n<p>Defaults to: <code>0</code></p></div></li><li><span class='pre'>bottom</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>The width of the bottom framing element in pixels.</p>\n<p>Defaults to: <code>0</code></p></div></li><li><span class='pre'>left</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>The width of the left framing element in pixels.</p>\n<p>Defaults to: <code>0</code></p></div></li><li><span class='pre'>width</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>The total width of the left and right framing elements in pixels.</p>\n<p>Defaults to: <code>0</code></p></div></li><li><span class='pre'>height</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>The total height of the top and right bottom elements in pixels.</p>\n<p>Defaults to: <code>0</code></p></div></li></ul></div></div></div><div id='property-frameTableTpl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-property-frameTableTpl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-property-frameTableTpl' class='name not-expandable'>frameTableTpl</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'>\n</div><div class='long'>\n</div></div></div><div id='property-frameTpl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-property-frameTpl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-property-frameTpl' class='name expandable'>frameTpl</a><span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>['{%this.renderDockedItems(out,values,0);%}', '&lt;tpl if=&quot;top&quot;&gt;', '&lt;tpl if=&quot;left&quot;&gt;&lt;div id=&quot;{fgid}TL&quot; class=&quot;{frameCls}-tl {baseCls}-tl {baseCls}-{ui}-tl&lt;tpl for=&quot;uiCls&quot;&gt; {parent.baseCls}-{parent.ui}-{.}-tl&lt;/tpl&gt;{frameElCls}&quot; role=&quot;presentation&quot;&gt;&lt;/tpl&gt;', '&lt;tpl if=&quot;right&quot;&gt;&lt;div id=&quot;{fgid}TR&quot; class=&quot;{frameCls}-tr {baseCls}-tr {baseCls}-{ui}-tr&lt;tpl for=&quot;uiCls&quot;&gt; {parent.baseCls}-{parent.ui}-{.}-tr&lt;/tpl&gt;{frameElCls}&quot; role=&quot;presentation&quot;&gt;&lt;/tpl&gt;', '&lt;div id=&quot;{fgid}TC&quot; class=&quot;{frameCls}-tc {baseCls}-tc {baseCls}-{ui}-tc&lt;tpl for=&quot;uiCls&quot;&gt; {parent.baseCls}-{parent.ui}-{.}-tc&lt;/tpl&gt;{frameElCls}&quot; role=&quot;presentation&quot;&gt;&lt;/div&gt;', '&lt;tpl if=&quot;right&quot;&gt;&lt;/div&gt;&lt;/tpl&gt;', '&lt;tpl if=&quot;left&quot;&gt;&lt;/div&gt;&lt;/tpl&gt;', '&lt;/tpl&gt;', '&lt;tpl if=&quot;left&quot;&gt;&lt;div id=&quot;{fgid}ML&quot; class=&quot;{frameCls}-ml {baseCls}-ml {baseCls}-{ui}-ml&lt;tpl for=&quot;uiCls&quot;&gt; {parent.baseCls}-{parent.ui}-{.}-ml&lt;/tpl&gt;{frameElCls}&quot; role=&quot;presentation&quot;&gt;&lt;/tpl&gt;', '&lt;tpl if=&quot;right&quot;&gt;&lt;div id=&quot;{fgid}MR&quot; class=&quot;{frameCls}-mr {baseCls}-mr {baseCls}-{ui}-mr&lt;tpl for=&quot;uiCls&quot;&gt; {parent.baseCls}-{parent.ui}-{.}-mr&lt;/tpl&gt;{frameElCls}&quot; role=&quot;presentation&quot;&gt;&lt;/tpl&gt;', '&lt;div id=&quot;{fgid}MC&quot; class=&quot;{frameCls}-mc {baseCls}-mc {baseCls}-{ui}-mc&lt;tpl for=&quot;uiCls&quot;&gt; {parent.baseCls}-{parent.ui}-{.}-mc&lt;/tpl&gt;{frameElCls}&quot; role=&quot;presentation&quot;&gt;', '{%this.applyRenderTpl(out, values)%}', '&lt;/div&gt;', '&lt;tpl if=&quot;right&quot;&gt;&lt;/div&gt;&lt;/tpl&gt;', '&lt;tpl if=&quot;left&quot;&gt;&lt;/div&gt;&lt;/tpl&gt;', '&lt;tpl if=&quot;bottom&quot;&gt;', '&lt;tpl if=&quot;left&quot;&gt;&lt;div id=&quot;{fgid}BL&quot; class=&quot;{frameCls}-bl {baseCls}-bl {baseCls}-{ui}-bl&lt;tpl for=&quot;uiCls&quot;&gt; {parent.baseCls}-{parent.ui}-{.}-bl&lt;/tpl&gt;{frameElCls}&quot; role=&quot;presentation&quot;&gt;&lt;/tpl&gt;', '&lt;tpl if=&quot;right&quot;&gt;&lt;div id=&quot;{fgid}BR&quot; class=&quot;{frameCls}-br {baseCls}-br {baseCls}-{ui}-br&lt;tpl for=&quot;uiCls&quot;&gt; {parent.baseCls}-{parent.ui}-{.}-br&lt;/tpl&gt;{frameElCls}&quot; role=&quot;presentation&quot;&gt;&lt;/tpl&gt;', '&lt;div id=&quot;{fgid}BC&quot; class=&quot;{frameCls}-bc {baseCls}-bc {baseCls}-{ui}-bc&lt;tpl for=&quot;uiCls&quot;&gt; {parent.baseCls}-{parent.ui}-{.}-bc&lt;/tpl&gt;{frameElCls}&quot; role=&quot;presentation&quot;&gt;&lt;/div&gt;', '&lt;tpl if=&quot;right&quot;&gt;&lt;/div&gt;&lt;/tpl&gt;', '&lt;tpl if=&quot;left&quot;&gt;&lt;/div&gt;&lt;/tpl&gt;', '&lt;/tpl&gt;', '{%this.renderDockedItems(out,values,1);%}']</code></p></div></div></div><div id='property-hasListeners' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-property-hasListeners' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-property-hasListeners' class='name expandable'>hasListeners</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><strong class='readonly signature' >readonly</strong></div><div class='description'><div class='short'>This object holds a key for any event that has a listener. ...</div><div class='long'><p>This object holds a key for any event that has a listener. The listener may be set\ndirectly on the instance, or on its class or a super class (via <a href=\"#!/api/Ext.util.Observable-static-method-observe\" rel=\"Ext.util.Observable-static-method-observe\" class=\"docClass\">observe</a>) or\non the <a href=\"#!/api/Ext.app.EventBus\" rel=\"Ext.app.EventBus\" class=\"docClass\">MVC EventBus</a>. The values of this object are truthy\n(a non-zero number) and falsy (0 or undefined). They do not represent an exact count\nof listeners. The value for an event is truthy if the event must be fired and is\nfalsy if there is no need to fire the event.</p>\n\n<p>The intended use of this property is to avoid the expense of fireEvent calls when\nthere are no listeners. This can be particularly helpful when one would otherwise\nhave to call fireEvent hundreds or thousands of times. It is used like this:</p>\n\n<pre><code> if (this.hasListeners.foo) {\n this.fireEvent('foo', this, arg1);\n }\n</code></pre>\n</div></div></div><div id='property-horizontalPosProp' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-horizontalPosProp' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-horizontalPosProp' class='name expandable'>horizontalPosProp</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>'left'</code></p></div></div></div><div id='property-initConfigList' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-property-initConfigList' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-property-initConfigList' class='name expandable'>initConfigList</a><span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>[]</code></p></div></div></div><div id='property-initConfigMap' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-property-initConfigMap' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-property-initConfigMap' class='name expandable'>initConfigMap</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>{}</code></p></div></div></div><div id='property-isAnimate' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Animate' rel='Ext.util.Animate' class='defined-in docClass'>Ext.util.Animate</a><br/><a href='source/Animate.html#Ext-util-Animate-property-isAnimate' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Animate-property-isAnimate' class='name expandable'>isAnimate</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>true</code></p></div></div></div><div id='property-isComponent' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-isComponent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-isComponent' class='name expandable'>isComponent</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>true in this class to identify an object as an instantiated Component, or subclass thereof. ...</div><div class='long'><p><code>true</code> in this class to identify an object as an instantiated Component, or subclass thereof.</p>\n<p>Defaults to: <code>true</code></p></div></div></div><div id='property-isInstance' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-property-isInstance' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-property-isInstance' class='name expandable'>isInstance</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>true</code></p></div></div></div><div id='property-isObservable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-property-isObservable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-property-isObservable' class='name expandable'>isObservable</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>true in this class to identify an object as an instantiated Observable, or subclass thereof. ...</div><div class='long'><p><code>true</code> in this class to identify an object as an instantiated Observable, or subclass thereof.</p>\n<p>Defaults to: <code>true</code></p></div></div></div><div id='property-layoutSuspendCount' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-layoutSuspendCount' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-layoutSuspendCount' class='name expandable'>layoutSuspendCount</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>0</code></p></div></div></div><div id='property-maskOnDisable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-maskOnDisable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-maskOnDisable' class='name expandable'>maskOnDisable</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span></div><div class='description'><div class='short'>This is an internal flag that you use when creating custom components. ...</div><div class='long'><p>This is an internal flag that you use when creating custom components. By default this is set to <code>true</code> which means\nthat every component gets a mask when it's disabled. Components like FieldContainer, FieldSet, Field, Button, Tab\noverride this property to <code>false</code> since they want to implement custom disable logic.</p>\n<p>Defaults to: <code>true</code></p></div></div></div><div id='property-offsetsCls' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-property-offsetsCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-property-offsetsCls' class='name expandable'>offsetsCls</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>Ext.baseCSSPrefix + 'hide-offsets'</code></p></div></div></div><div id='property-ownerCt' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-ownerCt' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-ownerCt' class='name expandable'>ownerCt</a><span> : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.Container</a></span><strong class='readonly signature' >readonly</strong></div><div class='description'><div class='short'>This Component's owner Container (is set automatically\nwhen this Component is added to a Container). ...</div><div class='long'><p>This Component's owner <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Container</a> (is set automatically\nwhen this Component is added to a Container).</p>\n\n<p><em>Important.</em> This is not a universal upwards navigation pointer. It indicates the Container which owns and manages\nthis Component if any. There are other similar relationships such as the <a href=\"#!/api/Ext.button.Button\" rel=\"Ext.button.Button\" class=\"docClass\">button</a> which activates a <a href=\"#!/api/Ext.button.Button-cfg-menu\" rel=\"Ext.button.Button-cfg-menu\" class=\"docClass\">menu</a>, or the\n<a href=\"#!/api/Ext.menu.Item\" rel=\"Ext.menu.Item\" class=\"docClass\">menu item</a> which activated a <a href=\"#!/api/Ext.menu.Item-cfg-menu\" rel=\"Ext.menu.Item-cfg-menu\" class=\"docClass\">submenu</a>, or the\n<a href=\"#!/api/Ext.grid.column.Column\" rel=\"Ext.grid.column.Column\" class=\"docClass\">column header</a> which activated the column menu.</p>\n\n<p>These differences are abstracted away by the <a href=\"#!/api/Ext.AbstractComponent-method-up\" rel=\"Ext.AbstractComponent-method-up\" class=\"docClass\">up</a> method.</p>\n\n<p><strong>Note</strong>: to access items within the Container see <a href=\"#!/api/Ext.AbstractComponent-cfg-itemId\" rel=\"Ext.AbstractComponent-cfg-itemId\" class=\"docClass\">itemId</a>.</p>\n <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='property-rendered' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-rendered' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-rendered' class='name expandable'>rendered</a><span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><strong class='readonly signature' >readonly</strong></div><div class='description'><div class='short'>Indicates whether or not the component has been rendered. ...</div><div class='long'><p>Indicates whether or not the component has been rendered.</p>\n<p>Defaults to: <code>false</code></p> <p>Available since: <b>1.1.0</b></p>\n</div></div></div><div id='property-scrollFlags' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/AbstractComponent.html#Ext-Component-property-scrollFlags' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-property-scrollFlags' class='name expandable'>scrollFlags</a><span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><strong class='readonly signature' >readonly</strong></div><div class='description'><div class='short'>An object property which provides unified information as to which dimensions are scrollable based upon\nthe autoScroll...</div><div class='long'><p>An object property which provides unified information as to which dimensions are scrollable based upon\nthe <a href=\"#!/api/Ext.Component-cfg-autoScroll\" rel=\"Ext.Component-cfg-autoScroll\" class=\"docClass\">autoScroll</a>, <a href=\"#!/api/Ext.Component-cfg-overflowX\" rel=\"Ext.Component-cfg-overflowX\" class=\"docClass\">overflowX</a> and <a href=\"#!/api/Ext.Component-cfg-overflowY\" rel=\"Ext.Component-cfg-overflowY\" class=\"docClass\">overflowY</a> settings (And for <em>views</em> of trees and grids, the owning panel's <a href=\"#!/api/Ext.panel.Table-cfg-scroll\" rel=\"Ext.panel.Table-cfg-scroll\" class=\"docClass\">scroll</a> setting).</p>\n\n<p>Note that if you set overflow styles using the <a href=\"#!/api/Ext.Component-cfg-style\" rel=\"Ext.Component-cfg-style\" class=\"docClass\">style</a> config or <a href=\"#!/api/Ext.panel.Panel-cfg-bodyStyle\" rel=\"Ext.panel.Panel-cfg-bodyStyle\" class=\"docClass\">bodyStyle</a> config, this object does not include that information;\nit is best to use <a href=\"#!/api/Ext.Component-cfg-autoScroll\" rel=\"Ext.Component-cfg-autoScroll\" class=\"docClass\">autoScroll</a>, <a href=\"#!/api/Ext.Component-cfg-overflowX\" rel=\"Ext.Component-cfg-overflowX\" class=\"docClass\">overflowX</a> and <a href=\"#!/api/Ext.Component-cfg-overflowY\" rel=\"Ext.Component-cfg-overflowY\" class=\"docClass\">overflowY</a> if you need to access these flags.</p>\n\n<p>This object has the following properties:</p>\n<ul><li><span class='pre'>x</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p><code>true</code> if this Component is scrollable horizontally - style setting may be <code>'auto'</code> or <code>'scroll'</code>.</p>\n</div></li><li><span class='pre'>y</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p><code>true</code> if this Component is scrollable vertically - style setting may be <code>'auto'</code> or <code>'scroll'</code>.</p>\n</div></li><li><span class='pre'>both</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p><code>true</code> if this Component is scrollable both horizontally and vertically.</p>\n</div></li><li><span class='pre'>overflowX</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The <code>overflow-x</code> style setting, <code>'auto'</code> or <code>'scroll'</code> or <code>''</code>.</p>\n</div></li><li><span class='pre'>overflowY</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The <code>overflow-y</code> style setting, <code>'auto'</code> or <code>'scroll'</code> or <code>''</code>.</p>\n</div></li></ul></div></div></div><div id='property-self' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-property-self' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-property-self' class='name expandable'>self</a><span> : <a href=\"#!/api/Ext.Class\" rel=\"Ext.Class\" class=\"docClass\">Ext.Class</a></span><strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Get the reference to the current class from which this object was instantiated. ...</div><div class='long'><p>Get the reference to the current class from which this object was instantiated. Unlike <a href=\"#!/api/Ext.Base-method-statics\" rel=\"Ext.Base-method-statics\" class=\"docClass\">statics</a>,\n<code>this.self</code> is scope-dependent and it's meant to be used for dynamic inheritance. See <a href=\"#!/api/Ext.Base-method-statics\" rel=\"Ext.Base-method-statics\" class=\"docClass\">statics</a>\nfor a detailed comparison</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.Cat', {\n statics: {\n speciesName: 'Cat' // My.Cat.speciesName = 'Cat'\n },\n\n constructor: function() {\n alert(this.self.speciesName); // dependent on 'this'\n },\n\n clone: function() {\n return new this.self();\n }\n});\n\n\n<a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.SnowLeopard', {\n extend: 'My.Cat',\n statics: {\n speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'\n }\n});\n\nvar cat = new My.Cat(); // alerts 'Cat'\nvar snowLeopard = new My.SnowLeopard(); // alerts 'Snow Leopard'\n\nvar clone = snowLeopard.clone();\nalert(<a href=\"#!/api/Ext-method-getClassName\" rel=\"Ext-method-getClassName\" class=\"docClass\">Ext.getClassName</a>(clone)); // alerts 'My.SnowLeopard'\n</code></pre>\n</div></div></div><div id='property-weight' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-property-weight' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-property-weight' class='name expandable'>weight</a><span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>0</code></p></div></div></div><div id='property-zIndexManager' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-property-zIndexManager' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-property-zIndexManager' class='name expandable'>zIndexManager</a><span> : <a href=\"#!/api/Ext.ZIndexManager\" rel=\"Ext.ZIndexManager\" class=\"docClass\">Ext.ZIndexManager</a></span><strong class='readonly signature' >readonly</strong></div><div class='description'><div class='short'>Only present for floating Components after they have been rendered. ...</div><div class='long'><p>Only present for <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a> Components after they have been rendered.</p>\n\n<p>A reference to the ZIndexManager which is managing this Component's z-index.</p>\n\n<p>The <a href=\"#!/api/Ext.ZIndexManager\" rel=\"Ext.ZIndexManager\" class=\"docClass\">ZIndexManager</a> maintains a stack of floating Component z-indices, and also provides\na single modal mask which is insert just beneath the topmost visible modal floating Component.</p>\n\n<p>Floating Components may be <a href=\"#!/api/Ext.Component-method-toFront\" rel=\"Ext.Component-method-toFront\" class=\"docClass\">brought to the front</a> or <a href=\"#!/api/Ext.Component-method-toBack\" rel=\"Ext.Component-method-toBack\" class=\"docClass\">sent to the back</a> of the\nz-index stack.</p>\n\n<p>This defaults to the global <a href=\"#!/api/Ext.WindowManager\" rel=\"Ext.WindowManager\" class=\"docClass\">ZIndexManager</a> for floating Components that are\nprogramatically <a href=\"#!/api/Ext.Component-method-render\" rel=\"Ext.Component-method-render\" class=\"docClass\">rendered</a>.</p>\n\n<p>For <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a> Components which are added to a Container, the ZIndexManager is acquired from the first\nancestor Container found which is floating. If no floating ancestor is found, the global <a href=\"#!/api/Ext.WindowManager\" rel=\"Ext.WindowManager\" class=\"docClass\">ZIndexManager</a> is\nused.</p>\n\n<p>See <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a> and <a href=\"#!/api/Ext.Component-property-zIndexParent\" rel=\"Ext.Component-property-zIndexParent\" class=\"docClass\">zIndexParent</a></p>\n</div></div></div><div id='property-zIndexParent' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-property-zIndexParent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-property-zIndexParent' class='name expandable'>zIndexParent</a><span> : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.Container</a></span><strong class='readonly signature' >readonly</strong></div><div class='description'><div class='short'>Only present for floating Components which were inserted as child items of Containers, and which have a floating\nCont...</div><div class='long'><p>Only present for <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a> Components which were inserted as child items of Containers, and which have a floating\nContainer in their containment ancestry.</p>\n\n<p>For <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a> Components which are child items of a Container, the zIndexParent will be a floating\nancestor Container which is responsible for the base z-index value of all its floating descendants. It provides\na <a href=\"#!/api/Ext.ZIndexManager\" rel=\"Ext.ZIndexManager\" class=\"docClass\">ZIndexManager</a> which provides z-indexing services for all its descendant floating\nComponents.</p>\n\n<p>Floating Components that are programatically <a href=\"#!/api/Ext.Component-method-render\" rel=\"Ext.Component-method-render\" class=\"docClass\">rendered</a> will not have a <code>zIndexParent</code>\nproperty.</p>\n\n<p>For example, the dropdown <a href=\"#!/api/Ext.view.BoundList\" rel=\"Ext.view.BoundList\" class=\"docClass\">BoundList</a> of a ComboBox which is in a Window will have the\nWindow as its <code>zIndexParent</code>, and will always show above that Window, wherever the Window is placed in the z-index stack.</p>\n\n<p>See <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a> and <a href=\"#!/api/Ext.Component-property-zIndexManager\" rel=\"Ext.Component-property-zIndexManager\" class=\"docClass\">zIndexManager</a></p>\n</div></div></div></div><div class='subsection'><div class='definedBy'>Defined By</div><h4 class='members-subtitle'>Static Properties</h3><div id='static-property-S-onExtended' class='member first-child inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-property-S-onExtended' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-property-S-onExtended' class='name expandable'>$onExtended</a><span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a></span><strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>[]</code></p></div></div></div><div id='property-DIRECTION_BOTTOM' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-property-DIRECTION_BOTTOM' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-property-DIRECTION_BOTTOM' class='name expandable'>DIRECTION_BOTTOM</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>'bottom'</code></p></div></div></div><div id='property-DIRECTION_LEFT' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-property-DIRECTION_LEFT' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-property-DIRECTION_LEFT' class='name expandable'>DIRECTION_LEFT</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>'left'</code></p></div></div></div><div id='property-DIRECTION_RIGHT' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-property-DIRECTION_RIGHT' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-property-DIRECTION_RIGHT' class='name expandable'>DIRECTION_RIGHT</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>'right'</code></p></div></div></div><div id='property-DIRECTION_TOP' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-property-DIRECTION_TOP' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-property-DIRECTION_TOP' class='name expandable'>DIRECTION_TOP</a><span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'>Collapse/expand directions ...</div><div class='long'><p>Collapse/expand directions</p>\n<p>Defaults to: <code>'top'</code></p></div></div></div><div id='property-INVALID_ID_CHARS_Re' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-property-INVALID_ID_CHARS_Re' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-property-INVALID_ID_CHARS_Re' class='name expandable'>INVALID_ID_CHARS_Re</a><span> : <a href=\"#!/api/RegExp\" rel=\"RegExp\" class=\"docClass\">RegExp</a></span><strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'>RegExp whih specifies characters in an xtype which must be translated to '-' when generating auto IDs. ...</div><div class='long'><p>RegExp whih specifies characters in an xtype which must be translated to '-' when generating auto IDs.\nThis includes dot, comma and whitespace</p>\n<p>Defaults to: <code>/[\\.,\\s]/g</code></p></div></div></div><div id='property-VERTICAL_DIRECTION_Re' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-property-VERTICAL_DIRECTION_Re' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-property-VERTICAL_DIRECTION_Re' class='name expandable'>VERTICAL_DIRECTION_Re</a><span> : <a href=\"#!/api/RegExp\" rel=\"RegExp\" class=\"docClass\">RegExp</a></span><strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Defaults to: <code>/^(?:top|bottom)$/</code></p></div></div></div></div></div><div class='members-section'><h3 class='members-title icon-method'>Methods</h3><div class='subsection'><div class='definedBy'>Defined By</div><h4 class='members-subtitle'>Instance Methods</h3><div id='method-constructor' class='member first-child not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-constructor' target='_blank' class='view-source'>view source</a></div><strong class='new-keyword'>new</strong><a href='#!/api/Ext.Component-method-constructor' class='name expandable'>Ext.Component</a>( <span class='pre'>config</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Creates new Component. ...</div><div class='long'><p>Creates new Component.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>config</span> : <a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The configuration options may be specified as either:</p>\n\n\n\n\n<ul>\n<li><strong>an element</strong> : it is set as the internal element and its id used as the component id</li>\n<li><strong>a string</strong> : it is assumed to be the id of an existing element and is used as the component id</li>\n<li><strong>anything else</strong> : it is assumed to be a standard config object and is applied to the component</li>\n</ul>\n\n\n\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-constructor' rel='Ext.AbstractComponent-method-constructor' class='docClass'>Ext.AbstractComponent.constructor</a></p></div></div></div><div id='method-addChildEls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.ElementContainer' rel='Ext.util.ElementContainer' class='defined-in docClass'>Ext.util.ElementContainer</a><br/><a href='source/ElementContainer.html#Ext-util-ElementContainer-method-addChildEls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.ElementContainer-method-addChildEls' class='name expandable'>addChildEls</a>( <span class='pre'></span> )</div><div class='description'><div class='short'>Adds each argument passed to this method to the childEls array. ...</div><div class='long'><p>Adds each argument passed to this method to the <a href=\"#!/api/Ext.AbstractComponent-cfg-childEls\" rel=\"Ext.AbstractComponent-cfg-childEls\" class=\"docClass\">childEls</a> array.</p>\n</div></div></div><div id='method-addClass' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-addClass' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-addClass' class='name expandable'>addClass</a>( <span class='pre'>cls</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><strong class='deprecated signature' >deprecated</strong></div><div class='description'><div class='short'>Adds a CSS class to the top level element representing this component. ...</div><div class='long'><p>Adds a CSS class to the top level element representing this component.</p>\n <div class='signature-box deprecated'>\n <p>This method has been <strong>deprecated</strong> since 4.1</p>\n <p>Use <a href=\"#!/api/Ext.AbstractComponent-method-addCls\" rel=\"Ext.AbstractComponent-method-addCls\" class=\"docClass\">addCls</a> instead.</p>\n\n </div>\n <p>Available since: <b>2.3.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>cls</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>[]<div class='sub-desc'><p>The CSS class name to add.</p>\n\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>Returns the Component to allow method chaining.</p>\n\n</div></li></ul></div></div></div><div id='method-addCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-addCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-addCls' class='name expandable'>addCls</a>( <span class='pre'>cls</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Adds a CSS class to the top level element representing this component. ...</div><div class='long'><p>Adds a CSS class to the top level element representing this component.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>cls</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>[]<div class='sub-desc'><p>The CSS class name to add.</p>\n\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>Returns the Component to allow method chaining.</p>\n\n</div></li></ul></div></div></div><div id='method-addClsWithUI' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-addClsWithUI' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-addClsWithUI' class='name expandable'>addClsWithUI</a>( <span class='pre'>classes, skip</span> )</div><div class='description'><div class='short'>Adds a cls to the uiCls array, which will also call addUIClsToElement and adds to all elements of this\ncomponent. ...</div><div class='long'><p>Adds a <code>cls</code> to the <code>uiCls</code> array, which will also call <a href=\"#!/api/Ext.AbstractComponent-method-addUIClsToElement\" rel=\"Ext.AbstractComponent-method-addUIClsToElement\" class=\"docClass\">addUIClsToElement</a> and adds to all elements of this\ncomponent.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>classes</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>[]<div class='sub-desc'><p>A string or an array of strings to add to the <code>uiCls</code>.</p>\n</div></li><li><span class='pre'>skip</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>(Boolean) skip <code>true</code> to skip adding it to the class and do it later (via the return).</p>\n</div></li></ul></div></div></div><div id='method-addEvents' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-addEvents' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-addEvents' class='name expandable'>addEvents</a>( <span class='pre'>eventNames</span> )</div><div class='description'><div class='short'>Adds the specified events to the list of events which this Observable may fire. ...</div><div class='long'><p>Adds the specified events to the list of events which this Observable may fire.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>eventNames</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>...<div class='sub-desc'><p>Either an object with event names as properties with\na value of <code>true</code>. For example:</p>\n\n<pre><code>this.addEvents({\n storeloaded: true,\n storecleared: true\n});\n</code></pre>\n\n<p>Or any number of event names as separate parameters. For example:</p>\n\n<pre><code>this.addEvents('storeloaded', 'storecleared');\n</code></pre>\n</div></li></ul></div></div></div><div id='method-addFocusListener' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-addFocusListener' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-addFocusListener' class='name expandable'>addFocusListener</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Sets up the focus listener on this Component's focusEl if it has one. ...</div><div class='long'><p>Sets up the focus listener on this Component's <a href=\"#!/api/Ext.AbstractComponent-method-getFocusEl\" rel=\"Ext.AbstractComponent-method-getFocusEl\" class=\"docClass\">focusEl</a> if it has one.</p>\n\n<p>Form Components which must implicitly participate in tabbing order usually have a naturally focusable\nelement as their <a href=\"#!/api/Ext.AbstractComponent-method-getFocusEl\" rel=\"Ext.AbstractComponent-method-getFocusEl\" class=\"docClass\">focusEl</a>, and it is the DOM event of that receiving focus which drives\nthe Component's <code>onFocus</code> handling, and the DOM event of it being blurred which drives the <code>onBlur</code> handling.</p>\n\n<p>If the <a href=\"#!/api/Ext.AbstractComponent-method-getFocusEl\" rel=\"Ext.AbstractComponent-method-getFocusEl\" class=\"docClass\">focusEl</a> is <strong>not</strong> naturally focusable, then the listeners are only added\nif the <a href=\"#!/api/Ext.FocusManager\" rel=\"Ext.FocusManager\" class=\"docClass\">FocusManager</a> is enabled.</p>\n</div></div></div><div id='method-addListener' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-addListener' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-addListener' class='name expandable'>addListener</a>( <span class='pre'>eventName, [fn], [scope], [options]</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>Appends an event handler to this object. ...</div><div class='long'><p>Appends an event handler to this object. For example:</p>\n\n<pre><code>myGridPanel.on(\"mouseover\", this.onMouseOver, this);\n</code></pre>\n\n<p>The method also allows for a single argument to be passed which is a config object\ncontaining properties which specify multiple events. For example:</p>\n\n<pre><code>myGridPanel.on({\n cellClick: this.onCellClick,\n mouseover: this.onMouseOver,\n mouseout: this.onMouseOut,\n scope: this // Important. Ensure \"this\" is correct during handler execution\n});\n</code></pre>\n\n<p>One can also specify options for each event handler separately:</p>\n\n<pre><code>myGridPanel.on({\n cellClick: {fn: this.onCellClick, scope: this, single: true},\n mouseover: {fn: panel.onMouseOver, scope: panel}\n});\n</code></pre>\n\n<p><em>Names</em> of methods in a specified scope may also be used. Note that\n<code>scope</code> MUST be specified to use this option:</p>\n\n<pre><code>myGridPanel.on({\n cellClick: {fn: 'onCellClick', scope: this, single: true},\n mouseover: {fn: 'onMouseOver', scope: panel}\n});\n</code></pre>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>eventName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The name of the event to listen for.\nMay also be an object who's property names are event names.</p>\n</div></li><li><span class='pre'>fn</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'><p>The method the event invokes, or <em>if <code>scope</code> is specified, the </em>name* of the method within\nthe specified <code>scope</code>. Will be called with arguments\ngiven to <a href=\"#!/api/Ext.util.Observable-method-fireEvent\" rel=\"Ext.util.Observable-method-fireEvent\" class=\"docClass\">Ext.util.Observable.fireEvent</a> plus the <code>options</code> parameter described below.</p>\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>The scope (<code>this</code> reference) in which the handler function is\nexecuted. <strong>If omitted, defaults to the object which fired the event.</strong></p>\n</div></li><li><span class='pre'>options</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>An object containing handler configuration.</p>\n\n<p><strong>Note:</strong> Unlike in ExtJS 3.x, the options object will also be passed as the last\nargument to every event handler.</p>\n\n<p>This object may contain any of the following properties:</p>\n<ul><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The scope (<code>this</code> reference) in which the handler function is executed. <strong>If omitted,\n defaults to the object which fired the event.</strong></p>\n</div></li><li><span class='pre'>delay</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The number of milliseconds to delay the invocation of the handler after the event fires.</p>\n</div></li><li><span class='pre'>single</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p>True to add a handler to handle just the next firing of the event, and then remove itself.</p>\n</div></li><li><span class='pre'>buffer</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>Causes the handler to be scheduled to run in an <a href=\"#!/api/Ext.util.DelayedTask\" rel=\"Ext.util.DelayedTask\" class=\"docClass\">Ext.util.DelayedTask</a> delayed\n by the specified number of milliseconds. If the event fires again within that time,\n the original handler is <em>not</em> invoked, but the new handler is scheduled in its place.</p>\n</div></li><li><span class='pre'>target</span> : <a href=\"#!/api/Ext.util.Observable\" rel=\"Ext.util.Observable\" class=\"docClass\">Ext.util.Observable</a><div class='sub-desc'><p>Only call the handler if the event was fired on the target Observable, <em>not</em> if the event\n was bubbled up from a child Observable.</p>\n</div></li><li><span class='pre'>element</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p><strong>This option is only valid for listeners bound to <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Components</a>.</strong>\n The name of a Component property which references an element to add a listener to.</p>\n\n<p> This option is useful during Component construction to add DOM event listeners to elements of\n <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Components</a> which will exist only after the Component is rendered.\n For example, to add a click listener to a Panel's body:</p>\n\n<pre><code> new <a href=\"#!/api/Ext.panel.Panel\" rel=\"Ext.panel.Panel\" class=\"docClass\">Ext.panel.Panel</a>({\n title: 'The title',\n listeners: {\n click: this.handlePanelClick,\n element: 'body'\n }\n });\n</code></pre>\n</div></li><li><span class='pre'>destroyable</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>When specified as <code>true</code>, the function returns A <code>Destroyable</code> object. An object which implements the <code>destroy</code> method which removes all listeners added in this call.</p>\n<p>Defaults to: <code>false</code></p></div></li><li><span class='pre'>priority</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>An optional numeric priority that determines the order in which event handlers\n are run. Event handlers with no priority will be run as if they had a priority\n of 0. Handlers with a higher priority will be prioritized to run sooner than\n those with a lower priority. Negative numbers can be used to set a priority\n lower than the default. Internally, the framework uses a range of 1000 or\n greater, and -1000 or lesser for handers that are intended to run before or\n after all others, so it is recommended to stay within the range of -999 to 999\n when setting the priority of event handlers in application-level code.</p>\n\n<p><strong>Combining Options</strong></p>\n\n<p>Using the options argument, it is possible to combine different types of listeners:</p>\n\n<p>A delayed, one-time listener.</p>\n\n<pre><code>myPanel.on('hide', this.handleClick, this, {\n single: true,\n delay: 100\n});\n</code></pre>\n</div></li></ul></div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p><strong>Only when the <code>destroyable</code> option is specified. </strong></p>\n\n<p> A <code>Destroyable</code> object. An object which implements the <code>destroy</code> method which removes all listeners added in this call. For example:</p>\n\n<pre><code>this.btnListeners = = myButton.on({\n destroyable: true\n mouseover: function() { console.log('mouseover'); },\n mouseout: function() { console.log('mouseout'); },\n click: function() { console.log('click'); }\n});\n</code></pre>\n\n<p>And when those listeners need to be removed:</p>\n\n<pre><code><a href=\"#!/api/Ext-method-destroy\" rel=\"Ext-method-destroy\" class=\"docClass\">Ext.destroy</a>(this.btnListeners);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>this.btnListeners.destroy();\n</code></pre>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Observable-method-addListener' rel='Ext.util.Observable-method-addListener' class='docClass'>Ext.util.Observable.addListener</a></p></div></div></div><div id='method-addManagedListener' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-addManagedListener' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-addManagedListener' class='name expandable'>addManagedListener</a>( <span class='pre'>item, ename, [fn], [scope], [options]</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>Adds listeners to any Observable object (or Ext.Element) which are automatically removed when this Component is\ndestr...</div><div class='long'><p>Adds listeners to any Observable object (or <a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a>) which are automatically removed when this Component is\ndestroyed.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>item</span> : <a href=\"#!/api/Ext.util.Observable\" rel=\"Ext.util.Observable\" class=\"docClass\">Ext.util.Observable</a>/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a><div class='sub-desc'><p>The item to which to add a listener/listeners.</p>\n\n</div></li><li><span class='pre'>ename</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The event name, or an object containing event name properties.</p>\n\n</div></li><li><span class='pre'>fn</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'><p>If the <code>ename</code> parameter was an event name, this is the handler function.</p>\n\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>If the <code>ename</code> parameter was an event name, this is the scope (<code>this</code> reference)\nin which the handler function is executed.</p>\n\n</div></li><li><span class='pre'>options</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>If the <code>ename</code> parameter was an event name, this is the\n<a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">addListener</a> options.</p>\n\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p><strong>Only when the <code>destroyable</code> option is specified. </strong></p>\n\n\n\n\n<p> A <code>Destroyable</code> object. An object which implements the <code>destroy</code> method which removes all listeners added in this call. For example:</p>\n\n\n\n\n<pre><code>this.btnListeners = = myButton.mon({\n destroyable: true\n mouseover: function() { console.log('mouseover'); },\n mouseout: function() { console.log('mouseout'); },\n click: function() { console.log('click'); }\n});\n</code></pre>\n\n\n\n\n<p>And when those listeners need to be removed:</p>\n\n\n\n\n<pre><code><a href=\"#!/api/Ext-method-destroy\" rel=\"Ext-method-destroy\" class=\"docClass\">Ext.destroy</a>(this.btnListeners);\n</code></pre>\n\n\n\n\n<p>or</p>\n\n\n\n\n<pre><code>this.btnListeners.destroy();\n</code></pre>\n\n</div></li></ul></div></div></div><div id='method-addOverCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-addOverCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-addOverCls' class='name expandable'>addOverCls</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'><p></debug></p>\n</div></div></div><div id='method-addPlugin' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-addPlugin' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-addPlugin' class='name expandable'>addPlugin</a>( <span class='pre'>plugin</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Adds a plugin. ...</div><div class='long'><p>Adds a plugin. May be called at any time in the component's lifecycle.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>plugin</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-addPropertyToState' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-addPropertyToState' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-addPropertyToState' class='name expandable'>addPropertyToState</a>( <span class='pre'>state, propName, [value]</span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Save a property to the given state object if it is not its default or configured\nvalue. ...</div><div class='long'><p>Save a property to the given state object if it is not its default or configured\nvalue.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>state</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The state object.</p>\n</div></li><li><span class='pre'>propName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The name of the property on this object to save.</p>\n</div></li><li><span class='pre'>value</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>The value of the state property (defaults to <code>this[propName]</code>).</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p>The state object or a new object if state was <code>null</code> and the property\nwas saved.</p>\n</div></li></ul></div></div></div><div id='method-addStateEvents' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-method-addStateEvents' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-method-addStateEvents' class='name expandable'>addStateEvents</a>( <span class='pre'>events</span> )</div><div class='description'><div class='short'>Add events that will trigger the state to be saved. ...</div><div class='long'><p>Add events that will trigger the state to be saved. If the first argument is an\narray, each element of that array is the name of a state event. Otherwise, each\nargument passed to this method is the name of a state event.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>events</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>[]<div class='sub-desc'><p>The event name or an array of event names.</p>\n</div></li></ul></div></div></div><div id='method-addUIClsToElement' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-addUIClsToElement' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-addUIClsToElement' class='name expandable'>addUIClsToElement</a>( <span class='pre'>ui</span> )</div><div class='description'><div class='short'>Method which adds a specified UI + uiCls to the components element. ...</div><div class='long'><p>Method which adds a specified UI + <code>uiCls</code> to the components element. Can be overridden to remove the UI from more\nthan just the components element.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>ui</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The UI to remove from the element.</p>\n</div></li></ul></div></div></div><div id='method-addUIToElement' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-addUIToElement' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-addUIToElement' class='name expandable'>addUIToElement</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Method which adds a specified UI to the components element. ...</div><div class='long'><p>Method which adds a specified UI to the components element.</p>\n</div></div></div><div id='method-adjustForConstraints' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-adjustForConstraints' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-adjustForConstraints' class='name expandable'>adjustForConstraints</a>( <span class='pre'>xy, parent</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>private ==> used outside of core\nTODO: currently only used by ToolTip. ...</div><div class='long'><p>private ==> used outside of core\nTODO: currently only used by ToolTip. does this method belong here?</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>xy</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>parent</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-adjustPosition' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-adjustPosition' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-adjustPosition' class='name expandable'>adjustPosition</a>( <span class='pre'>x, y</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>x</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>y</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-afterComponentLayout' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-afterComponentLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-afterComponentLayout' class='name expandable'>afterComponentLayout</a>( <span class='pre'>width, height, oldWidth, oldHeight</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Called by the layout system after the Component has been laid out. ...</div><div class='long'><p>Called by the layout system after the Component has been laid out.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>width</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The width that was set</p>\n\n</div></li><li><span class='pre'>height</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The height that was set</p>\n\n</div></li><li><span class='pre'>oldWidth</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/undefined<div class='sub-desc'><p>The old width, or <code>undefined</code> if this was the initial layout.</p>\n\n</div></li><li><span class='pre'>oldHeight</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/undefined<div class='sub-desc'><p>The old height, or <code>undefined</code> if this was the initial layout.</p>\n\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-afterComponentLayout' rel='Ext.AbstractComponent-method-afterComponentLayout' class='docClass'>Ext.AbstractComponent.afterComponentLayout</a></p></div></div></div><div id='method-afterFirstLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-afterFirstLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-afterFirstLayout' class='name expandable'>afterFirstLayout</a>( <span class='pre'>width, height</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>width</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>height</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-afterHide' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-afterHide' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-afterHide' class='name expandable'>afterHide</a>( <span class='pre'>[callback], [scope]</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Invoked after the Component has been hidden. ...</div><div class='long'><p>Invoked after the Component has been hidden.</p>\n\n<p>Gets passed the same <code>callback</code> and <code>scope</code> parameters that <a href=\"#!/api/Ext.Component-method-onHide\" rel=\"Ext.Component-method-onHide\" class=\"docClass\">onHide</a> received.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>callback</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'>\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-afterRender' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-afterRender' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-afterRender' class='name expandable'>afterRender</a>( <span class='pre'></span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Allows addition of behavior after rendering is complete. ...</div><div class='long'><p>Allows addition of behavior after rendering is complete. At this stage the Component’s Element\nwill have been styled according to the configuration, will have had any configured CSS class\nnames added, and will be in the configured visibility and the configured enable state.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<p>Overrides: <a href='#!/api/Ext.util.Renderable-method-afterRender' rel='Ext.util.Renderable-method-afterRender' class='docClass'>Ext.util.Renderable.afterRender</a></p></div></div></div><div id='method-afterSetPosition' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-afterSetPosition' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-afterSetPosition' class='name expandable'>afterSetPosition</a>( <span class='pre'>x, y</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Template method called after a Component has been positioned. ...</div><div class='long'><p>Template method called after a Component has been positioned.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>x</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'>\n</div></li><li><span class='pre'>y</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-afterSetPosition' rel='Ext.AbstractComponent-method-afterSetPosition' class='docClass'>Ext.AbstractComponent.afterSetPosition</a></p></div></div></div><div id='method-afterShow' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-afterShow' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-afterShow' class='name expandable'>afterShow</a>( <span class='pre'>[animateTarget], [callback], [scope]</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Invoked after the Component is shown (after onShow is called). ...</div><div class='long'><p>Invoked after the Component is shown (after <a href=\"#!/api/Ext.Component-method-onShow\" rel=\"Ext.Component-method-onShow\" class=\"docClass\">onShow</a> is called).</p>\n\n<p>Gets passed the same parameters as <a href=\"#!/api/Ext.Component-method-show\" rel=\"Ext.Component-method-show\" class=\"docClass\">show</a>.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>animateTarget</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a> (optional)<div class='sub-desc'>\n</div></li><li><span class='pre'>callback</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'>\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-alignTo' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-alignTo' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-alignTo' class='name expandable'>alignTo</a>( <span class='pre'>element, [position], [offsets], [animate]</span> ) : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Aligns the element with another element relative to the specified anchor points. ...</div><div class='long'><p>Aligns the element with another element relative to the specified anchor points. If\nthe other element is the document it aligns it to the viewport. The position\nparameter is optional, and can be specified in any one of the following formats:</p>\n\n<ul>\n<li><strong>Blank</strong>: Defaults to aligning the element's top-left corner to the target's\nbottom-left corner (\"tl-bl\").</li>\n<li><strong>One anchor (deprecated)</strong>: The passed anchor position is used as the target\nelement's anchor point. The element being aligned will position its top-left\ncorner (tl) to that point. <em>This method has been deprecated in favor of the newer\ntwo anchor syntax below</em>.</li>\n<li><strong>Two anchors</strong>: If two values from the table below are passed separated by a dash,\nthe first value is used as the element's anchor point, and the second value is\nused as the target's anchor point.</li>\n</ul>\n\n\n<p>In addition to the anchor points, the position parameter also supports the \"?\"\ncharacter. If \"?\" is passed at the end of the position string, the element will\nattempt to align as specified, but the position will be adjusted to constrain to\nthe viewport if necessary. Note that the element being aligned might be swapped to\nalign to a different position than that specified in order to enforce the viewport\nconstraints. Following are all of the supported anchor positions:</p>\n\n<pre>Value Description\n----- -----------------------------\ntl The top left corner (default)\nt The center of the top edge\ntr The top right corner\nl The center of the left edge\nc In the center of the element\nr The center of the right edge\nbl The bottom left corner\nb The center of the bottom edge\nbr The bottom right corner\n</pre>\n\n\n<p>Example Usage:</p>\n\n<pre><code>// align el to other-el using the default positioning\n// (\"tl-bl\", non-constrained)\nel.alignTo(\"other-el\");\n\n// align the top left corner of el with the top right corner of other-el\n// (constrained to viewport)\nel.alignTo(\"other-el\", \"tr?\");\n\n// align the bottom right corner of el with the center left edge of other-el\nel.alignTo(\"other-el\", \"br-l?\");\n\n// align the center of el with the bottom left corner of other-el and\n// adjust the x position by -6 pixels (and the y position by 0)\nel.alignTo(\"other-el\", \"c-bl\", [-6, 0]);\n</code></pre>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>element</span> : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a>/HTMLElement/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The Positionable,\nHTMLElement, or id of the element to align to.</p>\n</div></li><li><span class='pre'>position</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>The position to align to</p>\n<p>Defaults to: <code>&quot;tl-bl?&quot;</code></p></div></li><li><span class='pre'>offsets</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[] (optional)<div class='sub-desc'><p>Offset the positioning by [x, y]</p>\n</div></li><li><span class='pre'>animate</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>true for the default animation or a standard\nElement animation config object</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-anchorTo' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-anchorTo' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-anchorTo' class='name expandable'>anchorTo</a>( <span class='pre'>element, [position], [offsets], [animate], [monitorScroll], [callback]</span> ) : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Anchors an element to another element and realigns it when the window is resized. ...</div><div class='long'><p>Anchors an element to another element and realigns it when the window is resized.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>element</span> : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a>/HTMLElement/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The Positionable,\nHTMLElement, or id of the element to align to.</p>\n</div></li><li><span class='pre'>position</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>The position to align to</p>\n<p>Defaults to: <code>&quot;tl-bl?&quot;</code></p></div></li><li><span class='pre'>offsets</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[] (optional)<div class='sub-desc'><p>Offset the positioning by [x, y]</p>\n</div></li><li><span class='pre'>animate</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>true for the default animation or a standard\nElement animation config object</p>\n</div></li><li><span class='pre'>monitorScroll</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>True to monitor body scroll and\nreposition. If this parameter is a number, it is used as the buffer delay in\nmilliseconds.</p>\n<p>Defaults to: <code>50</code></p></div></li><li><span class='pre'>callback</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'><p>The function to call after the animation finishes</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-anim' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Animate' rel='Ext.util.Animate' class='defined-in docClass'>Ext.util.Animate</a><br/><a href='source/Animate.html#Ext-util-Animate-method-anim' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Animate-method-anim' class='name expandable'>anim</a>( <span class='pre'>config</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>process the passed fx configuration. ...</div><div class='long'><ul>\n<li>process the passed fx configuration.</li>\n</ul>\n\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>config</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-animate' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-animate' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-animate' class='name expandable'>animate</a>( <span class='pre'>config</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>Performs custom animation on this object. ...</div><div class='long'><p>Performs custom animation on this object.</p>\n\n<p>This method is applicable to both the <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Component</a> class and the <a href=\"#!/api/Ext.draw.Sprite\" rel=\"Ext.draw.Sprite\" class=\"docClass\">Sprite</a>\nclass. It performs animated transitions of certain properties of this object over a specified timeline.</p>\n\n<h3>Animating a <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Component</a></h3>\n\n<p>When animating a Component, the following properties may be specified in <code>from</code>, <code>to</code>, and <code>keyframe</code> objects:</p>\n\n<ul>\n<li><p><code>x</code> - The Component's page X position in pixels.</p></li>\n<li><p><code>y</code> - The Component's page Y position in pixels</p></li>\n<li><p><code>left</code> - The Component's <code>left</code> value in pixels.</p></li>\n<li><p><code>top</code> - The Component's <code>top</code> value in pixels.</p></li>\n<li><p><code>width</code> - The Component's <code>width</code> value in pixels.</p></li>\n<li><p><code>height</code> - The Component's <code>height</code> value in pixels.</p></li>\n<li><p><code>dynamic</code> - Specify as true to update the Component's layout (if it is a Container) at every frame of the animation.\n<em>Use sparingly as laying out on every intermediate size change is an expensive operation.</em></p></li>\n</ul>\n\n\n<p>For example, to animate a Window to a new size, ensuring that its internal layout and any shadow is correct:</p>\n\n<pre><code>myWindow = <a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.window.Window\" rel=\"Ext.window.Window\" class=\"docClass\">Ext.window.Window</a>', {\n title: 'Test Component animation',\n width: 500,\n height: 300,\n layout: {\n type: 'hbox',\n align: 'stretch'\n },\n items: [{\n title: 'Left: 33%',\n margins: '5 0 5 5',\n flex: 1\n }, {\n title: 'Left: 66%',\n margins: '5 5 5 5',\n flex: 2\n }]\n});\nmyWindow.show();\nmyWindow.header.el.on('click', function() {\n myWindow.animate({\n to: {\n width: (myWindow.getWidth() == 500) ? 700 : 500,\n height: (myWindow.getHeight() == 300) ? 400 : 300\n }\n });\n});\n</code></pre>\n\n<p>For performance reasons, by default, the internal layout is only updated when the Window reaches its final <code>\"to\"</code>\nsize. If dynamic updating of the Window's child Components is required, then configure the animation with\n<code>dynamic: true</code> and the two child items will maintain their proportions during the animation.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>config</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>Configuration for <a href=\"#!/api/Ext.fx.Anim\" rel=\"Ext.fx.Anim\" class=\"docClass\">Ext.fx.Anim</a>.\nNote that the <a href=\"#!/api/Ext.fx.Anim-cfg-to\" rel=\"Ext.fx.Anim-cfg-to\" class=\"docClass\">to</a> config is required.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Animate-method-animate' rel='Ext.util.Animate-method-animate' class='docClass'>Ext.util.Animate.animate</a></p></div></div></div><div id='method-applyChildEls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.ElementContainer' rel='Ext.util.ElementContainer' class='defined-in docClass'>Ext.util.ElementContainer</a><br/><a href='source/ElementContainer.html#Ext-util-ElementContainer-method-applyChildEls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.ElementContainer-method-applyChildEls' class='name expandable'>applyChildEls</a>( <span class='pre'>el, id</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Sets references to elements inside the component. ...</div><div class='long'><p>Sets references to elements inside the component.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>el</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>id</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-applyRenderSelectors' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-applyRenderSelectors' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-applyRenderSelectors' class='name expandable'>applyRenderSelectors</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Sets references to elements inside the component. ...</div><div class='long'><p>Sets references to elements inside the component. This applies <a href=\"#!/api/Ext.AbstractComponent-cfg-renderSelectors\" rel=\"Ext.AbstractComponent-cfg-renderSelectors\" class=\"docClass\">renderSelectors</a>\nas well as <a href=\"#!/api/Ext.AbstractComponent-cfg-childEls\" rel=\"Ext.AbstractComponent-cfg-childEls\" class=\"docClass\">childEls</a>.</p>\n</div></div></div><div id='method-applyState' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-method-applyState' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-method-applyState' class='name expandable'>applyState</a>( <span class='pre'>state</span> )</div><div class='description'><div class='short'>Applies the state to the object. ...</div><div class='long'><p>Applies the state to the object. This should be overridden in subclasses to do\nmore complex state operations. By default it applies the state properties onto\nthe current object.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>state</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The state</p>\n</div></li></ul></div></div></div><div id='method-beforeBlur' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-beforeBlur' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-beforeBlur' class='name expandable'>beforeBlur</a>( <span class='pre'>e</span> )<strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Template method to do any pre-blur processing. ...</div><div class='long'><p>Template method to do any pre-blur processing.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>e</span> : <a href=\"#!/api/Ext.EventObject\" rel=\"Ext.EventObject\" class=\"docClass\">Ext.EventObject</a><div class='sub-desc'><p>The event object</p>\n</div></li></ul></div></div></div><div id='method-beforeComponentLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-beforeComponentLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-beforeComponentLayout' class='name expandable'>beforeComponentLayout</a>( <span class='pre'>adjWidth, adjHeight</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Occurs before componentLayout is run. ...</div><div class='long'><p>Occurs before <code>componentLayout</code> is run. Returning <code>false</code> from this method will prevent the <code>componentLayout</code> from\nbeing executed.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>adjWidth</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The box-adjusted width that was set.</p>\n</div></li><li><span class='pre'>adjHeight</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The box-adjusted height that was set.</p>\n</div></li></ul></div></div></div><div id='method-beforeDestroy' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-beforeDestroy' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-beforeDestroy' class='name expandable'>beforeDestroy</a>( <span class='pre'></span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Invoked before the Component is destroyed. ...</div><div class='long'><p>Invoked before the Component is destroyed.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n</div></div></div><div id='method-beforeFocus' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-beforeFocus' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-beforeFocus' class='name expandable'>beforeFocus</a>( <span class='pre'>e</span> )<strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Template method to do any pre-focus processing. ...</div><div class='long'><p>Template method to do any pre-focus processing.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>e</span> : <a href=\"#!/api/Ext.EventObject\" rel=\"Ext.EventObject\" class=\"docClass\">Ext.EventObject</a><div class='sub-desc'><p>The event object</p>\n</div></li></ul></div></div></div><div id='method-beforeLayout' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-beforeLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-beforeLayout' class='name expandable'>beforeLayout</a>( <span class='pre'></span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Occurs before componentLayout is run. ...</div><div class='long'><p>Occurs before componentLayout is run. In previous releases, this method could\nreturn <code>false</code> to prevent its layout but that is not supported in Ext JS 4.1 or\nhigher. This method is simply a notification of the impending layout to give the\ncomponent a chance to adjust the DOM. Ideally, DOM reads should be avoided at this\ntime to reduce expensive document reflows.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-beforeLayout' rel='Ext.AbstractComponent-method-beforeLayout' class='docClass'>Ext.AbstractComponent.beforeLayout</a></p></div></div></div><div id='method-beforeRender' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-beforeRender' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-beforeRender' class='name expandable'>beforeRender</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Overrides: <a href='#!/api/Ext.util.Renderable-method-beforeRender' rel='Ext.util.Renderable-method-beforeRender' class='docClass'>Ext.util.Renderable.beforeRender</a></p></div></div></div><div id='method-beforeSetPosition' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-beforeSetPosition' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-beforeSetPosition' class='name expandable'>beforeSetPosition</a>( <span class='pre'>x, y, animate</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Template method called before a Component is positioned. ...</div><div class='long'><p>Template method called before a Component is positioned.</p>\n\n<p>Ensures that the position is adjusted so that the Component is constrained if so configured.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>x</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>y</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>animate</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-beforeSetPosition' rel='Ext.AbstractComponent-method-beforeSetPosition' class='docClass'>Ext.AbstractComponent.beforeSetPosition</a></p></div></div></div><div id='method-beforeShow' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-beforeShow' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-beforeShow' class='name expandable'>beforeShow</a>( <span class='pre'></span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Invoked before the Component is shown. ...</div><div class='long'><p>Invoked before the Component is shown.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n</div></div></div><div id='method-blur' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-blur' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-blur' class='name expandable'>blur</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><strong class='chainable signature' >chainable</strong><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-bubble' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-bubble' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-bubble' class='name expandable'>bubble</a>( <span class='pre'>fn, [scope], [args]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Bubbles up the component/container heirarchy, calling the specified function with each component. ...</div><div class='long'><p>Bubbles up the component/container heirarchy, calling the specified function with each component. The scope\n(<em>this</em>) of function call will be the scope provided or the current component. The arguments to the function will\nbe the args provided or the current component. If the function returns false at any point, the bubble is stopped.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>fn</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a><div class='sub-desc'><p>The function to call</p>\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>The scope of the function. Defaults to current node.</p>\n</div></li><li><span class='pre'>args</span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a> (optional)<div class='sub-desc'><p>The args to call the function with. Defaults to passing the current component.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-calculateAnchorXY' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-calculateAnchorXY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-calculateAnchorXY' class='name expandable'>calculateAnchorXY</a>( <span class='pre'>[anchor], [extraX], [extraY], [size]</span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Calculates x,y coordinates specified by the anchor position on the element, adding\nextraX and extraY values. ...</div><div class='long'><p>Calculates x,y coordinates specified by the anchor position on the element, adding\nextraX and extraY values.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>anchor</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>The specified anchor position.\nSee <a href=\"#!/api/Ext.util.Positionable-method-alignTo\" rel=\"Ext.util.Positionable-method-alignTo\" class=\"docClass\">alignTo</a> for details on supported anchor positions.</p>\n<p>Defaults to: <code>'tl'</code></p></div></li><li><span class='pre'>extraX</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>value to be added to the x coordinate</p>\n</div></li><li><span class='pre'>extraY</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>value to be added to the y coordinate</p>\n</div></li><li><span class='pre'>size</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>An object containing the size to use for calculating anchor\nposition {width: (target width), height: (target height)} (defaults to the\nelement's current size)</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</span><div class='sub-desc'><p>[x, y] An array containing the element's x and y coordinates</p>\n</div></li></ul></div></div></div><div id='method-calculateConstrainedPosition' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-calculateConstrainedPosition' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-calculateConstrainedPosition' class='name expandable'>calculateConstrainedPosition</a>( <span class='pre'>[constrainTo], [proposedPosition], [local], [proposedSize]</span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</div><div class='description'><div class='short'>Calculates the new [x,y] position to move this Positionable into a constrain region. ...</div><div class='long'><p>Calculates the new [x,y] position to move this Positionable into a constrain region.</p>\n\n<p>By default, this Positionable is constrained to be within the container it was added to, or the element it was\nrendered to.</p>\n\n<p>Priority is given to constraining the top and left within the constraint.</p>\n\n<p>An alternative constraint may be passed.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>constrainTo</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/HTMLElement/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a>/<a href=\"#!/api/Ext.util.Region\" rel=\"Ext.util.Region\" class=\"docClass\">Ext.util.Region</a> (optional)<div class='sub-desc'><p>The Element or <a href=\"#!/api/Ext.util.Region\" rel=\"Ext.util.Region\" class=\"docClass\">Region</a>\ninto which this Component is to be constrained. Defaults to the element into which this Positionable\nwas rendered, or this Component's {@link <a href=\"#!/api/Ext.Component-cfg-constrainTo\" rel=\"Ext.Component-cfg-constrainTo\" class=\"docClass\">Ext.Component.constrainTo</a>.</p>\n</div></li><li><span class='pre'>proposedPosition</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[] (optional)<div class='sub-desc'><p>A proposed <code>[X, Y]</code> position to test for validity\nand to coerce into constraints instead of using this Positionable's current position.</p>\n</div></li><li><span class='pre'>local</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>The proposedPosition is local <em>(relative to floatParent if a floating Component)</em></p>\n</div></li><li><span class='pre'>proposedSize</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[] (optional)<div class='sub-desc'><p>A proposed <code>[width, height]</code> size to use when calculating\nconstraints instead of using this Positionable's current size.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</span><div class='sub-desc'><p><strong>If</strong> the element <em>needs</em> to be translated, the new <code>[X, Y]</code> position within\nconstraints if possible, giving priority to keeping the top and left edge in the constrain region.\nOtherwise, <code>false</code>.</p>\n</div></li></ul></div></div></div><div id='method-callOverridden' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-method-callOverridden' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-method-callOverridden' class='name expandable'>callOverridden</a>( <span class='pre'>args</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><strong class='deprecated signature' >deprecated</strong><strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Call the original method that was previously overridden with override\n\nExt.define('My.Cat', {\n constructor: functi...</div><div class='long'><p>Call the original method that was previously overridden with <a href=\"#!/api/Ext.Base-static-method-override\" rel=\"Ext.Base-static-method-override\" class=\"docClass\">override</a></p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.Cat', {\n constructor: function() {\n alert(\"I'm a cat!\");\n }\n});\n\nMy.Cat.override({\n constructor: function() {\n alert(\"I'm going to be a cat!\");\n\n this.callOverridden();\n\n alert(\"Meeeeoooowwww\");\n }\n});\n\nvar kitty = new My.Cat(); // alerts \"I'm going to be a cat!\"\n // alerts \"I'm a cat!\"\n // alerts \"Meeeeoooowwww\"\n</code></pre>\n <div class='signature-box deprecated'>\n <p>This method has been <strong>deprecated</strong> </p>\n <p>as of 4.1. Use <a href=\"#!/api/Ext.Base-method-callParent\" rel=\"Ext.Base-method-callParent\" class=\"docClass\">callParent</a> instead.</p>\n\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>args</span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a>/Arguments<div class='sub-desc'><p>The arguments, either an array or the <code>arguments</code> object\nfrom the current method, for example: <code>this.callOverridden(arguments)</code></p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>Returns the result of calling the overridden method</p>\n</div></li></ul></div></div></div><div id='method-callParent' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-method-callParent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-method-callParent' class='name expandable'>callParent</a>( <span class='pre'>args</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Call the \"parent\" method of the current method. ...</div><div class='long'><p>Call the \"parent\" method of the current method. That is the method previously\noverridden by derivation or by an override (see <a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>).</p>\n\n<pre><code> <a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.Base', {\n constructor: function (x) {\n this.x = x;\n },\n\n statics: {\n method: function (x) {\n return x;\n }\n }\n });\n\n <a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.Derived', {\n extend: 'My.Base',\n\n constructor: function () {\n this.callParent([21]);\n }\n });\n\n var obj = new My.Derived();\n\n alert(obj.x); // alerts 21\n</code></pre>\n\n<p>This can be used with an override as follows:</p>\n\n<pre><code> <a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.DerivedOverride', {\n override: 'My.Derived',\n\n constructor: function (x) {\n this.callParent([x*2]); // calls original My.Derived constructor\n }\n });\n\n var obj = new My.Derived();\n\n alert(obj.x); // now alerts 42\n</code></pre>\n\n<p>This also works with static methods.</p>\n\n<pre><code> <a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.Derived2', {\n extend: 'My.Base',\n\n statics: {\n method: function (x) {\n return this.callParent([x*2]); // calls My.Base.method\n }\n }\n });\n\n alert(My.Base.method(10); // alerts 10\n alert(My.Derived2.method(10); // alerts 20\n</code></pre>\n\n<p>Lastly, it also works with overridden static methods.</p>\n\n<pre><code> <a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.Derived2Override', {\n override: 'My.Derived2',\n\n statics: {\n method: function (x) {\n return this.callParent([x*2]); // calls My.Derived2.method\n }\n }\n });\n\n alert(My.Derived2.method(10); // now alerts 40\n</code></pre>\n\n<p>To override a method and replace it and also call the superclass method, use\n<a href=\"#!/api/Ext.Base-method-callSuper\" rel=\"Ext.Base-method-callSuper\" class=\"docClass\">callSuper</a>. This is often done to patch a method to fix a bug.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>args</span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a>/Arguments<div class='sub-desc'><p>The arguments, either an array or the <code>arguments</code> object\nfrom the current method, for example: <code>this.callParent(arguments)</code></p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>Returns the result of calling the parent method</p>\n</div></li></ul></div></div></div><div id='method-callSuper' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-method-callSuper' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-method-callSuper' class='name expandable'>callSuper</a>( <span class='pre'>args</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>This method is used by an override to call the superclass method but bypass any\noverridden method. ...</div><div class='long'><p>This method is used by an override to call the superclass method but bypass any\noverridden method. This is often done to \"patch\" a method that contains a bug\nbut for whatever reason cannot be fixed directly.</p>\n\n<p>Consider:</p>\n\n<pre><code> <a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('Ext.some.Class', {\n method: function () {\n console.log('Good');\n }\n });\n\n <a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('Ext.some.DerivedClass', {\n method: function () {\n console.log('Bad');\n\n // ... logic but with a bug ...\n\n this.callParent();\n }\n });\n</code></pre>\n\n<p>To patch the bug in <code>DerivedClass.method</code>, the typical solution is to create an\noverride:</p>\n\n<pre><code> <a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('App.paches.DerivedClass', {\n override: 'Ext.some.DerivedClass',\n\n method: function () {\n console.log('Fixed');\n\n // ... logic but with bug fixed ...\n\n this.callSuper();\n }\n });\n</code></pre>\n\n<p>The patch method cannot use <code>callParent</code> to call the superclass <code>method</code> since\nthat would call the overridden method containing the bug. In other words, the\nabove patch would only produce \"Fixed\" then \"Good\" in the console log, whereas,\nusing <code>callParent</code> would produce \"Fixed\" then \"Bad\" then \"Good\".</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>args</span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a>/Arguments<div class='sub-desc'><p>The arguments, either an array or the <code>arguments</code> object\nfrom the current method, for example: <code>this.callSuper(arguments)</code></p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>Returns the result of calling the superclass method</p>\n</div></li></ul></div></div></div><div id='method-cancelFocus' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-cancelFocus' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-cancelFocus' class='name expandable'>cancelFocus</a>( <span class='pre'></span> )<strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Cancel any deferred focus on this component ...</div><div class='long'><p>Cancel any deferred focus on this component</p>\n</div></div></div><div id='method-captureArgs' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-captureArgs' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-captureArgs' class='name expandable'>captureArgs</a>( <span class='pre'>o, fn, scope</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>o</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>fn</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-center' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-center' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-center' class='name expandable'>center</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Center this Component in its container. ...</div><div class='long'><p>Center this Component in its container.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-clearListeners' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-clearListeners' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-clearListeners' class='name expandable'>clearListeners</a>( <span class='pre'></span> )</div><div class='description'><div class='short'>Removes all listeners for this object including the managed listeners ...</div><div class='long'><p>Removes all listeners for this object including the managed listeners</p>\n</div></div></div><div id='method-clearManagedListeners' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-clearManagedListeners' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-clearManagedListeners' class='name expandable'>clearManagedListeners</a>( <span class='pre'></span> )</div><div class='description'><div class='short'>Removes all managed listeners for this object. ...</div><div class='long'><p>Removes all managed listeners for this object.</p>\n</div></div></div><div id='method-cloneConfig' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-cloneConfig' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-cloneConfig' class='name expandable'>cloneConfig</a>( <span class='pre'>overrides</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Clone the current component using the original config values passed into this instance by default. ...</div><div class='long'><p>Clone the current component using the original config values passed into this instance by default.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>overrides</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>A new config containing any properties to override in the cloned version.\nAn id property can be passed on this object, otherwise one will be generated to avoid duplicates.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>clone The cloned copy of this component</p>\n</div></li></ul></div></div></div><div id='method-configClass' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-method-configClass' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-method-configClass' class='name expandable'>configClass</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-constructPlugin' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-constructPlugin' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-constructPlugin' class='name expandable'>constructPlugin</a>( <span class='pre'>ptype</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>ptype</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>string or config object containing a ptype property.</p>\n\n<p>Constructs a plugin according to the passed config object/ptype string.</p>\n\n<p>Ensures that the constructed plugin always has a <code>cmp</code> reference back to this component.\nThe setting up of this is done in PluginManager. The PluginManager ensures that a reference to this\ncomponent is passed to the constructor. It also ensures that the plugin's <code>setCmp</code> method (if any) is called.</p>\n</div></li></ul></div></div></div><div id='method-constructPlugins' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-constructPlugins' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-constructPlugins' class='name expandable'>constructPlugins</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Returns an array of fully constructed plugin instances. ...</div><div class='long'><p>Returns an array of fully constructed plugin instances. This converts any configs into their\nappropriate instances.</p>\n\n<p>It does not mutate the plugins array. It creates a new array.</p>\n</div></div></div><div id='method-continueFireEvent' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-continueFireEvent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-continueFireEvent' class='name expandable'>continueFireEvent</a>( <span class='pre'>eventName, args, bubbles</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Continue to fire event. ...</div><div class='long'><p>Continue to fire event.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>eventName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'>\n</div></li><li><span class='pre'>args</span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a><div class='sub-desc'>\n</div></li><li><span class='pre'>bubbles</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-convertPositionSpec' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent2.html#Ext-AbstractComponent-method-convertPositionSpec' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-convertPositionSpec' class='name expandable'>convertPositionSpec</a>( <span class='pre'>posSpec</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Defined in override Ext.rtl.AbstractComponent. ...</div><div class='long'><p><strong>Defined in override Ext.rtl.AbstractComponent.</strong></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>posSpec</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-createRelayer' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-createRelayer' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-createRelayer' class='name expandable'>createRelayer</a>( <span class='pre'>newName, [beginEnd]</span> ) : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Creates an event handling function which refires the event from this object as the passed event name. ...</div><div class='long'><p>Creates an event handling function which refires the event from this object as the passed event name.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>newName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The name under which to refire the passed parameters.</p>\n</div></li><li><span class='pre'>beginEnd</span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a> (optional)<div class='sub-desc'><p>The caller can specify on which indices to slice.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a></span><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-deleteMembers' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-deleteMembers' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-deleteMembers' class='name expandable'>deleteMembers</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-destroy' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-method-destroy' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-method-destroy' class='name expandable'>destroy</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<p>Overrides: <a href='#!/api/Ext.state.Stateful-method-destroy' rel='Ext.state.Stateful-method-destroy' class='docClass'>Ext.state.Stateful.destroy</a>, <a href='#!/api/Ext.util.ElementContainer-method-destroy' rel='Ext.util.ElementContainer-method-destroy' class='docClass'>Ext.util.ElementContainer.destroy</a>, <a href='#!/api/Ext.AbstractComponent-method-destroy' rel='Ext.AbstractComponent-method-destroy' class='docClass'>Ext.AbstractComponent.destroy</a>, <a href='#!/api/Ext.AbstractPlugin-method-destroy' rel='Ext.AbstractPlugin-method-destroy' class='docClass'>Ext.AbstractPlugin.destroy</a></p></div></div></div><div id='method-disable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-disable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-disable' class='name expandable'>disable</a>( <span class='pre'>[silent]</span> )</div><div class='description'><div class='short'>Disable the component. ...</div><div class='long'><p>Disable the component.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>silent</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>Passing <code>true</code> will suppress the <code>disable</code> event from being fired.</p>\n<p>Defaults to: <code>false</code></p></div></li></ul></div></div></div><div id='method-doApplyRenderTpl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-doApplyRenderTpl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-doApplyRenderTpl' class='name expandable'>doApplyRenderTpl</a>( <span class='pre'>out, values</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Called from the selected frame generation template to insert this Component's inner structure inside the framing stru...</div><div class='long'><p>Called from the selected frame generation template to insert this Component's inner structure inside the framing structure.</p>\n\n<p>When framing is used, a selected frame generation template is used as the primary template of the <a href=\"#!/api/Ext.util.Renderable-method-getElConfig\" rel=\"Ext.util.Renderable-method-getElConfig\" class=\"docClass\">getElConfig</a> instead\nof the configured <a href=\"#!/api/Ext.AbstractComponent-cfg-renderTpl\" rel=\"Ext.AbstractComponent-cfg-renderTpl\" class=\"docClass\">renderTpl</a>. The renderTpl is invoked by this method which is injected into the framing template.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>out</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>values</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-doAutoRender' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-doAutoRender' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-doAutoRender' class='name expandable'>doAutoRender</a>( <span class='pre'></span> )</div><div class='description'><div class='short'>Handles autoRender. ...</div><div class='long'><p>Handles autoRender.\nFloating Components may have an ownerCt. If they are asking to be constrained, constrain them within that\nownerCt, and have their z-index managed locally. Floating Components are always rendered to document.body</p>\n</div></div></div><div id='method-doComponentLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-doComponentLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-doComponentLayout' class='name expandable'>doComponentLayout</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>This method needs to be called whenever you change something on this component that requires the Component's\nlayout t...</div><div class='long'><p>This method needs to be called whenever you change something on this component that requires the Component's\nlayout to be recalculated.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-doConstrain' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-doConstrain' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-doConstrain' class='name expandable'>doConstrain</a>( <span class='pre'>[constrainTo]</span> )</div><div class='description'><div class='short'>Moves this floating Component into a constrain region. ...</div><div class='long'><p>Moves this floating Component into a constrain region.</p>\n\n<p>By default, this Component is constrained to be within the container it was added to, or the element it was\nrendered to.</p>\n\n<p>An alternative constraint may be passed.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>constrainTo</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/HTMLElement/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a>/<a href=\"#!/api/Ext.util.Region\" rel=\"Ext.util.Region\" class=\"docClass\">Ext.util.Region</a> (optional)<div class='sub-desc'><p>The Element or <a href=\"#!/api/Ext.util.Region\" rel=\"Ext.util.Region\" class=\"docClass\">Region</a>\ninto which this Component is to be constrained. Defaults to the element into which this floating Component\nwas rendered.</p>\n</div></li></ul></div></div></div><div id='method-doRenderContent' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-doRenderContent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-doRenderContent' class='name expandable'>doRenderContent</a>( <span class='pre'>out, renderData</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>out</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>renderData</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-doRenderFramingDockedItems' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-doRenderFramingDockedItems' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-doRenderFramingDockedItems' class='name expandable'>doRenderFramingDockedItems</a>( <span class='pre'>out, renderData, after</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>out</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>renderData</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>after</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-enable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-enable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-enable' class='name expandable'>enable</a>( <span class='pre'>[silent]</span> )</div><div class='description'><div class='short'>Enable the component ...</div><div class='long'><p>Enable the component</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>silent</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>Passing <code>true</code> will suppress the <code>enable</code> event from being fired.</p>\n<p>Defaults to: <code>false</code></p></div></li></ul></div></div></div><div id='method-enableBubble' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-enableBubble' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-enableBubble' class='name expandable'>enableBubble</a>( <span class='pre'>eventNames</span> )</div><div class='description'><div class='short'>Enables events fired by this Observable to bubble up an owner hierarchy by calling this.getBubbleTarget() if\npresent. ...</div><div class='long'><p>Enables events fired by this Observable to bubble up an owner hierarchy by calling <code>this.getBubbleTarget()</code> if\npresent. There is no implementation in the Observable base class.</p>\n\n<p>This is commonly used by Ext.Components to bubble events to owner Containers.\nSee <a href=\"#!/api/Ext.Component-method-getBubbleTarget\" rel=\"Ext.Component-method-getBubbleTarget\" class=\"docClass\">Ext.Component.getBubbleTarget</a>. The default implementation in <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> returns the\nComponent's immediate owner. But if a known target is required, this can be overridden to access the\nrequired target more quickly.</p>\n\n<p>Example:</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('Ext.overrides.form.field.Base', {\n override: '<a href=\"#!/api/Ext.form.field.Base\" rel=\"Ext.form.field.Base\" class=\"docClass\">Ext.form.field.Base</a>',\n\n // Add functionality to Field's initComponent to enable the change event to bubble\n initComponent: function () {\n this.callParent();\n this.enableBubble('change');\n }\n});\n\nvar myForm = <a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.form.Panel\" rel=\"Ext.form.Panel\" class=\"docClass\">Ext.form.Panel</a>', {\n title: 'User Details',\n items: [{\n ...\n }],\n listeners: {\n change: function() {\n // Title goes red if form has been modified.\n myForm.header.setStyle('color', 'red');\n }\n }\n});\n</code></pre>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>eventNames</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>[]<div class='sub-desc'><p>The event name to bubble, or an Array of event names.</p>\n</div></li></ul></div></div></div><div id='method-ensureAttachedToBody' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-ensureAttachedToBody' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-ensureAttachedToBody' class='name expandable'>ensureAttachedToBody</a>( <span class='pre'>[runLayout]</span> )</div><div class='description'><div class='short'>Ensures that this component is attached to document.body. ...</div><div class='long'><p>Ensures that this component is attached to <code>document.body</code>. If the component was\nrendered to <a href=\"#!/api/Ext-method-getDetachedBody\" rel=\"Ext-method-getDetachedBody\" class=\"docClass\">Ext.getDetachedBody</a>, then it will be appended to <code>document.body</code>.\nAny configured position is also restored.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>runLayout</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>True to run the component's layout.</p>\n<p>Defaults to: <code>false</code></p></div></li></ul></div></div></div><div id='method-findParentBy' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-findParentBy' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-findParentBy' class='name expandable'>findParentBy</a>( <span class='pre'>fn</span> ) : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a></div><div class='description'><div class='short'>Find a container above this component at any level by a custom function. ...</div><div class='long'><p>Find a container above this component at any level by a custom function. If the passed function returns true, the\ncontainer will be returned.</p>\n\n<p>See also the <a href=\"#!/api/Ext.Component-method-up\" rel=\"Ext.Component-method-up\" class=\"docClass\">up</a> method.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>fn</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a><div class='sub-desc'><p>The custom function to call with the arguments (container, this component).</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a></span><div class='sub-desc'><p>The first Container for which the custom function returns true</p>\n</div></li></ul></div></div></div><div id='method-findParentByType' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-findParentByType' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-findParentByType' class='name expandable'>findParentByType</a>( <span class='pre'>xtype</span> ) : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a></div><div class='description'><div class='short'>Find a container above this component at any level by xtype or class\n\nSee also the up method. ...</div><div class='long'><p>Find a container above this component at any level by xtype or class</p>\n\n<p>See also the <a href=\"#!/api/Ext.Component-method-up\" rel=\"Ext.Component-method-up\" class=\"docClass\">up</a> method.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>xtype</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Ext.Class\" rel=\"Ext.Class\" class=\"docClass\">Ext.Class</a><div class='sub-desc'><p>The xtype string for a component, or the class of the component directly</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a></span><div class='sub-desc'><p>The first Container which matches the given xtype or class</p>\n</div></li></ul></div></div></div><div id='method-findPlugin' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-findPlugin' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-findPlugin' class='name expandable'>findPlugin</a>( <span class='pre'>ptype</span> ) : <a href=\"#!/api/Ext.AbstractPlugin\" rel=\"Ext.AbstractPlugin\" class=\"docClass\">Ext.AbstractPlugin</a></div><div class='description'><div class='short'>Retrieves plugin from this component's collection by its ptype. ...</div><div class='long'><p>Retrieves plugin from this component's collection by its <code>ptype</code>.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>ptype</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The Plugin's ptype as specified by the class's <code>alias</code> configuration.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.AbstractPlugin\" rel=\"Ext.AbstractPlugin\" class=\"docClass\">Ext.AbstractPlugin</a></span><div class='sub-desc'><p>plugin instance.</p>\n</div></li></ul></div></div></div><div id='method-finishRender' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-finishRender' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-finishRender' class='name expandable'>finishRender</a>( <span class='pre'>containerIdx</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>This method visits the rendered component tree in a \"top-down\" order. ...</div><div class='long'><p>This method visits the rendered component tree in a \"top-down\" order. That is, this\ncode runs on a parent component before running on a child. This method calls the\n<a href=\"#!/api/Ext.util.Renderable-method-onRender\" rel=\"Ext.util.Renderable-method-onRender\" class=\"docClass\">onRender</a> method of each component.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>containerIdx</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The index into the Container items of this Component.</p>\n</div></li></ul></div></div></div><div id='method-finishRenderChildren' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-finishRenderChildren' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-finishRenderChildren' class='name expandable'>finishRenderChildren</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-fireEvent' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-fireEvent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-fireEvent' class='name expandable'>fireEvent</a>( <span class='pre'>eventName, args</span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Fires the specified event with the passed parameters (minus the event name, plus the options object passed\nto addList...</div><div class='long'><p>Fires the specified event with the passed parameters (minus the event name, plus the <code>options</code> object passed\nto <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">addListener</a>).</p>\n\n<p>An event may be set to bubble up an Observable parent hierarchy (See <a href=\"#!/api/Ext.Component-method-getBubbleTarget\" rel=\"Ext.Component-method-getBubbleTarget\" class=\"docClass\">Ext.Component.getBubbleTarget</a>) by\ncalling <a href=\"#!/api/Ext.util.Observable-method-enableBubble\" rel=\"Ext.util.Observable-method-enableBubble\" class=\"docClass\">enableBubble</a>.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>eventName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The name of the event to fire.</p>\n</div></li><li><span class='pre'>args</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>...<div class='sub-desc'><p>Variable number of parameters are passed to handlers.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p>returns false if any of the handlers return false otherwise it returns true.</p>\n</div></li></ul></div></div></div><div id='method-fireEventArgs' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-fireEventArgs' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-fireEventArgs' class='name expandable'>fireEventArgs</a>( <span class='pre'>eventName, args</span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Fires the specified event with the passed parameter list. ...</div><div class='long'><p>Fires the specified event with the passed parameter list.</p>\n\n<p>An event may be set to bubble up an Observable parent hierarchy (See <a href=\"#!/api/Ext.Component-method-getBubbleTarget\" rel=\"Ext.Component-method-getBubbleTarget\" class=\"docClass\">Ext.Component.getBubbleTarget</a>) by\ncalling <a href=\"#!/api/Ext.util.Observable-method-enableBubble\" rel=\"Ext.util.Observable-method-enableBubble\" class=\"docClass\">enableBubble</a>.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>eventName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The name of the event to fire.</p>\n</div></li><li><span class='pre'>args</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>[]<div class='sub-desc'><p>An array of parameters which are passed to handlers.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p>returns false if any of the handlers return false otherwise it returns true.</p>\n</div></li></ul></div></div></div><div id='method-fireHierarchyEvent' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-fireHierarchyEvent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-fireHierarchyEvent' class='name expandable'>fireHierarchyEvent</a>( <span class='pre'>ename</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>For more information on the hierarchy events, see the note for the\nhierarchyEventSource observer defined in the onCla...</div><div class='long'><p>For more information on the hierarchy events, see the note for the\nhierarchyEventSource observer defined in the onClassCreated callback.</p>\n\n<p>This functionality is contained in Component (as opposed to Container)\nbecause a Component can be the ownerCt for a floating component (loadmask),\nand the loadmask needs to know when its owner is shown/hidden via the\nhierarchyEventSource so that its hidden state can be synchronized.</p>\n\n<p>TODO: merge this functionality with <a href=\"#!/api/Ext-property-globalEvents\" rel=\"Ext-property-globalEvents\" class=\"docClass\">Ext.globalEvents</a></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>ename</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-fitContainer' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-fitContainer' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-fitContainer' class='name expandable'>fitContainer</a>( <span class='pre'>animate</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>animate</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-focus' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-focus' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-focus' class='name expandable'>focus</a>( <span class='pre'>[selectText], [delay], [callback], [scope]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Try to focus this component. ...</div><div class='long'><p>Try to focus this component.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>selectText</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>If applicable, true to also select the text in this component</p>\n</div></li><li><span class='pre'>delay</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>Delay the focus this number of milliseconds (true for 10 milliseconds).</p>\n</div></li><li><span class='pre'>callback</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'><p>Only needed if the <code>delay</code> parameter is used. A function to call upon focus.</p>\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'><p>Only needed if the <code>delay</code> parameter is used. The scope (<code>this</code> reference) in which to execute the callback.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>The focused Component. Usually <code>this</code> Component. Some Containers may\ndelegate focus to a descendant Component (<a href=\"#!/api/Ext.window.Window\" rel=\"Ext.window.Window\" class=\"docClass\">Window</a>s can do this through their\n<a href=\"#!/api/Ext.window.Window-cfg-defaultFocus\" rel=\"Ext.window.Window-cfg-defaultFocus\" class=\"docClass\">defaultFocus</a> config option.</p>\n</div></li></ul></div></div></div><div id='method-forceComponentLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-forceComponentLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-forceComponentLayout' class='name expandable'>forceComponentLayout</a>( <span class='pre'></span> )<strong class='deprecated signature' >deprecated</strong></div><div class='description'><div class='short'>Forces this component to redo its componentLayout. ...</div><div class='long'><p>Forces this component to redo its componentLayout.</p>\n <div class='signature-box deprecated'>\n <p>This method has been <strong>deprecated</strong> since 4.1.0</p>\n <p>Use <a href=\"#!/api/Ext.AbstractComponent-method-updateLayout\" rel=\"Ext.AbstractComponent-method-updateLayout\" class=\"docClass\">updateLayout</a> instead.</p>\n\n </div>\n</div></div></div><div id='method-getActionEl' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getActionEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getActionEl' class='name expandable'>getActionEl</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Deprecate 5.0 ...</div><div class='long'><p>Deprecate 5.0</p>\n</div></div></div><div id='method-getActiveAnimation' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Animate' rel='Ext.util.Animate' class='defined-in docClass'>Ext.util.Animate</a><br/><a href='source/Animate.html#Ext-util-Animate-method-getActiveAnimation' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Animate-method-getActiveAnimation' class='name expandable'>getActiveAnimation</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.fx.Anim\" rel=\"Ext.fx.Anim\" class=\"docClass\">Ext.fx.Anim</a>/<a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Returns the current animation if this object has any effects actively running or queued, else returns false. ...</div><div class='long'><p>Returns the current animation if this object has any effects actively running or queued, else returns false.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.fx.Anim\" rel=\"Ext.fx.Anim\" class=\"docClass\">Ext.fx.Anim</a>/<a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p>Anim if element has active effects, else false</p>\n\n</div></li></ul></div></div></div><div id='method-getAlignToXY' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-getAlignToXY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-getAlignToXY' class='name expandable'>getAlignToXY</a>( <span class='pre'>element, [position], [offsets]</span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</div><div class='description'><div class='short'>Gets the x,y coordinates to align this element with another element. ...</div><div class='long'><p>Gets the x,y coordinates to align this element with another element. See\n<a href=\"#!/api/Ext.util.Positionable-method-alignTo\" rel=\"Ext.util.Positionable-method-alignTo\" class=\"docClass\">alignTo</a> for more info on the supported position values.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>element</span> : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a>/HTMLElement/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The Positionable,\nHTMLElement, or id of the element to align to.</p>\n</div></li><li><span class='pre'>position</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>The position to align to</p>\n<p>Defaults to: <code>&quot;tl-bl?&quot;</code></p></div></li><li><span class='pre'>offsets</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[] (optional)<div class='sub-desc'><p>Offset the positioning by [x, y]</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</span><div class='sub-desc'><p>[x, y]</p>\n</div></li></ul></div></div></div><div id='method-getAnchor' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-getAnchor' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-getAnchor' class='name expandable'>getAnchor</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>private ...</div><div class='long'><p>private</p>\n</div></div></div><div id='method-getAnchorToXY' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getAnchorToXY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getAnchorToXY' class='name expandable'>getAnchorToXY</a>( <span class='pre'>el, [anchor], [local], [size]</span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Begin Positionable methods\n\n\n\nOverridden in Ext.rtl.AbstractComponent. ...</div><div class='long'><hr />\n\n<p> Begin Positionable methods</p>\n\n<hr />\n\n<p><strong>Overridden in Ext.rtl.AbstractComponent.</strong></p>\n\n<p>Gets the x,y coordinates of an element specified by the anchor position on the\nelement.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>el</span> : <a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.dom.Element</a><div class='sub-desc'><p>The element</p>\n</div></li><li><span class='pre'>anchor</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>The specified anchor position.\nSee <a href=\"#!/api/Ext.AbstractComponent-method-alignTo\" rel=\"Ext.AbstractComponent-method-alignTo\" class=\"docClass\">alignTo</a> for details on supported anchor positions.</p>\n<p>Defaults to: <code>'tl'</code></p></div></li><li><span class='pre'>local</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>True to get the local (element top/left-relative) anchor\nposition instead of page coordinates</p>\n</div></li><li><span class='pre'>size</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>An object containing the size to use for calculating anchor\nposition {width: (target width), height: (target height)} (defaults to the\nelement's current size)</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</span><div class='sub-desc'><p>[x, y] An array containing the element's x and y coordinates</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-getAnchorToXY' rel='Ext.util.Positionable-method-getAnchorToXY' class='docClass'>Ext.util.Positionable.getAnchorToXY</a></p></div></div></div><div id='method-getAnchorXY' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-getAnchorXY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-getAnchorXY' class='name expandable'>getAnchorXY</a>( <span class='pre'>[anchor], [local], [size]</span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</div><div class='description'><div class='short'>Gets the x,y coordinates specified by the anchor position on the element. ...</div><div class='long'><p>Gets the x,y coordinates specified by the anchor position on the element.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>anchor</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>The specified anchor position.\nSee <a href=\"#!/api/Ext.util.Positionable-method-alignTo\" rel=\"Ext.util.Positionable-method-alignTo\" class=\"docClass\">alignTo</a> for details on supported anchor positions.</p>\n<p>Defaults to: <code>'tl'</code></p></div></li><li><span class='pre'>local</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>True to get the local (element top/left-relative) anchor\nposition instead of page coordinates</p>\n</div></li><li><span class='pre'>size</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>An object containing the size to use for calculating anchor\nposition {width: (target width), height: (target height)} (defaults to the\nelement's current size)</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</span><div class='sub-desc'><p>[x, y] An array containing the element's x and y coordinates</p>\n</div></li></ul></div></div></div><div id='method-getAnimateTarget' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getAnimateTarget' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getAnimateTarget' class='name expandable'>getAnimateTarget</a>( <span class='pre'>target</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>target</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-getAutoId' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getAutoId' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getAutoId' class='name expandable'>getAutoId</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-getBorderPadding' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getBorderPadding' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getBorderPadding' class='name expandable'>getBorderPadding</a>( <span class='pre'></span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Overridden in Ext.rtl.AbstractComponent. ...</div><div class='long'><p><strong>Overridden in Ext.rtl.AbstractComponent.</strong></p>\n\n<p>Returns the size of the element's borders and padding.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>an object with the following numeric properties\n- beforeX\n- afterX\n- beforeY\n- afterY</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-getBorderPadding' rel='Ext.util.Positionable-method-getBorderPadding' class='docClass'>Ext.util.Positionable.getBorderPadding</a></p></div></div></div><div id='method-getBox' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-getBox' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-getBox' class='name expandable'>getBox</a>( <span class='pre'>[contentBox], [local]</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>Return an object defining the area of this Element which can be passed to\nsetBox to set another Element's size/locati...</div><div class='long'><p>Return an object defining the area of this Element which can be passed to\n<a href=\"#!/api/Ext.util.Positionable-method-setBox\" rel=\"Ext.util.Positionable-method-setBox\" class=\"docClass\">setBox</a> to set another Element's size/location to match this element.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>contentBox</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>If true a box for the content of the element is\nreturned.</p>\n</div></li><li><span class='pre'>local</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>If true the element's left and top relative to its\n<code>offsetParent</code> are returned instead of page x/y.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>box An object in the format:</p>\n\n<pre><code>{\n x: &lt;Element's X position&gt;,\n y: &lt;Element's Y position&gt;,\n left: &lt;Element's X position (an alias for x)&gt;,\n top: &lt;Element's Y position (an alias for y)&gt;,\n width: &lt;Element's width&gt;,\n height: &lt;Element's height&gt;,\n bottom: &lt;Element's lower bound&gt;,\n right: &lt;Element's rightmost bound&gt;\n}\n</code></pre>\n\n<p>The returned object may also be addressed as an Array where index 0 contains the X\nposition and index 1 contains the Y position. The result may also be used for\n<a href=\"#!/api/Ext.util.Positionable-method-setXY\" rel=\"Ext.util.Positionable-method-setXY\" class=\"docClass\">setXY</a></p>\n</div></li></ul></div></div></div><div id='method-getBubbleParent' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-getBubbleParent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-getBubbleParent' class='name expandable'>getBubbleParent</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.util.Observable\" rel=\"Ext.util.Observable\" class=\"docClass\">Ext.util.Observable</a><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Gets the bubbling parent for an Observable ...</div><div class='long'><p>Gets the bubbling parent for an Observable</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Observable\" rel=\"Ext.util.Observable\" class=\"docClass\">Ext.util.Observable</a></span><div class='sub-desc'><p>The bubble parent. null is returned if no bubble target exists</p>\n</div></li></ul></div></div></div><div id='method-getBubbleTarget' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getBubbleTarget' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getBubbleTarget' class='name expandable'>getBubbleTarget</a>( <span class='pre'></span> )<strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Implements an upward event bubbling policy. ...</div><div class='long'><p>Implements an upward event bubbling policy. By default a Component bubbles events up to its <a href=\"#!/api/Ext.Component-method-getRefOwner\" rel=\"Ext.Component-method-getRefOwner\" class=\"docClass\">reference owner</a>.</p>\n\n<p>Component subclasses may implement a different bubbling strategy by overriding this method.</p>\n<p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-getBubbleTarget' rel='Ext.AbstractComponent-method-getBubbleTarget' class='docClass'>Ext.AbstractComponent.getBubbleTarget</a></p></div></div></div><div id='method-getChildEls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.ElementContainer' rel='Ext.util.ElementContainer' class='defined-in docClass'>Ext.util.ElementContainer</a><br/><a href='source/ElementContainer.html#Ext-util-ElementContainer-method-getChildEls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.ElementContainer-method-getChildEls' class='name expandable'>getChildEls</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-getClassChildEls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.ElementContainer' rel='Ext.util.ElementContainer' class='defined-in docClass'>Ext.util.ElementContainer</a><br/><a href='source/ElementContainer.html#Ext-util-ElementContainer-method-getClassChildEls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.ElementContainer-method-getClassChildEls' class='name expandable'>getClassChildEls</a>( <span class='pre'>cls</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>cls</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-getComponentLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getComponentLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getComponentLayout' class='name expandable'>getComponentLayout</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-getConfig' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-method-getConfig' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-method-getConfig' class='name expandable'>getConfig</a>( <span class='pre'>name</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>name</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-getConstrainVector' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-getConstrainVector' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-getConstrainVector' class='name expandable'>getConstrainVector</a>( <span class='pre'>[constrainTo], [proposedPosition], [proposedSize]</span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]/<a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Returns the [X, Y] vector by which this Positionable's element must be translated to make a best\nattempt to constrain...</div><div class='long'><p>Returns the <code>[X, Y]</code> vector by which this Positionable's element must be translated to make a best\nattempt to constrain within the passed constraint. Returns <code>false</code> if the element\ndoes not need to be moved.</p>\n\n<p>Priority is given to constraining the top and left within the constraint.</p>\n\n<p>The constraint may either be an existing element into which the element is to be\nconstrained, or a <a href=\"#!/api/Ext.util.Region\" rel=\"Ext.util.Region\" class=\"docClass\">Region</a> into which this element is to be\nconstrained.</p>\n\n<p>By default, any extra shadow around the element is <strong>not</strong> included in the constrain calculations - the edges\nof the element are used as the element bounds. To constrain the shadow within the constrain region, set the\n<code>constrainShadow</code> property on this element to <code>true</code>.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>constrainTo</span> : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a>/HTMLElement/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Ext.util.Region\" rel=\"Ext.util.Region\" class=\"docClass\">Ext.util.Region</a> (optional)<div class='sub-desc'><p>The\nPositionable, HTMLElement, element id, or Region into which the element is to be\nconstrained.</p>\n</div></li><li><span class='pre'>proposedPosition</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[] (optional)<div class='sub-desc'><p>A proposed <code>[X, Y]</code> position to test for validity\nand to produce a vector for instead of using the element's current position</p>\n</div></li><li><span class='pre'>proposedSize</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[] (optional)<div class='sub-desc'><p>A proposed <code>[width, height]</code> size to constrain\ninstead of using the element's current size</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]/<a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p><strong>If</strong> the element <em>needs</em> to be translated, an <code>[X, Y]</code>\nvector by which this element must be translated. Otherwise, <code>false</code>.</p>\n</div></li></ul></div></div></div><div id='method-getContentTarget' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getContentTarget' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getContentTarget' class='name expandable'>getContentTarget</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-getDragEl' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getDragEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getDragEl' class='name expandable'>getDragEl</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-getEl' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getEl' class='name expandable'>getEl</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.dom.Element</a></div><div class='description'><div class='short'>Retrieves the top level element representing this component. ...</div><div class='long'><p>Retrieves the top level element representing this component.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.dom.Element</a></span><div class='sub-desc'>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-getEl' rel='Ext.AbstractComponent-method-getEl' class='docClass'>Ext.AbstractComponent.getEl</a></p></div></div></div><div id='method-getElConfig' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-getElConfig' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-getElConfig' class='name expandable'>getElConfig</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-getFocusEl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getFocusEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getFocusEl' class='name expandable'>getFocusEl</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Returns the focus holder element associated with this Component. ...</div><div class='long'><p>Returns the focus holder element associated with this Component. At the Component base class level, this function returns <code>undefined</code>.</p>\n\n<p>Subclasses which use embedded focusable elements (such as Window, Field and Button) should override this\nfor use by the <a href=\"#!/api/Ext.Component-method-focus\" rel=\"Ext.Component-method-focus\" class=\"docClass\">focus</a> method.</p>\n\n<p>Containers which need to participate in the <a href=\"#!/api/Ext.FocusManager\" rel=\"Ext.FocusManager\" class=\"docClass\">FocusManager</a>'s navigation and Container focusing scheme also\nneed to return a <code>focusEl</code>, although focus is only listened for in this case if the <a href=\"#!/api/Ext.FocusManager\" rel=\"Ext.FocusManager\" class=\"docClass\">FocusManager</a> is <a href=\"#!/api/Ext.FocusManager-method-enable\" rel=\"Ext.FocusManager-method-enable\" class=\"docClass\">enable</a>d.</p>\n</div></div></div><div id='method-getFrameInfo' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-getFrameInfo' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-getFrameInfo' class='name expandable'>getFrameInfo</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>On render, reads an encoded style attribute, \"filter\" from the style of this Component's element. ...</div><div class='long'><p>On render, reads an encoded style attribute, \"filter\" from the style of this Component's element.\nThis information is memoized based upon the CSS class name of this Component's element.\nBecause child Components are rendered as textual HTML as part of the topmost Container, a dummy div is inserted\ninto the document to receive the document element's CSS class name, and therefore style attributes.</p>\n</div></div></div><div id='method-getFrameRenderData' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-getFrameRenderData' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-getFrameRenderData' class='name expandable'>getFrameRenderData</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-getFrameTpl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-getFrameTpl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-getFrameTpl' class='name expandable'>getFrameTpl</a>( <span class='pre'>table</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>table</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-getFramingInfoCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-getFramingInfoCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-getFramingInfoCls' class='name expandable'>getFramingInfoCls</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-getHeight' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getHeight' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getHeight' class='name expandable'>getHeight</a>( <span class='pre'></span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></div><div class='description'><div class='short'>Gets the current height of the component's underlying element. ...</div><div class='long'><p>Gets the current height of the component's underlying element.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-getHierarchyState' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getHierarchyState' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getHierarchyState' class='name expandable'>getHierarchyState</a>( <span class='pre'>inner</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>A component's hierarchyState is used to keep track of aspects of a component's\nstate that affect its descendants hier...</div><div class='long'><p>A component's hierarchyState is used to keep track of aspects of a component's\nstate that affect its descendants hierarchically like \"collapsed\" and \"hidden\".\nFor example, if this.hierarchyState.hidden == true, it means that either this\ncomponent, or one of its ancestors is hidden.</p>\n\n<p>Hierarchical state management is implemented by chaining each component's\nhierarchyState property to its parent container's hierarchyState property via the\nprototype. The result is such that if a component's hierarchyState does not have\nit's own property, it inherits the property from the nearest ancestor that does.</p>\n\n<p>To set a hierarchical \"hidden\" value:</p>\n\n<pre><code>this.getHierarchyState().hidden = true;\n</code></pre>\n\n<p>It is important to remember when unsetting hierarchyState properties to delete\nthem instead of just setting them to a falsy value. This ensures that the\nhierarchyState returns to a state of inheriting the value instead of overriding it\nTo unset the hierarchical \"hidden\" value:</p>\n\n<pre><code>delete this.getHierarchyState().hidden;\n</code></pre>\n\n<p>IMPORTANT! ALWAYS access hierarchyState using this method, not by accessing\nthis.hierarchyState directly. The hierarchyState property does not exist until\nthe first time getHierarchyState() is called. At that point getHierarchyState()\nwalks up the component tree to establish the hierarchyState prototype chain.\nAdditionally the hierarchyState property should NOT be relied upon even after\nthe initial call to getHierarchyState() because it is possible for the\nhierarchyState to be invalidated. Invalidation typically happens when a component\nis moved to a new container. In such a case the hierarchy state remains invalid\nuntil the next time getHierarchyState() is called on the component or one of its\ndescendants.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>inner</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-getId' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getId' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getId' class='name expandable'>getId</a>( <span class='pre'></span> ) : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></div><div class='description'><div class='short'>Retrieves the id of this component. ...</div><div class='long'><p>Retrieves the <code>id</code> of this component. Will auto-generate an <code>id</code> if one has not already been set.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><div class='sub-desc'>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-getId' rel='Ext.AbstractComponent-method-getId' class='docClass'>Ext.AbstractComponent.getId</a></p></div></div></div><div id='method-getInitialConfig' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-method-getInitialConfig' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-method-getInitialConfig' class='name expandable'>getInitialConfig</a>( <span class='pre'>[name]</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>/Mixed</div><div class='description'><div class='short'>Returns the initial configuration passed to constructor when instantiating\nthis class. ...</div><div class='long'><p>Returns the initial configuration passed to constructor when instantiating\nthis class.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>name</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>Name of the config option to return.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>/Mixed</span><div class='sub-desc'><p>The full config object or a single config value\nwhen <code>name</code> parameter specified.</p>\n</div></li></ul></div></div></div><div id='method-getInsertPosition' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-getInsertPosition' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-getInsertPosition' class='name expandable'>getInsertPosition</a>( <span class='pre'>position</span> ) : HTMLElement</div><div class='description'><div class='short'>This function takes the position argument passed to onRender and returns a\nDOM element that you can use in the insert...</div><div class='long'><p>This function takes the position argument passed to onRender and returns a\nDOM element that you can use in the insertBefore.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>position</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.dom.Element</a>/HTMLElement<div class='sub-desc'><p>Index, element id or element you want\nto put this component before.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'>HTMLElement</span><div class='sub-desc'><p>DOM element that you can use in the insertBefore</p>\n</div></li></ul></div></div></div><div id='method-getItemId' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getItemId' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getItemId' class='name expandable'>getItemId</a>( <span class='pre'></span> ) : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></div><div class='description'><div class='short'>Returns the value of itemId assigned to this component, or when that\nis not set, returns the value of id. ...</div><div class='long'><p>Returns the value of <a href=\"#!/api/Ext.AbstractComponent-cfg-itemId\" rel=\"Ext.AbstractComponent-cfg-itemId\" class=\"docClass\">itemId</a> assigned to this component, or when that\nis not set, returns the value of <a href=\"#!/api/Ext.AbstractComponent-cfg-id\" rel=\"Ext.AbstractComponent-cfg-id\" class=\"docClass\">id</a>.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-getLoader' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getLoader' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getLoader' class='name expandable'>getLoader</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.ComponentLoader\" rel=\"Ext.ComponentLoader\" class=\"docClass\">Ext.ComponentLoader</a></div><div class='description'><div class='short'>Gets the Ext.ComponentLoader for this Component. ...</div><div class='long'><p>Gets the <a href=\"#!/api/Ext.ComponentLoader\" rel=\"Ext.ComponentLoader\" class=\"docClass\">Ext.ComponentLoader</a> for this Component.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.ComponentLoader\" rel=\"Ext.ComponentLoader\" class=\"docClass\">Ext.ComponentLoader</a></span><div class='sub-desc'><p>The loader instance, null if it doesn't exist.</p>\n</div></li></ul></div></div></div><div id='method-getLocalX' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getLocalX' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getLocalX' class='name expandable'>getLocalX</a>( <span class='pre'></span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></div><div class='description'><div class='short'>Overridden in Ext.rtl.AbstractComponent. ...</div><div class='long'><p><strong>Overridden in Ext.rtl.AbstractComponent.</strong></p>\n\n<p>Returns the x coordinate of this element reletive to its <code>offsetParent</code>.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span><div class='sub-desc'><p>The local x coordinate</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-getLocalX' rel='Ext.util.Positionable-method-getLocalX' class='docClass'>Ext.util.Positionable.getLocalX</a></p></div></div></div><div id='method-getLocalXY' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getLocalXY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getLocalXY' class='name expandable'>getLocalXY</a>( <span class='pre'></span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</div><div class='description'><div class='short'>Overridden in Ext.rtl.AbstractComponent. ...</div><div class='long'><p><strong>Overridden in Ext.rtl.AbstractComponent.</strong></p>\n\n<p>Returns the x and y coordinates of this element relative to its <code>offsetParent</code>.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</span><div class='sub-desc'><p>The local XY position of the element</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-getLocalXY' rel='Ext.util.Positionable-method-getLocalXY' class='docClass'>Ext.util.Positionable.getLocalXY</a></p></div></div></div><div id='method-getLocalY' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getLocalY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getLocalY' class='name expandable'>getLocalY</a>( <span class='pre'></span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></div><div class='description'><div class='short'>Returns the y coordinate of this element reletive to its offsetParent. ...</div><div class='long'><p>Returns the y coordinate of this element reletive to its <code>offsetParent</code>.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span><div class='sub-desc'><p>The local y coordinate</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-getLocalY' rel='Ext.util.Positionable-method-getLocalY' class='docClass'>Ext.util.Positionable.getLocalY</a></p></div></div></div><div id='method-getMaskTarget' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getMaskTarget' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getMaskTarget' class='name expandable'>getMaskTarget</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-getOffsetsTo' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-getOffsetsTo' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-getOffsetsTo' class='name expandable'>getOffsetsTo</a>( <span class='pre'>offsetsTo</span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</div><div class='description'><div class='short'>Returns the offsets of this element from the passed element. ...</div><div class='long'><p>Returns the offsets of this element from the passed element. The element must both\nbe part of the DOM tree and not have display:none to have page coordinates.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>offsetsTo</span> : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a>/HTMLElement/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The Positionable,\nHTMLElement, or element id to get get the offsets from.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</span><div class='sub-desc'><p>The XY page offsets (e.g. <code>[100, -200]</code>)</p>\n</div></li></ul></div></div></div><div id='method-getOuterSize' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getOuterSize' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getOuterSize' class='name expandable'>getOuterSize</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Include margins ...</div><div class='long'><p>Include margins</p>\n</div></div></div><div id='method-getOverflowEl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getOverflowEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getOverflowEl' class='name expandable'>getOverflowEl</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Get an el for overflowing, defaults to the target el ...</div><div class='long'><p>Get an el for overflowing, defaults to the target el</p>\n</div></div></div><div id='method-getOverflowStyle' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getOverflowStyle' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getOverflowStyle' class='name expandable'>getOverflowStyle</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Returns the CSS style object which will set the Component's scroll styles. ...</div><div class='long'><p>Returns the CSS style object which will set the Component's scroll styles. This must be applied\nto the <a href=\"#!/api/Ext.AbstractComponent-method-getTargetEl\" rel=\"Ext.AbstractComponent-method-getTargetEl\" class=\"docClass\">target element</a>.</p>\n</div></div></div><div id='method-getOwningBorderContainer' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Region2.html#Ext-Component-method-getOwningBorderContainer' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getOwningBorderContainer' class='name expandable'>getOwningBorderContainer</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Returns the owning container if that container uses border layout. ...</div><div class='long'><p>Returns the owning container if that container uses <code>border</code> layout. Otherwise\nthis method returns <code>null</code>.</p>\n\n<p><strong>Defined in override Ext.layout.container.border.Region.</strong></p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a></span><div class='sub-desc'><p>The owning border container or <code>null</code>.</p>\n</div></li></ul></div></div></div><div id='method-getOwningBorderLayout' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Region2.html#Ext-Component-method-getOwningBorderLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getOwningBorderLayout' class='name expandable'>getOwningBorderLayout</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.layout.container.Border\" rel=\"Ext.layout.container.Border\" class=\"docClass\">Ext.layout.container.Border</a><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Returns the owning border (Ext.layout.container.Border) instance if there is\none. ...</div><div class='long'><p>Returns the owning <code>border</code> (<code><a href=\"#!/api/Ext.layout.container.Border\" rel=\"Ext.layout.container.Border\" class=\"docClass\">Ext.layout.container.Border</a></code>) instance if there is\none. Otherwise this method returns <code>null</code>.</p>\n\n<p><strong>Defined in override Ext.layout.container.border.Region.</strong></p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.layout.container.Border\" rel=\"Ext.layout.container.Border\" class=\"docClass\">Ext.layout.container.Border</a></span><div class='sub-desc'><p>The owning border layout or <code>null</code>.</p>\n</div></li></ul></div></div></div><div id='method-getPlugin' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getPlugin' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getPlugin' class='name expandable'>getPlugin</a>( <span class='pre'>pluginId</span> ) : <a href=\"#!/api/Ext.AbstractPlugin\" rel=\"Ext.AbstractPlugin\" class=\"docClass\">Ext.AbstractPlugin</a></div><div class='description'><div class='short'>Retrieves a plugin from this component's collection by its pluginId. ...</div><div class='long'><p>Retrieves a plugin from this component's collection by its <code>pluginId</code>.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>pluginId</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.AbstractPlugin\" rel=\"Ext.AbstractPlugin\" class=\"docClass\">Ext.AbstractPlugin</a></span><div class='sub-desc'><p>plugin instance.</p>\n</div></li></ul></div></div></div><div id='method-getPosition' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getPosition' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getPosition' class='name expandable'>getPosition</a>( <span class='pre'>[local]</span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</div><div class='description'><div class='short'>Gets the current XY position of the component's underlying element. ...</div><div class='long'><p>Gets the current XY position of the component's underlying element.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>local</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>If true the element's left and top are returned instead of page XY.</p>\n<p>Defaults to: <code>false</code></p></div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</span><div class='sub-desc'><p>The XY position of the element (e.g., [100, 200])</p>\n</div></li></ul></div></div></div><div id='method-getPositionEl' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getPositionEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getPositionEl' class='name expandable'>getPositionEl</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Deprecate 5.0 ...</div><div class='long'><p>Deprecate 5.0</p>\n</div></div></div><div id='method-getProxy' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getProxy' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getProxy' class='name expandable'>getProxy</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-getRefOwner' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getRefOwner' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getRefOwner' class='name expandable'>getRefOwner</a>( <span class='pre'></span> )<strong class='private signature' >private</strong><strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Used by ComponentQuery, and the up method to find the\nowning Component in the linkage hierarchy. ...</div><div class='long'><p>Used by <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">ComponentQuery</a>, and the <a href=\"#!/api/Ext.AbstractComponent-method-up\" rel=\"Ext.AbstractComponent-method-up\" class=\"docClass\">up</a> method to find the\nowning Component in the linkage hierarchy.</p>\n\n<p>By default this returns the Container which contains this Component.</p>\n\n<p>This may be overriden by Component authors who implement ownership hierarchies which are not\nbased upon ownerCt, such as BoundLists being owned by Fields or Menus being owned by Buttons.</p>\n</div></div></div><div id='method-getRegion' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-getRegion' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-getRegion' class='name expandable'>getRegion</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.util.Region\" rel=\"Ext.util.Region\" class=\"docClass\">Ext.util.Region</a></div><div class='description'><div class='short'>Returns a region object that defines the area of this element. ...</div><div class='long'><p>Returns a region object that defines the area of this element.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Region\" rel=\"Ext.util.Region\" class=\"docClass\">Ext.util.Region</a></span><div class='sub-desc'><p>A Region containing \"top, left, bottom, right\" properties.</p>\n</div></li></ul></div></div></div><div id='method-getRenderTree' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-getRenderTree' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-getRenderTree' class='name expandable'>getRenderTree</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-getResizeEl' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getResizeEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getResizeEl' class='name expandable'>getResizeEl</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Deprecate 5.0 ...</div><div class='long'><p>Deprecate 5.0</p>\n</div></div></div><div id='method-getSize' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getSize' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getSize' class='name expandable'>getSize</a>( <span class='pre'></span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>Gets the current size of the component's underlying element. ...</div><div class='long'><p>Gets the current size of the component's underlying element.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>An object containing the element's size <code>{width: (element width), height: (element height)}</code></p>\n</div></li></ul></div></div></div><div id='method-getSizeModel' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getSizeModel' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getSizeModel' class='name expandable'>getSizeModel</a>( <span class='pre'>ownerCtSizeModel</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>Returns an object that describes how this component's width and height are managed. ...</div><div class='long'><p>Returns an object that describes how this component's width and height are managed.\nAll of these objects are shared and should not be modified.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>ownerCtSizeModel</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>The size model for this component.</p>\n<ul><li><span class='pre'>width</span> : <a href=\"#!/api/Ext.layout.SizeModel\" rel=\"Ext.layout.SizeModel\" class=\"docClass\">Ext.layout.SizeModel</a><div class='sub-desc'><p>The <a href=\"#!/api/Ext.layout.SizeModel\" rel=\"Ext.layout.SizeModel\" class=\"docClass\">size model</a>\nfor the width.</p>\n</div></li><li><span class='pre'>height</span> : <a href=\"#!/api/Ext.layout.SizeModel\" rel=\"Ext.layout.SizeModel\" class=\"docClass\">Ext.layout.SizeModel</a><div class='sub-desc'><p>The <a href=\"#!/api/Ext.layout.SizeModel\" rel=\"Ext.layout.SizeModel\" class=\"docClass\">size model</a>\nfor the height.</p>\n</div></li></ul></div></li></ul></div></div></div><div id='method-getState' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getState' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getState' class='name expandable'>getState</a>( <span class='pre'></span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>The supplied default state gathering method for the AbstractComponent class. ...</div><div class='long'><p>The supplied default state gathering method for the AbstractComponent class.</p>\n\n<p>This method returns dimension settings such as <code>flex</code>, <code>anchor</code>, <code>width</code> and <code>height</code> along with <code>collapsed</code>\nstate.</p>\n\n<p>Subclasses which implement more complex state should call the superclass's implementation, and apply their state\nto the result if this basic state is to be saved.</p>\n\n<p>Note that Component state will only be saved if the Component has a <a href=\"#!/api/Ext.AbstractComponent-cfg-stateId\" rel=\"Ext.AbstractComponent-cfg-stateId\" class=\"docClass\">stateId</a> and there as a StateProvider\nconfigured for the document.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.state.Stateful-method-getState' rel='Ext.state.Stateful-method-getState' class='docClass'>Ext.state.Stateful.getState</a></p></div></div></div><div id='method-getStateId' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-method-getStateId' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-method-getStateId' class='name expandable'>getStateId</a>( <span class='pre'></span> ) : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Gets the state id for this object. ...</div><div class='long'><p>Gets the state id for this object.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><div class='sub-desc'><p>The 'stateId' or the implicit 'id' specified by component configuration.</p>\n</div></li></ul></div></div></div><div id='method-getStyleProxy' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-getStyleProxy' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-getStyleProxy' class='name expandable'>getStyleProxy</a>( <span class='pre'>cls</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Returns an offscreen div with the same class name as the element this is being rendered. ...</div><div class='long'><p>Returns an offscreen div with the same class name as the element this is being rendered.\nThis is because child item rendering takes place in a detached div which, being not\npart of the document, has no styling.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>cls</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-getTargetEl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getTargetEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getTargetEl' class='name expandable'>getTargetEl</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>This is used to determine where to insert the 'html', 'contentEl' and 'items' in this component. ...</div><div class='long'><p>This is used to determine where to insert the 'html', 'contentEl' and 'items' in this component.</p>\n</div></div></div><div id='method-getTpl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getTpl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getTpl' class='name expandable'>getTpl</a>( <span class='pre'>name</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>name</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-getViewRegion' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-getViewRegion' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-getViewRegion' class='name expandable'>getViewRegion</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.util.Region\" rel=\"Ext.util.Region\" class=\"docClass\">Ext.util.Region</a></div><div class='description'><div class='short'>Returns the content region of this element. ...</div><div class='long'><p>Returns the <strong>content</strong> region of this element. That is the region within the borders\nand padding.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Region\" rel=\"Ext.util.Region\" class=\"docClass\">Ext.util.Region</a></span><div class='sub-desc'><p>A Region containing \"top, left, bottom, right\" member data.</p>\n</div></li></ul></div></div></div><div id='method-getVisibilityEl' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getVisibilityEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getVisibilityEl' class='name expandable'>getVisibilityEl</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Deprecate 5.0 ...</div><div class='long'><p>Deprecate 5.0</p>\n</div></div></div><div id='method-getWidth' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getWidth' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getWidth' class='name expandable'>getWidth</a>( <span class='pre'></span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></div><div class='description'><div class='short'>Gets the current width of the component's underlying element. ...</div><div class='long'><p>Gets the current width of the component's underlying element.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-getX' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getX' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getX' class='name expandable'>getX</a>( <span class='pre'></span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></div><div class='description'><div class='short'>Gets the current X position of the DOM element based on page coordinates. ...</div><div class='long'><p>Gets the current X position of the DOM element based on page coordinates.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span><div class='sub-desc'><p>The X position of the element</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-getX' rel='Ext.util.Positionable-method-getX' class='docClass'>Ext.util.Positionable.getX</a></p></div></div></div><div id='method-getXType' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-getXType' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-getXType' class='name expandable'>getXType</a>( <span class='pre'></span> ) : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></div><div class='description'><div class='short'>Gets the xtype for this component as registered with Ext.ComponentManager. ...</div><div class='long'><p>Gets the xtype for this component as registered with <a href=\"#!/api/Ext.ComponentManager\" rel=\"Ext.ComponentManager\" class=\"docClass\">Ext.ComponentManager</a>. For a list of all available\nxtypes, see the <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> header. Example usage:</p>\n\n<pre><code>var t = new <a href=\"#!/api/Ext.form.field.Text\" rel=\"Ext.form.field.Text\" class=\"docClass\">Ext.form.field.Text</a>();\nalert(t.getXType()); // alerts 'textfield'\n</code></pre>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><div class='sub-desc'><p>The xtype</p>\n</div></li></ul></div></div></div><div id='method-getXTypes' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getXTypes' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getXTypes' class='name expandable'>getXTypes</a>( <span class='pre'></span> ) : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></div><div class='description'><div class='short'>Returns this Component's xtype hierarchy as a slash-delimited string. ...</div><div class='long'><p>Returns this Component's xtype hierarchy as a slash-delimited string. For a list of all available xtypes, see the\n<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> header.</p>\n\n<p><strong>If using your own subclasses, be aware that a Component must register its own xtype to participate in\ndetermination of inherited xtypes.</strong></p>\n\n<p>Example usage:</p>\n\n<pre class='inline-example '><code>var t = new <a href=\"#!/api/Ext.form.field.Text\" rel=\"Ext.form.field.Text\" class=\"docClass\">Ext.form.field.Text</a>();\nalert(t.getXTypes()); // alerts 'component/field/textfield'\n</code></pre>\n <p>Available since: <b>2.3.0</b></p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><div class='sub-desc'><p>The xtype hierarchy string</p>\n</div></li></ul></div></div></div><div id='method-getXY' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getXY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getXY' class='name expandable'>getXY</a>( <span class='pre'></span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</div><div class='description'><div class='short'>Gets the current position of the DOM element based on page coordinates. ...</div><div class='long'><p>Gets the current position of the DOM element based on page coordinates.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]</span><div class='sub-desc'><p>The XY position of the element</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-getXY' rel='Ext.util.Positionable-method-getXY' class='docClass'>Ext.util.Positionable.getXY</a></p></div></div></div><div id='method-getY' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-getY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-getY' class='name expandable'>getY</a>( <span class='pre'></span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></div><div class='description'><div class='short'>Gets the current Y position of the DOM element based on page coordinates. ...</div><div class='long'><p>Gets the current Y position of the DOM element based on page coordinates.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span><div class='sub-desc'><p>The Y position of the element</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-getY' rel='Ext.util.Positionable-method-getY' class='docClass'>Ext.util.Positionable.getY</a></p></div></div></div><div id='method-hasActiveFx' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Animate' rel='Ext.util.Animate' class='defined-in docClass'>Ext.util.Animate</a><br/><a href='source/Animate.html#Ext-util-Animate-method-hasActiveFx' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Animate-method-hasActiveFx' class='name expandable'>hasActiveFx</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.fx.Anim\" rel=\"Ext.fx.Anim\" class=\"docClass\">Ext.fx.Anim</a>/<a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><strong class='deprecated signature' >deprecated</strong></div><div class='description'><div class='short'>Returns the current animation if this object has any effects actively running or queued, else returns false. ...</div><div class='long'><p>Returns the current animation if this object has any effects actively running or queued, else returns false.</p>\n <div class='signature-box deprecated'>\n <p>This method has been <strong>deprecated</strong> since 4.0</p>\n <p>Replaced by <a href=\"#!/api/Ext.util.Animate-method-getActiveAnimation\" rel=\"Ext.util.Animate-method-getActiveAnimation\" class=\"docClass\">getActiveAnimation</a></p>\n\n </div>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.fx.Anim\" rel=\"Ext.fx.Anim\" class=\"docClass\">Ext.fx.Anim</a>/<a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p>Anim if element has active effects, else false</p>\n\n</div></li></ul></div></div></div><div id='method-hasCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-hasCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-hasCls' class='name expandable'>hasCls</a>( <span class='pre'>className</span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Checks if the specified CSS class exists on this element's DOM node. ...</div><div class='long'><p>Checks if the specified CSS class exists on this element's DOM node.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>className</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The CSS class to check for.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p><code>true</code> if the class exists, else <code>false</code>.</p>\n</div></li></ul></div></div></div><div id='method-hasConfig' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-method-hasConfig' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-method-hasConfig' class='name expandable'>hasConfig</a>( <span class='pre'>config</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>config</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-hasListener' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-hasListener' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-hasListener' class='name expandable'>hasListener</a>( <span class='pre'>eventName</span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Checks to see if this object has any listeners for a specified event, or whether the event bubbles. ...</div><div class='long'><p>Checks to see if this object has any listeners for a specified event, or whether the event bubbles. The answer\nindicates whether the event needs firing or not.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>eventName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The name of the event to check for</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p><code>true</code> if the event is being listened for or bubbles, else <code>false</code></p>\n</div></li></ul></div></div></div><div id='method-hasUICls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-hasUICls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-hasUICls' class='name expandable'>hasUICls</a>( <span class='pre'>cls</span> )</div><div class='description'><div class='short'>Checks if there is currently a specified uiCls. ...</div><div class='long'><p>Checks if there is currently a specified <code>uiCls</code>.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>cls</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The <code>cls</code> to check.</p>\n</div></li></ul></div></div></div><div id='method-hide' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-hide' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-hide' class='name expandable'>hide</a>( <span class='pre'>[animateTarget], [callback], [scope]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Hides this Component, setting it to invisible using the configured hideMode. ...</div><div class='long'><p>Hides this Component, setting it to invisible using the configured <a href=\"#!/api/Ext.Component-cfg-hideMode\" rel=\"Ext.Component-cfg-hideMode\" class=\"docClass\">hideMode</a>.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>animateTarget</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a>/<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> (optional)<div class='sub-desc'><p><strong>only valid for <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a> Components\nsuch as <a href=\"#!/api/Ext.window.Window\" rel=\"Ext.window.Window\" class=\"docClass\">Window</a>s or <a href=\"#!/api/Ext.tip.ToolTip\" rel=\"Ext.tip.ToolTip\" class=\"docClass\">ToolTip</a>s, or regular Components which have\nbeen configured with <code>floating: true</code>.</strong>. The target to which the Component should animate while hiding.</p>\n<p>Defaults to: <code>null</code></p></div></li><li><span class='pre'>callback</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'><p>A callback function to call after the Component is hidden.</p>\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>The scope (<code>this</code> reference) in which the callback is executed.\nDefaults to this Component.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-initBorderRegion' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Region2.html#Ext-Component-method-initBorderRegion' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-initBorderRegion' class='name expandable'>initBorderRegion</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>This method is called by the Ext.layout.container.Border class when instances are\nadded as regions to the layout. ...</div><div class='long'><p>This method is called by the <code><a href=\"#!/api/Ext.layout.container.Border\" rel=\"Ext.layout.container.Border\" class=\"docClass\">Ext.layout.container.Border</a></code> class when instances are\nadded as regions to the layout. Since it is valid to add any component to a border\nlayout as a region, this method must be added to <code><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></code> but is only ever\ncalled when that component is owned by a <code>border</code> layout.</p>\n\n<p><strong>Defined in override Ext.layout.container.border.Region.</strong></p>\n</div></div></div><div id='method-initCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-initCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-initCls' class='name expandable'>initCls</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-initComponent' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-initComponent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-initComponent' class='name expandable'>initComponent</a>( <span class='pre'></span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>The initComponent template method is an important initialization step for a Component. ...</div><div class='long'><p>The initComponent template method is an important initialization step for a Component. It is intended to be\nimplemented by each subclass of <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> to provide any needed constructor logic. The\ninitComponent method of the class being created is called first, with each initComponent method\nup the hierarchy to <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> being called thereafter. This makes it easy to implement and,\nif needed, override the constructor logic of the Component at any step in the hierarchy.</p>\n\n<p>The initComponent method <strong>must</strong> contain a call to <a href=\"#!/api/Ext.Base-method-callParent\" rel=\"Ext.Base-method-callParent\" class=\"docClass\">callParent</a> in order\nto ensure that the parent class' initComponent method is also called.</p>\n\n<p>All config options passed to the constructor are applied to <code>this</code> before initComponent is called,\nso you can simply access them with <code>this.someOption</code>.</p>\n\n<p>The following example demonstrates using a dynamic string for the text of a button at the time of\ninstantiation of the class.</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('DynamicButtonText', {\n extend: '<a href=\"#!/api/Ext.button.Button\" rel=\"Ext.button.Button\" class=\"docClass\">Ext.button.Button</a>',\n\n initComponent: function() {\n this.text = new Date();\n this.renderTo = <a href=\"#!/api/Ext-method-getBody\" rel=\"Ext-method-getBody\" class=\"docClass\">Ext.getBody</a>();\n this.callParent();\n }\n});\n\n<a href=\"#!/api/Ext-method-onReady\" rel=\"Ext-method-onReady\" class=\"docClass\">Ext.onReady</a>(function() {\n <a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('DynamicButtonText');\n});\n</code></pre>\n <p>Available since: <b>1.1.0</b></p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-initComponent' rel='Ext.AbstractComponent-method-initComponent' class='docClass'>Ext.AbstractComponent.initComponent</a></p></div></div></div><div id='method-initConfig' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-method-initConfig' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-method-initConfig' class='name expandable'>initConfig</a>( <span class='pre'>config</span> ) : <a href=\"#!/api/Ext.Base\" rel=\"Ext.Base\" class=\"docClass\">Ext.Base</a><strong class='chainable signature' >chainable</strong><strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Initialize configuration for this class. ...</div><div class='long'><p>Initialize configuration for this class. a typical example:</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.awesome.Class', {\n // The default config\n config: {\n name: 'Awesome',\n isAwesome: true\n },\n\n constructor: function(config) {\n this.initConfig(config);\n }\n});\n\nvar awesome = new My.awesome.Class({\n name: 'Super Awesome'\n});\n\nalert(awesome.getName()); // 'Super Awesome'\n</code></pre>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>config</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Base\" rel=\"Ext.Base\" class=\"docClass\">Ext.Base</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-initContainer' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-initContainer' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-initContainer' class='name expandable'>initContainer</a>( <span class='pre'>container</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>container</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-initDraggable' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-initDraggable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-initDraggable' class='name expandable'>initDraggable</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-initEvents' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-initEvents' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-initEvents' class='name expandable'>initEvents</a>( <span class='pre'></span> )<strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Initialize any events on this component ...</div><div class='long'><p>Initialize any events on this component</p>\n</div></div></div><div id='method-initFrame' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-initFrame' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-initFrame' class='name expandable'>initFrame</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-initFramingTpl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-initFramingTpl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-initFramingTpl' class='name expandable'>initFramingTpl</a>( <span class='pre'>table</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Poke in a reference to applyRenderTpl(frameInfo, out) ...</div><div class='long'><p>Poke in a reference to applyRenderTpl(frameInfo, out)</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>table</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-initHierarchyEvents' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-initHierarchyEvents' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-initHierarchyEvents' class='name expandable'>initHierarchyEvents</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-initHierarchyState' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-initHierarchyState' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-initHierarchyState' class='name expandable'>initHierarchyState</a>( <span class='pre'>hierarchyState</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Called by getHierarchyState to initialize the hierarchyState the first\ntime it is requested. ...</div><div class='long'><p>Called by <a href=\"#!/api/Ext.AbstractComponent-method-getHierarchyState\" rel=\"Ext.AbstractComponent-method-getHierarchyState\" class=\"docClass\">getHierarchyState</a> to initialize the hierarchyState the first\ntime it is requested.</p>\n\n<p><strong>Overridden in Ext.rtl.AbstractComponent.</strong></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>hierarchyState</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-initPadding' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-initPadding' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-initPadding' class='name expandable'>initPadding</a>( <span class='pre'>targetEl</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Initializes padding by applying it to the target element, or if the layout manages\npadding ensures that the padding o...</div><div class='long'><p>Initializes padding by applying it to the target element, or if the layout manages\npadding ensures that the padding on the target element is \"0\".</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>targetEl</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-initPlugin' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-initPlugin' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-initPlugin' class='name expandable'>initPlugin</a>( <span class='pre'>plugin</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>plugin</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-initRenderData' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-initRenderData' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-initRenderData' class='name expandable'>initRenderData</a>( <span class='pre'></span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Initialized the renderData to be used when rendering the renderTpl. ...</div><div class='long'><p>Initialized the renderData to be used when rendering the renderTpl.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>Object with keys and values that are going to be applied to the renderTpl</p>\n</div></li></ul></div></div></div><div id='method-initRenderTpl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-initRenderTpl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-initRenderTpl' class='name expandable'>initRenderTpl</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.XTemplate\" rel=\"Ext.XTemplate\" class=\"docClass\">Ext.XTemplate</a><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Initializes the renderTpl. ...</div><div class='long'><p>Initializes the renderTpl.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.XTemplate\" rel=\"Ext.XTemplate\" class=\"docClass\">Ext.XTemplate</a></span><div class='sub-desc'><p>The renderTpl XTemplate instance.</p>\n</div></li></ul></div></div></div><div id='method-initResizable' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-initResizable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-initResizable' class='name expandable'>initResizable</a>( <span class='pre'>resizable</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>resizable</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-initState' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-method-initState' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-method-initState' class='name expandable'>initState</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Initializes the state of the object upon construction. ...</div><div class='long'><p>Initializes the state of the object upon construction.</p>\n</div></div></div><div id='method-initStyles' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-initStyles' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-initStyles' class='name expandable'>initStyles</a>( <span class='pre'>targetEl</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Applies padding, margin, border, top, left, height, and width configs to the\nappropriate elements. ...</div><div class='long'><p>Applies padding, margin, border, top, left, height, and width configs to the\nappropriate elements.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>targetEl</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-is' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-is' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-is' class='name expandable'>is</a>( <span class='pre'>selector</span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Tests whether this Component matches the selector string. ...</div><div class='long'><p>Tests whether this Component matches the selector string.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>selector</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The selector string to test against.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p><code>true</code> if this Component matches the selector.</p>\n</div></li></ul></div></div></div><div id='method-isContainedFloater' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-isContainedFloater' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-isContainedFloater' class='name expandable'>isContainedFloater</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Utility method to determine if a Component is floating, and has an owning Container whose coordinate system\nit must b...</div><div class='long'><p>Utility method to determine if a Component is floating, and has an owning Container whose coordinate system\nit must be positioned in when using setPosition.</p>\n</div></div></div><div id='method-isDescendant' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-isDescendant' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isDescendant' class='name expandable'>isDescendant</a>( <span class='pre'>ancestor</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>ancestor</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-isDescendantOf' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-isDescendantOf' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isDescendantOf' class='name expandable'>isDescendantOf</a>( <span class='pre'>container</span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Determines whether this component is the descendant of a particular container. ...</div><div class='long'><p>Determines whether this component is the descendant of a particular container.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>container</span> : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.Container</a><div class='sub-desc'>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p><code>true</code> if the component is the descendant of a particular container, otherwise <code>false</code>.</p>\n</div></li></ul></div></div></div><div id='method-isDisabled' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-isDisabled' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isDisabled' class='name expandable'>isDisabled</a>( <span class='pre'></span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Method to determine whether this Component is currently disabled. ...</div><div class='long'><p>Method to determine whether this Component is currently disabled.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p>the disabled state of this Component.</p>\n</div></li></ul></div></div></div><div id='method-isDraggable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-isDraggable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isDraggable' class='name expandable'>isDraggable</a>( <span class='pre'></span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Method to determine whether this Component is draggable. ...</div><div class='long'><p>Method to determine whether this Component is draggable.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p>the draggable state of this component.</p>\n</div></li></ul></div></div></div><div id='method-isDroppable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-isDroppable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isDroppable' class='name expandable'>isDroppable</a>( <span class='pre'></span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Method to determine whether this Component is droppable. ...</div><div class='long'><p>Method to determine whether this Component is droppable.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p>the droppable state of this component.</p>\n</div></li></ul></div></div></div><div id='method-isFloating' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-isFloating' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isFloating' class='name expandable'>isFloating</a>( <span class='pre'></span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Method to determine whether this Component is floating. ...</div><div class='long'><p>Method to determine whether this Component is floating.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p>the floating state of this component.</p>\n</div></li></ul></div></div></div><div id='method-isFocusable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-isFocusable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isFocusable' class='name expandable'>isFocusable</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-isHidden' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-isHidden' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isHidden' class='name expandable'>isHidden</a>( <span class='pre'></span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Method to determine whether this Component is currently set to hidden. ...</div><div class='long'><p>Method to determine whether this Component is currently set to hidden.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p>the hidden state of this Component.</p>\n</div></li></ul></div></div></div><div id='method-isHierarchicallyHidden' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-isHierarchicallyHidden' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isHierarchicallyHidden' class='name expandable'>isHierarchicallyHidden</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-isLayoutRoot' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-isLayoutRoot' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isLayoutRoot' class='name expandable'>isLayoutRoot</a>( <span class='pre'></span> )<strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Determines whether this Component is the root of a layout. ...</div><div class='long'><p>Determines whether this Component is the root of a layout. This returns <code>true</code> if\nthis component can run its layout without assistance from or impact on its owner.\nIf this component cannot run its layout given these restrictions, <code>false</code> is returned\nand its owner will be considered as the next candidate for the layout root.</p>\n\n<p>Setting the <a href=\"#!/api/Ext.AbstractComponent-property-_isLayoutRoot\" rel=\"Ext.AbstractComponent-property-_isLayoutRoot\" class=\"docClass\">_isLayoutRoot</a> property to <code>true</code> causes this method to always\nreturn <code>true</code>. This may be useful when updating a layout of a Container which shrink\nwraps content, and you know that it will not change size, and so can safely be the\ntopmost participant in the layout run.</p>\n</div></div></div><div id='method-isLayoutSuspended' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-isLayoutSuspended' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isLayoutSuspended' class='name expandable'>isLayoutSuspended</a>( <span class='pre'></span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Returns true if layout is suspended for this component. ...</div><div class='long'><p>Returns <code>true</code> if layout is suspended for this component. This can come from direct\nsuspension of this component's layout activity (<a href=\"#!/api/Ext.container.Container-cfg-suspendLayout\" rel=\"Ext.container.Container-cfg-suspendLayout\" class=\"docClass\">Ext.Container.suspendLayout</a>) or if one\nof this component's containers is suspended.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p><code>true</code> layout of this component is suspended.</p>\n</div></li></ul></div></div></div><div id='method-isLocalRtl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent2.html#Ext-AbstractComponent-method-isLocalRtl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isLocalRtl' class='name expandable'>isLocalRtl</a>( <span class='pre'></span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Returns true if this component's local coordinate system is rtl. ...</div><div class='long'><p>Returns true if this component's local coordinate system is rtl. For normal\ncomponents this equates to the value of isParentRtl(). Floaters are a bit different\nbecause a floater's element can be a childNode of something other than its\nparent component's element. For floaters we have to read the dom to see if the\ncomponent's element's parentNode has a css direction value of \"rtl\".</p>\n\n<p><strong>Defined in override Ext.rtl.AbstractComponent.</strong></p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-isOppositeRootDirection' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent2.html#Ext-AbstractComponent-method-isOppositeRootDirection' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isOppositeRootDirection' class='name expandable'>isOppositeRootDirection</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Defined in override Ext.rtl.AbstractComponent. ...</div><div class='long'><p><strong>Defined in override Ext.rtl.AbstractComponent.</strong></p>\n</div></div></div><div id='method-isParentRtl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent2.html#Ext-AbstractComponent-method-isParentRtl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isParentRtl' class='name expandable'>isParentRtl</a>( <span class='pre'></span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Returns true if this component's parent container is rtl. ...</div><div class='long'><p>Returns true if this component's parent container is rtl. Used by rtl positioning\nmethods to determine if the component should be positioned using a right-to-left\ncoordinate system.</p>\n\n<p><strong>Defined in override Ext.rtl.AbstractComponent.</strong></p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-isVisible' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-isVisible' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isVisible' class='name expandable'>isVisible</a>( <span class='pre'>[deep]</span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Returns true if this component is visible. ...</div><div class='long'><p>Returns <code>true</code> if this component is visible.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>deep</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>Pass <code>true</code> to interrogate the visibility status of all parent Containers to\ndetermine whether this Component is truly visible to the user.</p>\n\n<p>Generally, to determine whether a Component is hidden, the no argument form is needed. For example when creating\ndynamically laid out UIs in a hidden Container before showing them.</p>\n<p>Defaults to: <code>false</code></p></div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p><code>true</code> if this component is visible, <code>false</code> otherwise.</p>\n</div></li></ul></div></div></div><div id='method-isXType' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-isXType' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-isXType' class='name expandable'>isXType</a>( <span class='pre'>xtype, [shallow]</span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Tests whether or not this Component is of a specific xtype. ...</div><div class='long'><p>Tests whether or not this Component is of a specific xtype. This can test whether this Component is descended\nfrom the xtype (default) or whether it is directly of the xtype specified (<code>shallow = true</code>).</p>\n\n<p><strong>If using your own subclasses, be aware that a Component must register its own xtype to participate in\ndetermination of inherited xtypes.</strong></p>\n\n<p>For a list of all available xtypes, see the <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> header.</p>\n\n<p>Example usage:</p>\n\n<pre class='inline-example '><code>var t = new <a href=\"#!/api/Ext.form.field.Text\" rel=\"Ext.form.field.Text\" class=\"docClass\">Ext.form.field.Text</a>();\nvar isText = t.isXType('textfield'); // true\nvar isBoxSubclass = t.isXType('field'); // true, descended from <a href=\"#!/api/Ext.form.field.Base\" rel=\"Ext.form.field.Base\" class=\"docClass\">Ext.form.field.Base</a>\nvar isBoxInstance = t.isXType('field', true); // false, not a direct <a href=\"#!/api/Ext.form.field.Base\" rel=\"Ext.form.field.Base\" class=\"docClass\">Ext.form.field.Base</a> instance\n</code></pre>\n <p>Available since: <b>2.3.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>xtype</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The xtype to check for this Component</p>\n</div></li><li><span class='pre'>shallow</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p><code>true</code> to check whether this Component is directly of the specified xtype, <code>false</code> to\ncheck whether this Component is descended from the xtype.</p>\n<p>Defaults to: <code>false</code></p></div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p><code>true</code> if this component descends from the specified xtype, <code>false</code> otherwise.</p>\n</div></li></ul></div></div></div><div id='method-makeFloating' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-makeFloating' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-makeFloating' class='name expandable'>makeFloating</a>( <span class='pre'>dom</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>dom</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-mask' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-mask' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-mask' class='name expandable'>mask</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-mon' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-mon' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-mon' class='name expandable'>mon</a>( <span class='pre'>item, ename, [fn], [scope], [options]</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>Shorthand for addManagedListener. ...</div><div class='long'><p>Shorthand for <a href=\"#!/api/Ext.util.Observable-method-addManagedListener\" rel=\"Ext.util.Observable-method-addManagedListener\" class=\"docClass\">addManagedListener</a>.</p>\n\n<p>Adds listeners to any Observable object (or <a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a>) which are automatically removed when this Component is\ndestroyed.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>item</span> : <a href=\"#!/api/Ext.util.Observable\" rel=\"Ext.util.Observable\" class=\"docClass\">Ext.util.Observable</a>/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a><div class='sub-desc'><p>The item to which to add a listener/listeners.</p>\n\n</div></li><li><span class='pre'>ename</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The event name, or an object containing event name properties.</p>\n\n</div></li><li><span class='pre'>fn</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'><p>If the <code>ename</code> parameter was an event name, this is the handler function.</p>\n\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>If the <code>ename</code> parameter was an event name, this is the scope (<code>this</code> reference)\nin which the handler function is executed.</p>\n\n</div></li><li><span class='pre'>options</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>If the <code>ename</code> parameter was an event name, this is the\n<a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">addListener</a> options.</p>\n\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p><strong>Only when the <code>destroyable</code> option is specified. </strong></p>\n\n\n\n\n<p> A <code>Destroyable</code> object. An object which implements the <code>destroy</code> method which removes all listeners added in this call. For example:</p>\n\n\n\n\n<pre><code>this.btnListeners = = myButton.mon({\n destroyable: true\n mouseover: function() { console.log('mouseover'); },\n mouseout: function() { console.log('mouseout'); },\n click: function() { console.log('click'); }\n});\n</code></pre>\n\n\n\n\n<p>And when those listeners need to be removed:</p>\n\n\n\n\n<pre><code><a href=\"#!/api/Ext-method-destroy\" rel=\"Ext-method-destroy\" class=\"docClass\">Ext.destroy</a>(this.btnListeners);\n</code></pre>\n\n\n\n\n<p>or</p>\n\n\n\n\n<pre><code>this.btnListeners.destroy();\n</code></pre>\n\n</div></li></ul></div></div></div><div id='method-move' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-move' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-move' class='name expandable'>move</a>( <span class='pre'>direction, distance, [animate]</span> )</div><div class='description'><div class='short'>Move the element relative to its current position. ...</div><div class='long'><p>Move the element relative to its current position.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>direction</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>Possible values are:</p>\n\n<ul>\n<li><code>\"l\"</code> (or <code>\"left\"</code>)</li>\n<li><code>\"r\"</code> (or <code>\"right\"</code>)</li>\n<li><code>\"t\"</code> (or <code>\"top\"</code>, or <code>\"up\"</code>)</li>\n<li><code>\"b\"</code> (or <code>\"bottom\"</code>, or <code>\"down\"</code>)</li>\n</ul>\n\n</div></li><li><span class='pre'>distance</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>How far to move the element in pixels</p>\n</div></li><li><span class='pre'>animate</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>true for the default animation or a standard\nElement animation config object</p>\n</div></li></ul></div></div></div><div id='method-mun' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-mun' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-mun' class='name expandable'>mun</a>( <span class='pre'>item, ename, [fn], [scope]</span> )</div><div class='description'><div class='short'>Shorthand for removeManagedListener. ...</div><div class='long'><p>Shorthand for <a href=\"#!/api/Ext.util.Observable-method-removeManagedListener\" rel=\"Ext.util.Observable-method-removeManagedListener\" class=\"docClass\">removeManagedListener</a>.</p>\n\n<p>Removes listeners that were added by the <a href=\"#!/api/Ext.util.Observable-method-mon\" rel=\"Ext.util.Observable-method-mon\" class=\"docClass\">mon</a> method.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>item</span> : <a href=\"#!/api/Ext.util.Observable\" rel=\"Ext.util.Observable\" class=\"docClass\">Ext.util.Observable</a>/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a><div class='sub-desc'><p>The item from which to remove a listener/listeners.</p>\n\n</div></li><li><span class='pre'>ename</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The event name, or an object containing event name properties.</p>\n\n</div></li><li><span class='pre'>fn</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'><p>If the <code>ename</code> parameter was an event name, this is the handler function.</p>\n\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>If the <code>ename</code> parameter was an event name, this is the scope (<code>this</code> reference)\nin which the handler function is executed.</p>\n\n</div></li></ul></div></div></div><div id='method-nextNode' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-nextNode' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-nextNode' class='name expandable'>nextNode</a>( <span class='pre'>[selector]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Returns the next node in the Component tree in tree traversal order. ...</div><div class='long'><p>Returns the next node in the Component tree in tree traversal order.</p>\n\n<p>Note that this is not limited to siblings, and if invoked upon a node with no matching siblings, will walk the\ntree to attempt to find a match. Contrast with <a href=\"#!/api/Ext.AbstractComponent-method-nextSibling\" rel=\"Ext.AbstractComponent-method-nextSibling\" class=\"docClass\">nextSibling</a>.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>selector</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>A <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">ComponentQuery</a> selector to filter the following nodes.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>The next node (or the next node which matches the selector).\nReturns <code>null</code> if there is no matching node.</p>\n</div></li></ul></div></div></div><div id='method-nextSibling' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-nextSibling' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-nextSibling' class='name expandable'>nextSibling</a>( <span class='pre'>[selector]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Returns the next sibling of this Component. ...</div><div class='long'><p>Returns the next sibling of this Component.</p>\n\n<p>Optionally selects the next sibling which matches the passed <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">ComponentQuery</a> selector.</p>\n\n<p>May also be referred to as <strong><code>next()</code></strong></p>\n\n<p>Note that this is limited to siblings, and if no siblings of the item match, <code>null</code> is returned. Contrast with\n<a href=\"#!/api/Ext.AbstractComponent-method-nextNode\" rel=\"Ext.AbstractComponent-method-nextNode\" class=\"docClass\">nextNode</a></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>selector</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>A <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">ComponentQuery</a> selector to filter the following items.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>The next sibling (or the next sibling which matches the selector).\nReturns <code>null</code> if there is no matching sibling.</p>\n</div></li></ul></div></div></div><div id='method-on' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-on' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-on' class='name expandable'>on</a>( <span class='pre'>eventName, [fn], [scope], [options]</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>Shorthand for addListener. ...</div><div class='long'><p>Shorthand for <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">addListener</a>.</p>\n\n<p>Appends an event handler to this object. For example:</p>\n\n<pre><code>myGridPanel.on(\"mouseover\", this.onMouseOver, this);\n</code></pre>\n\n<p>The method also allows for a single argument to be passed which is a config object\ncontaining properties which specify multiple events. For example:</p>\n\n<pre><code>myGridPanel.on({\n cellClick: this.onCellClick,\n mouseover: this.onMouseOver,\n mouseout: this.onMouseOut,\n scope: this // Important. Ensure \"this\" is correct during handler execution\n});\n</code></pre>\n\n<p>One can also specify options for each event handler separately:</p>\n\n<pre><code>myGridPanel.on({\n cellClick: {fn: this.onCellClick, scope: this, single: true},\n mouseover: {fn: panel.onMouseOver, scope: panel}\n});\n</code></pre>\n\n<p><em>Names</em> of methods in a specified scope may also be used. Note that\n<code>scope</code> MUST be specified to use this option:</p>\n\n<pre><code>myGridPanel.on({\n cellClick: {fn: 'onCellClick', scope: this, single: true},\n mouseover: {fn: 'onMouseOver', scope: panel}\n});\n</code></pre>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>eventName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The name of the event to listen for.\nMay also be an object who's property names are event names.</p>\n\n</div></li><li><span class='pre'>fn</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'><p>The method the event invokes, or <em>if <code>scope</code> is specified, the </em>name* of the method within\nthe specified <code>scope</code>. Will be called with arguments\ngiven to <a href=\"#!/api/Ext.util.Observable-method-fireEvent\" rel=\"Ext.util.Observable-method-fireEvent\" class=\"docClass\">fireEvent</a> plus the <code>options</code> parameter described below.</p>\n\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>The scope (<code>this</code> reference) in which the handler function is\nexecuted. <strong>If omitted, defaults to the object which fired the event.</strong></p>\n\n</div></li><li><span class='pre'>options</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>An object containing handler configuration.</p>\n\n\n\n\n<p><strong>Note:</strong> Unlike in ExtJS 3.x, the options object will also be passed as the last\nargument to every event handler.</p>\n\n\n\n\n<p>This object may contain any of the following properties:</p>\n\n<ul><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The scope (<code>this</code> reference) in which the handler function is executed. <strong>If omitted,\n defaults to the object which fired the event.</strong></p>\n\n</div></li><li><span class='pre'>delay</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The number of milliseconds to delay the invocation of the handler after the event fires.</p>\n\n</div></li><li><span class='pre'>single</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p>True to add a handler to handle just the next firing of the event, and then remove itself.</p>\n\n</div></li><li><span class='pre'>buffer</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>Causes the handler to be scheduled to run in an <a href=\"#!/api/Ext.util.DelayedTask\" rel=\"Ext.util.DelayedTask\" class=\"docClass\">Ext.util.DelayedTask</a> delayed\n by the specified number of milliseconds. If the event fires again within that time,\n the original handler is <em>not</em> invoked, but the new handler is scheduled in its place.</p>\n\n</div></li><li><span class='pre'>target</span> : <a href=\"#!/api/Ext.util.Observable\" rel=\"Ext.util.Observable\" class=\"docClass\">Ext.util.Observable</a><div class='sub-desc'><p>Only call the handler if the event was fired on the target Observable, <em>not</em> if the event\n was bubbled up from a child Observable.</p>\n\n</div></li><li><span class='pre'>element</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p><strong>This option is only valid for listeners bound to <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Components</a>.</strong>\n The name of a Component property which references an element to add a listener to.</p>\n\n\n\n\n<p> This option is useful during Component construction to add DOM event listeners to elements of\n <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Components</a> which will exist only after the Component is rendered.\n For example, to add a click listener to a Panel's body:</p>\n\n\n\n\n<pre><code> new <a href=\"#!/api/Ext.panel.Panel\" rel=\"Ext.panel.Panel\" class=\"docClass\">Ext.panel.Panel</a>({\n title: 'The title',\n listeners: {\n click: this.handlePanelClick,\n element: 'body'\n }\n });\n</code></pre>\n\n</div></li><li><span class='pre'>destroyable</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>When specified as <code>true</code>, the function returns A <code>Destroyable</code> object. An object which implements the <code>destroy</code> method which removes all listeners added in this call.</p>\n\n<p>Defaults to: <code>false</code></p></div></li><li><span class='pre'>priority</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>An optional numeric priority that determines the order in which event handlers\n are run. Event handlers with no priority will be run as if they had a priority\n of 0. Handlers with a higher priority will be prioritized to run sooner than\n those with a lower priority. Negative numbers can be used to set a priority\n lower than the default. Internally, the framework uses a range of 1000 or\n greater, and -1000 or lesser for handers that are intended to run before or\n after all others, so it is recommended to stay within the range of -999 to 999\n when setting the priority of event handlers in application-level code.</p>\n\n\n\n\n<p><strong>Combining Options</strong></p>\n\n\n\n\n<p>Using the options argument, it is possible to combine different types of listeners:</p>\n\n\n\n\n<p>A delayed, one-time listener.</p>\n\n\n\n\n<pre><code>myPanel.on('hide', this.handleClick, this, {\n single: true,\n delay: 100\n});\n</code></pre>\n\n</div></li></ul></div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p><strong>Only when the <code>destroyable</code> option is specified. </strong></p>\n\n\n\n\n<p> A <code>Destroyable</code> object. An object which implements the <code>destroy</code> method which removes all listeners added in this call. For example:</p>\n\n\n\n\n<pre><code>this.btnListeners = = myButton.on({\n destroyable: true\n mouseover: function() { console.log('mouseover'); },\n mouseout: function() { console.log('mouseout'); },\n click: function() { console.log('click'); }\n});\n</code></pre>\n\n\n\n\n<p>And when those listeners need to be removed:</p>\n\n\n\n\n<pre><code><a href=\"#!/api/Ext-method-destroy\" rel=\"Ext-method-destroy\" class=\"docClass\">Ext.destroy</a>(this.btnListeners);\n</code></pre>\n\n\n\n\n<p>or</p>\n\n\n\n\n<pre><code>this.btnListeners.destroy();\n</code></pre>\n\n</div></li></ul></div></div></div><div id='method-onAdded' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-onAdded' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-onAdded' class='name expandable'>onAdded</a>( <span class='pre'>container, pos</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Method to manage awareness of when components are added to their\nrespective Container, firing an added event. ...</div><div class='long'><p>Method to manage awareness of when components are added to their\nrespective Container, firing an <a href=\"#!/api/Ext.Component-event-added\" rel=\"Ext.Component-event-added\" class=\"docClass\">added</a> event. References are\nestablished at add time rather than at render time.</p>\n\n<p>Allows addition of behavior when a Component is added to a\nContainer. At this stage, the Component is in the parent\nContainer's collection of child items. After calling the\nsuperclass's <code>onAdded</code>, the <code>ownerCt</code> reference will be present,\nand if configured with a ref, the <code>refOwner</code> will be set.</p>\n <p>Available since: <b>3.4.0</b></p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>container</span> : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a><div class='sub-desc'><p>Container which holds the component.</p>\n</div></li><li><span class='pre'>pos</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>Position at which the component was added.</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-onAdded' rel='Ext.AbstractComponent-method-onAdded' class='docClass'>Ext.AbstractComponent.onAdded</a></p></div></div></div><div id='method-onAfterFloatLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-onAfterFloatLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-onAfterFloatLayout' class='name expandable'>onAfterFloatLayout</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-onBeforeFloatLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-onBeforeFloatLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-onBeforeFloatLayout' class='name expandable'>onBeforeFloatLayout</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-onBlur' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-onBlur' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-onBlur' class='name expandable'>onBlur</a>( <span class='pre'>e</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>private ...</div><div class='long'><p>private</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>e</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-onBoxReady' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-onBoxReady' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-onBoxReady' class='name expandable'>onBoxReady</a>( <span class='pre'>width, height</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>width</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>height</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-onConfigUpdate' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-method-onConfigUpdate' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-method-onConfigUpdate' class='name expandable'>onConfigUpdate</a>( <span class='pre'>names, callback, scope</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>names</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>callback</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-onDestroy' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-onDestroy' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-onDestroy' class='name expandable'>onDestroy</a>( <span class='pre'></span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Allows addition of behavior to the destroy operation. ...</div><div class='long'><p>Allows addition of behavior to the destroy operation.\nAfter calling the superclass's onDestroy, the Component will be destroyed.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-onDestroy' rel='Ext.AbstractComponent-method-onDestroy' class='docClass'>Ext.AbstractComponent.onDestroy</a></p></div></div></div><div id='method-onDisable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-onDisable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-onDisable' class='name expandable'>onDisable</a>( <span class='pre'></span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Allows addition of behavior to the disable operation. ...</div><div class='long'><p>Allows addition of behavior to the disable operation.\nAfter calling the superclass's <code>onDisable</code>, the Component will be disabled.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n</div></div></div><div id='method-onEnable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-onEnable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-onEnable' class='name expandable'>onEnable</a>( <span class='pre'></span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Allows addition of behavior to the enable operation. ...</div><div class='long'><p>Allows addition of behavior to the enable operation.\nAfter calling the superclass's <code>onEnable</code>, the Component will be enabled.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n</div></div></div><div id='method-onFloatShow' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-onFloatShow' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-onFloatShow' class='name expandable'>onFloatShow</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-onFocus' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-onFocus' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-onFocus' class='name expandable'>onFocus</a>( <span class='pre'>e</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>private ...</div><div class='long'><p>private</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>e</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-onHide' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-onHide' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-onHide' class='name expandable'>onHide</a>( <span class='pre'>[animateTarget], [callback], [scope]</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Possibly animates down to a target element. ...</div><div class='long'><p>Possibly animates down to a target element.</p>\n\n<p>Allows addition of behavior to the hide operation. After\ncalling the superclass’s onHide, the Component will be hidden.</p>\n\n<p>Gets passed the same parameters as <a href=\"#!/api/Ext.Component-method-hide\" rel=\"Ext.Component-method-hide\" class=\"docClass\">hide</a>.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>animateTarget</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a>/<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> (optional)<div class='sub-desc'>\n</div></li><li><span class='pre'>callback</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'>\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-onHide' rel='Ext.AbstractComponent-method-onHide' class='docClass'>Ext.AbstractComponent.onHide</a></p></div></div></div><div id='method-onKeyDown' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-onKeyDown' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-onKeyDown' class='name expandable'>onKeyDown</a>( <span class='pre'>e</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Listen for TAB events and wrap round if tabbing of either end of the Floater ...</div><div class='long'><p>Listen for TAB events and wrap round if tabbing of either end of the Floater</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>e</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-onMouseDown' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-onMouseDown' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-onMouseDown' class='name expandable'>onMouseDown</a>( <span class='pre'>e</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Mousedown brings to front, and programatically grabs focus unless the mousedown was on a focusable element ...</div><div class='long'><p>Mousedown brings to front, and programatically grabs focus <em>unless the mousedown was on a focusable element</em></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>e</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-onPosition' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-onPosition' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-onPosition' class='name expandable'>onPosition</a>( <span class='pre'>x, y</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Called after the component is moved, this method is empty by default but can be implemented by any\nsubclass that need...</div><div class='long'><p>Called after the component is moved, this method is empty by default but can be implemented by any\nsubclass that needs to perform custom logic after a move occurs.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>x</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The new x position.</p>\n</div></li><li><span class='pre'>y</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The new y position.</p>\n</div></li></ul></div></div></div><div id='method-onRemoved' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-onRemoved' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-onRemoved' class='name expandable'>onRemoved</a>( <span class='pre'>destroying</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Method to manage awareness of when components are removed from their\nrespective Container, firing a removed event. ...</div><div class='long'><p>Method to manage awareness of when components are removed from their\nrespective Container, firing a <a href=\"#!/api/Ext.AbstractComponent-event-removed\" rel=\"Ext.AbstractComponent-event-removed\" class=\"docClass\">removed</a> event. References are properly\ncleaned up after removing a component from its owning container.</p>\n\n<p>Allows addition of behavior when a Component is removed from\nits parent Container. At this stage, the Component has been\nremoved from its parent Container's collection of child items,\nbut has not been destroyed (It will be destroyed if the parent\nContainer's <code>autoDestroy</code> is <code>true</code>, or if the remove call was\npassed a truthy second parameter). After calling the\nsuperclass's <code>onRemoved</code>, the <code>ownerCt</code> and the <code>refOwner</code> will not\nbe present.</p>\n <p>Available since: <b>3.4.0</b></p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>destroying</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p>Will be passed as <code>true</code> if the Container performing the remove operation will delete this\nComponent upon remove.</p>\n</div></li></ul></div></div></div><div id='method-onRender' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-onRender' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-onRender' class='name expandable'>onRender</a>( <span class='pre'>parentNode, containerIdx</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Template method called when this Component's DOM structure is created. ...</div><div class='long'><p>Template method called when this Component's DOM structure is created.</p>\n\n<p>At this point, this Component's (and all descendants') DOM structure <em>exists</em> but it has not\nbeen layed out (positioned and sized).</p>\n\n<p>Subclasses which override this to gain access to the structure at render time should\ncall the parent class's method before attempting to access any child elements of the Component.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>parentNode</span> : <a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.core.Element</a><div class='sub-desc'><p>The parent Element in which this Component's encapsulating element is contained.</p>\n</div></li><li><span class='pre'>containerIdx</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The index within the parent Container's child collection of this Component.</p>\n</div></li></ul></div></div></div><div id='method-onResize' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-onResize' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-onResize' class='name expandable'>onResize</a>( <span class='pre'>width, height, oldWidth, oldHeight</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Allows addition of behavior to the resize operation. ...</div><div class='long'><p>Allows addition of behavior to the resize operation.</p>\n\n<p>Called when Ext.resizer.Resizer#drag event is fired.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>width</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>height</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>oldWidth</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>oldHeight</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-onShow' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-onShow' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-onShow' class='name expandable'>onShow</a>( <span class='pre'>[animateTarget], [callback], [scope]</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Allows addition of behavior to the show operation. ...</div><div class='long'><p>Allows addition of behavior to the show operation. After\ncalling the superclass's onShow, the Component will be visible.</p>\n\n<p>Override in subclasses where more complex behaviour is needed.</p>\n\n<p>Gets passed the same parameters as <a href=\"#!/api/Ext.Component-method-show\" rel=\"Ext.Component-method-show\" class=\"docClass\">show</a>.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>animateTarget</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a> (optional)<div class='sub-desc'>\n</div></li><li><span class='pre'>callback</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'>\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-onShow' rel='Ext.AbstractComponent-method-onShow' class='docClass'>Ext.AbstractComponent.onShow</a></p></div></div></div><div id='method-onShowComplete' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-onShowComplete' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-onShowComplete' class='name expandable'>onShowComplete</a>( <span class='pre'>[callback], [scope]</span> )<strong class='protected signature' >protected</strong><strong class='template signature' >template</strong></div><div class='description'><div class='short'>Invoked after the afterShow method is complete. ...</div><div class='long'><p>Invoked after the <a href=\"#!/api/Ext.Component-method-afterShow\" rel=\"Ext.Component-method-afterShow\" class=\"docClass\">afterShow</a> method is complete.</p>\n\n<p>Gets passed the same <code>callback</code> and <code>scope</code> parameters that <a href=\"#!/api/Ext.Component-method-afterShow\" rel=\"Ext.Component-method-afterShow\" class=\"docClass\">afterShow</a> received.</p>\n <div class='signature-box template'>\n <p>This is a <a href=\"#!/guide/components\">template method</a>.\n a hook into the functionality of this class.\n Feel free to override it in child classes.</p>\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>callback</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'>\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-onShowVeto' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-onShowVeto' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-onShowVeto' class='name expandable'>onShowVeto</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-onStateChange' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-method-onStateChange' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-method-onStateChange' class='name expandable'>onStateChange</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>This method is called when any of the stateEvents are fired. ...</div><div class='long'><p>This method is called when any of the <a href=\"#!/api/Ext.state.Stateful-cfg-stateEvents\" rel=\"Ext.state.Stateful-cfg-stateEvents\" class=\"docClass\">stateEvents</a> are fired.</p>\n</div></div></div><div id='method-parseBox' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-parseBox' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-parseBox' class='name expandable'>parseBox</a>( <span class='pre'>box</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Overridden in Ext.rtl.AbstractComponent. ...</div><div class='long'><p><strong>Overridden in Ext.rtl.AbstractComponent.</strong></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>box</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-postBlur' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-postBlur' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-postBlur' class='name expandable'>postBlur</a>( <span class='pre'>e</span> )<strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Template method to do any post-blur processing. ...</div><div class='long'><p>Template method to do any post-blur processing.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>e</span> : <a href=\"#!/api/Ext.EventObject\" rel=\"Ext.EventObject\" class=\"docClass\">Ext.EventObject</a><div class='sub-desc'><p>The event object</p>\n</div></li></ul></div></div></div><div id='method-prepareClass' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-prepareClass' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-prepareClass' class='name expandable'>prepareClass</a>( <span class='pre'>T</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Prepares a given class for observable instances. ...</div><div class='long'><p>Prepares a given class for observable instances. This method is called when a\nclass derives from this class or uses this class as a mixin.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>T</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a><div class='sub-desc'><p>The class constructor to prepare.</p>\n</div></li></ul></div></div></div><div id='method-previousNode' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-previousNode' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-previousNode' class='name expandable'>previousNode</a>( <span class='pre'>[selector]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Returns the previous node in the Component tree in tree traversal order. ...</div><div class='long'><p>Returns the previous node in the Component tree in tree traversal order.</p>\n\n<p>Note that this is not limited to siblings, and if invoked upon a node with no matching siblings, will walk the\ntree in reverse order to attempt to find a match. Contrast with <a href=\"#!/api/Ext.AbstractComponent-method-previousSibling\" rel=\"Ext.AbstractComponent-method-previousSibling\" class=\"docClass\">previousSibling</a>.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>selector</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>A <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">ComponentQuery</a> selector to filter the preceding nodes.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>The previous node (or the previous node which matches the selector).\nReturns <code>null</code> if there is no matching node.</p>\n</div></li></ul></div></div></div><div id='method-previousSibling' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-previousSibling' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-previousSibling' class='name expandable'>previousSibling</a>( <span class='pre'>[selector]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Returns the previous sibling of this Component. ...</div><div class='long'><p>Returns the previous sibling of this Component.</p>\n\n<p>Optionally selects the previous sibling which matches the passed <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">ComponentQuery</a>\nselector.</p>\n\n<p>May also be referred to as <strong><code>prev()</code></strong></p>\n\n<p>Note that this is limited to siblings, and if no siblings of the item match, <code>null</code> is returned. Contrast with\n<a href=\"#!/api/Ext.AbstractComponent-method-previousNode\" rel=\"Ext.AbstractComponent-method-previousNode\" class=\"docClass\">previousNode</a></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>selector</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>A <a href=\"#!/api/Ext.ComponentQuery\" rel=\"Ext.ComponentQuery\" class=\"docClass\">ComponentQuery</a> selector to filter the preceding items.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>The previous sibling (or the previous sibling which matches the selector).\nReturns <code>null</code> if there is no matching sibling.</p>\n</div></li></ul></div></div></div><div id='method-prune' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.ElementContainer' rel='Ext.util.ElementContainer' class='defined-in docClass'>Ext.util.ElementContainer</a><br/><a href='source/ElementContainer.html#Ext-util-ElementContainer-method-prune' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.ElementContainer-method-prune' class='name expandable'>prune</a>( <span class='pre'>childEls, shared</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>childEls</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>shared</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-registerFloatingItem' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-registerFloatingItem' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-registerFloatingItem' class='name expandable'>registerFloatingItem</a>( <span class='pre'>cmp</span> )</div><div class='description'><div class='short'>Called by Component#doAutoRender\n\nRegister a Container configured floating: true with this Component's ZIndexManager. ...</div><div class='long'><p>Called by Component#doAutoRender</p>\n\n<p>Register a Container configured <code>floating: true</code> with this Component's <a href=\"#!/api/Ext.ZIndexManager\" rel=\"Ext.ZIndexManager\" class=\"docClass\">ZIndexManager</a>.</p>\n\n<p>Components added in this way will not participate in any layout, but will be rendered\nupon first show in the way that <a href=\"#!/api/Ext.window.Window\" rel=\"Ext.window.Window\" class=\"docClass\">Window</a>s are.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>cmp</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-registerWithOwnerCt' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-registerWithOwnerCt' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-registerWithOwnerCt' class='name expandable'>registerWithOwnerCt</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-relayEvents' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-relayEvents' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-relayEvents' class='name expandable'>relayEvents</a>( <span class='pre'>origin, events, [prefix]</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>Relays selected events from the specified Observable as if the events were fired by this. ...</div><div class='long'><p>Relays selected events from the specified Observable as if the events were fired by <code>this</code>.</p>\n\n<p>For example if you are extending Grid, you might decide to forward some events from store.\nSo you can do this inside your initComponent:</p>\n\n<pre><code>this.relayEvents(this.getStore(), ['load']);\n</code></pre>\n\n<p>The grid instance will then have an observable 'load' event which will be passed the\nparameters of the store's load event and any function fired with the grid's load event\nwould have access to the grid using the <code>this</code> keyword.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>origin</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The Observable whose events this object is to relay.</p>\n</div></li><li><span class='pre'>events</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>[]<div class='sub-desc'><p>Array of event names to relay.</p>\n</div></li><li><span class='pre'>prefix</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>A common prefix to prepend to the event names. For example:</p>\n\n<pre><code>this.relayEvents(this.getStore(), ['load', 'clear'], 'store');\n</code></pre>\n\n<p>Now the grid will forward 'load' and 'clear' events of store as 'storeload' and 'storeclear'.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>A <code>Destroyable</code> object. An object which implements the <code>destroy</code> method which, when destroyed, removes all relayers. For example:</p>\n\n<pre><code>this.storeRelayers = this.relayEvents(this.getStore(), ['load', 'clear'], 'store');\n</code></pre>\n\n<p>Can be undone by calling</p>\n\n<pre><code><a href=\"#!/api/Ext-method-destroy\" rel=\"Ext-method-destroy\" class=\"docClass\">Ext.destroy</a>(this.storeRelayers);\n</code></pre>\n\n<p>or</p>\n\n<pre><code>this.store.relayers.destroy();\n</code></pre>\n</div></li></ul></div></div></div><div id='method-removeAnchor' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-removeAnchor' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-removeAnchor' class='name expandable'>removeAnchor</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Remove any anchor to this element. ...</div><div class='long'><p>Remove any anchor to this element. See <a href=\"#!/api/Ext.util.Positionable-method-anchorTo\" rel=\"Ext.util.Positionable-method-anchorTo\" class=\"docClass\">anchorTo</a>.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-removeChildEls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.ElementContainer' rel='Ext.util.ElementContainer' class='defined-in docClass'>Ext.util.ElementContainer</a><br/><a href='source/ElementContainer.html#Ext-util-ElementContainer-method-removeChildEls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.ElementContainer-method-removeChildEls' class='name expandable'>removeChildEls</a>( <span class='pre'>testFn</span> )</div><div class='description'><div class='short'>Removes items in the childEls array based on the return value of a supplied test\nfunction. ...</div><div class='long'><p>Removes items in the childEls array based on the return value of a supplied test\nfunction. The function is called with a entry in childEls and if the test function\nreturn true, that entry is removed. If false, that entry is kept.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>testFn</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a><div class='sub-desc'><p>The test function.</p>\n</div></li></ul></div></div></div><div id='method-removeClass' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-removeClass' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-removeClass' class='name expandable'>removeClass</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'><p><debug></p>\n <p>Available since: <b>2.3.0</b></p>\n</div></div></div><div id='method-removeCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-removeCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-removeCls' class='name expandable'>removeCls</a>( <span class='pre'>cls</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Removes a CSS class from the top level element representing this component. ...</div><div class='long'><p>Removes a CSS class from the top level element representing this component.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>cls</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>[]<div class='sub-desc'><p>The CSS class name to remove.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>Returns the Component to allow method chaining.</p>\n</div></li></ul></div></div></div><div id='method-removeClsWithUI' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-removeClsWithUI' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-removeClsWithUI' class='name expandable'>removeClsWithUI</a>( <span class='pre'>cls</span> )</div><div class='description'><div class='short'>Removes a cls to the uiCls array, which will also call removeUIClsFromElement and removes it from all\nelements of thi...</div><div class='long'><p>Removes a <code>cls</code> to the <code>uiCls</code> array, which will also call <a href=\"#!/api/Ext.AbstractComponent-method-removeUIClsFromElement\" rel=\"Ext.AbstractComponent-method-removeUIClsFromElement\" class=\"docClass\">removeUIClsFromElement</a> and removes it from all\nelements of this component.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>cls</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>[]<div class='sub-desc'><p>A string or an array of strings to remove to the <code>uiCls</code>.</p>\n</div></li></ul></div></div></div><div id='method-removeListener' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-removeListener' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-removeListener' class='name expandable'>removeListener</a>( <span class='pre'>eventName, fn, [scope]</span> )</div><div class='description'><div class='short'>Removes an event handler. ...</div><div class='long'><p>Removes an event handler.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>eventName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The type of event the handler was associated with.</p>\n\n</div></li><li><span class='pre'>fn</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a><div class='sub-desc'><p>The handler to remove. <strong>This must be a reference to the function passed into the\n<a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">addListener</a> call.</strong></p>\n\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>The scope originally specified for the handler. It must be the same as the\nscope argument specified in the original call to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">addListener</a> or the listener will not be removed.</p>\n\n</div></li></ul></div></div></div><div id='method-removeManagedListener' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-removeManagedListener' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-removeManagedListener' class='name expandable'>removeManagedListener</a>( <span class='pre'>item, ename, [fn], [scope]</span> )</div><div class='description'><div class='short'>Removes listeners that were added by the mon method. ...</div><div class='long'><p>Removes listeners that were added by the <a href=\"#!/api/Ext.util.Observable-method-mon\" rel=\"Ext.util.Observable-method-mon\" class=\"docClass\">mon</a> method.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>item</span> : <a href=\"#!/api/Ext.util.Observable\" rel=\"Ext.util.Observable\" class=\"docClass\">Ext.util.Observable</a>/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a><div class='sub-desc'><p>The item from which to remove a listener/listeners.</p>\n\n</div></li><li><span class='pre'>ename</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The event name, or an object containing event name properties.</p>\n\n</div></li><li><span class='pre'>fn</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'><p>If the <code>ename</code> parameter was an event name, this is the handler function.</p>\n\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>If the <code>ename</code> parameter was an event name, this is the scope (<code>this</code> reference)\nin which the handler function is executed.</p>\n\n</div></li></ul></div></div></div><div id='method-removeManagedListenerItem' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-removeManagedListenerItem' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-removeManagedListenerItem' class='name expandable'>removeManagedListenerItem</a>( <span class='pre'>isClear, managedListener</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>inherit docs\n\nRemove a single managed listener item ...</div><div class='long'><p>inherit docs</p>\n\n<p>Remove a single managed listener item</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>isClear</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p>True if this is being called during a clear</p>\n</div></li><li><span class='pre'>managedListener</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The managed listener item\nSee removeManagedListener for other args</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Observable-method-removeManagedListenerItem' rel='Ext.util.Observable-method-removeManagedListenerItem' class='docClass'>Ext.util.Observable.removeManagedListenerItem</a></p></div></div></div><div id='method-removeOverCls' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-removeOverCls' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-removeOverCls' class='name expandable'>removeOverCls</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-removePlugin' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-removePlugin' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-removePlugin' class='name expandable'>removePlugin</a>( <span class='pre'>plugin</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>plugin</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-removeUIClsFromElement' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-removeUIClsFromElement' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-removeUIClsFromElement' class='name expandable'>removeUIClsFromElement</a>( <span class='pre'>ui</span> )</div><div class='description'><div class='short'>Method which removes a specified UI + uiCls from the components element. ...</div><div class='long'><p>Method which removes a specified UI + <code>uiCls</code> from the components element. The <code>cls</code> which is added to the element\nwill be: <code>this.baseCls + '-' + ui</code>.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>ui</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The UI to add to the element.</p>\n</div></li></ul></div></div></div><div id='method-removeUIFromElement' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-removeUIFromElement' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-removeUIFromElement' class='name expandable'>removeUIFromElement</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Method which removes a specified UI from the components element. ...</div><div class='long'><p>Method which removes a specified UI from the components element.</p>\n</div></div></div><div id='method-render' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-render' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-render' class='name expandable'>render</a>( <span class='pre'>[container], [position]</span> )</div><div class='description'><div class='short'>Renders the Component into the passed HTML element. ...</div><div class='long'><p>Renders the Component into the passed HTML element.</p>\n\n<p><strong>If you are using a <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Container</a> object to house this\nComponent, then do not use the render method.</strong></p>\n\n<p>A Container's child Components are rendered by that Container's\n<a href=\"#!/api/Ext.container.Container-cfg-layout\" rel=\"Ext.container.Container-cfg-layout\" class=\"docClass\">layout</a> manager when the Container is first rendered.</p>\n\n<p>If the Container is already rendered when a new child Component is added, you may need to call\nthe Container's <a href=\"#!/api/Ext.container.Container-method-doLayout\" rel=\"Ext.container.Container-method-doLayout\" class=\"docClass\">doLayout</a> to refresh the view which\ncauses any unrendered child Components to be rendered. This is required so that you can add\nmultiple child components if needed while only refreshing the layout once.</p>\n\n<p>When creating complex UIs, it is important to remember that sizing and positioning\nof child items is the responsibility of the Container's <a href=\"#!/api/Ext.container.Container-cfg-layout\" rel=\"Ext.container.Container-cfg-layout\" class=\"docClass\">layout</a>\nmanager. If you expect child items to be sized in response to user interactions, you must\nconfigure the Container with a layout manager which creates and manages the type of layout you\nhave in mind.</p>\n\n<p><strong>Omitting the Container's <a href=\"#!/api/Ext.container.Container-cfg-layout\" rel=\"Ext.container.Container-cfg-layout\" class=\"docClass\">layout</a> config means that a basic\nlayout manager is used which does nothing but render child components sequentially into the\nContainer. No sizing or positioning will be performed in this situation.</strong></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>container</span> : <a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a>/HTMLElement/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>The element this Component should be\nrendered into. If it is being created from existing markup, this should be omitted.</p>\n</div></li><li><span class='pre'>position</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>The element ID or DOM node index within the container <strong>before</strong>\nwhich this component will be inserted (defaults to appending to the end of the container)</p>\n</div></li></ul></div></div></div><div id='method-resumeEvent' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-resumeEvent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-resumeEvent' class='name expandable'>resumeEvent</a>( <span class='pre'>eventName</span> )</div><div class='description'><div class='short'>Resumes firing of the named event(s). ...</div><div class='long'><p>Resumes firing of the named event(s).</p>\n\n<p>After calling this method to resume events, the events will fire when requested to fire.</p>\n\n<p><strong>Note that if the <a href=\"#!/api/Ext.util.Observable-method-suspendEvent\" rel=\"Ext.util.Observable-method-suspendEvent\" class=\"docClass\">suspendEvent</a> method is called multiple times for a certain event,\nthis converse method will have to be called the same number of times for it to resume firing.</strong></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>eventName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>...<div class='sub-desc'><p>Multiple event names to resume.</p>\n</div></li></ul></div></div></div><div id='method-resumeEvents' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-resumeEvents' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-resumeEvents' class='name expandable'>resumeEvents</a>( <span class='pre'></span> )</div><div class='description'><div class='short'>Resumes firing events (see suspendEvents). ...</div><div class='long'><p>Resumes firing events (see <a href=\"#!/api/Ext.util.Observable-method-suspendEvents\" rel=\"Ext.util.Observable-method-suspendEvents\" class=\"docClass\">suspendEvents</a>).</p>\n\n<p>If events were suspended using the <code>queueSuspended</code> parameter, then all events fired\nduring event suspension will be sent to any listeners now.</p>\n</div></div></div><div id='method-resumeLayouts' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-resumeLayouts' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-resumeLayouts' class='name expandable'>resumeLayouts</a>( <span class='pre'>flushOptions</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>flushOptions</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-savePropToState' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-method-savePropToState' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-method-savePropToState' class='name expandable'>savePropToState</a>( <span class='pre'>propName, state, [stateName]</span> ) : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></div><div class='description'><div class='short'>Conditionally saves a single property from this object to the given state object. ...</div><div class='long'><p>Conditionally saves a single property from this object to the given state object.\nThe idea is to only save state which has changed from the initial state so that\ncurrent software settings do not override future software settings. Only those\nvalues that are user-changed state should be saved.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>propName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The name of the property to save.</p>\n</div></li><li><span class='pre'>state</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The state object in to which to save the property.</p>\n</div></li><li><span class='pre'>stateName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>The name to use for the property in state.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a></span><div class='sub-desc'><p>True if the property was saved, false if not.</p>\n</div></li></ul></div></div></div><div id='method-savePropsToState' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-method-savePropsToState' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-method-savePropsToState' class='name expandable'>savePropsToState</a>( <span class='pre'>propNames, state</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>Gathers additional named properties of the instance and adds their current values\nto the passed state object. ...</div><div class='long'><p>Gathers additional named properties of the instance and adds their current values\nto the passed state object.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>propNames</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>[]<div class='sub-desc'><p>The name (or array of names) of the property to save.</p>\n</div></li><li><span class='pre'>state</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The state object in to which to save the property values.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>state</p>\n</div></li></ul></div></div></div><div id='method-saveState' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-method-saveState' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-method-saveState' class='name expandable'>saveState</a>( <span class='pre'></span> )</div><div class='description'><div class='short'>Saves the state of the object to the persistence store. ...</div><div class='long'><p>Saves the state of the object to the persistence store.</p>\n</div></div></div><div id='method-scrollBy' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-scrollBy' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-scrollBy' class='name expandable'>scrollBy</a>( <span class='pre'>deltaX, deltaY, animate</span> )</div><div class='description'><div class='short'>Scrolls this Component's target element by the passed delta values, optionally animating. ...</div><div class='long'><p>Scrolls this Component's <a href=\"#!/api/Ext.Component-method-getTargetEl\" rel=\"Ext.Component-method-getTargetEl\" class=\"docClass\">target element</a> by the passed delta values, optionally animating.</p>\n\n<p>All of the following are equivalent:</p>\n\n<pre><code> comp.scrollBy(10, 10, true);\n comp.scrollBy([10, 10], true);\n comp.scrollBy({ x: 10, y: 10 }, true);\n</code></pre>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>deltaX</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>Either the x delta, an Array specifying x and y deltas or\nan object with \"x\" and \"y\" properties.</p>\n</div></li><li><span class='pre'>deltaY</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>Either the y delta, or an animate flag or config object.</p>\n</div></li><li><span class='pre'>animate</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>Animate flag/config object if the delta values were passed separately.</p>\n</div></li></ul></div></div></div><div id='method-sequenceFx' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Animate' rel='Ext.util.Animate' class='defined-in docClass'>Ext.util.Animate</a><br/><a href='source/Animate.html#Ext-util-Animate-method-sequenceFx' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Animate-method-sequenceFx' class='name expandable'>sequenceFx</a>( <span class='pre'></span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Ensures that all effects queued after sequenceFx is called on this object are run in sequence. ...</div><div class='long'><p>Ensures that all effects queued after sequenceFx is called on this object are run in sequence. This is the\nopposite of <a href=\"#!/api/Ext.util.Animate-method-syncFx\" rel=\"Ext.util.Animate-method-syncFx\" class=\"docClass\">syncFx</a>.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-setActive' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-setActive' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-setActive' class='name expandable'>setActive</a>( <span class='pre'>[active], [newActive]</span> )</div><div class='description'><div class='short'>This method is called internally by Ext.ZIndexManager to signal that a floating Component has either been\nmoved to th...</div><div class='long'><p>This method is called internally by <a href=\"#!/api/Ext.ZIndexManager\" rel=\"Ext.ZIndexManager\" class=\"docClass\">Ext.ZIndexManager</a> to signal that a floating Component has either been\nmoved to the top of its zIndex stack, or pushed from the top of its zIndex stack.</p>\n\n<p>If a <em>Window</em> is superceded by another Window, deactivating it hides its shadow.</p>\n\n<p>This method also fires the <a href=\"#!/api/Ext.Component-event-activate\" rel=\"Ext.Component-event-activate\" class=\"docClass\">activate</a> or\n<a href=\"#!/api/Ext.Component-event-deactivate\" rel=\"Ext.Component-event-deactivate\" class=\"docClass\">deactivate</a> event depending on which action occurred.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>active</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>True to activate the Component, false to deactivate it.</p>\n<p>Defaults to: <code>false</code></p></div></li><li><span class='pre'>newActive</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> (optional)<div class='sub-desc'><p>The newly active Component which is taking over topmost zIndex position.</p>\n</div></li></ul></div></div></div><div id='method-setAutoScroll' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-setAutoScroll' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-setAutoScroll' class='name expandable'>setAutoScroll</a>( <span class='pre'>scroll</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Sets the overflow on the content element of the component. ...</div><div class='long'><p>Sets the overflow on the content element of the component.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>scroll</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p>True to allow the Component to auto scroll.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-setBorder' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setBorder' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setBorder' class='name expandable'>setBorder</a>( <span class='pre'>border</span> )</div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>border</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The border, see <a href=\"#!/api/Ext.AbstractComponent-cfg-border\" rel=\"Ext.AbstractComponent-cfg-border\" class=\"docClass\">border</a>. If a falsey value is passed\nthe border will be removed.</p>\n</div></li></ul></div></div></div><div id='method-setBorderRegion' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Region2.html#Ext-Component-method-setBorderRegion' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-setBorderRegion' class='name expandable'>setBorderRegion</a>( <span class='pre'>region</span> ) : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></div><div class='description'><div class='short'>This method changes the region config property for this border region. ...</div><div class='long'><p>This method changes the <code>region</code> config property for this border region. This is\nonly valid if this component is in a <code>border</code> layout (<code><a href=\"#!/api/Ext.layout.container.Border\" rel=\"Ext.layout.container.Border\" class=\"docClass\">Ext.layout.container.Border</a></code>).</p>\n\n<p><strong>Defined in override Ext.layout.container.border.Region.</strong></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>region</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The new <code>region</code> value (<code>\"north\"</code>, <code>\"south\"</code>, <code>\"east\"</code> or\n<code>\"west\"</code>).</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><div class='sub-desc'><p>The previous value of the <code>region</code> property.</p>\n</div></li></ul></div></div></div><div id='method-setBox' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-setBox' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-setBox' class='name expandable'>setBox</a>( <span class='pre'>box, [animate]</span> ) : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Sets the element's box. ...</div><div class='long'><p>Sets the element's box. If animate is true then x, y, width, and height will be\nanimated concurrently.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>box</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The box to fill {x, y, width, height}</p>\n</div></li><li><span class='pre'>animate</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>true for the default animation or a standard\nElement animation config object</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-setComponentLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setComponentLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setComponentLayout' class='name expandable'>setComponentLayout</a>( <span class='pre'>layout</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>layout</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-setConfig' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-method-setConfig' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-method-setConfig' class='name expandable'>setConfig</a>( <span class='pre'>config, applyIfNotSet</span> ) : <a href=\"#!/api/Ext.Base\" rel=\"Ext.Base\" class=\"docClass\">Ext.Base</a><strong class='chainable signature' >chainable</strong><strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>config</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>applyIfNotSet</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Base\" rel=\"Ext.Base\" class=\"docClass\">Ext.Base</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-setDisabled' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setDisabled' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setDisabled' class='name expandable'>setDisabled</a>( <span class='pre'>disabled</span> )</div><div class='description'><div class='short'>Enable or disable the component. ...</div><div class='long'><p>Enable or disable the component.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>disabled</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p><code>true</code> to disable.</p>\n</div></li></ul></div></div></div><div id='method-setDocked' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setDocked' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setDocked' class='name expandable'>setDocked</a>( <span class='pre'>dock, [layoutParent]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Sets the dock position of this component in its parent panel. ...</div><div class='long'><p>Sets the dock position of this component in its parent panel. Note that this only has effect if this item is part\nof the <code>dockedItems</code> collection of a parent that has a DockLayout (note that any Panel has a DockLayout by default)</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>dock</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The dock position.</p>\n</div></li><li><span class='pre'>layoutParent</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p><code>true</code> to re-layout parent.</p>\n<p>Defaults to: <code>false</code></p></div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-setFloatParent' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-setFloatParent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-setFloatParent' class='name expandable'>setFloatParent</a>( <span class='pre'>floatParent</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>floatParent</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-setHeight' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setHeight' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setHeight' class='name expandable'>setHeight</a>( <span class='pre'>height</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Sets the height of the component. ...</div><div class='long'><p>Sets the height of the component. This method fires the <a href=\"#!/api/Ext.AbstractComponent-event-resize\" rel=\"Ext.AbstractComponent-event-resize\" class=\"docClass\">resize</a> event.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>height</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The new height to set. This may be one of:</p>\n\n<ul>\n<li>A Number specifying the new height in the <a href=\"#!/api/Ext.AbstractComponent-method-getEl\" rel=\"Ext.AbstractComponent-method-getEl\" class=\"docClass\">Element</a>'s <a href=\"#!/api/Ext.dom.Element-property-defaultUnit\" rel=\"Ext.dom.Element-property-defaultUnit\" class=\"docClass\">Ext.Element.defaultUnit</a>s (by default, pixels).</li>\n<li>A String used to set the CSS height style.</li>\n<li><em>undefined</em> to leave the height unchanged.</li>\n</ul>\n\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-setHiddenState' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setHiddenState' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setHiddenState' class='name expandable'>setHiddenState</a>( <span class='pre'>hidden</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>hidden</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-setLoading' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-setLoading' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-setLoading' class='name expandable'>setLoading</a>( <span class='pre'>load, [targetEl]</span> ) : <a href=\"#!/api/Ext.LoadMask\" rel=\"Ext.LoadMask\" class=\"docClass\">Ext.LoadMask</a></div><div class='description'><div class='short'>This method allows you to show or hide a LoadMask on top of this component. ...</div><div class='long'><p>This method allows you to show or hide a LoadMask on top of this component.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>load</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>True to show the default LoadMask, a config object that will be passed to the\nLoadMask constructor, or a message String to show. False to hide the current LoadMask.</p>\n</div></li><li><span class='pre'>targetEl</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>True to mask the targetEl of this Component instead of the <code>this.el</code>. For example,\nsetting this to true on a Panel will cause only the body to be masked.</p>\n<p>Defaults to: <code>false</code></p></div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.LoadMask\" rel=\"Ext.LoadMask\" class=\"docClass\">Ext.LoadMask</a></span><div class='sub-desc'><p>The LoadMask instance that has just been shown.</p>\n</div></li></ul></div></div></div><div id='method-setLocalX' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setLocalX' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setLocalX' class='name expandable'>setLocalX</a>( <span class='pre'>x</span> ) : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></div><div class='description'><div class='short'>Overridden in Ext.rtl.AbstractComponent. ...</div><div class='long'><p><strong>Overridden in Ext.rtl.AbstractComponent.</strong></p>\n\n<p>Sets the local x coordinate of this element using CSS style. When used on an\nabsolute positioned element this method is symmetrical with <a href=\"#!/api/Ext.AbstractComponent-method-getLocalX\" rel=\"Ext.AbstractComponent-method-getLocalX\" class=\"docClass\">getLocalX</a>, but\nmay not be symmetrical when used on a relatively positioned element.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>x</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The x coordinate. A value of <code>null</code> sets the left style to 'auto'.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-setLocalX' rel='Ext.util.Positionable-method-setLocalX' class='docClass'>Ext.util.Positionable.setLocalX</a></p></div></div></div><div id='method-setLocalXY' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setLocalXY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setLocalXY' class='name expandable'>setLocalXY</a>( <span class='pre'>x, [y]</span> ) : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></div><div class='description'><div class='short'>Overridden in Ext.rtl.AbstractComponent. ...</div><div class='long'><p><strong>Overridden in Ext.rtl.AbstractComponent.</strong></p>\n\n<p>Sets the local x and y coordinates of this element using CSS style. When used on an\nabsolute positioned element this method is symmetrical with <a href=\"#!/api/Ext.AbstractComponent-method-getLocalXY\" rel=\"Ext.AbstractComponent-method-getLocalXY\" class=\"docClass\">getLocalXY</a>, but\nmay not be symmetrical when used on a relatively positioned element.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>x</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a><div class='sub-desc'><p>The x coordinate or an array containing [x, y]. A value of\n<code>null</code> sets the left style to 'auto'</p>\n</div></li><li><span class='pre'>y</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>The y coordinate, required if x is not an array. A value of\n<code>null</code> sets the top style to 'auto'</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-setLocalXY' rel='Ext.util.Positionable-method-setLocalXY' class='docClass'>Ext.util.Positionable.setLocalXY</a></p></div></div></div><div id='method-setLocalY' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setLocalY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setLocalY' class='name expandable'>setLocalY</a>( <span class='pre'>y</span> ) : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></div><div class='description'><div class='short'>Sets the local y coordinate of this element using CSS style. ...</div><div class='long'><p>Sets the local y coordinate of this element using CSS style. When used on an\nabsolute positioned element this method is symmetrical with <a href=\"#!/api/Ext.AbstractComponent-method-getLocalY\" rel=\"Ext.AbstractComponent-method-getLocalY\" class=\"docClass\">getLocalY</a>, but\nmay not be symmetrical when used on a relatively positioned element.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>y</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The y coordinate. A value of <code>null</code> sets the top style to 'auto'.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-setLocalY' rel='Ext.util.Positionable-method-setLocalY' class='docClass'>Ext.util.Positionable.setLocalY</a></p></div></div></div><div id='method-setMargin' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setMargin' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setMargin' class='name expandable'>setMargin</a>( <span class='pre'>margin</span> )</div><div class='description'><div class='short'>Sets the margin on the target element. ...</div><div class='long'><p>Sets the margin on the target element.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>margin</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The margin to set. See the <a href=\"#!/api/Ext.AbstractComponent-cfg-margin\" rel=\"Ext.AbstractComponent-cfg-margin\" class=\"docClass\">margin</a> config.</p>\n</div></li></ul></div></div></div><div id='method-setOverflowXY' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-setOverflowXY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-setOverflowXY' class='name expandable'>setOverflowXY</a>( <span class='pre'>overflowX, overflowY</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Sets the overflow x/y on the content element of the component. ...</div><div class='long'><p>Sets the overflow x/y on the content element of the component. The x/y overflow\nvalues can be any valid CSS overflow (e.g., 'auto' or 'scroll'). By default, the\nvalue is 'hidden'. Passing null for one of the values will erase the inline style.\nPassing <code>undefined</code> will preserve the current value.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>overflowX</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The overflow-x value.</p>\n</div></li><li><span class='pre'>overflowY</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The overflow-y value.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-setPagePosition' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-setPagePosition' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-setPagePosition' class='name expandable'>setPagePosition</a>( <span class='pre'>x, [y], [animate]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Sets the page XY position of the component. ...</div><div class='long'><p>Sets the page XY position of the component. To set the left and top instead, use <a href=\"#!/api/Ext.Component-method-setPosition\" rel=\"Ext.Component-method-setPosition\" class=\"docClass\">setPosition</a>.\nThis method fires the <a href=\"#!/api/Ext.Component-event-move\" rel=\"Ext.Component-event-move\" class=\"docClass\">move</a> event.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>x</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]<div class='sub-desc'><p>The new x position or an array of <code>[x,y]</code>.</p>\n</div></li><li><span class='pre'>y</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>The new y position.</p>\n</div></li><li><span class='pre'>animate</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>True to animate the Component into its new position. You may also pass an\nanimation configuration.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-setPosition' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/AbstractComponent.html#Ext-Component-method-setPosition' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-setPosition' class='name expandable'>setPosition</a>( <span class='pre'>x, [y], [animate]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Sets the left and top of the component. ...</div><div class='long'><p>Sets the left and top of the component. To set the page XY position instead, use <a href=\"#!/api/Ext.Component-method-setPagePosition\" rel=\"Ext.Component-method-setPagePosition\" class=\"docClass\">setPagePosition</a>. This\nmethod fires the <a href=\"#!/api/Ext.Component-event-move\" rel=\"Ext.Component-event-move\" class=\"docClass\">move</a> event.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>x</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The new left, an array of <code>[x,y]</code>, or animation config object containing <code>x</code> and <code>y</code> properties.</p>\n</div></li><li><span class='pre'>y</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>The new top.</p>\n</div></li><li><span class='pre'>animate</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>If <code>true</code>, the Component is <em>animated</em> into its new position. You may also pass an\nanimation configuration.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-setRegion' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-setRegion' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-setRegion' class='name expandable'>setRegion</a>( <span class='pre'>region, [animate]</span> ) : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Sets the element's position and size to the specified region. ...</div><div class='long'><p>Sets the element's position and size to the specified region. If animation is true\nthen width, height, x and y will be animated concurrently.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>region</span> : <a href=\"#!/api/Ext.util.Region\" rel=\"Ext.util.Region\" class=\"docClass\">Ext.util.Region</a><div class='sub-desc'><p>The region to fill</p>\n</div></li><li><span class='pre'>animate</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>true for the default animation or a standard\nElement animation config object</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-setRegionWeight' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Region2.html#Ext-Component-method-setRegionWeight' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-setRegionWeight' class='name expandable'>setRegionWeight</a>( <span class='pre'>weight</span> ) : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></div><div class='description'><div class='short'>Sets the weight config property for this component. ...</div><div class='long'><p>Sets the <code>weight</code> config property for this component. This is only valid if this\ncomponent is in a <code>border</code> layout (<code><a href=\"#!/api/Ext.layout.container.Border\" rel=\"Ext.layout.container.Border\" class=\"docClass\">Ext.layout.container.Border</a></code>).</p>\n\n<p><strong>Defined in override Ext.layout.container.border.Region.</strong></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>weight</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The new <code>weight</code> value.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a></span><div class='sub-desc'><p>The previous value of the <code>weight</code> property.</p>\n</div></li></ul></div></div></div><div id='method-setSize' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setSize' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setSize' class='name expandable'>setSize</a>( <span class='pre'>width, height</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Sets the width and height of this Component. ...</div><div class='long'><p>Sets the width and height of this Component. This method fires the <a href=\"#!/api/Ext.AbstractComponent-event-resize\" rel=\"Ext.AbstractComponent-event-resize\" class=\"docClass\">resize</a> event. This method can accept\neither width and height as separate arguments, or you can pass a size object like <code>{width:10, height:20}</code>.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>width</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The new width to set. This may be one of:</p>\n\n<ul>\n<li>A Number specifying the new width in the <a href=\"#!/api/Ext.AbstractComponent-method-getEl\" rel=\"Ext.AbstractComponent-method-getEl\" class=\"docClass\">Element</a>'s <a href=\"#!/api/Ext.dom.Element-property-defaultUnit\" rel=\"Ext.dom.Element-property-defaultUnit\" class=\"docClass\">Ext.Element.defaultUnit</a>s (by default, pixels).</li>\n<li>A String used to set the CSS width style.</li>\n<li>A size object in the format <code>{width: widthValue, height: heightValue}</code>.</li>\n<li><code>undefined</code> to leave the width unchanged.</li>\n</ul>\n\n</div></li><li><span class='pre'>height</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The new height to set (not required if a size object is passed as the first arg).\nThis may be one of:</p>\n\n<ul>\n<li>A Number specifying the new height in the <a href=\"#!/api/Ext.AbstractComponent-method-getEl\" rel=\"Ext.AbstractComponent-method-getEl\" class=\"docClass\">Element</a>'s <a href=\"#!/api/Ext.dom.Element-property-defaultUnit\" rel=\"Ext.dom.Element-property-defaultUnit\" class=\"docClass\">Ext.Element.defaultUnit</a>s (by default, pixels).</li>\n<li>A String used to set the CSS height style. Animation may <strong>not</strong> be used.</li>\n<li><code>undefined</code> to leave the height unchanged.</li>\n</ul>\n\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-setUI' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setUI' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setUI' class='name expandable'>setUI</a>( <span class='pre'>ui</span> )</div><div class='description'><div class='short'>Sets the UI for the component. ...</div><div class='long'><p>Sets the UI for the component. This will remove any existing UIs on the component. It will also loop through any\n<code>uiCls</code> set on the component and rename them so they include the new UI.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>ui</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The new UI for the component.</p>\n</div></li></ul></div></div></div><div id='method-setVisible' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setVisible' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setVisible' class='name expandable'>setVisible</a>( <span class='pre'>visible</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Convenience function to hide or show this component by Boolean. ...</div><div class='long'><p>Convenience function to hide or show this component by Boolean.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>visible</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p><code>true</code> to show, <code>false</code> to hide.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-setWidth' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setWidth' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setWidth' class='name expandable'>setWidth</a>( <span class='pre'>width</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Sets the width of the component. ...</div><div class='long'><p>Sets the width of the component. This method fires the <a href=\"#!/api/Ext.AbstractComponent-event-resize\" rel=\"Ext.AbstractComponent-event-resize\" class=\"docClass\">resize</a> event.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>width</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The new width to setThis may be one of:</p>\n\n<ul>\n<li>A Number specifying the new width in the <a href=\"#!/api/Ext.AbstractComponent-method-getEl\" rel=\"Ext.AbstractComponent-method-getEl\" class=\"docClass\">Element</a>'s <a href=\"#!/api/Ext.dom.Element-property-defaultUnit\" rel=\"Ext.dom.Element-property-defaultUnit\" class=\"docClass\">Ext.Element.defaultUnit</a>s (by default, pixels).</li>\n<li>A String used to set the CSS width style.</li>\n</ul>\n\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-setX' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setX' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setX' class='name expandable'>setX</a>( <span class='pre'>The, [animate]</span> ) : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></div><div class='description'><div class='short'>Sets the X position of the DOM element based on page coordinates. ...</div><div class='long'><p>Sets the X position of the DOM element based on page coordinates.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>The</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>X position</p>\n</div></li><li><span class='pre'>animate</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>True for the default animation, or a standard\nElement animation config object</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-setX' rel='Ext.util.Positionable-method-setX' class='docClass'>Ext.util.Positionable.setX</a></p></div></div></div><div id='method-setXY' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setXY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setXY' class='name expandable'>setXY</a>( <span class='pre'>pos, [animate]</span> ) : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></div><div class='description'><div class='short'>Sets the position of the DOM element in page coordinates. ...</div><div class='long'><p>Sets the position of the DOM element in page coordinates.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>pos</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]<div class='sub-desc'><p>Contains X &amp; Y [x, y] values for new position (coordinates\nare page-based)</p>\n</div></li><li><span class='pre'>animate</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>True for the default animation, or a standard\nElement animation config object</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-setXY' rel='Ext.util.Positionable-method-setXY' class='docClass'>Ext.util.Positionable.setXY</a></p></div></div></div><div id='method-setY' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setY' class='name expandable'>setY</a>( <span class='pre'>The, [animate]</span> ) : <a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></div><div class='description'><div class='short'>Sets the Y position of the DOM element based on page coordinates. ...</div><div class='long'><p>Sets the Y position of the DOM element based on page coordinates.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>The</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>Y position</p>\n</div></li><li><span class='pre'>animate</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>True for the default animation, or a standard\nElement animation config object</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.util.Positionable\" rel=\"Ext.util.Positionable\" class=\"docClass\">Ext.util.Positionable</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Positionable-method-setY' rel='Ext.util.Positionable-method-setY' class='docClass'>Ext.util.Positionable.setY</a></p></div></div></div><div id='method-setZIndex' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-setZIndex' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-setZIndex' class='name expandable'>setZIndex</a>( <span class='pre'>index</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>z-index is managed by the zIndexManager and may be overwritten at any time. ...</div><div class='long'><p>z-index is managed by the zIndexManager and may be overwritten at any time.\nReturns the next z-index to be used.\nIf this is a Container, then it will have rebased any managed floating Components,\nand so the next available z-index will be approximately 10000 above that.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>index</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-setupFramingTpl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-setupFramingTpl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-setupFramingTpl' class='name expandable'>setupFramingTpl</a>( <span class='pre'>frameTpl</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Inject a reference to the function which applies the render template into the framing template. ...</div><div class='long'><p>Inject a reference to the function which applies the render template into the framing template. The framing template\nwraps the content.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>frameTpl</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-setupProtoEl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-setupProtoEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-setupProtoEl' class='name expandable'>setupProtoEl</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-setupRenderTpl' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-setupRenderTpl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-setupRenderTpl' class='name expandable'>setupRenderTpl</a>( <span class='pre'>renderTpl</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>renderTpl</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-show' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-show' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-show' class='name expandable'>show</a>( <span class='pre'>[animateTarget], [callback], [scope]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Shows this Component, rendering it first if autoRender or floating are true. ...</div><div class='long'><p>Shows this Component, rendering it first if <a href=\"#!/api/Ext.Component-cfg-autoRender\" rel=\"Ext.Component-cfg-autoRender\" class=\"docClass\">autoRender</a> or <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a> are <code>true</code>.</p>\n\n<p>After being shown, a <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a> Component (such as a <a href=\"#!/api/Ext.window.Window\" rel=\"Ext.window.Window\" class=\"docClass\">Ext.window.Window</a>), is activated it and\nbrought to the front of its <a href=\"#!/api/Ext.Component-property-zIndexManager\" rel=\"Ext.Component-property-zIndexManager\" class=\"docClass\">z-index stack</a>.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>animateTarget</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a> (optional)<div class='sub-desc'><p><strong>only valid for <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a> Components such as <a href=\"#!/api/Ext.window.Window\" rel=\"Ext.window.Window\" class=\"docClass\">Window</a>s or <a href=\"#!/api/Ext.tip.ToolTip\" rel=\"Ext.tip.ToolTip\" class=\"docClass\">ToolTip</a>s, or regular Components which have been configured\nwith <code>floating: true</code>.</strong> The target from which the Component should animate from while opening.</p>\n<p>Defaults to: <code>null</code></p></div></li><li><span class='pre'>callback</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'><p>A callback function to call after the Component is displayed.\nOnly necessary if animation was specified.</p>\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>The scope (<code>this</code> reference) in which the callback is executed.\nDefaults to this Component.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.AbstractComponent-method-show' rel='Ext.AbstractComponent-method-show' class='docClass'>Ext.AbstractComponent.show</a></p></div></div></div><div id='method-showAt' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-showAt' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-showAt' class='name expandable'>showAt</a>( <span class='pre'>x, [y], [animate]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Displays component at specific xy position. ...</div><div class='long'><p>Displays component at specific xy position.\nA floating component (like a menu) is positioned relative to its ownerCt if any.\nUseful for popping up a context menu:</p>\n\n<pre><code>listeners: {\n itemcontextmenu: function(view, record, item, index, event, options) {\n <a href=\"#!/api/Ext-method-create\" rel=\"Ext-method-create\" class=\"docClass\">Ext.create</a>('<a href=\"#!/api/Ext.menu.Menu\" rel=\"Ext.menu.Menu\" class=\"docClass\">Ext.menu.Menu</a>', {\n width: 100,\n height: 100,\n margin: '0 0 10 0',\n items: [{\n text: 'regular item 1'\n },{\n text: 'regular item 2'\n },{\n text: 'regular item 3'\n }]\n }).showAt(event.getXY());\n }\n}\n</code></pre>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>x</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[]<div class='sub-desc'><p>The new x position or array of <code>[x,y]</code>.</p>\n</div></li><li><span class='pre'>y</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>The new y position</p>\n</div></li><li><span class='pre'>animate</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>True to animate the Component into its new position. You may also pass an\nanimation configuration.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-showBy' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-showBy' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-showBy' class='name expandable'>showBy</a>( <span class='pre'>component, [position], [offsets]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Shows this component by the specified Component or Element. ...</div><div class='long'><p>Shows this component by the specified <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Component</a> or <a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Element</a>.\nUsed when this component is <a href=\"#!/api/Ext.Component-cfg-floating\" rel=\"Ext.Component-cfg-floating\" class=\"docClass\">floating</a>.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>component</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a>/<a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.dom.Element</a><div class='sub-desc'><p>The <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> or <a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a> to show the component by.</p>\n</div></li><li><span class='pre'>position</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a> (optional)<div class='sub-desc'><p>Alignment position as used by <a href=\"#!/api/Ext.util.Positionable-method-getAlignToXY\" rel=\"Ext.util.Positionable-method-getAlignToXY\" class=\"docClass\">Ext.util.Positionable.getAlignToXY</a>.\nDefaults to <code><a href=\"#!/api/Ext.Component-cfg-defaultAlign\" rel=\"Ext.Component-cfg-defaultAlign\" class=\"docClass\">defaultAlign</a></code>.</p>\n</div></li><li><span class='pre'>offsets</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>[] (optional)<div class='sub-desc'><p>Alignment offsets as used by <a href=\"#!/api/Ext.util.Positionable-method-getAlignToXY\" rel=\"Ext.util.Positionable-method-getAlignToXY\" class=\"docClass\">Ext.util.Positionable.getAlignToXY</a>.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-statics' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-method-statics' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-method-statics' class='name expandable'>statics</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.Class\" rel=\"Ext.Class\" class=\"docClass\">Ext.Class</a><strong class='protected signature' >protected</strong></div><div class='description'><div class='short'>Get the reference to the class from which this object was instantiated. ...</div><div class='long'><p>Get the reference to the class from which this object was instantiated. Note that unlike <a href=\"#!/api/Ext.Base-property-self\" rel=\"Ext.Base-property-self\" class=\"docClass\">self</a>,\n<code>this.statics()</code> is scope-independent and it always returns the class from which it was called, regardless of what\n<code>this</code> points to during run-time</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.Cat', {\n statics: {\n totalCreated: 0,\n speciesName: 'Cat' // My.Cat.speciesName = 'Cat'\n },\n\n constructor: function() {\n var statics = this.statics();\n\n alert(statics.speciesName); // always equals to 'Cat' no matter what 'this' refers to\n // equivalent to: My.Cat.speciesName\n\n alert(this.self.speciesName); // dependent on 'this'\n\n statics.totalCreated++;\n },\n\n clone: function() {\n var cloned = new this.self; // dependent on 'this'\n\n cloned.groupName = this.statics().speciesName; // equivalent to: My.Cat.speciesName\n\n return cloned;\n }\n});\n\n\n<a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.SnowLeopard', {\n extend: 'My.Cat',\n\n statics: {\n speciesName: 'Snow Leopard' // My.SnowLeopard.speciesName = 'Snow Leopard'\n },\n\n constructor: function() {\n this.callParent();\n }\n});\n\nvar cat = new My.Cat(); // alerts 'Cat', then alerts 'Cat'\n\nvar snowLeopard = new My.SnowLeopard(); // alerts 'Cat', then alerts 'Snow Leopard'\n\nvar clone = snowLeopard.clone();\nalert(<a href=\"#!/api/Ext-method-getClassName\" rel=\"Ext-method-getClassName\" class=\"docClass\">Ext.getClassName</a>(clone)); // alerts 'My.SnowLeopard'\nalert(clone.groupName); // alerts 'Cat'\n\nalert(My.Cat.totalCreated); // alerts 3\n</code></pre>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Class\" rel=\"Ext.Class\" class=\"docClass\">Ext.Class</a></span><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-stopAnimation' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Animate' rel='Ext.util.Animate' class='defined-in docClass'>Ext.util.Animate</a><br/><a href='source/Animate.html#Ext-util-Animate-method-stopAnimation' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Animate-method-stopAnimation' class='name expandable'>stopAnimation</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Stops any running effects and clears this object's internal effects queue if it contains any additional effects\nthat ...</div><div class='long'><p>Stops any running effects and clears this object's internal effects queue if it contains any additional effects\nthat haven't started yet.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a></span><div class='sub-desc'><p>The Element</p>\n</div></li></ul></div></div></div><div id='method-stopFx' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Animate' rel='Ext.util.Animate' class='defined-in docClass'>Ext.util.Animate</a><br/><a href='source/Animate.html#Ext-util-Animate-method-stopFx' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Animate-method-stopFx' class='name expandable'>stopFx</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a><strong class='deprecated signature' >deprecated</strong></div><div class='description'><div class='short'>Stops any running effects and clears this object's internal effects queue if it contains any additional effects\nthat ...</div><div class='long'><p>Stops any running effects and clears this object's internal effects queue if it contains any additional effects\nthat haven't started yet.</p>\n <div class='signature-box deprecated'>\n <p>This method has been <strong>deprecated</strong> since 4.0</p>\n <p>Replaced by <a href=\"#!/api/Ext.util.Animate-method-stopAnimation\" rel=\"Ext.util.Animate-method-stopAnimation\" class=\"docClass\">stopAnimation</a></p>\n\n </div>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a></span><div class='sub-desc'><p>The Element</p>\n</div></li></ul></div></div></div><div id='method-suspendEvent' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-suspendEvent' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-suspendEvent' class='name expandable'>suspendEvent</a>( <span class='pre'>eventName</span> )</div><div class='description'><div class='short'>Suspends firing of the named event(s). ...</div><div class='long'><p>Suspends firing of the named event(s).</p>\n\n<p>After calling this method to suspend events, the events will no longer fire when requested to fire.</p>\n\n<p><strong>Note that if this is called multiple times for a certain event, the converse method\n<a href=\"#!/api/Ext.util.Observable-method-resumeEvent\" rel=\"Ext.util.Observable-method-resumeEvent\" class=\"docClass\">resumeEvent</a> will have to be called the same number of times for it to resume firing.</strong></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>eventName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>...<div class='sub-desc'><p>Multiple event names to suspend.</p>\n</div></li></ul></div></div></div><div id='method-suspendEvents' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-suspendEvents' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-suspendEvents' class='name expandable'>suspendEvents</a>( <span class='pre'>queueSuspended</span> )</div><div class='description'><div class='short'>Suspends the firing of all events. ...</div><div class='long'><p>Suspends the firing of all events. (see <a href=\"#!/api/Ext.util.Observable-method-resumeEvents\" rel=\"Ext.util.Observable-method-resumeEvents\" class=\"docClass\">resumeEvents</a>)</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>queueSuspended</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p>Pass as true to queue up suspended events to be fired\nafter the <a href=\"#!/api/Ext.util.Observable-method-resumeEvents\" rel=\"Ext.util.Observable-method-resumeEvents\" class=\"docClass\">resumeEvents</a> call instead of discarding all suspended events.</p>\n</div></li></ul></div></div></div><div id='method-suspendLayouts' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-suspendLayouts' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-suspendLayouts' class='name expandable'>suspendLayouts</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-syncFx' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Animate' rel='Ext.util.Animate' class='defined-in docClass'>Ext.util.Animate</a><br/><a href='source/Animate.html#Ext-util-Animate-method-syncFx' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Animate-method-syncFx' class='name expandable'>syncFx</a>( <span class='pre'></span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Ensures that all effects queued after syncFx is called on this object are run concurrently. ...</div><div class='long'><p>Ensures that all effects queued after syncFx is called on this object are run concurrently. This is the opposite\nof <a href=\"#!/api/Ext.util.Animate-method-sequenceFx\" rel=\"Ext.util.Animate-method-sequenceFx\" class=\"docClass\">sequenceFx</a>.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-syncHidden' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-syncHidden' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-syncHidden' class='name expandable'>syncHidden</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>synchronizes the hidden state of this component with the state of its hierarchy ...</div><div class='long'><p>synchronizes the hidden state of this component with the state of its hierarchy</p>\n</div></div></div><div id='method-syncShadow' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-syncShadow' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-syncShadow' class='name expandable'>syncShadow</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-toBack' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-toBack' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-toBack' class='name expandable'>toBack</a>( <span class='pre'></span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Sends this Component to the back of (lower z-index than) any other visible windows ...</div><div class='long'><p>Sends this Component to the back of (lower z-index than) any other visible windows</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-toFront' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Floating' rel='Ext.util.Floating' class='defined-in docClass'>Ext.util.Floating</a><br/><a href='source/Floating2.html#Ext-util-Floating-method-toFront' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Floating-method-toFront' class='name expandable'>toFront</a>( <span class='pre'>[preventFocus]</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></div><div class='description'><div class='short'>Brings this floating Component to the front of any other visible, floating Components managed by the same\nZIndexManag...</div><div class='long'><p>Brings this floating Component to the front of any other visible, floating Components managed by the same\n<a href=\"#!/api/Ext.ZIndexManager\" rel=\"Ext.ZIndexManager\" class=\"docClass\">ZIndexManager</a></p>\n\n<p>If this Component is modal, inserts the modal mask just below this Component in the z-index stack.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>preventFocus</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>Specify <code>true</code> to prevent the Component from being focused.</p>\n<p>Defaults to: <code>false</code></p></div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-translatePoints' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-translatePoints' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-translatePoints' class='name expandable'>translatePoints</a>( <span class='pre'>x, [y]</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></div><div class='description'><div class='short'>Translates the passed page coordinates into left/top css values for the element ...</div><div class='long'><p>Translates the passed page coordinates into left/top css values for the element</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>x</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a><div class='sub-desc'><p>The page x or an array containing [x, y]</p>\n</div></li><li><span class='pre'>y</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>The page y, required if x is not an array</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>An object with left and top properties. e.g.\n{left: (value), top: (value)}</p>\n</div></li></ul></div></div></div><div id='method-translateXY' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Positionable' rel='Ext.util.Positionable' class='defined-in docClass'>Ext.util.Positionable</a><br/><a href='source/Positionable.html#Ext-util-Positionable-method-translateXY' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Positionable-method-translateXY' class='name expandable'>translateXY</a>( <span class='pre'>x, [y]</span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><strong class='private signature' >private</strong></div><div class='description'><div class='short'>Translates the passed page coordinates into x and y css values for the element ...</div><div class='long'><p>Translates the passed page coordinates into x and y css values for the element</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>x</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a><div class='sub-desc'><p>The page x or an array containing [x, y]</p>\n</div></li><li><span class='pre'>y</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a> (optional)<div class='sub-desc'><p>The page y, required if x is not an array</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>An object with x and y properties. e.g.\n{x: (value), y: (value)}</p>\n</div></li></ul></div></div></div><div id='method-un' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Observable' rel='Ext.util.Observable' class='defined-in docClass'>Ext.util.Observable</a><br/><a href='source/Observable.html#Ext-util-Observable-method-un' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Observable-method-un' class='name expandable'>un</a>( <span class='pre'>eventName, fn, [scope]</span> )</div><div class='description'><div class='short'>Shorthand for removeListener. ...</div><div class='long'><p>Shorthand for <a href=\"#!/api/Ext.util.Observable-method-removeListener\" rel=\"Ext.util.Observable-method-removeListener\" class=\"docClass\">removeListener</a>.</p>\n\n<p>Removes an event handler.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>eventName</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The type of event the handler was associated with.</p>\n\n</div></li><li><span class='pre'>fn</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a><div class='sub-desc'><p>The handler to remove. <strong>This must be a reference to the function passed into the\n<a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">addListener</a> call.</strong></p>\n\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>The scope originally specified for the handler. It must be the same as the\nscope argument specified in the original call to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">addListener</a> or the listener will not be removed.</p>\n\n</div></li></ul></div></div></div><div id='method-unitizeBox' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-unitizeBox' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-unitizeBox' class='name expandable'>unitizeBox</a>( <span class='pre'>box</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Overridden in Ext.rtl.AbstractComponent. ...</div><div class='long'><p><strong>Overridden in Ext.rtl.AbstractComponent.</strong></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>box</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-unmask' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-unmask' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-unmask' class='name expandable'>unmask</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-unregisterFloatingItem' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-unregisterFloatingItem' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-unregisterFloatingItem' class='name expandable'>unregisterFloatingItem</a>( <span class='pre'>cmp</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>cmp</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='method-up' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-up' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-up' class='name expandable'>up</a>( <span class='pre'>[selector], [limit]</span> ) : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a></div><div class='description'><div class='short'>Navigates up the ownership hierarchy searching for an ancestor Container which matches any passed simple selector or ...</div><div class='long'><p>Navigates up the ownership hierarchy searching for an ancestor Container which matches any passed simple selector or component.</p>\n\n<p><em>Important.</em> There is not a universal upwards navigation pointer. There are several upwards relationships\nsuch as the <a href=\"#!/api/Ext.button.Button\" rel=\"Ext.button.Button\" class=\"docClass\">button</a> which activates a <a href=\"#!/api/Ext.button.Button-cfg-menu\" rel=\"Ext.button.Button-cfg-menu\" class=\"docClass\">menu</a>, or the\n<a href=\"#!/api/Ext.menu.Item\" rel=\"Ext.menu.Item\" class=\"docClass\">menu item</a> which activated a <a href=\"#!/api/Ext.menu.Item-cfg-menu\" rel=\"Ext.menu.Item-cfg-menu\" class=\"docClass\">submenu</a>, or the\n<a href=\"#!/api/Ext.grid.column.Column\" rel=\"Ext.grid.column.Column\" class=\"docClass\">column header</a> which activated the column menu.</p>\n\n<p>These differences are abstracted away by this method.</p>\n\n<p>Example:</p>\n\n<pre><code>var owningTabPanel = grid.up('tabpanel');\n</code></pre>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>selector</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> (optional)<div class='sub-desc'><p>The simple selector component or actual component to test. If not passed the immediate owner/activater is returned.</p>\n</div></li><li><span class='pre'>limit</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a>/<a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a> (optional)<div class='sub-desc'><p>This may be a selector upon which to stop the upward scan, or a limit of teh number of steps, or Component reference to stop on.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a></span><div class='sub-desc'><p>The matching ancestor Container (or <code>undefined</code> if no match was found).</p>\n</div></li></ul></div></div></div><div id='method-update' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-update' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-update' class='name expandable'>update</a>( <span class='pre'>htmlOrData, [loadScripts], [callback]</span> )</div><div class='description'><div class='short'>Update the content area of a component. ...</div><div class='long'><p>Update the content area of a component.</p>\n <p>Available since: <b>3.4.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>htmlOrData</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>If this component has been configured with a template via the tpl config then\nit will use this argument as data to populate the template. If this component was not configured with a template,\nthe components content area will be updated via <a href=\"#!/api/Ext.dom.Element\" rel=\"Ext.dom.Element\" class=\"docClass\">Ext.Element</a> update.</p>\n</div></li><li><span class='pre'>loadScripts</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a> (optional)<div class='sub-desc'><p>Only legitimate when using the <code>html</code> configuration.</p>\n<p>Defaults to: <code>false</code></p></div></li><li><span class='pre'>callback</span> : <a href=\"#!/api/Function\" rel=\"Function\" class=\"docClass\">Function</a> (optional)<div class='sub-desc'><p>Only legitimate when using the <code>html</code> configuration. Callback to execute when\nscripts have finished loading.</p>\n</div></li></ul></div></div></div><div id='method-updateAria' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-updateAria' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-updateAria' class='name expandable'>updateAria</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'>Injected as an override by Ext.Aria.initialize ...</div><div class='long'><p>Injected as an override by Ext.Aria.initialize</p>\n</div></div></div><div id='method-updateBox' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-updateBox' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-updateBox' class='name expandable'>updateBox</a>( <span class='pre'>box</span> ) : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><strong class='chainable signature' >chainable</strong></div><div class='description'><div class='short'>Sets the current box measurements of the component's underlying element. ...</div><div class='long'><p>Sets the current box measurements of the component's underlying element.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>box</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>An object in the format {x, y, width, height}</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='method-updateFrame' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.util.Renderable' rel='Ext.util.Renderable' class='defined-in docClass'>Ext.util.Renderable</a><br/><a href='source/Renderable2.html#Ext-util-Renderable-method-updateFrame' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.util.Renderable-method-updateFrame' class='name expandable'>updateFrame</a>( <span class='pre'></span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div><div id='method-updateLayout' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-method-updateLayout' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-method-updateLayout' class='name expandable'>updateLayout</a>( <span class='pre'>[options]</span> )</div><div class='description'><div class='short'>Updates this component's layout. ...</div><div class='long'><p>Updates this component's layout. If this update affects this components <a href=\"#!/api/Ext.AbstractComponent-property-ownerCt\" rel=\"Ext.AbstractComponent-property-ownerCt\" class=\"docClass\">ownerCt</a>,\nthat component's <code>updateLayout</code> method will be called to perform the layout instead.\nOtherwise, just this component (and its child items) will layout.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>options</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a> (optional)<div class='sub-desc'><p>An object with layout options.</p>\n<ul><li><span class='pre'>defer</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p><code>true</code> if this layout should be deferred.</p>\n</div></li><li><span class='pre'>isRoot</span> : <a href=\"#!/api/Boolean\" rel=\"Boolean\" class=\"docClass\">Boolean</a><div class='sub-desc'><p><code>true</code> if this layout should be the root of the layout.</p>\n</div></li></ul></div></li></ul></div></div></div><div id='method-wrapPrimaryEl' class='member not-inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><span class='defined-in' rel='Ext.Component'>Ext.Component</span><br/><a href='source/Component5.html#Ext-Component-method-wrapPrimaryEl' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Component-method-wrapPrimaryEl' class='name expandable'>wrapPrimaryEl</a>( <span class='pre'>dom</span> )<strong class='private signature' >private</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>dom</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul><p>Overrides: <a href='#!/api/Ext.util.Renderable-method-wrapPrimaryEl' rel='Ext.util.Renderable-method-wrapPrimaryEl' class='docClass'>Ext.util.Renderable.wrapPrimaryEl</a></p></div></div></div></div><div class='subsection'><div class='definedBy'>Defined By</div><h4 class='members-subtitle'>Static Methods</h3><div id='static-method-addConfig' class='member first-child inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-addConfig' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-addConfig' class='name expandable'>addConfig</a>( <span class='pre'>config</span> )<strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>config</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='static-method-addInheritableStatics' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-addInheritableStatics' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-addInheritableStatics' class='name expandable'>addInheritableStatics</a>( <span class='pre'>members</span> )<strong class='chainable signature' >chainable</strong><strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>members</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='static-method-addMember' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-addMember' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-addMember' class='name expandable'>addMember</a>( <span class='pre'>name, member</span> )<strong class='chainable signature' >chainable</strong><strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>name</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>member</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='static-method-addMembers' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-addMembers' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-addMembers' class='name expandable'>addMembers</a>( <span class='pre'>members</span> )<strong class='chainable signature' >chainable</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'>Add methods / properties to the prototype of this class. ...</div><div class='long'><p>Add methods / properties to the prototype of this class.</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.awesome.Cat', {\n constructor: function() {\n ...\n }\n});\n\n My.awesome.Cat.addMembers({\n meow: function() {\n alert('Meowww...');\n }\n });\n\n var kitty = new My.awesome.Cat;\n kitty.meow();\n</code></pre>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>members</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='static-method-addStatics' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-addStatics' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-addStatics' class='name expandable'>addStatics</a>( <span class='pre'>members</span> ) : <a href=\"#!/api/Ext.Base\" rel=\"Ext.Base\" class=\"docClass\">Ext.Base</a><strong class='chainable signature' >chainable</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'>Add / override static properties of this class. ...</div><div class='long'><p>Add / override static properties of this class.</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.cool.Class', {\n ...\n});\n\nMy.cool.Class.addStatics({\n someProperty: 'someValue', // My.cool.Class.someProperty = 'someValue'\n method1: function() { ... }, // My.cool.Class.method1 = function() { ... };\n method2: function() { ... } // My.cool.Class.method2 = function() { ... };\n});\n</code></pre>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>members</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Base\" rel=\"Ext.Base\" class=\"docClass\">Ext.Base</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='static-method-addXtype' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-addXtype' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-addXtype' class='name expandable'>addXtype</a>( <span class='pre'>xtype</span> )<strong class='chainable signature' >chainable</strong><strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>xtype</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='static-method-borrow' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-borrow' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-borrow' class='name expandable'>borrow</a>( <span class='pre'>fromClass, members</span> ) : <a href=\"#!/api/Ext.Base\" rel=\"Ext.Base\" class=\"docClass\">Ext.Base</a><strong class='chainable signature' >chainable</strong><strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'>Borrow another class' members to the prototype of this class. ...</div><div class='long'><p>Borrow another class' members to the prototype of this class.</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('Bank', {\n money: '$$$',\n printMoney: function() {\n alert('$$$$$$$');\n }\n});\n\n<a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('Thief', {\n ...\n});\n\nThief.borrow(Bank, ['money', 'printMoney']);\n\nvar steve = new Thief();\n\nalert(steve.money); // alerts '$$$'\nsteve.printMoney(); // alerts '$$$$$$$'\n</code></pre>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>fromClass</span> : <a href=\"#!/api/Ext.Base\" rel=\"Ext.Base\" class=\"docClass\">Ext.Base</a><div class='sub-desc'><p>The class to borrow members from</p>\n</div></li><li><span class='pre'>members</span> : <a href=\"#!/api/Array\" rel=\"Array\" class=\"docClass\">Array</a>/<a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><div class='sub-desc'><p>The names of the members to borrow</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Base\" rel=\"Ext.Base\" class=\"docClass\">Ext.Base</a></span><div class='sub-desc'><p>this</p>\n</div></li></ul></div></div></div><div id='static-method-create' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-create' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-create' class='name expandable'>create</a>( <span class='pre'></span> ) : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><strong class='static signature' >static</strong></div><div class='description'><div class='short'>Create a new instance of this Class. ...</div><div class='long'><p>Create a new instance of this Class.</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.cool.Class', {\n ...\n});\n\nMy.cool.Class.create({\n someConfig: true\n});\n</code></pre>\n\n<p>All parameters are passed to the constructor of the class.</p>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a></span><div class='sub-desc'><p>the created instance.</p>\n</div></li></ul></div></div></div><div id='static-method-createAlias' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-createAlias' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-createAlias' class='name expandable'>createAlias</a>( <span class='pre'>alias, origin</span> )<strong class='static signature' >static</strong></div><div class='description'><div class='short'>Create aliases for existing prototype methods. ...</div><div class='long'><p>Create aliases for existing prototype methods. Example:</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.cool.Class', {\n method1: function() { ... },\n method2: function() { ... }\n});\n\nvar test = new My.cool.Class();\n\nMy.cool.Class.createAlias({\n method3: 'method1',\n method4: 'method2'\n});\n\ntest.method3(); // test.method1()\n\nMy.cool.Class.createAlias('method5', 'method3');\n\ntest.method5(); // test.method3() -&gt; test.method1()\n</code></pre>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>alias</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The new method name, or an object to set multiple aliases. See\n<a href=\"#!/api/Ext.Function-method-flexSetter\" rel=\"Ext.Function-method-flexSetter\" class=\"docClass\">flexSetter</a></p>\n</div></li><li><span class='pre'>origin</span> : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a>/<a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The original method name</p>\n</div></li></ul></div></div></div><div id='static-method-extend' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-extend' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-extend' class='name expandable'>extend</a>( <span class='pre'>config</span> )<strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>config</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='static-method-getName' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-getName' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-getName' class='name expandable'>getName</a>( <span class='pre'></span> ) : <a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a><strong class='static signature' >static</strong></div><div class='description'><div class='short'>Get the current class' name in string format. ...</div><div class='long'><p>Get the current class' name in string format.</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.cool.Class', {\n constructor: function() {\n alert(this.self.getName()); // alerts 'My.cool.Class'\n }\n});\n\nMy.cool.Class.getName(); // 'My.cool.Class'\n</code></pre>\n<h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/String\" rel=\"String\" class=\"docClass\">String</a></span><div class='sub-desc'><p>className</p>\n</div></li></ul></div></div></div><div id='static-method-implement' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-implement' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-implement' class='name expandable'>implement</a>( <span class='pre'></span> )<strong class='deprecated signature' >deprecated</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'>Adds members to class. ...</div><div class='long'><p>Adds members to class.</p>\n <div class='signature-box deprecated'>\n <p>This method has been <strong>deprecated</strong> since 4.1</p>\n <p>Use <a href=\"#!/api/Ext.Base-static-method-addMembers\" rel=\"Ext.Base-static-method-addMembers\" class=\"docClass\">addMembers</a> instead.</p>\n\n </div>\n</div></div></div><div id='static-method-mixin' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-mixin' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-mixin' class='name expandable'>mixin</a>( <span class='pre'>name, mixinClass</span> )<strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'>Used internally by the mixins pre-processor ...</div><div class='long'><p>Used internally by the mixins pre-processor</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>name</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>mixinClass</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='static-method-onExtended' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-onExtended' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-onExtended' class='name expandable'>onExtended</a>( <span class='pre'>fn, scope</span> )<strong class='chainable signature' >chainable</strong><strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>fn</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li><li><span class='pre'>scope</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'>\n</div></li></ul></div></div></div><div id='static-method-override' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-override' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-override' class='name expandable'>override</a>( <span class='pre'>members</span> ) : <a href=\"#!/api/Ext.Base\" rel=\"Ext.Base\" class=\"docClass\">Ext.Base</a><strong class='chainable signature' >chainable</strong><strong class='deprecated signature' >deprecated</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'>Override members of this class. ...</div><div class='long'><p>Override members of this class. Overridden methods can be invoked via\n<a href=\"#!/api/Ext.Base-method-callParent\" rel=\"Ext.Base-method-callParent\" class=\"docClass\">callParent</a>.</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.Cat', {\n constructor: function() {\n alert(\"I'm a cat!\");\n }\n});\n\nMy.Cat.override({\n constructor: function() {\n alert(\"I'm going to be a cat!\");\n\n this.callParent(arguments);\n\n alert(\"Meeeeoooowwww\");\n }\n});\n\nvar kitty = new My.Cat(); // alerts \"I'm going to be a cat!\"\n // alerts \"I'm a cat!\"\n // alerts \"Meeeeoooowwww\"\n</code></pre>\n\n<p>As of 4.1, direct use of this method is deprecated. Use <a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>\ninstead:</p>\n\n<pre><code><a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a>('My.CatOverride', {\n override: 'My.Cat',\n constructor: function() {\n alert(\"I'm going to be a cat!\");\n\n this.callParent(arguments);\n\n alert(\"Meeeeoooowwww\");\n }\n});\n</code></pre>\n\n<p>The above accomplishes the same result but can be managed by the <a href=\"#!/api/Ext.Loader\" rel=\"Ext.Loader\" class=\"docClass\">Ext.Loader</a>\nwhich can properly order the override and its target class and the build process\ncan determine whether the override is needed based on the required state of the\ntarget class (My.Cat).</p>\n <div class='signature-box deprecated'>\n <p>This method has been <strong>deprecated</strong> since 4.1.0</p>\n <p>Use <a href=\"#!/api/Ext-method-define\" rel=\"Ext-method-define\" class=\"docClass\">Ext.define</a> instead</p>\n\n </div>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>members</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The properties to add to this class. This should be\nspecified as an object literal containing one or more properties.</p>\n</div></li></ul><h3 class='pa'>Returns</h3><ul><li><span class='pre'><a href=\"#!/api/Ext.Base\" rel=\"Ext.Base\" class=\"docClass\">Ext.Base</a></span><div class='sub-desc'><p>this class</p>\n</div></li></ul></div></div></div><div id='static-method-triggerExtended' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.Base' rel='Ext.Base' class='defined-in docClass'>Ext.Base</a><br/><a href='source/Base.html#Ext-Base-static-method-triggerExtended' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.Base-static-method-triggerExtended' class='name expandable'>triggerExtended</a>( <span class='pre'></span> )<strong class='private signature' >private</strong><strong class='static signature' >static</strong></div><div class='description'><div class='short'> ...</div><div class='long'>\n</div></div></div></div></div><div class='members-section'><div class='definedBy'>Defined By</div><h3 class='members-title icon-event'>Events</h3><div class='subsection'><div id='event-activate' class='member first-child inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-activate' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-activate' class='name expandable'>activate</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires after a Component has been visually activated. ...</div><div class='long'><p>Fires after a Component has been visually activated.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-added' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-added' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-added' class='name expandable'>added</a>( <span class='pre'>this, container, pos, eOpts</span> )</div><div class='description'><div class='short'>Fires after a Component had been added to a Container. ...</div><div class='long'><p>Fires after a Component had been added to a Container.</p>\n <p>Available since: <b>3.4.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>container</span> : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a><div class='sub-desc'><p>Parent Container</p>\n</div></li><li><span class='pre'>pos</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>position of Component</p>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-afterrender' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-afterrender' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-afterrender' class='name expandable'>afterrender</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires after the component rendering is finished. ...</div><div class='long'><p>Fires after the component rendering is finished.</p>\n\n<p>The <code>afterrender</code> event is fired after this Component has been <a href=\"#!/api/Ext.AbstractComponent-property-rendered\" rel=\"Ext.AbstractComponent-property-rendered\" class=\"docClass\">rendered</a>, been postprocessed by any\n<code>afterRender</code> method defined for the Component.</p>\n <p>Available since: <b>3.4.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-beforeactivate' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-beforeactivate' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-beforeactivate' class='name expandable'>beforeactivate</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires before a Component has been visually activated. ...</div><div class='long'><p>Fires before a Component has been visually activated. Returning <code>false</code> from an event listener can prevent\nthe activate from occurring.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-beforedeactivate' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-beforedeactivate' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-beforedeactivate' class='name expandable'>beforedeactivate</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires before a Component has been visually deactivated. ...</div><div class='long'><p>Fires before a Component has been visually deactivated. Returning <code>false</code> from an event listener can\nprevent the deactivate from occurring.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-beforedestroy' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-beforedestroy' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-beforedestroy' class='name expandable'>beforedestroy</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires before the component is destroyed. ...</div><div class='long'><p>Fires before the component is <a href=\"#!/api/Ext.AbstractComponent-method-destroy\" rel=\"Ext.AbstractComponent-method-destroy\" class=\"docClass\">destroy</a>ed. Return <code>false</code> from an event handler to stop the\n<a href=\"#!/api/Ext.AbstractComponent-method-destroy\" rel=\"Ext.AbstractComponent-method-destroy\" class=\"docClass\">destroy</a>.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-beforehide' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-beforehide' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-beforehide' class='name expandable'>beforehide</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires before the component is hidden when calling the hide method. ...</div><div class='long'><p>Fires before the component is hidden when calling the <a href=\"#!/api/Ext.Component-method-hide\" rel=\"Ext.Component-method-hide\" class=\"docClass\">hide</a> method. Return <code>false</code> from an event\nhandler to stop the hide.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-beforerender' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-beforerender' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-beforerender' class='name expandable'>beforerender</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires before the component is rendered. ...</div><div class='long'><p>Fires before the component is <a href=\"#!/api/Ext.AbstractComponent-property-rendered\" rel=\"Ext.AbstractComponent-property-rendered\" class=\"docClass\">rendered</a>. Return <code>false</code> from an event handler to stop the\n<a href=\"#!/api/Ext.AbstractComponent-method-render\" rel=\"Ext.AbstractComponent-method-render\" class=\"docClass\">render</a>.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-beforeshow' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-beforeshow' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-beforeshow' class='name expandable'>beforeshow</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires before the component is shown when calling the show method. ...</div><div class='long'><p>Fires before the component is shown when calling the <a href=\"#!/api/Ext.Component-method-show\" rel=\"Ext.Component-method-show\" class=\"docClass\">show</a> method. Return <code>false</code> from an event\nhandler to stop the show.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-beforestaterestore' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-event-beforestaterestore' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-event-beforestaterestore' class='name expandable'>beforestaterestore</a>( <span class='pre'>this, state, eOpts</span> )</div><div class='description'><div class='short'>Fires before the state of the object is restored. ...</div><div class='long'><p>Fires before the state of the object is restored. Return false from an event handler to stop the restore.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.state.Stateful\" rel=\"Ext.state.Stateful\" class=\"docClass\">Ext.state.Stateful</a><div class='sub-desc'>\n</div></li><li><span class='pre'>state</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The hash of state values returned from the StateProvider. If this\nevent is not vetoed, then the state object is passed to <b><tt>applyState</tt></b>. By default,\nthat simply copies property values into this object. The method maybe overriden to\nprovide custom state restoration.</p>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-beforestatesave' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-event-beforestatesave' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-event-beforestatesave' class='name expandable'>beforestatesave</a>( <span class='pre'>this, state, eOpts</span> )</div><div class='description'><div class='short'>Fires before the state of the object is saved to the configured state provider. ...</div><div class='long'><p>Fires before the state of the object is saved to the configured state provider. Return false to stop the save.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.state.Stateful\" rel=\"Ext.state.Stateful\" class=\"docClass\">Ext.state.Stateful</a><div class='sub-desc'>\n</div></li><li><span class='pre'>state</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The hash of state values. This is determined by calling\n<b><tt>getState()</tt></b> on the object. This method must be provided by the\ndeveloper to return whetever representation of state is required, by default, <a href=\"#!/api/Ext.state.Stateful\" rel=\"Ext.state.Stateful\" class=\"docClass\">Ext.state.Stateful</a>\nhas a null implementation.</p>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-blur' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-blur' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-blur' class='name expandable'>blur</a>( <span class='pre'>this, The, eOpts</span> )</div><div class='description'><div class='short'>Fires when this Component loses focus. ...</div><div class='long'><p>Fires when this Component loses focus.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>The</span> : <a href=\"#!/api/Ext.EventObject\" rel=\"Ext.EventObject\" class=\"docClass\">Ext.EventObject</a><div class='sub-desc'><p>blur event.</p>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-boxready' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-boxready' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-boxready' class='name expandable'>boxready</a>( <span class='pre'>this, width, height, eOpts</span> )</div><div class='description'><div class='short'>Fires one time - after the component has been laid out for the first time at its initial size. ...</div><div class='long'><p>Fires <em>one time</em> - after the component has been laid out for the first time at its initial size.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>width</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The initial width.</p>\n</div></li><li><span class='pre'>height</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The initial height.</p>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-deactivate' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-deactivate' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-deactivate' class='name expandable'>deactivate</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires after a Component has been visually deactivated. ...</div><div class='long'><p>Fires after a Component has been visually deactivated.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-destroy' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-destroy' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-destroy' class='name expandable'>destroy</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires after the component is destroyed. ...</div><div class='long'><p>Fires after the component is <a href=\"#!/api/Ext.AbstractComponent-method-destroy\" rel=\"Ext.AbstractComponent-method-destroy\" class=\"docClass\">destroy</a>ed.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-disable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-disable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-disable' class='name expandable'>disable</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires after the component is disabled. ...</div><div class='long'><p>Fires after the component is disabled.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-enable' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-enable' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-enable' class='name expandable'>enable</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires after the component is enabled. ...</div><div class='long'><p>Fires after the component is enabled.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-focus' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-focus' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-focus' class='name expandable'>focus</a>( <span class='pre'>this, The, eOpts</span> )</div><div class='description'><div class='short'>Fires when this Component receives focus. ...</div><div class='long'><p>Fires when this Component receives focus.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>The</span> : <a href=\"#!/api/Ext.EventObject\" rel=\"Ext.EventObject\" class=\"docClass\">Ext.EventObject</a><div class='sub-desc'><p>focus event.</p>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-hide' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-hide' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-hide' class='name expandable'>hide</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires after the component is hidden. ...</div><div class='long'><p>Fires after the component is hidden. Fires after the component is hidden when calling the <a href=\"#!/api/Ext.Component-method-hide\" rel=\"Ext.Component-method-hide\" class=\"docClass\">hide</a>\nmethod.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-move' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-move' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-move' class='name expandable'>move</a>( <span class='pre'>this, x, y, eOpts</span> )</div><div class='description'><div class='short'>Fires after the component is moved. ...</div><div class='long'><p>Fires after the component is moved.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>x</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The new x position.</p>\n</div></li><li><span class='pre'>y</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The new y position.</p>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-removed' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-removed' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-removed' class='name expandable'>removed</a>( <span class='pre'>this, ownerCt, eOpts</span> )</div><div class='description'><div class='short'>Fires when a component is removed from an Ext.container.Container ...</div><div class='long'><p>Fires when a component is removed from an <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a></p>\n <p>Available since: <b>3.4.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>ownerCt</span> : <a href=\"#!/api/Ext.container.Container\" rel=\"Ext.container.Container\" class=\"docClass\">Ext.container.Container</a><div class='sub-desc'><p>Container which holds the component</p>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-render' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-render' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-render' class='name expandable'>render</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires after the component markup is rendered. ...</div><div class='long'><p>Fires after the component markup is <a href=\"#!/api/Ext.AbstractComponent-property-rendered\" rel=\"Ext.AbstractComponent-property-rendered\" class=\"docClass\">rendered</a>.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-resize' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-resize' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-resize' class='name expandable'>resize</a>( <span class='pre'>this, width, height, oldWidth, oldHeight, eOpts</span> )</div><div class='description'><div class='short'>Fires after the component is resized. ...</div><div class='long'><p>Fires after the component is resized. Note that this does <em>not</em> fire when the component is first laid out at its initial\nsize. To hook that point in the life cycle, use the <a href=\"#!/api/Ext.AbstractComponent-event-boxready\" rel=\"Ext.AbstractComponent-event-boxready\" class=\"docClass\">boxready</a> event.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>width</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The new width that was set.</p>\n</div></li><li><span class='pre'>height</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The new height that was set.</p>\n</div></li><li><span class='pre'>oldWidth</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The previous width.</p>\n</div></li><li><span class='pre'>oldHeight</span> : <a href=\"#!/api/Number\" rel=\"Number\" class=\"docClass\">Number</a><div class='sub-desc'><p>The previous height.</p>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-show' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.AbstractComponent' rel='Ext.AbstractComponent' class='defined-in docClass'>Ext.AbstractComponent</a><br/><a href='source/AbstractComponent.html#Ext-AbstractComponent-event-show' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.AbstractComponent-event-show' class='name expandable'>show</a>( <span class='pre'>this, eOpts</span> )</div><div class='description'><div class='short'>Fires after the component is shown when calling the show method. ...</div><div class='long'><p>Fires after the component is shown when calling the <a href=\"#!/api/Ext.Component-method-show\" rel=\"Ext.Component-method-show\" class=\"docClass\">show</a> method.</p>\n <p>Available since: <b>1.1.0</b></p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.Component\" rel=\"Ext.Component\" class=\"docClass\">Ext.Component</a><div class='sub-desc'>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-staterestore' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-event-staterestore' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-event-staterestore' class='name expandable'>staterestore</a>( <span class='pre'>this, state, eOpts</span> )</div><div class='description'><div class='short'>Fires after the state of the object is restored. ...</div><div class='long'><p>Fires after the state of the object is restored.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.state.Stateful\" rel=\"Ext.state.Stateful\" class=\"docClass\">Ext.state.Stateful</a><div class='sub-desc'>\n</div></li><li><span class='pre'>state</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The hash of state values returned from the StateProvider. This is passed\nto <b><tt>applyState</tt></b>. By default, that simply copies property values into this\nobject. The method maybe overriden to provide custom state restoration.</p>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div><div id='event-statesave' class='member inherited'><a href='#' class='side expandable'><span>&nbsp;</span></a><div class='title'><div class='meta'><a href='#!/api/Ext.state.Stateful' rel='Ext.state.Stateful' class='defined-in docClass'>Ext.state.Stateful</a><br/><a href='source/Stateful.html#Ext-state-Stateful-event-statesave' target='_blank' class='view-source'>view source</a></div><a href='#!/api/Ext.state.Stateful-event-statesave' class='name expandable'>statesave</a>( <span class='pre'>this, state, eOpts</span> )</div><div class='description'><div class='short'>Fires after the state of the object is saved to the configured state provider. ...</div><div class='long'><p>Fires after the state of the object is saved to the configured state provider.</p>\n<h3 class=\"pa\">Parameters</h3><ul><li><span class='pre'>this</span> : <a href=\"#!/api/Ext.state.Stateful\" rel=\"Ext.state.Stateful\" class=\"docClass\">Ext.state.Stateful</a><div class='sub-desc'>\n</div></li><li><span class='pre'>state</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The hash of state values. This is determined by calling\n<b><tt>getState()</tt></b> on the object. This method must be provided by the\ndeveloper to return whetever representation of state is required, by default, <a href=\"#!/api/Ext.state.Stateful\" rel=\"Ext.state.Stateful\" class=\"docClass\">Ext.state.Stateful</a>\nhas a null implementation.</p>\n</div></li><li><span class='pre'>eOpts</span> : <a href=\"#!/api/Object\" rel=\"Object\" class=\"docClass\">Object</a><div class='sub-desc'><p>The options object passed to <a href=\"#!/api/Ext.util.Observable-method-addListener\" rel=\"Ext.util.Observable-method-addListener\" class=\"docClass\">Ext.util.Observable.addListener</a>.</p>\n\n\n\n</div></li></ul></div></div></div></div></div></div></div>","superclasses":["Ext.Base","Ext.AbstractComponent"],"meta":{},"code_type":"ext_define","requires":[],"html_meta":{},"statics":{"property":[{"tagname":"property","owner":"Ext.Base","meta":{"static":true,"private":true},"name":"$onExtended","id":"static-property-S-onExtended"},{"tagname":"property","owner":"Ext.Component","meta":{"static":true,"private":true},"name":"DIRECTION_BOTTOM","id":"property-DIRECTION_BOTTOM"},{"tagname":"property","owner":"Ext.Component","meta":{"static":true,"private":true},"name":"DIRECTION_LEFT","id":"property-DIRECTION_LEFT"},{"tagname":"property","owner":"Ext.Component","meta":{"static":true,"private":true},"name":"DIRECTION_RIGHT","id":"property-DIRECTION_RIGHT"},{"tagname":"property","owner":"Ext.Component","meta":{"static":true,"private":true},"name":"DIRECTION_TOP","id":"property-DIRECTION_TOP"},{"tagname":"property","owner":"Ext.Component","meta":{"static":true,"private":true},"name":"INVALID_ID_CHARS_Re","id":"property-INVALID_ID_CHARS_Re"},{"tagname":"property","owner":"Ext.Component","meta":{"static":true,"private":true},"name":"VERTICAL_DIRECTION_Re","id":"property-VERTICAL_DIRECTION_Re"}],"cfg":[],"css_var":[],"method":[{"tagname":"method","owner":"Ext.Base","meta":{"static":true,"private":true},"name":"addConfig","id":"static-method-addConfig"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true,"chainable":true,"private":true},"name":"addInheritableStatics","id":"static-method-addInheritableStatics"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true,"chainable":true,"private":true},"name":"addMember","id":"static-method-addMember"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true,"chainable":true},"name":"addMembers","id":"static-method-addMembers"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true,"chainable":true},"name":"addStatics","id":"static-method-addStatics"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true,"chainable":true,"private":true},"name":"addXtype","id":"static-method-addXtype"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true,"chainable":true,"private":true},"name":"borrow","id":"static-method-borrow"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true},"name":"create","id":"static-method-create"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true},"name":"createAlias","id":"static-method-createAlias"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true,"private":true},"name":"extend","id":"static-method-extend"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true},"name":"getName","id":"static-method-getName"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true,"deprecated":{"text":"Use {@link #addMembers} instead.","version":"4.1"}},"name":"implement","id":"static-method-implement"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true,"private":true},"name":"mixin","id":"static-method-mixin"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true,"chainable":true,"private":true},"name":"onExtended","id":"static-method-onExtended"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true,"chainable":true,"markdown":true,"deprecated":{"text":"Use {@link Ext#define Ext.define} instead","version":"4.1.0"}},"name":"override","id":"static-method-override"},{"tagname":"method","owner":"Ext.Base","meta":{"static":true,"private":true},"name":"triggerExtended","id":"static-method-triggerExtended"}],"event":[],"css_mixin":[]},"files":[{"href":"Component5.html#Ext-Component","filename":"Component.js"},{"href":"Region2.html#Ext-layout-container-border-Region","filename":"Region.js"}],"linenr":1,"members":{"property":[{"tagname":"property","owner":"Ext.Base","meta":{"private":true},"name":"$className","id":"property-S-className"},{"tagname":"property","owner":"Ext.util.Positionable","meta":{"private":true},"name":"_alignRe","id":"property-_alignRe"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"protected":true},"name":"_isLayoutRoot","id":"property-_isLayoutRoot"},{"tagname":"property","owner":"Ext.util.Positionable","meta":{"private":true},"name":"_positionTopLeft","id":"property-_positionTopLeft"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"allowDomMove","id":"property-allowDomMove"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"autoGenId","id":"property-autoGenId"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"borderBoxCls","id":"property-borderBoxCls"},{"tagname":"property","owner":"Ext.Component","meta":{"private":true},"name":"bubbleEvents","id":"property-bubbleEvents"},{"tagname":"property","owner":"Ext.util.ElementContainer","meta":{"private":true},"name":"childEls","id":"property-childEls"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"componentLayoutCounter","id":"property-componentLayoutCounter"},{"tagname":"property","owner":"Ext.Base","meta":{"private":true},"name":"configMap","id":"property-configMap"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{},"name":"contentPaddingProperty","id":"property-contentPaddingProperty"},{"tagname":"property","owner":"Ext.util.Positionable","meta":{"private":true},"name":"convertPositionSpec","id":"property-convertPositionSpec"},{"tagname":"property","owner":"Ext.Component","meta":{"private":true},"name":"defaultComponentLayoutType","id":"property-defaultComponentLayoutType"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"deferLayouts","id":"property-deferLayouts"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"readonly":true},"name":"draggable","id":"property-draggable"},{"tagname":"property","owner":"Ext.util.Observable","meta":{"private":true},"name":"eventsSuspended","id":"property-eventsSuspended"},{"tagname":"property","owner":"Ext.Component","meta":{"readonly":true},"name":"floatParent","id":"property-floatParent"},{"tagname":"property","owner":"Ext.util.Renderable","meta":{"private":true},"name":"frameCls","id":"property-frameCls"},{"tagname":"property","owner":"Ext.util.Renderable","meta":{"private":true},"name":"frameElNames","id":"property-frameElNames"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"frameElementsArray","id":"property-frameElementsArray"},{"tagname":"property","owner":"Ext.util.Renderable","meta":{"private":true},"name":"frameIdRegex","id":"property-frameIdRegex"},{"tagname":"property","owner":"Ext.util.Renderable","meta":{"private":true},"name":"frameInfoCache","id":"property-frameInfoCache"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"readonly":true},"name":"frameSize","id":"property-frameSize"},{"tagname":"property","owner":"Ext.util.Renderable","meta":{"private":true},"name":"frameTableTpl","id":"property-frameTableTpl"},{"tagname":"property","owner":"Ext.util.Renderable","meta":{"private":true},"name":"frameTpl","id":"property-frameTpl"},{"tagname":"property","owner":"Ext.util.Observable","meta":{"readonly":true},"name":"hasListeners","id":"property-hasListeners"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"horizontalPosProp","id":"property-horizontalPosProp"},{"tagname":"property","owner":"Ext.Base","meta":{"private":true},"name":"initConfigList","id":"property-initConfigList"},{"tagname":"property","owner":"Ext.Base","meta":{"private":true},"name":"initConfigMap","id":"property-initConfigMap"},{"tagname":"property","owner":"Ext.util.Animate","meta":{"private":true},"name":"isAnimate","id":"property-isAnimate"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{},"name":"isComponent","id":"property-isComponent"},{"tagname":"property","owner":"Ext.Base","meta":{"private":true},"name":"isInstance","id":"property-isInstance"},{"tagname":"property","owner":"Ext.util.Observable","meta":{},"name":"isObservable","id":"property-isObservable"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"layoutSuspendCount","id":"property-layoutSuspendCount"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{},"name":"maskOnDisable","id":"property-maskOnDisable"},{"tagname":"property","owner":"Ext.Component","meta":{"private":true},"name":"offsetsCls","id":"property-offsetsCls"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"since":"2.3.0","readonly":true},"name":"ownerCt","id":"property-ownerCt"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0","readonly":true},"name":"rendered","id":"property-rendered"},{"tagname":"property","owner":"Ext.Component","meta":{"readonly":true},"name":"scrollFlags","id":"property-scrollFlags"},{"tagname":"property","owner":"Ext.Base","meta":{"protected":true},"name":"self","id":"property-self"},{"tagname":"property","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"weight","id":"property-weight"},{"tagname":"property","owner":"Ext.Component","meta":{"readonly":true},"name":"zIndexManager","id":"property-zIndexManager"},{"tagname":"property","owner":"Ext.Component","meta":{"readonly":true},"name":"zIndexParent","id":"property-zIndexParent"}],"cfg":[{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"2.3.0"},"name":"autoEl","id":"cfg-autoEl"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"deprecated":{"text":"Use {@link #loader} config instead.","version":"4.1.1"}},"name":"autoLoad","id":"cfg-autoLoad"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"autoRender","id":"cfg-autoRender"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"autoScroll","id":"cfg-autoScroll"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"2.3.0"},"name":"autoShow","id":"cfg-autoShow"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"baseCls","id":"cfg-baseCls"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"border","id":"cfg-border"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"childEls","id":"cfg-childEls"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"cls","id":"cfg-cls"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"columnWidth","id":"cfg-columnWidth"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"componentCls","id":"cfg-componentCls"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"componentLayout","id":"cfg-componentLayout"},{"tagname":"cfg","owner":"Ext.util.Floating","meta":{},"name":"constrain","id":"cfg-constrain"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"constrainTo","id":"cfg-constrainTo"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"constraintInsets","id":"cfg-constraintInsets"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"3.4.0"},"name":"contentEl","id":"cfg-contentEl"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"3.4.0"},"name":"data","id":"cfg-data"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"defaultAlign","id":"cfg-defaultAlign"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"2.3.0"},"name":"disabled","id":"cfg-disabled"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"disabledCls","id":"cfg-disabledCls"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"draggable","id":"cfg-draggable"},{"tagname":"cfg","owner":"Ext.util.Floating","meta":{},"name":"fixed","id":"cfg-fixed"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"floating","id":"cfg-floating"},{"tagname":"cfg","owner":"Ext.util.Floating","meta":{},"name":"focusOnToFront","id":"cfg-focusOnToFront"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"formBind","id":"cfg-formBind"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"frame","id":"cfg-frame"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"height","id":"cfg-height"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"2.3.0"},"name":"hidden","id":"cfg-hidden"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"hideMode","id":"cfg-hideMode"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"3.4.0"},"name":"html","id":"cfg-html"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"id","id":"cfg-id"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"3.4.0"},"name":"itemId","id":"cfg-itemId"},{"tagname":"cfg","owner":"Ext.util.Observable","meta":{},"name":"listeners","id":"cfg-listeners"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"loader","id":"cfg-loader"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"margin","id":"cfg-margin"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"maxHeight","id":"cfg-maxHeight"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"maxWidth","id":"cfg-maxWidth"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"minHeight","id":"cfg-minHeight"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"minWidth","id":"cfg-minWidth"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"2.3.0"},"name":"overCls","id":"cfg-overCls"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"overflowX","id":"cfg-overflowX"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"overflowY","id":"cfg-overflowY"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"padding","id":"cfg-padding"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"2.3.0"},"name":"plugins","id":"cfg-plugins"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"region","id":"cfg-region"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"renderData","id":"cfg-renderData"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"renderSelectors","id":"cfg-renderSelectors"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"2.3.0"},"name":"renderTo","id":"cfg-renderTo"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"protected":true},"name":"renderTpl","id":"cfg-renderTpl"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"resizable","id":"cfg-resizable"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"resizeHandles","id":"cfg-resizeHandles"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"rtl","id":"cfg-rtl"},{"tagname":"cfg","owner":"Ext.state.Stateful","meta":{},"name":"saveDelay","id":"cfg-saveDelay"},{"tagname":"cfg","owner":"Ext.util.Floating","meta":{},"name":"shadow","id":"cfg-shadow"},{"tagname":"cfg","owner":"Ext.util.Floating","meta":{},"name":"shadowOffset","id":"cfg-shadowOffset"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"shrinkWrap","id":"cfg-shrinkWrap"},{"tagname":"cfg","owner":"Ext.state.Stateful","meta":{},"name":"stateEvents","id":"cfg-stateEvents"},{"tagname":"cfg","owner":"Ext.state.Stateful","meta":{},"name":"stateId","id":"cfg-stateId"},{"tagname":"cfg","owner":"Ext.state.Stateful","meta":{},"name":"stateful","id":"cfg-stateful"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"style","id":"cfg-style"},{"tagname":"cfg","owner":"Ext.Component","meta":{},"name":"toFrontOnShow","id":"cfg-toFrontOnShow"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"3.4.0"},"name":"tpl","id":"cfg-tpl"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"3.4.0"},"name":"tplWriteMode","id":"cfg-tplWriteMode"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"ui","id":"cfg-ui"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"uiCls","id":"cfg-uiCls"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{},"name":"width","id":"cfg-width"},{"tagname":"cfg","owner":"Ext.AbstractComponent","meta":{"since":"2.3.0"},"name":"xtype","id":"cfg-xtype"}],"css_var":[],"method":[{"tagname":"method","owner":"Ext.Component","meta":{},"name":"constructor","id":"method-constructor"},{"tagname":"method","owner":"Ext.util.ElementContainer","meta":{},"name":"addChildEls","id":"method-addChildEls"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"since":"2.3.0","deprecated":{"text":"Use {@link #addCls} instead.","version":"4.1"}},"name":"addClass","id":"method-addClass"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"addCls","id":"method-addCls"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"addClsWithUI","id":"method-addClsWithUI"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"addEvents","id":"method-addEvents"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"addFocusListener","id":"method-addFocusListener"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"addListener","id":"method-addListener"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"addManagedListener","id":"method-addManagedListener"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"addOverCls","id":"method-addOverCls"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"addPlugin","id":"method-addPlugin"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"protected":true},"name":"addPropertyToState","id":"method-addPropertyToState"},{"tagname":"method","owner":"Ext.state.Stateful","meta":{},"name":"addStateEvents","id":"method-addStateEvents"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"addUIClsToElement","id":"method-addUIClsToElement"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"addUIToElement","id":"method-addUIToElement"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{"private":true},"name":"adjustForConstraints","id":"method-adjustForConstraints"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"adjustPosition","id":"method-adjustPosition"},{"tagname":"method","owner":"Ext.Component","meta":{"template":true,"protected":true},"name":"afterComponentLayout","id":"method-afterComponentLayout"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"afterFirstLayout","id":"method-afterFirstLayout"},{"tagname":"method","owner":"Ext.Component","meta":{"protected":true,"template":true},"name":"afterHide","id":"method-afterHide"},{"tagname":"method","owner":"Ext.Component","meta":{"template":true,"protected":true},"name":"afterRender","id":"method-afterRender"},{"tagname":"method","owner":"Ext.Component","meta":{"template":true,"protected":true},"name":"afterSetPosition","id":"method-afterSetPosition"},{"tagname":"method","owner":"Ext.Component","meta":{"protected":true,"template":true},"name":"afterShow","id":"method-afterShow"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{"chainable":true},"name":"alignTo","id":"method-alignTo"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{"chainable":true},"name":"anchorTo","id":"method-anchorTo"},{"tagname":"method","owner":"Ext.util.Animate","meta":{"private":true},"name":"anim","id":"method-anim"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"animate","id":"method-animate"},{"tagname":"method","owner":"Ext.util.ElementContainer","meta":{"private":true},"name":"applyChildEls","id":"method-applyChildEls"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"applyRenderSelectors","id":"method-applyRenderSelectors"},{"tagname":"method","owner":"Ext.state.Stateful","meta":{},"name":"applyState","id":"method-applyState"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"protected":true},"name":"beforeBlur","id":"method-beforeBlur"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"protected":true,"template":true},"name":"beforeComponentLayout","id":"method-beforeComponentLayout"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"protected":true,"template":true},"name":"beforeDestroy","id":"method-beforeDestroy"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"protected":true},"name":"beforeFocus","id":"method-beforeFocus"},{"tagname":"method","owner":"Ext.Component","meta":{"template":true,"protected":true},"name":"beforeLayout","id":"method-beforeLayout"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"beforeRender","id":"method-beforeRender"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"beforeSetPosition","id":"method-beforeSetPosition"},{"tagname":"method","owner":"Ext.Component","meta":{"protected":true,"template":true},"name":"beforeShow","id":"method-beforeShow"},{"tagname":"method","owner":"Ext.Component","meta":{"chainable":true,"private":true},"name":"blur","id":"method-blur"},{"tagname":"method","owner":"Ext.Component","meta":{"chainable":true},"name":"bubble","id":"method-bubble"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{"private":true},"name":"calculateAnchorXY","id":"method-calculateAnchorXY"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{},"name":"calculateConstrainedPosition","id":"method-calculateConstrainedPosition"},{"tagname":"method","owner":"Ext.Base","meta":{"protected":true,"deprecated":{"text":"as of 4.1. Use {@link #callParent} instead."}},"name":"callOverridden","id":"method-callOverridden"},{"tagname":"method","owner":"Ext.Base","meta":{"protected":true},"name":"callParent","id":"method-callParent"},{"tagname":"method","owner":"Ext.Base","meta":{"protected":true},"name":"callSuper","id":"method-callSuper"},{"tagname":"method","owner":"Ext.Component","meta":{"protected":true},"name":"cancelFocus","id":"method-cancelFocus"},{"tagname":"method","owner":"Ext.util.Observable","meta":{"private":true},"name":"captureArgs","id":"method-captureArgs"},{"tagname":"method","owner":"Ext.util.Floating","meta":{},"name":"center","id":"method-center"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"clearListeners","id":"method-clearListeners"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"clearManagedListeners","id":"method-clearManagedListeners"},{"tagname":"method","owner":"Ext.Component","meta":{},"name":"cloneConfig","id":"method-cloneConfig"},{"tagname":"method","owner":"Ext.Base","meta":{"private":true},"name":"configClass","id":"method-configClass"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"constructPlugin","id":"method-constructPlugin"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"constructPlugins","id":"method-constructPlugins"},{"tagname":"method","owner":"Ext.util.Observable","meta":{"private":true},"name":"continueFireEvent","id":"method-continueFireEvent"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"convertPositionSpec","id":"method-convertPositionSpec"},{"tagname":"method","owner":"Ext.util.Observable","meta":{"private":true},"name":"createRelayer","id":"method-createRelayer"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"deleteMembers","id":"method-deleteMembers"},{"tagname":"method","owner":"Ext.Base","meta":{"private":true},"name":"destroy","id":"method-destroy"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"disable","id":"method-disable"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"doApplyRenderTpl","id":"method-doApplyRenderTpl"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{},"name":"doAutoRender","id":"method-doAutoRender"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"chainable":true},"name":"doComponentLayout","id":"method-doComponentLayout"},{"tagname":"method","owner":"Ext.util.Floating","meta":{},"name":"doConstrain","id":"method-doConstrain"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"doRenderContent","id":"method-doRenderContent"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"doRenderFramingDockedItems","id":"method-doRenderFramingDockedItems"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"enable","id":"method-enable"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"enableBubble","id":"method-enableBubble"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{},"name":"ensureAttachedToBody","id":"method-ensureAttachedToBody"},{"tagname":"method","owner":"Ext.Component","meta":{},"name":"findParentBy","id":"method-findParentBy"},{"tagname":"method","owner":"Ext.Component","meta":{},"name":"findParentByType","id":"method-findParentByType"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"findPlugin","id":"method-findPlugin"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"finishRender","id":"method-finishRender"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"finishRenderChildren","id":"method-finishRenderChildren"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"fireEvent","id":"method-fireEvent"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"fireEventArgs","id":"method-fireEventArgs"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"fireHierarchyEvent","id":"method-fireHierarchyEvent"},{"tagname":"method","owner":"Ext.util.Floating","meta":{"private":true},"name":"fitContainer","id":"method-fitContainer"},{"tagname":"method","owner":"Ext.Component","meta":{},"name":"focus","id":"method-focus"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"deprecated":{"text":"Use {@link #updateLayout} instead.","version":"4.1.0"}},"name":"forceComponentLayout","id":"method-forceComponentLayout"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"getActionEl","id":"method-getActionEl"},{"tagname":"method","owner":"Ext.util.Animate","meta":{},"name":"getActiveAnimation","id":"method-getActiveAnimation"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{},"name":"getAlignToXY","id":"method-getAlignToXY"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{"private":true},"name":"getAnchor","id":"method-getAnchor"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"getAnchorToXY","id":"method-getAnchorToXY"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{},"name":"getAnchorXY","id":"method-getAnchorXY"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"getAnimateTarget","id":"method-getAnimateTarget"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"getAutoId","id":"method-getAutoId"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"getBorderPadding","id":"method-getBorderPadding"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{},"name":"getBox","id":"method-getBox"},{"tagname":"method","owner":"Ext.util.Observable","meta":{"private":true},"name":"getBubbleParent","id":"method-getBubbleParent"},{"tagname":"method","owner":"Ext.Component","meta":{"protected":true},"name":"getBubbleTarget","id":"method-getBubbleTarget"},{"tagname":"method","owner":"Ext.util.ElementContainer","meta":{"private":true},"name":"getChildEls","id":"method-getChildEls"},{"tagname":"method","owner":"Ext.util.ElementContainer","meta":{"private":true},"name":"getClassChildEls","id":"method-getClassChildEls"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"getComponentLayout","id":"method-getComponentLayout"},{"tagname":"method","owner":"Ext.Base","meta":{"private":true},"name":"getConfig","id":"method-getConfig"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{},"name":"getConstrainVector","id":"method-getConstrainVector"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"getContentTarget","id":"method-getContentTarget"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"getDragEl","id":"method-getDragEl"},{"tagname":"method","owner":"Ext.Component","meta":{"since":"1.1.0"},"name":"getEl","id":"method-getEl"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"getElConfig","id":"method-getElConfig"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"getFocusEl","id":"method-getFocusEl"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"getFrameInfo","id":"method-getFrameInfo"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"getFrameRenderData","id":"method-getFrameRenderData"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"getFrameTpl","id":"method-getFrameTpl"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"getFramingInfoCls","id":"method-getFramingInfoCls"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getHeight","id":"method-getHeight"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"getHierarchyState","id":"method-getHierarchyState"},{"tagname":"method","owner":"Ext.Component","meta":{},"name":"getId","id":"method-getId"},{"tagname":"method","owner":"Ext.Base","meta":{},"name":"getInitialConfig","id":"method-getInitialConfig"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{},"name":"getInsertPosition","id":"method-getInsertPosition"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getItemId","id":"method-getItemId"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getLoader","id":"method-getLoader"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getLocalX","id":"method-getLocalX"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getLocalXY","id":"method-getLocalXY"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getLocalY","id":"method-getLocalY"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"getMaskTarget","id":"method-getMaskTarget"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{},"name":"getOffsetsTo","id":"method-getOffsetsTo"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"getOuterSize","id":"method-getOuterSize"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"getOverflowEl","id":"method-getOverflowEl"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"getOverflowStyle","id":"method-getOverflowStyle"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"getOwningBorderContainer","id":"method-getOwningBorderContainer"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"getOwningBorderLayout","id":"method-getOwningBorderLayout"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getPlugin","id":"method-getPlugin"},{"tagname":"method","owner":"Ext.Component","meta":{},"name":"getPosition","id":"method-getPosition"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"getPositionEl","id":"method-getPositionEl"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"getProxy","id":"method-getProxy"},{"tagname":"method","owner":"Ext.Component","meta":{"protected":true,"private":true},"name":"getRefOwner","id":"method-getRefOwner"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{},"name":"getRegion","id":"method-getRegion"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"getRenderTree","id":"method-getRenderTree"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"getResizeEl","id":"method-getResizeEl"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getSize","id":"method-getSize"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getSizeModel","id":"method-getSizeModel"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getState","id":"method-getState"},{"tagname":"method","owner":"Ext.state.Stateful","meta":{"private":true},"name":"getStateId","id":"method-getStateId"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"getStyleProxy","id":"method-getStyleProxy"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"getTargetEl","id":"method-getTargetEl"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"getTpl","id":"method-getTpl"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{},"name":"getViewRegion","id":"method-getViewRegion"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"getVisibilityEl","id":"method-getVisibilityEl"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getWidth","id":"method-getWidth"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getX","id":"method-getX"},{"tagname":"method","owner":"Ext.Component","meta":{},"name":"getXType","id":"method-getXType"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"since":"2.3.0"},"name":"getXTypes","id":"method-getXTypes"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getXY","id":"method-getXY"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"getY","id":"method-getY"},{"tagname":"method","owner":"Ext.util.Animate","meta":{"deprecated":{"text":"Replaced by {@link #getActiveAnimation}","version":"4.0"}},"name":"hasActiveFx","id":"method-hasActiveFx"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"hasCls","id":"method-hasCls"},{"tagname":"method","owner":"Ext.Base","meta":{"private":true},"name":"hasConfig","id":"method-hasConfig"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"hasListener","id":"method-hasListener"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"hasUICls","id":"method-hasUICls"},{"tagname":"method","owner":"Ext.Component","meta":{"chainable":true},"name":"hide","id":"method-hide"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"initBorderRegion","id":"method-initBorderRegion"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"initCls","id":"method-initCls"},{"tagname":"method","owner":"Ext.Component","meta":{"since":"1.1.0","protected":true,"template":true},"name":"initComponent","id":"method-initComponent"},{"tagname":"method","owner":"Ext.Base","meta":{"chainable":true,"protected":true},"name":"initConfig","id":"method-initConfig"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"initContainer","id":"method-initContainer"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"initDraggable","id":"method-initDraggable"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"protected":true},"name":"initEvents","id":"method-initEvents"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"initFrame","id":"method-initFrame"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"initFramingTpl","id":"method-initFramingTpl"},{"tagname":"method","owner":"Ext.util.Floating","meta":{"private":true},"name":"initHierarchyEvents","id":"method-initHierarchyEvents"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"initHierarchyState","id":"method-initHierarchyState"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"initPadding","id":"method-initPadding"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"initPlugin","id":"method-initPlugin"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"protected":true},"name":"initRenderData","id":"method-initRenderData"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"initRenderTpl","id":"method-initRenderTpl"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"initResizable","id":"method-initResizable"},{"tagname":"method","owner":"Ext.state.Stateful","meta":{"private":true},"name":"initState","id":"method-initState"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"initStyles","id":"method-initStyles"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"is","id":"method-is"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"isContainedFloater","id":"method-isContainedFloater"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"isDescendant","id":"method-isDescendant"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"isDescendantOf","id":"method-isDescendantOf"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"isDisabled","id":"method-isDisabled"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"isDraggable","id":"method-isDraggable"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"isDroppable","id":"method-isDroppable"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"isFloating","id":"method-isFloating"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"isFocusable","id":"method-isFocusable"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"isHidden","id":"method-isHidden"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"isHierarchicallyHidden","id":"method-isHierarchicallyHidden"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"protected":true},"name":"isLayoutRoot","id":"method-isLayoutRoot"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"isLayoutSuspended","id":"method-isLayoutSuspended"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"isLocalRtl","id":"method-isLocalRtl"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"isOppositeRootDirection","id":"method-isOppositeRootDirection"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"isParentRtl","id":"method-isParentRtl"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"isVisible","id":"method-isVisible"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"since":"2.3.0"},"name":"isXType","id":"method-isXType"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"makeFloating","id":"method-makeFloating"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"mask","id":"method-mask"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"mon","id":"method-mon"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{},"name":"move","id":"method-move"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"mun","id":"method-mun"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"nextNode","id":"method-nextNode"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"nextSibling","id":"method-nextSibling"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"on","id":"method-on"},{"tagname":"method","owner":"Ext.Component","meta":{"since":"3.4.0","template":true,"protected":true},"name":"onAdded","id":"method-onAdded"},{"tagname":"method","owner":"Ext.util.Floating","meta":{"private":true},"name":"onAfterFloatLayout","id":"method-onAfterFloatLayout"},{"tagname":"method","owner":"Ext.util.Floating","meta":{"private":true},"name":"onBeforeFloatLayout","id":"method-onBeforeFloatLayout"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"onBlur","id":"method-onBlur"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"onBoxReady","id":"method-onBoxReady"},{"tagname":"method","owner":"Ext.Base","meta":{"private":true},"name":"onConfigUpdate","id":"method-onConfigUpdate"},{"tagname":"method","owner":"Ext.Component","meta":{"protected":true,"template":true},"name":"onDestroy","id":"method-onDestroy"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"protected":true,"template":true},"name":"onDisable","id":"method-onDisable"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"protected":true,"template":true},"name":"onEnable","id":"method-onEnable"},{"tagname":"method","owner":"Ext.util.Floating","meta":{"private":true},"name":"onFloatShow","id":"method-onFloatShow"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"onFocus","id":"method-onFocus"},{"tagname":"method","owner":"Ext.Component","meta":{"protected":true,"template":true},"name":"onHide","id":"method-onHide"},{"tagname":"method","owner":"Ext.util.Floating","meta":{"private":true},"name":"onKeyDown","id":"method-onKeyDown"},{"tagname":"method","owner":"Ext.util.Floating","meta":{"private":true},"name":"onMouseDown","id":"method-onMouseDown"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"protected":true,"template":true},"name":"onPosition","id":"method-onPosition"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"since":"3.4.0","protected":true,"template":true},"name":"onRemoved","id":"method-onRemoved"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"protected":true,"template":true},"name":"onRender","id":"method-onRender"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"protected":true,"template":true},"name":"onResize","id":"method-onResize"},{"tagname":"method","owner":"Ext.Component","meta":{"protected":true,"template":true},"name":"onShow","id":"method-onShow"},{"tagname":"method","owner":"Ext.Component","meta":{"protected":true,"template":true},"name":"onShowComplete","id":"method-onShowComplete"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"onShowVeto","id":"method-onShowVeto"},{"tagname":"method","owner":"Ext.state.Stateful","meta":{"private":true},"name":"onStateChange","id":"method-onStateChange"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"parseBox","id":"method-parseBox"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"protected":true},"name":"postBlur","id":"method-postBlur"},{"tagname":"method","owner":"Ext.util.Observable","meta":{"private":true},"name":"prepareClass","id":"method-prepareClass"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"previousNode","id":"method-previousNode"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"previousSibling","id":"method-previousSibling"},{"tagname":"method","owner":"Ext.util.ElementContainer","meta":{"private":true},"name":"prune","id":"method-prune"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"registerFloatingItem","id":"method-registerFloatingItem"},{"tagname":"method","owner":"Ext.util.Floating","meta":{"private":true},"name":"registerWithOwnerCt","id":"method-registerWithOwnerCt"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"relayEvents","id":"method-relayEvents"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{"chainable":true},"name":"removeAnchor","id":"method-removeAnchor"},{"tagname":"method","owner":"Ext.util.ElementContainer","meta":{},"name":"removeChildEls","id":"method-removeChildEls"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"since":"2.3.0","private":true},"name":"removeClass","id":"method-removeClass"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"removeCls","id":"method-removeCls"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"removeClsWithUI","id":"method-removeClsWithUI"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"removeListener","id":"method-removeListener"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"removeManagedListener","id":"method-removeManagedListener"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"removeManagedListenerItem","id":"method-removeManagedListenerItem"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"removeOverCls","id":"method-removeOverCls"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"removePlugin","id":"method-removePlugin"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"removeUIClsFromElement","id":"method-removeUIClsFromElement"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"removeUIFromElement","id":"method-removeUIFromElement"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{},"name":"render","id":"method-render"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"resumeEvent","id":"method-resumeEvent"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"resumeEvents","id":"method-resumeEvents"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"resumeLayouts","id":"method-resumeLayouts"},{"tagname":"method","owner":"Ext.state.Stateful","meta":{},"name":"savePropToState","id":"method-savePropToState"},{"tagname":"method","owner":"Ext.state.Stateful","meta":{},"name":"savePropsToState","id":"method-savePropsToState"},{"tagname":"method","owner":"Ext.state.Stateful","meta":{},"name":"saveState","id":"method-saveState"},{"tagname":"method","owner":"Ext.Component","meta":{},"name":"scrollBy","id":"method-scrollBy"},{"tagname":"method","owner":"Ext.util.Animate","meta":{"chainable":true},"name":"sequenceFx","id":"method-sequenceFx"},{"tagname":"method","owner":"Ext.util.Floating","meta":{},"name":"setActive","id":"method-setActive"},{"tagname":"method","owner":"Ext.Component","meta":{"chainable":true},"name":"setAutoScroll","id":"method-setAutoScroll"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setBorder","id":"method-setBorder"},{"tagname":"method","owner":"Ext.Component","meta":{},"name":"setBorderRegion","id":"method-setBorderRegion"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{"chainable":true},"name":"setBox","id":"method-setBox"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"setComponentLayout","id":"method-setComponentLayout"},{"tagname":"method","owner":"Ext.Base","meta":{"chainable":true,"private":true},"name":"setConfig","id":"method-setConfig"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setDisabled","id":"method-setDisabled"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setDocked","id":"method-setDocked"},{"tagname":"method","owner":"Ext.util.Floating","meta":{"private":true},"name":"setFloatParent","id":"method-setFloatParent"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setHeight","id":"method-setHeight"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"setHiddenState","id":"method-setHiddenState"},{"tagname":"method","owner":"Ext.Component","meta":{},"name":"setLoading","id":"method-setLoading"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setLocalX","id":"method-setLocalX"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setLocalXY","id":"method-setLocalXY"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setLocalY","id":"method-setLocalY"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setMargin","id":"method-setMargin"},{"tagname":"method","owner":"Ext.Component","meta":{"chainable":true},"name":"setOverflowXY","id":"method-setOverflowXY"},{"tagname":"method","owner":"Ext.Component","meta":{"chainable":true},"name":"setPagePosition","id":"method-setPagePosition"},{"tagname":"method","owner":"Ext.Component","meta":{"chainable":true},"name":"setPosition","id":"method-setPosition"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{"chainable":true},"name":"setRegion","id":"method-setRegion"},{"tagname":"method","owner":"Ext.Component","meta":{},"name":"setRegionWeight","id":"method-setRegionWeight"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setSize","id":"method-setSize"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setUI","id":"method-setUI"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"setVisible","id":"method-setVisible"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setWidth","id":"method-setWidth"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setX","id":"method-setX"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setXY","id":"method-setXY"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"setY","id":"method-setY"},{"tagname":"method","owner":"Ext.util.Floating","meta":{"private":true},"name":"setZIndex","id":"method-setZIndex"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"setupFramingTpl","id":"method-setupFramingTpl"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"setupProtoEl","id":"method-setupProtoEl"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"setupRenderTpl","id":"method-setupRenderTpl"},{"tagname":"method","owner":"Ext.Component","meta":{"chainable":true},"name":"show","id":"method-show"},{"tagname":"method","owner":"Ext.Component","meta":{"chainable":true},"name":"showAt","id":"method-showAt"},{"tagname":"method","owner":"Ext.Component","meta":{"chainable":true},"name":"showBy","id":"method-showBy"},{"tagname":"method","owner":"Ext.Base","meta":{"protected":true},"name":"statics","id":"method-statics"},{"tagname":"method","owner":"Ext.util.Animate","meta":{"chainable":true},"name":"stopAnimation","id":"method-stopAnimation"},{"tagname":"method","owner":"Ext.util.Animate","meta":{"deprecated":{"text":"Replaced by {@link #stopAnimation}","version":"4.0"}},"name":"stopFx","id":"method-stopFx"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"suspendEvent","id":"method-suspendEvent"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"suspendEvents","id":"method-suspendEvents"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"suspendLayouts","id":"method-suspendLayouts"},{"tagname":"method","owner":"Ext.util.Animate","meta":{"chainable":true},"name":"syncFx","id":"method-syncFx"},{"tagname":"method","owner":"Ext.util.Floating","meta":{"private":true},"name":"syncHidden","id":"method-syncHidden"},{"tagname":"method","owner":"Ext.util.Floating","meta":{"private":true},"name":"syncShadow","id":"method-syncShadow"},{"tagname":"method","owner":"Ext.util.Floating","meta":{"chainable":true},"name":"toBack","id":"method-toBack"},{"tagname":"method","owner":"Ext.util.Floating","meta":{},"name":"toFront","id":"method-toFront"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{},"name":"translatePoints","id":"method-translatePoints"},{"tagname":"method","owner":"Ext.util.Positionable","meta":{"private":true},"name":"translateXY","id":"method-translateXY"},{"tagname":"method","owner":"Ext.util.Observable","meta":{},"name":"un","id":"method-un"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"unitizeBox","id":"method-unitizeBox"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"unmask","id":"method-unmask"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"unregisterFloatingItem","id":"method-unregisterFloatingItem"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"up","id":"method-up"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"since":"3.4.0"},"name":"update","id":"method-update"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{"private":true},"name":"updateAria","id":"method-updateAria"},{"tagname":"method","owner":"Ext.Component","meta":{"chainable":true},"name":"updateBox","id":"method-updateBox"},{"tagname":"method","owner":"Ext.util.Renderable","meta":{"private":true},"name":"updateFrame","id":"method-updateFrame"},{"tagname":"method","owner":"Ext.AbstractComponent","meta":{},"name":"updateLayout","id":"method-updateLayout"},{"tagname":"method","owner":"Ext.Component","meta":{"private":true},"name":"wrapPrimaryEl","id":"method-wrapPrimaryEl"}],"event":[{"tagname":"event","owner":"Ext.AbstractComponent","meta":{},"name":"activate","id":"event-activate"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"3.4.0"},"name":"added","id":"event-added"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"3.4.0"},"name":"afterrender","id":"event-afterrender"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{},"name":"beforeactivate","id":"event-beforeactivate"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{},"name":"beforedeactivate","id":"event-beforedeactivate"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"beforedestroy","id":"event-beforedestroy"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"beforehide","id":"event-beforehide"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"beforerender","id":"event-beforerender"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"beforeshow","id":"event-beforeshow"},{"tagname":"event","owner":"Ext.state.Stateful","meta":{},"name":"beforestaterestore","id":"event-beforestaterestore"},{"tagname":"event","owner":"Ext.state.Stateful","meta":{},"name":"beforestatesave","id":"event-beforestatesave"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{},"name":"blur","id":"event-blur"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{},"name":"boxready","id":"event-boxready"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{},"name":"deactivate","id":"event-deactivate"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"destroy","id":"event-destroy"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"disable","id":"event-disable"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"enable","id":"event-enable"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{},"name":"focus","id":"event-focus"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"hide","id":"event-hide"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{},"name":"move","id":"event-move"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"3.4.0"},"name":"removed","id":"event-removed"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"render","id":"event-render"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{},"name":"resize","id":"event-resize"},{"tagname":"event","owner":"Ext.AbstractComponent","meta":{"since":"1.1.0"},"name":"show","id":"event-show"},{"tagname":"event","owner":"Ext.state.Stateful","meta":{},"name":"staterestore","id":"event-staterestore"},{"tagname":"event","owner":"Ext.state.Stateful","meta":{},"name":"statesave","id":"event-statesave"}],"css_mixin":[]},"inheritable":null,"private":null,"component":true,"name":"Ext.Component","singleton":false,"override":null,"inheritdoc":null,"id":"class-Ext.Component","mixins":["Ext.util.Floating"],"mixedInto":[]});
js/src/views/Status/components/RpcNav/RpcNav.js
pdaian/parity
// Copyright 2015, 2016 Ethcore (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import React, { Component } from 'react'; import { Link } from 'react-router'; import styles from './RpcNav.css'; export default class RpcNav extends Component { render () { return ( <div className={ styles.nav }> <Link to={ '/rpc/calls' } activeClassName={ styles.activeNav } { ...this._test('rpc-calls-link') }> <i className='icon-call-out' /> </Link> <Link to={ '/rpc/docs' } activeClassName={ styles.activeNav } { ...this._test('rpc-docs-link') }> <i className='icon-docs' /> </Link> </div> ); } }
front-end/src/screens/NotFound.js
AuthEceSoftEng/npm-miner
import React, { Component } from 'react'; class NotFound extends Component { render() { return ( <div> <h1>Not Found</h1> </div> ); } } export default NotFound;
fields/types/password/PasswordFilter.js
lojack/keystone
import React from 'react'; import { SegmentedControl } from 'elemental'; const OPTIONS = [ { label: 'Is Set', value: true }, { label: 'Is NOT Set', value: false } ]; var PasswordFilter = React.createClass({ getInitialState () { return { checked: this.props.value || true }; }, toggleChecked (checked) { this.setState({ checked: checked }); }, render () { return <SegmentedControl equalWidthSegments options={OPTIONS} value={this.state.checked} onChange={this.toggleChecked} />; } }); module.exports = PasswordFilter;
app/components/AboutButton/AbstractAboutButtonContainer.js
ihor/ReactNativeCodeReuseExample
import React from 'react'; import AboutButtonView from './AboutButtonView'; export default class AbstractAboutButtonContainer extends React.Component { constructor(props) { // new.target is not working on Android // if (new.target === AbstractAboutButtonContainer) { // throw new TypeError('Cannot construct AbstractAboutButtonContainer instances directly'); // } super(props); this.onClick = this.onClick.bind(this); } onClick() { throw new TypeError('Abstract method onClick is not implemented'); } render() { return <AboutButtonView onClick={this.onClick}/>; } }
public/js/components/admin/Settings.react.js
rajikaimal/Coupley
/** * Created by Isuru 1 on 21/01/2016. */ import React from 'react'; import { Link } from 'react-router'; const Settings = React.createClass({ render: function () { return ( <div className="settings"> <aside className="control-sidebar control-sidebar-dark"> <ul className="nav nav-tabs nav-justified control-sidebar-tabs"> </ul> <div className="tab-content"> <div className="tab-pane" id="control-sidebar-home-tab"> </div> <div className="tab-pane" id="control-sidebar-stats-tab">Stats Tab Content</div> </div> </aside> </div> ); }, }); export default Settings;
src/Form/FormHelperText.js
dsslimshaddy/material-ui
// @flow import React from 'react'; import type { Element } from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; export const styles = (theme: Object) => ({ root: { color: theme.palette.input.helperText, fontFamily: theme.typography.fontFamily, fontSize: 12, textAlign: 'left', marginTop: theme.spacing.unit, lineHeight: '1em', minHeight: '1em', margin: 0, }, dense: { marginTop: theme.spacing.unit / 2, }, error: { color: theme.palette.error.A400, }, disabled: { color: theme.palette.input.disabled, }, }); type DefaultProps = { classes: Object, }; export type Props = { /** * The content of the component. */ children?: Element<*>, /** * Useful to extend the style applied to components. */ classes?: Object, /** * @ignore */ className?: string, /** * If `true`, the helper text should be displayed in a disabled state. */ disabled?: boolean, /** * If `true`, helper text should be displayed in an error state. */ error?: boolean, /** * If `dense`, will adjust vertical spacing. This is normally obtained via context from * FormControl. */ margin?: 'dense', }; type AllProps = DefaultProps & Props; function FormHelperText(props: AllProps, context: { muiFormControl: Object }) { const { children, classes, className: classNameProp, disabled: disabledProp, error: errorProp, margin: marginProp, ...other } = props; const { muiFormControl } = context; let disabled = disabledProp; let error = errorProp; let margin = marginProp; if (muiFormControl) { if (typeof disabled === 'undefined') { disabled = muiFormControl.disabled; } if (typeof error === 'undefined') { error = muiFormControl.error; } if (typeof margin === 'undefined') { margin = muiFormControl.margin; } } const className = classNames( classes.root, { [classes.disabled]: disabled, [classes.error]: error, [classes.dense]: margin === 'dense', }, classNameProp, ); return ( <p className={className} {...other}> {children} </p> ); } FormHelperText.contextTypes = { muiFormControl: PropTypes.object, }; export default withStyles(styles, { name: 'MuiFormHelperText' })(FormHelperText);
ajax/libs/parse/2.18.0/parse.weapp.min.js
cdnjs/cdnjs
/** * Parse JavaScript SDK v2.18.0 * * Copyright (c) 2015-present, Parse, LLC. * All rights reserved. * * The source tree of this library can be found at * https://github.com/ParsePlatform/Parse-SDK-JS * 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(e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define([],e):("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).Parse=e()}(function(){return function n(a,s,o){function i(t,e){if(!s[t]){if(!a[t]){var r="function"==typeof require&&require;if(!e&&r)return r(t,!0);if(l)return l(t,!0);throw(r=new Error("Cannot find module '"+t+"'")).code="MODULE_NOT_FOUND",r}r=s[t]={exports:{}},a[t][0].call(r.exports,function(e){return i(a[t][1][e]||e)},r,r.exports,n,a,s,o)}return s[t].exports}for(var l="function"==typeof require&&require,e=0;e<o.length;e++)i(o[e]);return i}({1:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.track=function(e,t){if(0===(e=(e=(e=e||"").replace(/^\s*/,"")).replace(/\s*$/,"")).length)throw new TypeError("A name for the custom event must be provided");for(var r in t)if("string"!=typeof r||"string"!=typeof t[r])throw new TypeError('track() dimensions expects keys and values of type "string".');return a.default.getAnalyticsController().track(e,t)};var a=n(e("./CoreManager"));e={track:function(e,t){return a.default.getRESTController().request("POST","events/"+e,{dimensions:t})}};a.default.setAnalyticsController(e)},{"./CoreManager":4,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],2:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a=n(e("./ParseUser")),s=e("uuid/v4"),o=!1,e={isLinked:function(e){var t=this._getAuthProvider();return e._isLinked(t.getAuthType())},logIn:function(e){var t=this._getAuthProvider();return a.default.logInWith(t.getAuthType(),t.getAuthData(),e)},link:function(e,t){var r=this._getAuthProvider();return e.linkWith(r.getAuthType(),r.getAuthData(),t)},_getAuthProvider:function(){var e={restoreAuthentication:function(){return!0},getAuthType:function(){return"anonymous"},getAuthData:function(){return{authData:{id:s()}}}};return o||(a.default._registerAuthenticationProvider(e),o=!0),e}};r.default=e},{"./ParseUser":32,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"uuid/v4":476}],3:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.run=function(e,t,r){if(r=r||{},"string"!=typeof e||0===e.length)throw new TypeError("Cloud function name must be a string.");var n={};r.useMasterKey&&(n.useMasterKey=r.useMasterKey);r.sessionToken&&(n.sessionToken=r.sessionToken);r.context&&"object"===(0,o.default)(r.context)&&(n.context=r.context);return i.default.getCloudController().run(e,t,n)},r.getJobsData=function(){return i.default.getCloudController().getJobsData({useMasterKey:!0})},r.startJob=function(e,t){if("string"==typeof e&&0!==e.length)return i.default.getCloudController().startJob(e,t,{useMasterKey:!0});throw new TypeError("Cloud job name must be a string.")},r.getJobStatus=function(e){return new f.default("_JobStatus").get(e,{useMasterKey:!0})};var a=n(e("@babel/runtime-corejs3/core-js-stable/promise")),s=n(e("@babel/runtime-corejs3/core-js-stable/object/keys")),o=n(e("@babel/runtime-corejs3/helpers/typeof")),i=n(e("./CoreManager")),l=n(e("./decode")),u=n(e("./encode")),c=n(e("./ParseError")),f=n(e("./ParseQuery"));n(e("./ParseObject"));e={run:function(e,t,r){var n=i.default.getRESTController(),t=(0,u.default)(t,!0);return n.request("POST","functions/"+e,t,r).then(function(e){if("object"===(0,o.default)(e)&&0<(0,s.default)(e).length&&!e.hasOwnProperty("result"))throw new c.default(c.default.INVALID_JSON,"The server returned an invalid response.");e=(0,l.default)(e);return e&&e.hasOwnProperty("result")?a.default.resolve(e.result):a.default.resolve(void 0)})},getJobsData:function(e){return i.default.getRESTController().request("GET","cloud_code/jobs/data",null,e)},startJob:function(e,t,r){var n=i.default.getRESTController(),t=(0,u.default)(t,!0);return n.request("POST","jobs/"+e,t,r)}};i.default.setCloudController(e)},{"./CoreManager":4,"./ParseError":19,"./ParseObject":24,"./ParseQuery":27,"./decode":44,"./encode":45,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/object/keys":81,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/typeof":134}],4:[function(o,i,e){(function(e){"use strict";var t=o("@babel/runtime-corejs3/helpers/interopRequireDefault"),a=t(o("@babel/runtime-corejs3/core-js-stable/instance/concat")),s=t(o("@babel/runtime-corejs3/core-js-stable/instance/for-each")),r={IS_NODE:void 0!==e&&!!e.versions&&!!e.versions.node&&!e.versions.electron,REQUEST_ATTEMPT_LIMIT:5,REQUEST_BATCH_SIZE:20,REQUEST_HEADERS:{},SERVER_URL:"https://api.parse.com/1",SERVER_AUTH_TYPE:null,SERVER_AUTH_TOKEN:null,LIVEQUERY_SERVER_URL:null,ENCRYPTED_KEY:null,VERSION:"js2.18.0",APPLICATION_ID:null,JAVASCRIPT_KEY:null,MASTER_KEY:null,USE_MASTER_KEY:!1,PERFORM_USER_REWRITE:!0,FORCE_REVOCABLE_SESSION:!1,ENCRYPTED_USER:!1,IDEMPOTENCY:!1};function n(r,e,n){(0,s.default)(e).call(e,function(e){var t;if("function"!=typeof n[e])throw new Error((0,a.default)(t="".concat(r," must implement ")).call(t,e,"()"))})}i.exports={get:function(e){if(r.hasOwnProperty(e))return r[e];throw new Error("Configuration key not found: "+e)},set:function(e,t){r[e]=t},setAnalyticsController:function(e){n("AnalyticsController",["track"],e),r.AnalyticsController=e},getAnalyticsController:function(){return r.AnalyticsController},setCloudController:function(e){n("CloudController",["run","getJobsData","startJob"],e),r.CloudController=e},getCloudController:function(){return r.CloudController},setConfigController:function(e){n("ConfigController",["current","get","save"],e),r.ConfigController=e},getConfigController:function(){return r.ConfigController},setCryptoController:function(e){n("CryptoController",["encrypt","decrypt"],e),r.CryptoController=e},getCryptoController:function(){return r.CryptoController},setFileController:function(e){n("FileController",["saveFile","saveBase64"],e),r.FileController=e},getFileController:function(){return r.FileController},setInstallationController:function(e){n("InstallationController",["currentInstallationId"],e),r.InstallationController=e},getInstallationController:function(){return r.InstallationController},setObjectController:function(e){n("ObjectController",["save","fetch","destroy"],e),r.ObjectController=e},getObjectController:function(){return r.ObjectController},setObjectStateController:function(e){n("ObjectStateController",["getState","initializeState","removeState","getServerData","setServerData","getPendingOps","setPendingOp","pushPendingState","popPendingState","mergeFirstPendingState","getObjectCache","estimateAttribute","estimateAttributes","commitServerChanges","enqueueTask","clearAllState"],e),r.ObjectStateController=e},getObjectStateController:function(){return r.ObjectStateController},setPushController:function(e){n("PushController",["send"],e),r.PushController=e},getPushController:function(){return r.PushController},setQueryController:function(e){n("QueryController",["find","aggregate"],e),r.QueryController=e},getQueryController:function(){return r.QueryController},setRESTController:function(e){n("RESTController",["request","ajax"],e),r.RESTController=e},getRESTController:function(){return r.RESTController},setSchemaController:function(e){n("SchemaController",["get","create","update","delete","send","purge"],e),r.SchemaController=e},getSchemaController:function(){return r.SchemaController},setSessionController:function(e){n("SessionController",["getSession"],e),r.SessionController=e},getSessionController:function(){return r.SessionController},setStorageController:function(e){e.async?n("An async StorageController",["getItemAsync","setItemAsync","removeItemAsync","getAllKeysAsync"],e):n("A synchronous StorageController",["getItem","setItem","removeItem","getAllKeys"],e),r.StorageController=e},setLocalDatastoreController:function(e){n("LocalDatastoreController",["pinWithName","fromPinWithName","unPinWithName","getAllContents","clear"],e),r.LocalDatastoreController=e},getLocalDatastoreController:function(){return r.LocalDatastoreController},setLocalDatastore:function(e){r.LocalDatastore=e},getLocalDatastore:function(){return r.LocalDatastore},getStorageController:function(){return r.StorageController},setAsyncStorage:function(e){r.AsyncStorage=e},getAsyncStorage:function(){return r.AsyncStorage},setWebSocketController:function(e){r.WebSocketController=e},getWebSocketController:function(){return r.WebSocketController},setUserController:function(e){n("UserController",["setCurrentUser","currentUser","currentUserAsync","signUp","logIn","become","logOut","me","requestPasswordReset","upgradeToRevocableSession","requestEmailVerification","verifyPassword","linkWith"],e),r.UserController=e},getUserController:function(){return r.UserController},setLiveQueryController:function(e){n("LiveQueryController",["setDefaultLiveQueryClient","getDefaultLiveQueryClient","_clearCachedDefaultClient"],e),r.LiveQueryController=e},getLiveQueryController:function(){return r.LiveQueryController},setHooksController:function(e){n("HooksController",["create","get","update","remove"],e),r.HooksController=e},getHooksController:function(){return r.HooksController}}}).call(this,o("_process"))},{"@babel/runtime-corejs3/core-js-stable/instance/concat":56,"@babel/runtime-corejs3/core-js-stable/instance/for-each":59,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,_process:138}],5:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault")(e("@babel/runtime-corejs3/core-js-stable/json/stringify")),a=e("crypto-js/aes"),s=e("crypto-js/enc-utf8"),e={encrypt:function(e,t){return a.encrypt((0,n.default)(e),t).toString()},decrypt:function(e,t){return a.decrypt(e,t).toString(s)}};t.exports=e},{"@babel/runtime-corejs3/core-js-stable/json/stringify":70,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"crypto-js/aes":463,"crypto-js/enc-utf8":467}],6:[function(e,t,r){"use strict";t.exports=e("events").EventEmitter},{events:472}],7:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a,s,o=n(e("./ParseUser")),i=!1,l={authenticate:function(t){var r=this;"undefined"==typeof FB&&t.error(this,"Facebook SDK not found."),FB.login(function(e){e.authResponse?t.success&&t.success(r,{id:e.authResponse.userID,access_token:e.authResponse.accessToken,expiration_date:new Date(1e3*e.authResponse.expiresIn+(new Date).getTime()).toJSON()}):t.error&&t.error(r,e)},{scope:a})},restoreAuthentication:function(e){if(e){var t={};if(s)for(var r in s)t[r]=s[r];t.status=!1;var n=FB.getAuthResponse();n&&n.userID!==e.id&&FB.logout(),FB.init(t)}return!0},getAuthType:function(){return"facebook"},deauthenticate:function(){this.restoreAuthentication(null)}},e={init:function(e){if("undefined"==typeof FB)throw new Error("The Facebook JavaScript SDK must be loaded before calling init.");if(s={},e)for(var t in e)s[t]=e[t];s.status&&"undefined"!=typeof console&&(console.warn||console.log||function(){}).call(console,'The "status" flag passed into FB.init, when set to true, can interfere with Parse Facebook integration, so it has been suppressed. Please call FB.getLoginStatus() explicitly if you require this behavior.'),s.status=!1,FB.init(s),o.default._registerAuthenticationProvider(l),i=!0},isLinked:function(e){return e._isLinked("facebook")},logIn:function(e,t){if(e&&"string"!=typeof e)return o.default.logInWith("facebook",{authData:e},t);if(!i)throw new Error("You must initialize FacebookUtils before calling logIn.");return a=e,o.default.logInWith("facebook",t)},link:function(e,t,r){if(t&&"string"!=typeof t)return e.linkWith("facebook",{authData:t},r);if(!i)throw new Error("You must initialize FacebookUtils before calling link.");return a=t,e.linkWith("facebook",r)},unlink:function(e,t){if(!i)throw new Error("You must initialize FacebookUtils before calling unlink.");return e._unlinkFrom("facebook",t)},_getAuthProvider:function(){return l}};r.default=e},{"./ParseUser":32,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],8:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault"),a=n(e("@babel/runtime-corejs3/core-js-stable/promise")),s=n(e("./Storage")),o=e("uuid/v4"),i=null,e={currentInstallationId:function(){if("string"==typeof i)return a.default.resolve(i);var t=s.default.generatePath("installationId");return s.default.getItemAsync(t).then(function(e){return e?i=e:(e=o(),s.default.setItemAsync(t,e).then(function(){return i=e}))})},_clearCache:function(){i=null},_setInstallationIdCache:function(e){i=e}};t.exports=e},{"./Storage":37,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"uuid/v4":476}],9:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;n(e("@babel/runtime-corejs3/helpers/typeof"));var i=n(e("@babel/runtime-corejs3/core-js/get-iterator")),l=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),u=n(e("@babel/runtime-corejs3/core-js/get-iterator-method")),c=n(e("@babel/runtime-corejs3/core-js-stable/symbol")),f=n(e("@babel/runtime-corejs3/core-js-stable/array/from")),d=n(e("@babel/runtime-corejs3/core-js-stable/instance/slice")),a=n(e("@babel/runtime-corejs3/core-js-stable/reflect/construct")),s=n(e("@babel/runtime-corejs3/core-js-stable/instance/bind")),p=n(e("@babel/runtime-corejs3/core-js-stable/set-timeout")),o=n(e("@babel/runtime-corejs3/core-js-stable/instance/values")),b=n(e("@babel/runtime-corejs3/core-js-stable/instance/for-each")),h=n(e("@babel/runtime-corejs3/core-js-stable/json/stringify")),y=n(e("@babel/runtime-corejs3/core-js-stable/instance/keys")),m=n(e("@babel/runtime-corejs3/core-js-stable/map")),v=n(e("@babel/runtime-corejs3/core-js-stable/instance/index-of")),j=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),g=n(e("@babel/runtime-corejs3/helpers/createClass")),_=n(e("@babel/runtime-corejs3/helpers/assertThisInitialized")),w=n(e("@babel/runtime-corejs3/helpers/inherits")),x=n(e("@babel/runtime-corejs3/helpers/possibleConstructorReturn")),k=n(e("@babel/runtime-corejs3/helpers/getPrototypeOf")),C=n(e("@babel/runtime-corejs3/helpers/defineProperty")),S=n(e("./CoreManager")),E=n(e("./EventEmitter")),O=n(e("./ParseObject")),P=n(e("./LiveQuerySubscription")),A=e("./promiseUtils");function T(e,t){var r;if(void 0===c.default||null==(0,u.default)(e)){if((0,l.default)(e)||(r=function(e,t){if(!e)return;if("string"==typeof e)return R(e,t);var r=(0,d.default)(r=Object.prototype.toString.call(e)).call(r,8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return(0,f.default)(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return R(e,t)}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,t=function(){};return{s:t,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:t}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){r=(0,i.default)(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==r.return||r.return()}finally{if(o)throw a}}}}function R(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}function I(r){var n=function(){if("undefined"==typeof Reflect||!a.default)return!1;if(a.default.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call((0,a.default)(Date,[],function(){})),!0}catch(e){return!1}}();return function(){var e,t=(0,k.default)(r);return t=n?(e=(0,k.default)(this).constructor,(0,a.default)(t,arguments,e)):t.apply(this,arguments),(0,x.default)(this,t)}}var N={INITIALIZED:"initialized",CONNECTING:"connecting",CONNECTED:"connected",CLOSED:"closed",RECONNECTING:"reconnecting",DISCONNECTED:"disconnected"},D="connect",L="subscribe",M="unsubscribe",q="connected",U="subscribed",F="unsubscribed",K="error",W="close",z="error",B="open",J="open",Q="close",V="error",E=function(e){(0,w.default)(l,e);var i=I(l);function l(e){var t=e.applicationId,r=e.serverURL,n=e.javascriptKey,a=e.masterKey,s=e.sessionToken,o=e.installationId;if((0,j.default)(this,l),e=i.call(this),(0,C.default)((0,_.default)(e),"attempts",void 0),(0,C.default)((0,_.default)(e),"id",void 0),(0,C.default)((0,_.default)(e),"requestId",void 0),(0,C.default)((0,_.default)(e),"applicationId",void 0),(0,C.default)((0,_.default)(e),"serverURL",void 0),(0,C.default)((0,_.default)(e),"javascriptKey",void 0),(0,C.default)((0,_.default)(e),"masterKey",void 0),(0,C.default)((0,_.default)(e),"sessionToken",void 0),(0,C.default)((0,_.default)(e),"installationId",void 0),(0,C.default)((0,_.default)(e),"additionalProperties",void 0),(0,C.default)((0,_.default)(e),"connectPromise",void 0),(0,C.default)((0,_.default)(e),"subscriptions",void 0),(0,C.default)((0,_.default)(e),"socket",void 0),(0,C.default)((0,_.default)(e),"state",void 0),!r||0!==(0,v.default)(r).call(r,"ws"))throw new Error("You need to set a proper Parse LiveQuery server url before using LiveQueryClient");return e.reconnectHandle=null,e.attempts=1,e.id=0,e.requestId=1,e.serverURL=r,e.applicationId=t,e.javascriptKey=n,e.masterKey=a,e.sessionToken=s||void 0,e.installationId=o,e.additionalProperties=!0,e.connectPromise=(0,A.resolvingPromise)(),e.subscriptions=new m.default,e.state=N.INITIALIZED,e.on("error",function(){}),e}return(0,g.default)(l,[{key:"shouldOpen",value:function(){return this.state===N.INITIALIZED||this.state===N.DISCONNECTED}},{key:"subscribe",value:function(e,t){var r=this;if(e){var n=e.className,a=e.toJSON(),s=a.where,a=(0,y.default)(a)?(0,y.default)(a).split(","):void 0,o={op:L,requestId:this.requestId,query:{className:n,where:s,fields:a}};t&&(o.sessionToken=t);t=new P.default(this.requestId,e,t);return this.subscriptions.set(this.requestId,t),this.requestId+=1,this.connectPromise.then(function(){r.socket.send((0,h.default)(o))}),t}}},{key:"unsubscribe",value:function(e){var t,r=this;e&&(this.subscriptions.delete(e.id),t={op:M,requestId:e.id},this.connectPromise.then(function(){r.socket.send((0,h.default)(t))}))}},{key:"open",value:function(){var t=this,e=S.default.getWebSocketController();e?(this.state!==N.RECONNECTING&&(this.state=N.CONNECTING),this.socket=new e(this.serverURL),this.socket.onopen=function(){t._handleWebSocketOpen()},this.socket.onmessage=function(e){t._handleWebSocketMessage(e)},this.socket.onclose=function(){t._handleWebSocketClose()},this.socket.onerror=function(e){t._handleWebSocketError(e)}):this.emit(z,"Can not find WebSocket implementation")}},{key:"resubscribe",value:function(){var e,o=this;(0,b.default)(e=this.subscriptions).call(e,function(e,t){var r=e.query,n=r.toJSON(),a=n.where,n=(0,y.default)(n)?(0,y.default)(n).split(","):void 0,r=r.className,e=e.sessionToken,s={op:L,requestId:t,query:{className:r,where:a,fields:n}};e&&(s.sessionToken=e),o.connectPromise.then(function(){o.socket.send((0,h.default)(s))})})}},{key:"close",value:function(){var e;if(this.state!==N.INITIALIZED&&this.state!==N.DISCONNECTED){this.state=N.DISCONNECTED,this.socket.close();var t=T((0,o.default)(e=this.subscriptions).call(e));try{for(t.s();!(r=t.n()).done;){var r=r.value;r.subscribed=!1,r.emit(Q)}}catch(e){t.e(e)}finally{t.f()}this._handleReset(),this.emit(W)}}},{key:"_handleReset",value:function(){this.attempts=1,this.id=0,this.requestId=1,this.connectPromise=(0,A.resolvingPromise)(),this.subscriptions=new m.default}},{key:"_handleWebSocketOpen",value:function(){this.attempts=1;var e={op:D,applicationId:this.applicationId,javascriptKey:this.javascriptKey,masterKey:this.masterKey,sessionToken:this.sessionToken};this.additionalProperties&&(e.installationId=this.installationId),this.socket.send((0,h.default)(e))}},{key:"_handleWebSocketMessage",value:function(e){var t=e.data;"string"==typeof t&&(t=JSON.parse(t));var r=null;t.requestId&&(r=this.subscriptions.get(t.requestId));var n={clientId:t.clientId,installationId:t.installationId};switch(t.op){case q:this.state===N.RECONNECTING&&this.resubscribe(),this.emit(B),this.id=t.clientId,this.connectPromise.resolve(),this.state=N.CONNECTED;break;case U:r&&(r.subscribed=!0,r.subscribePromise.resolve(),(0,p.default)(function(){return r.emit(J,n)},200));break;case K:t.requestId?r&&(r.subscribePromise.resolve(),(0,p.default)(function(){return r.emit(V,t.error)},200)):this.emit(z,t.error),"Additional properties not allowed"===t.error&&(this.additionalProperties=!1),t.reconnect&&this._handleReconnect();break;case F:break;default:if(!r)break;var a=!1;if(t.original){for(var s in a=!0,delete t.original.__type,t.original)s in t.object||(t.object[s]=void 0);t.original=O.default.fromJSON(t.original,!1)}delete t.object.__type;var o=O.default.fromJSON(t.object,a);t.original?r.emit(t.op,o,t.original,n):r.emit(t.op,o,n);e=S.default.getLocalDatastore();a&&e.isEnabled&&e._updateObjectIfPinned(o).then(function(){})}}},{key:"_handleWebSocketClose",value:function(){var e;if(this.state!==N.DISCONNECTED){this.state=N.CLOSED,this.emit(W);var t,r=T((0,o.default)(e=this.subscriptions).call(e));try{for(r.s();!(t=r.n()).done;){t.value.emit(Q)}}catch(e){r.e(e)}finally{r.f()}this._handleReconnect()}}},{key:"_handleWebSocketError",value:function(e){var t;this.emit(z,e);var r,n=T((0,o.default)(t=this.subscriptions).call(t));try{for(n.s();!(r=n.n()).done;){r.value.emit(V,e)}}catch(e){n.e(e)}finally{n.f()}this._handleReconnect()}},{key:"_handleReconnect",value:function(){var e,t,r=this;this.state!==N.DISCONNECTED&&(this.state=N.RECONNECTING,t=this.attempts,e=Math.random()*Math.min(30,Math.pow(2,t)-1)*1e3,this.reconnectHandle&&clearTimeout(this.reconnectHandle),this.reconnectHandle=(0,p.default)((0,s.default)(t=function(){r.attempts++,r.connectPromise=(0,A.resolvingPromise)(),r.open()}).call(t,this),e))}}]),l}(E.default);S.default.setWebSocketController(e("./Socket.weapp")),r.default=E},{"./CoreManager":4,"./EventEmitter":6,"./LiveQuerySubscription":10,"./ParseObject":24,"./Socket.weapp":36,"./promiseUtils":50,"@babel/runtime-corejs3/core-js-stable/array/from":53,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/instance/bind":55,"@babel/runtime-corejs3/core-js-stable/instance/for-each":59,"@babel/runtime-corejs3/core-js-stable/instance/index-of":61,"@babel/runtime-corejs3/core-js-stable/instance/keys":62,"@babel/runtime-corejs3/core-js-stable/instance/slice":65,"@babel/runtime-corejs3/core-js-stable/instance/values":69,"@babel/runtime-corejs3/core-js-stable/json/stringify":70,"@babel/runtime-corejs3/core-js-stable/map":71,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/reflect/construct":84,"@babel/runtime-corejs3/core-js-stable/set-timeout":85,"@babel/runtime-corejs3/core-js-stable/symbol":87,"@babel/runtime-corejs3/core-js/get-iterator":92,"@babel/runtime-corejs3/core-js/get-iterator-method":91,"@babel/runtime-corejs3/helpers/assertThisInitialized":112,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/defineProperty":117,"@babel/runtime-corejs3/helpers/getPrototypeOf":119,"@babel/runtime-corejs3/helpers/inherits":120,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/possibleConstructorReturn":129,"@babel/runtime-corejs3/helpers/typeof":134}],10:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a=n(e("@babel/runtime-corejs3/core-js-stable/reflect/construct")),o=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),i=n(e("@babel/runtime-corejs3/helpers/createClass")),l=n(e("@babel/runtime-corejs3/helpers/inherits")),s=n(e("@babel/runtime-corejs3/helpers/possibleConstructorReturn")),u=n(e("@babel/runtime-corejs3/helpers/getPrototypeOf")),c=n(e("./EventEmitter")),f=n(e("./CoreManager")),d=e("./promiseUtils");function p(r){var n=function(){if("undefined"==typeof Reflect||!a.default)return!1;if(a.default.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call((0,a.default)(Date,[],function(){})),!0}catch(e){return!1}}();return function(){var e,t=(0,u.default)(r);return t=n?(e=(0,u.default)(this).constructor,(0,a.default)(t,arguments,e)):t.apply(this,arguments),(0,s.default)(this,t)}}c=function(e){(0,l.default)(s,e);var a=p(s);function s(e,t,r){var n;return(0,o.default)(this,s),(n=a.call(this)).id=e,n.query=t,n.sessionToken=r,n.subscribePromise=(0,d.resolvingPromise)(),n.subscribed=!1,n.on("error",function(){}),n}return(0,i.default)(s,[{key:"unsubscribe",value:function(){var t=this;return f.default.getLiveQueryController().getDefaultLiveQueryClient().then(function(e){e.unsubscribe(t),t.emit("close")})}}]),s}(c.default);r.default=c},{"./CoreManager":4,"./EventEmitter":6,"./promiseUtils":50,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/reflect/construct":84,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/getPrototypeOf":119,"@babel/runtime-corejs3/helpers/inherits":120,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/possibleConstructorReturn":129}],11:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault"),i=n(e("@babel/runtime-corejs3/core-js/get-iterator")),l=n(e("@babel/runtime-corejs3/core-js/get-iterator-method")),u=n(e("@babel/runtime-corejs3/core-js-stable/symbol")),c=n(e("@babel/runtime-corejs3/core-js-stable/instance/slice")),f=n(e("@babel/runtime-corejs3/core-js-stable/instance/find")),d=n(e("@babel/runtime-corejs3/core-js-stable/array/from")),p=n(e("@babel/runtime-corejs3/core-js-stable/instance/map")),b=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),h=n(e("@babel/runtime-corejs3/core-js-stable/instance/keys")),y=n(e("@babel/runtime-corejs3/core-js-stable/instance/starts-with")),m=n(e("@babel/runtime-corejs3/core-js-stable/object/keys")),v=n(e("@babel/runtime-corejs3/core-js-stable/instance/includes")),j=n(e("@babel/runtime-corejs3/core-js-stable/instance/filter")),g=n(e("@babel/runtime-corejs3/regenerator")),_=n(e("@babel/runtime-corejs3/core-js-stable/instance/concat")),w=n(e("@babel/runtime-corejs3/core-js-stable/set")),x=n(e("@babel/runtime-corejs3/helpers/toConsumableArray")),k=n(e("@babel/runtime-corejs3/core-js-stable/promise")),C=n(e("@babel/runtime-corejs3/helpers/slicedToArray")),s=n(e("@babel/runtime-corejs3/helpers/asyncToGenerator")),a=n(e("./CoreManager")),S=n(e("./ParseQuery")),E=e("./LocalDatastoreUtils");function O(e,t){var r;if(void 0===u.default||null==(0,l.default)(e)){if((0,b.default)(e)||(r=function(e,t){if(!e)return;if("string"==typeof e)return P(e,t);var r=(0,c.default)(r=Object.prototype.toString.call(e)).call(r,8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return(0,d.default)(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return P(e,t)}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,t=function(){};return{s:t,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:t}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){r=(0,i.default)(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==r.return||r.return()}finally{if(o)throw a}}}}function P(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}n={isEnabled:!1,isSyncing:!1,fromPinWithName:function(e){return a.default.getLocalDatastoreController().fromPinWithName(e)},pinWithName:function(e,t){return a.default.getLocalDatastoreController().pinWithName(e,t)},unPinWithName:function(e){return a.default.getLocalDatastoreController().unPinWithName(e)},_getAllContents:function(){return a.default.getLocalDatastoreController().getAllContents()},_getRawStorage:function(){return a.default.getLocalDatastoreController().getRawStorage()},_clear:function(){return a.default.getLocalDatastoreController().clear()},_handlePinAllWithName:function(d,p){var b=this;return(0,s.default)(g.default.mark(function e(){var t,r,n,a,s,o,i,l,u,c,f;return g.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:t=b.getPinName(d),r=[],n=[],a=O(p);try{for(a.s();!(l=a.n()).done;)for(u in s=l.value,o=b._getChildren(s),i=b.getKeyForObject(s),l=s._toFullJSON(void 0,!0),s._localId&&(l._localId=s._localId),o[i]=l,o)n.push(u),r.push(b.pinWithName(u,[o[u]]))}catch(e){a.e(e)}finally{a.f()}return c=b.fromPinWithName(t),e.next=8,k.default.all([c,r]);case 8:return f=e.sent,c=(0,C.default)(f,1),f=c[0],f=(0,x.default)(new w.default((0,_.default)(c=[]).call(c,(0,x.default)(f||[]),n))),e.abrupt("return",b.pinWithName(t,f));case 13:case"end":return e.stop()}},e)}))()},_handleUnPinAllWithName:function(d,p){var b=this;return(0,s.default)(g.default.mark(function e(){var t,r,n,a,s,o,i,l,u,c,f;return g.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,b._getAllContents();case 2:t=e.sent,r=b.getPinName(d),n=[],a=[],s=O(p);try{for(s.s();!(o=s.n()).done;)i=o.value,o=b._getChildren(i),i=b.getKeyForObject(i),a.push.apply(a,(0,_.default)(i=[i]).call(i,(0,x.default)((0,m.default)(o))))}catch(e){s.e(e)}finally{s.f()}a=(0,x.default)(new w.default(a)),l=t[r]||[],0==(l=(0,j.default)(l).call(l,function(e){return!(0,v.default)(a).call(a,e)})).length?(n.push(b.unPinWithName(r)),delete t[r]):(n.push(b.pinWithName(r,l)),t[r]=l),l=O(a),e.prev=13,l.s();case 15:if((f=l.n()).done){e.next=31;break}u=f.value,c=!1,e.t0=(0,h.default)(g.default).call(g.default,t);case 19:if((e.t1=e.t0()).done){e.next=28;break}if((f=e.t1.value)!==E.DEFAULT_PIN&&!(0,y.default)(f).call(f,E.PIN_PREFIX)){e.next=26;break}if(f=t[f]||[],(0,v.default)(f).call(f,u))return c=!0,e.abrupt("break",28);e.next=26;break;case 26:e.next=19;break;case 28:c||n.push(b.unPinWithName(u));case 29:e.next=15;break;case 31:e.next=36;break;case 33:e.prev=33,e.t2=e.catch(13),l.e(e.t2);case 36:return e.prev=36,l.f(),e.finish(36);case 39:return e.abrupt("return",k.default.all(n));case 40:case"end":return e.stop()}},e,null,[[13,33,36,39]])}))()},_getChildren:function(e){var t,r={},n=e._toFullJSON(void 0,!0);for(t in n)n[t]&&n[t].__type&&"Object"===n[t].__type&&this._traverse(n[t],r);return r},_traverse:function(e,t){if(e.objectId){var r=this.getKeyForObject(e);if(!t[r])for(var n in t[r]=e){var a=e[n];e[n]||(a=e),a.__type&&"Object"===a.__type&&this._traverse(a,t)}}},_serializeObjectsFromPinName:function(l){var u=this;return(0,s.default)(g.default.mark(function e(){var t,r,n,a,s,o,i;return g.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,u._getAllContents();case 2:for(n in t=e.sent,r=[],t)(0,y.default)(n).call(n,E.OBJECT_PREFIX)&&r.push(t[n][0]);if(l){e.next=7;break}return e.abrupt("return",r);case 7:if(a=u.getPinName(l),s=t[a],(0,b.default)(s)){e.next=11;break}return e.abrupt("return",[]);case 11:return o=(0,p.default)(s).call(s,function(e){return u.fromPinWithName(e)}),e.next=14,k.default.all(o);case 14:return i=e.sent,i=(o=(0,_.default)(a=[])).call.apply(o,(0,_.default)(a=[a]).call(a,(0,x.default)(i))),e.abrupt("return",(0,j.default)(i).call(i,function(e){return null!=e}));case 17:case"end":return e.stop()}},e)}))()},_serializeObject:function(c,f){var d=this;return(0,s.default)(g.default.mark(function e(){var t,r,n,a,s,o,i,l,u;return g.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t=f){e.next=5;break}return e.next=4,d._getAllContents();case 4:t=e.sent;case 5:if(t[c]&&0!==t[c].length){e.next=7;break}return e.abrupt("return",null);case 7:for(r=t[c][0],n=[],(a={})[s=0]=r,n.push(s);0!==n.length;)for(l in o=n.shift(),i=a[o])(u=i[l]).__type&&"Object"===u.__type&&(u=d.getKeyForObject(u),t[u]&&0<t[u].length&&(u=t[u][0],a[++s]=u,i[l]=u,n.push(s)));return e.abrupt("return",r);case 15:case"end":return e.stop()}},e)}))()},_updateObjectIfPinned:function(n){var a=this;return(0,s.default)(g.default.mark(function e(){var t,r;return g.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(a.isEnabled){e.next=2;break}return e.abrupt("return");case 2:return t=a.getKeyForObject(n),e.next=5,a.fromPinWithName(t);case 5:if((r=e.sent)&&0!==r.length){e.next=8;break}return e.abrupt("return");case 8:return e.abrupt("return",a.pinWithName(t,[n._toFullJSON()]));case 9:case"end":return e.stop()}},e)}))()},_destroyObjectIfPinned:function(o){var i=this;return(0,s.default)(g.default.mark(function e(){var t,r,n,a,s;return g.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(i.isEnabled){e.next=2;break}return e.abrupt("return");case 2:return e.next=4,i._getAllContents();case 4:if(t=e.sent,r=i.getKeyForObject(o),t[r]){e.next=9;break}return e.abrupt("return");case 9:for(a in n=[i.unPinWithName(r)],delete t[r],t)a!==E.DEFAULT_PIN&&!(0,y.default)(a).call(a,E.PIN_PREFIX)||(s=t[a]||[],(0,v.default)(s).call(s,r)&&(0==(s=(0,j.default)(s).call(s,function(e){return e!==r})).length?(n.push(i.unPinWithName(a)),delete t[a]):(n.push(i.pinWithName(a,s)),t[a]=s)));return e.abrupt("return",k.default.all(n));case 13:case"end":return e.stop()}},e)}))()},_updateLocalIdForObject:function(u,c){var f=this;return(0,s.default)(g.default.mark(function e(){var t,r,n,a,s,o,i,l;return g.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(f.isEnabled){e.next=2;break}return e.abrupt("return");case 2:return r=(0,_.default)(t=(0,_.default)(t="".concat(E.OBJECT_PREFIX)).call(t,c.className,"_")).call(t,u),n=f.getKeyForObject(c),e.next=6,f.fromPinWithName(r);case 6:if((a=e.sent)&&0!==a.length){e.next=9;break}return e.abrupt("return");case 9:return s=[f.unPinWithName(r),f.pinWithName(n,a)],e.next=12,f._getAllContents();case 12:for(i in o=e.sent)i!==E.DEFAULT_PIN&&!(0,y.default)(i).call(i,E.PIN_PREFIX)||(l=o[i]||[],(0,v.default)(l).call(l,r)&&((l=(0,j.default)(l).call(l,function(e){return e!==r})).push(n),s.push(f.pinWithName(i,l)),o[i]=l));return e.abrupt("return",k.default.all(s));case 15:case"end":return e.stop()}},e)}))()},updateFromServer:function(){var c=this;return(0,s.default)(g.default.mark(function e(){var t,r,n,a,s,o,i,l,u;return g.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(!c.checkIfEnabled()||c.isSyncing)return e.abrupt("return");e.next=2;break;case 2:return e.next=4,c._getAllContents();case 4:for(r in o=e.sent,t=[],o)(0,y.default)(r).call(r,E.OBJECT_PREFIX)&&t.push(r);if(0===t.length)return e.abrupt("return");e.next=9;break;case 9:c.isSyncing=!0,n={},a=0,s=t;case 12:if(!(a<s.length)){e.next=23;break}if(o=s[a],i=o.split("_"),l=(0,C.default)(i,4),i=l[2],l=l[3],5===o.split("_").length&&"User"===o.split("_")[3]&&(i="_User",l=o.split("_")[4]),(0,y.default)(l).call(l,"local"))return e.abrupt("continue",20);e.next=18;break;case 18:i in n||(n[i]=new w.default),n[i].add(l);case 20:a++,e.next=12;break;case 23:return u=(0,p.default)(u=(0,m.default)(n)).call(u,function(e){var t=(0,d.default)(n[e]),e=new S.default(e);return e.limit(t.length),1===t.length?e.equalTo("objectId",t[0]):e.containedIn("objectId",t),(0,f.default)(e).call(e)}),e.prev=24,e.next=27,k.default.all(u);case 27:return u=e.sent,u=(0,_.default)([]).apply([],u),u=(0,p.default)(u).call(u,function(e){var t=c.getKeyForObject(e);return c.pinWithName(t,e._toFullJSON())}),e.next=32,k.default.all(u);case 32:c.isSyncing=!1,e.next=39;break;case 35:e.prev=35,e.t0=e.catch(24),console.error("Error syncing LocalDatastore: ",e.t0),c.isSyncing=!1;case 39:case"end":return e.stop()}},e,null,[[24,35]])}))()},getKeyForObject:function(e){var t,r=e.objectId||e._getId();return(0,_.default)(e=(0,_.default)(t="".concat(E.OBJECT_PREFIX)).call(t,e.className,"_")).call(e,r)},getPinName:function(e){return e&&e!==E.DEFAULT_PIN?E.PIN_PREFIX+e:E.DEFAULT_PIN},checkIfEnabled:function(){return this.isEnabled||console.error("Parse.enableLocalDatastore() must be called first"),this.isEnabled}};t.exports=n,a.default.setLocalDatastoreController(e("./LocalDatastoreController")),a.default.setLocalDatastore(n)},{"./CoreManager":4,"./LocalDatastoreController":12,"./LocalDatastoreUtils":13,"./ParseQuery":27,"@babel/runtime-corejs3/core-js-stable/array/from":53,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/instance/concat":56,"@babel/runtime-corejs3/core-js-stable/instance/filter":57,"@babel/runtime-corejs3/core-js-stable/instance/find":58,"@babel/runtime-corejs3/core-js-stable/instance/includes":60,"@babel/runtime-corejs3/core-js-stable/instance/keys":62,"@babel/runtime-corejs3/core-js-stable/instance/map":63,"@babel/runtime-corejs3/core-js-stable/instance/slice":65,"@babel/runtime-corejs3/core-js-stable/instance/starts-with":68,"@babel/runtime-corejs3/core-js-stable/object/keys":81,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/core-js-stable/set":86,"@babel/runtime-corejs3/core-js-stable/symbol":87,"@babel/runtime-corejs3/core-js/get-iterator":92,"@babel/runtime-corejs3/core-js/get-iterator-method":91,"@babel/runtime-corejs3/helpers/asyncToGenerator":113,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/slicedToArray":131,"@babel/runtime-corejs3/helpers/toConsumableArray":133,"@babel/runtime-corejs3/regenerator":137}],12:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault"),i=n(e("@babel/runtime-corejs3/core-js/get-iterator")),l=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),u=n(e("@babel/runtime-corejs3/core-js/get-iterator-method")),c=n(e("@babel/runtime-corejs3/core-js-stable/symbol")),f=n(e("@babel/runtime-corejs3/core-js-stable/array/from")),d=n(e("@babel/runtime-corejs3/core-js-stable/instance/slice")),o=n(e("@babel/runtime-corejs3/core-js-stable/instance/map")),p=n(e("@babel/runtime-corejs3/core-js-stable/promise")),a=n(e("@babel/runtime-corejs3/core-js-stable/instance/reduce")),s=n(e("@babel/runtime-corejs3/core-js-stable/json/stringify")),b=n(e("@babel/runtime-corejs3/regenerator")),h=n(e("@babel/runtime-corejs3/helpers/asyncToGenerator")),y=e("./LocalDatastoreUtils"),m=n(e("./Storage"));function v(e,t){var r;if(void 0===c.default||null==(0,u.default)(e)){if((0,l.default)(e)||(r=function(e,t){if(!e)return;if("string"==typeof e)return j(e,t);var r=(0,d.default)(r=Object.prototype.toString.call(e)).call(r,8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return(0,f.default)(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return j(e,t)}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,t=function(){};return{s:t,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:t}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){r=(0,i.default)(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==r.return||r.return()}finally{if(o)throw a}}}}function j(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}e={fromPinWithName:function(n){return(0,h.default)(b.default.mark(function e(){var t,r;return b.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,m.default.getItemAsync(n);case 2:if(t=e.sent){e.next=5;break}return e.abrupt("return",[]);case 5:return r=JSON.parse(t),e.abrupt("return",r);case 7:case"end":return e.stop()}},e)}))()},pinWithName:function(e,t){t=(0,s.default)(t);return m.default.setItemAsync(e,t)},unPinWithName:function(e){return m.default.removeItemAsync(e)},getAllContents:function(){return(0,h.default)(b.default.mark(function e(){var t;return b.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,m.default.getAllKeysAsync();case 2:return t=e.sent,e.abrupt("return",(0,a.default)(t).call(t,function(){var e=(0,h.default)(b.default.mark(function e(t,r){var n,a;return b.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t;case 2:if(n=e.sent,(0,y.isLocalDatastoreKey)(r))return e.next=6,m.default.getItemAsync(r);e.next=8;break;case 6:a=e.sent;try{n[r]=JSON.parse(a)}catch(e){console.error("Error getAllContents: ",e)}case 8:return e.abrupt("return",n);case 9:case"end":return e.stop()}},e)}));return function(){return e.apply(this,arguments)}}(),p.default.resolve({})));case 4:case"end":return e.stop()}},e)}))()},getRawStorage:function(){return(0,h.default)(b.default.mark(function e(){var t;return b.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,m.default.getAllKeysAsync();case 2:return t=e.sent,e.abrupt("return",(0,a.default)(t).call(t,function(){var e=(0,h.default)(b.default.mark(function e(t,r){var n,a;return b.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,t;case 2:return n=e.sent,e.next=5,m.default.getItemAsync(r);case 5:return a=e.sent,n[r]=a,e.abrupt("return",n);case 8:case"end":return e.stop()}},e)}));return function(){return e.apply(this,arguments)}}(),p.default.resolve({})));case 4:case"end":return e.stop()}},e)}))()},clear:function(){var s=this;return(0,h.default)(b.default.mark(function e(){var t,r,n,a;return b.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,m.default.getAllKeysAsync();case 2:a=e.sent,t=[],r=v(a);try{for(r.s();!(n=r.n()).done;)n=n.value,(0,y.isLocalDatastoreKey)(n)&&t.push(n)}catch(e){r.e(e)}finally{r.f()}return a=(0,o.default)(t).call(t,s.unPinWithName),e.abrupt("return",p.default.all(a));case 8:case"end":return e.stop()}},e)}))()}};t.exports=e},{"./LocalDatastoreUtils":13,"./Storage":37,"@babel/runtime-corejs3/core-js-stable/array/from":53,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/instance/map":63,"@babel/runtime-corejs3/core-js-stable/instance/reduce":64,"@babel/runtime-corejs3/core-js-stable/instance/slice":65,"@babel/runtime-corejs3/core-js-stable/json/stringify":70,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/core-js-stable/symbol":87,"@babel/runtime-corejs3/core-js/get-iterator":92,"@babel/runtime-corejs3/core-js/get-iterator-method":91,"@babel/runtime-corejs3/helpers/asyncToGenerator":113,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/regenerator":137}],13:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.isLocalDatastoreKey=function(e){return!(!e||e!==s&&!(0,a.default)(e).call(e,o)&&!(0,a.default)(e).call(e,i))},r.OBJECT_PREFIX=r.PIN_PREFIX=r.DEFAULT_PIN=void 0;var a=n(e("@babel/runtime-corejs3/core-js-stable/instance/starts-with")),s="_default";r.DEFAULT_PIN=s;var o="parsePin_";r.PIN_PREFIX=o;var i="Parse_LDS_";r.OBJECT_PREFIX=i},{"@babel/runtime-corejs3/core-js-stable/instance/starts-with":68,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],14:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.defaultState=function(){return{serverData:{},pendingOps:[{}],objectCache:{},tasks:new a.default,existed:!1}},r.setServerData=function(e,t){for(var r in t)void 0!==t[r]?e[r]=t[r]:delete e[r]},r.setPendingOp=function(e,t,r){var n=e.length-1;r?e[n][t]=r:delete e[n][t]},r.pushPendingState=function(e){e.push({})},r.popPendingState=b,r.mergeFirstPendingState=function(e){var t,r=b(e),n=e[0];for(t in r){var a;n[t]&&r[t]?(a=n[t].mergeWith(r[t]))&&(n[t]=a):n[t]=r[t]}},r.estimateAttribute=function(e,t,r,n,a){for(var s=e[a],o=0;o<t.length;o++)t[o][a]&&(t[o][a]instanceof p.RelationOp?n&&(s=t[o][a].applyTo(s,{className:r,id:n},a)):s=t[o][a].applyTo(s));return s},r.estimateAttributes=function(e,t,r,n){var a,s={};for(a in e)s[a]=e[a];for(var o=0;o<t.length;o++)for(a in t[o])if(t[o][a]instanceof p.RelationOp)n&&(s[a]=t[o][a].applyTo(s[a],{className:r,id:n},a));else if((0,d.default)(a).call(a,".")){for(var i=a.split("."),l=i[i.length-1],u=(0,f.default)({},s),c=0;c<i.length-1;c++)u=u[i[c]];u[l]=t[o][a].applyTo(u[l])}else s[a]=t[o][a].applyTo(s[a]);return s},r.commitServerChanges=function(e,t,r){for(var n in r){var a=r[n];!(e[n]=a)||"object"!==(0,o.default)(a)||a instanceof u.default||a instanceof l.default||a instanceof c.default||(a=(0,i.default)(a,!1,!0),t[n]=(0,s.default)(a))}};var s=n(e("@babel/runtime-corejs3/core-js-stable/json/stringify")),o=n(e("@babel/runtime-corejs3/helpers/typeof")),f=n(e("@babel/runtime-corejs3/core-js-stable/object/assign")),d=n(e("@babel/runtime-corejs3/core-js-stable/instance/includes")),i=n(e("./encode")),l=n(e("./ParseFile")),u=n(e("./ParseObject")),c=n(e("./ParseRelation")),a=n(e("./TaskQueue")),p=e("./ParseOp");function b(e){var t=e.shift();return e.length||(e[0]={}),t}},{"./ParseFile":20,"./ParseObject":24,"./ParseOp":25,"./ParseRelation":28,"./TaskQueue":39,"./encode":45,"@babel/runtime-corejs3/core-js-stable/instance/includes":60,"@babel/runtime-corejs3/core-js-stable/json/stringify":70,"@babel/runtime-corejs3/core-js-stable/object/assign":72,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/typeof":134}],15:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault"),i=n(e("@babel/runtime-corejs3/core-js/get-iterator")),l=n(e("@babel/runtime-corejs3/core-js/get-iterator-method")),u=n(e("@babel/runtime-corejs3/core-js-stable/symbol")),c=n(e("@babel/runtime-corejs3/core-js-stable/array/from")),a=n(e("@babel/runtime-corejs3/core-js-stable/object/keys")),s=n(e("@babel/runtime-corejs3/core-js-stable/instance/for-each")),D=n(e("@babel/runtime-corejs3/core-js-stable/instance/map")),L=n(e("@babel/runtime-corejs3/core-js-stable/instance/filter")),M=n(e("@babel/runtime-corejs3/helpers/typeof")),q=n(e("@babel/runtime-corejs3/core-js-stable/instance/slice")),U=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),F=n(e("@babel/runtime-corejs3/core-js-stable/instance/index-of"));function K(e,t){var r;if(void 0===u.default||null==(0,l.default)(e)){if((0,U.default)(e)||(r=function(e,t){if(!e)return;if("string"==typeof e)return f(e,t);var r=(0,q.default)(r=Object.prototype.toString.call(e)).call(r,8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return(0,c.default)(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return f(e,t)}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,t=function(){};return{s:t,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:t}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){r=(0,i.default)(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==r.return||r.return()}finally{if(o)throw a}}}}function f(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var W=e("./equals").default,z=e("./decode").default,B=e("./ParseError").default,J=e("./ParsePolygon").default,Q=e("./ParseGeoPoint").default;function V(e,t){if(!t||!t.__type||"Pointer"!==t.__type&&"Object"!==t.__type)return-1<(0,F.default)(e).call(e,t);for(var r in e){var n=e[r];if("string"==typeof n&&n===t.objectId)return 1;if(n.className===t.className&&n.objectId===t.objectId)return 1}}function G(e){return e._toFullJSON?e._toFullJSON():e}function $(e,t,r,n){if(t.className!==e)return!1;var a,s=t,o=n;for(a in t.toJSON&&(s=t.toJSON()),n.toJSON&&(o=n.toJSON().where),s.className=e,o)if(!function e(t,r,n,a,s){if(null===s)return!1;if(0<=(0,F.default)(a).call(a,".")){var o=a.split("."),i=o[0],o=(0,q.default)(o).call(o,1).join(".");return e(t,r[i]||{},n,o,s)}var l;if("$or"===a){for(l=0;l<s.length;l++)if($(t,r,n,s[l]))return!0;return!1}if("$and"===a){for(l=0;l<s.length;l++)if(!$(t,r,n,s[l]))return!1;return!0}if("$nor"===a){for(l=0;l<s.length;l++)if($(t,r,n,s[l]))return!1;return!0}if("$relatedTo"===a)return!1;if(!/^[A-Za-z][0-9A-Za-z_]*$/.test(a))throw new B(B.INVALID_KEY_NAME,"Invalid Key: ".concat(a));if("object"!==(0,M.default)(s)){return(0,U.default)(r[a])?-1<(0,F.default)(o=r[a]).call(o,s):r[a]===s}var u;if(s.__type)return"Pointer"===s.__type?H(r[a],s,function(e,t){return void 0!==e&&t.className===e.className&&t.objectId===e.objectId}):H(z(r[a]),z(s),W);for(var c in s)switch((u=s[c]).__type&&(u=z(u)),"[object Date]"!==toString.call(u)&&("string"!=typeof u||"Invalid Date"===new Date(u)||isNaN(new Date(u)))||(r[a]=new Date(r[a].iso?r[a].iso:r[a])),c){case"$lt":if(r[a]>=u)return!1;break;case"$lte":if(r[a]>u)return!1;break;case"$gt":if(r[a]<=u)return!1;break;case"$gte":if(r[a]<u)return!1;break;case"$ne":if(W(r[a],u))return!1;break;case"$in":if(!V(u,r[a]))return!1;break;case"$nin":if(V(u,r[a]))return!1;break;case"$all":for(l=0;l<u.length;l++){var f;if((0,F.default)(f=r[a]).call(f,u[l])<0)return!1}break;case"$exists":var d=void 0!==r[a],p=s.$exists;if("boolean"!=typeof s.$exists)break;if(!d&&p||d&&!p)return!1;break;case"$regex":if("object"===(0,M.default)(u))return u.test(r[a]);for(var b="",h=-2,y=(0,F.default)(u).call(u,"\\Q");-1<y;)b+=u.substring(h+2,y),-1<(h=(0,F.default)(u).call(u,"\\E",y))&&(b+=u.substring(y+2,h).replace(/\\\\\\\\E/g,"\\E").replace(/\W/g,"\\$&")),y=(0,F.default)(u).call(u,"\\Q",h);b+=u.substring(Math.max(y,h+2));p=s.$options||"";p=p.replace("x","").replace("s","");var p=new RegExp(b,p);if(!p.test(r[a]))return!1;break;case"$nearSphere":if(!u||!r[a])return!1;var m=u.radiansTo(r[a]),v=s.$maxDistance||1/0;return m<=v;case"$within":if(!u||!r[a])return!1;var m=u.$box[0],v=u.$box[1];return m.latitude>v.latitude||m.longitude>v.longitude?!1:r[a].latitude>m.latitude&&r[a].latitude<v.latitude&&r[a].longitude>m.longitude&&r[a].longitude<v.longitude;case"$options":case"$maxDistance":break;case"$select":for(var j=(0,L.default)(n).call(n,function(e,t,r){return $(u.query.className,e,r,u.query.where)}),g=0;g<j.length;g+=1){var _=G(j[g]);return W(r[a],_[u.key])}return!1;case"$dontSelect":for(var w=(0,L.default)(n).call(n,function(e,t,r){return $(u.query.className,e,r,u.query.where)}),x=0;x<w.length;x+=1){var k=G(w[x]);return!W(r[a],k[u.key])}return!1;case"$inQuery":for(var C=(0,L.default)(n).call(n,function(e,t,r){return $(u.className,e,r,u.where)}),S=0;S<C.length;S+=1){var E=G(C[S]);if(r[a].className===E.className&&r[a].objectId===E.objectId)return!0}return!1;case"$notInQuery":for(var O=(0,L.default)(n).call(n,function(e,t,r){return $(u.className,e,r,u.where)}),P=0;P<O.length;P+=1){var A=G(O[P]);if(r[a].className===A.className&&r[a].objectId===A.objectId)return!1}return!0;case"$containedBy":var T=K(r[a]);try{for(T.s();!(R=T.n()).done;){var R=R.value;if(!V(u,R))return!1}}catch(e){T.e(e)}finally{T.f()}return!0;case"$geoWithin":var I=(0,D.default)(N=u.$polygon).call(N,function(e){return[e.latitude,e.longitude]}),N=new J(I);return N.containsPoint(r[a]);case"$geoIntersects":var I=new J(r[a].coordinates),N=new Q(u.$point);return I.containsPoint(N);default:return!1}return!0}(e,s,r,a,o[a]))return!1;return!0}function H(e,t,r){if((0,U.default)(e)){for(var n=0;n<e.length;n++)if(r(e[n],t))return!0;return!1}return r(e,t)}e={matchesQuery:$,validateQuery:function(e){var t=e;e.toJSON&&(t=e.toJSON().where);var r=["$and","$or","$nor","_rperm","_wperm","_perishable_token","_email_verify_token","_email_verify_token_expires_at","_account_lockout_expires_at","_failed_login_count"];(0,s.default)(e=(0,a.default)(t)).call(e,function(e){if(t&&t[e]&&t[e].$regex&&"string"==typeof t[e].$options&&!t[e].$options.match(/^[imxs]+$/))throw new B(B.INVALID_QUERY,"Bad $options value for query: ".concat(t[e].$options));if((0,F.default)(r).call(r,e)<0&&!e.match(/^[a-zA-Z][a-zA-Z0-9_\.]*$/))throw new B(B.INVALID_KEY_NAME,"Invalid key name: ".concat(e))})}};t.exports=e},{"./ParseError":19,"./ParseGeoPoint":21,"./ParsePolygon":26,"./decode":44,"./equals":46,"@babel/runtime-corejs3/core-js-stable/array/from":53,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/instance/filter":57,"@babel/runtime-corejs3/core-js-stable/instance/for-each":59,"@babel/runtime-corejs3/core-js-stable/instance/index-of":61,"@babel/runtime-corejs3/core-js-stable/instance/map":63,"@babel/runtime-corejs3/core-js-stable/instance/slice":65,"@babel/runtime-corejs3/core-js-stable/object/keys":81,"@babel/runtime-corejs3/core-js-stable/symbol":87,"@babel/runtime-corejs3/core-js/get-iterator":92,"@babel/runtime-corejs3/core-js/get-iterator-method":91,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/typeof":134}],16:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireWildcard"),a=e("@babel/runtime-corejs3/helpers/interopRequireDefault"),s=a(e("@babel/runtime-corejs3/core-js-stable/promise")),o=a(e("./decode")),i=a(e("./encode")),l=a(e("./CoreManager")),u=a(e("./CryptoController")),c=a(e("./InstallationController")),n=n(e("./ParseOp")),a=a(e("./RESTController")),f={initialize:function(e,t){f._initialize(e,t)},_initialize:function(e,t,r){l.default.set("APPLICATION_ID",e),l.default.set("JAVASCRIPT_KEY",t),l.default.set("MASTER_KEY",r),l.default.set("USE_MASTER_KEY",!1)},setAsyncStorage:function(e){l.default.setAsyncStorage(e)},setLocalDatastoreController:function(e){l.default.setLocalDatastoreController(e)},set applicationId(e){l.default.set("APPLICATION_ID",e)},get applicationId(){return l.default.get("APPLICATION_ID")},set javaScriptKey(e){l.default.set("JAVASCRIPT_KEY",e)},get javaScriptKey(){return l.default.get("JAVASCRIPT_KEY")},set masterKey(e){l.default.set("MASTER_KEY",e)},get masterKey(){return l.default.get("MASTER_KEY")},set serverURL(e){l.default.set("SERVER_URL",e)},get serverURL(){return l.default.get("SERVER_URL")},set serverAuthToken(e){l.default.set("SERVER_AUTH_TOKEN",e)},get serverAuthToken(){return l.default.get("SERVER_AUTH_TOKEN")},set serverAuthType(e){l.default.set("SERVER_AUTH_TYPE",e)},get serverAuthType(){return l.default.get("SERVER_AUTH_TYPE")},set liveQueryServerURL(e){l.default.set("LIVEQUERY_SERVER_URL",e)},get liveQueryServerURL(){return l.default.get("LIVEQUERY_SERVER_URL")},set encryptedUser(e){l.default.set("ENCRYPTED_USER",e)},get encryptedUser(){return l.default.get("ENCRYPTED_USER")},set secret(e){l.default.set("ENCRYPTED_KEY",e)},get secret(){return l.default.get("ENCRYPTED_KEY")},set idempotency(e){l.default.set("IDEMPOTENCY",e)},get idempotency(){return l.default.get("IDEMPOTENCY")}};f.ACL=e("./ParseACL").default,f.Analytics=e("./Analytics"),f.AnonymousUtils=e("./AnonymousUtils").default,f.Cloud=e("./Cloud"),f.CoreManager=e("./CoreManager"),f.Config=e("./ParseConfig").default,f.Error=e("./ParseError").default,f.FacebookUtils=e("./FacebookUtils").default,f.File=e("./ParseFile").default,f.GeoPoint=e("./ParseGeoPoint").default,f.Polygon=e("./ParsePolygon").default,f.Installation=e("./ParseInstallation").default,f.LocalDatastore=e("./LocalDatastore"),f.Object=e("./ParseObject").default,f.Op={Set:n.SetOp,Unset:n.UnsetOp,Increment:n.IncrementOp,Add:n.AddOp,Remove:n.RemoveOp,AddUnique:n.AddUniqueOp,Relation:n.RelationOp},f.Push=e("./Push"),f.Query=e("./ParseQuery").default,f.Relation=e("./ParseRelation").default,f.Role=e("./ParseRole").default,f.Schema=e("./ParseSchema").default,f.Session=e("./ParseSession").default,f.Storage=e("./Storage"),f.User=e("./ParseUser").default,f.LiveQuery=e("./ParseLiveQuery").default,f.LiveQueryClient=e("./LiveQueryClient").default,f._request=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return l.default.getRESTController().request.apply(null,t)},f._ajax=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return l.default.getRESTController().ajax.apply(null,t)},f._decode=function(e,t){return(0,o.default)(t)},f._encode=function(e,t,r){return(0,i.default)(e,r)},f._getInstallationId=function(){return l.default.getInstallationController().currentInstallationId()},f.enableLocalDatastore=function(){f.LocalDatastore.isEnabled=!0},f.isLocalDatastoreEnabled=function(){return f.LocalDatastore.isEnabled},f.dumpLocalDatastore=function(){return f.LocalDatastore.isEnabled?f.LocalDatastore._getAllContents():(console.log("Parse.enableLocalDatastore() must be called first"),s.default.resolve({}))},f.enableEncryptedUser=function(){f.encryptedUser=!0},f.isEncryptedUserEnabled=function(){return f.encryptedUser},l.default.setCryptoController(u.default),l.default.setInstallationController(c.default),l.default.setRESTController(a.default),f.Parse=f,t.exports=f},{"./Analytics":1,"./AnonymousUtils":2,"./Cloud":3,"./CoreManager":4,"./CryptoController":5,"./FacebookUtils":7,"./InstallationController":8,"./LiveQueryClient":9,"./LocalDatastore":11,"./ParseACL":17,"./ParseConfig":18,"./ParseError":19,"./ParseFile":20,"./ParseGeoPoint":21,"./ParseInstallation":22,"./ParseLiveQuery":23,"./ParseObject":24,"./ParseOp":25,"./ParsePolygon":26,"./ParseQuery":27,"./ParseRelation":28,"./ParseRole":29,"./ParseSchema":30,"./ParseSession":31,"./ParseUser":32,"./Push":33,"./RESTController":34,"./Storage":37,"./decode":44,"./encode":45,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/interopRequireWildcard":122}],17:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a=n(e("@babel/runtime-corejs3/core-js-stable/object/keys")),o=n(e("@babel/runtime-corejs3/helpers/typeof")),i=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),l=n(e("@babel/runtime-corejs3/helpers/createClass")),u=n(e("@babel/runtime-corejs3/helpers/defineProperty")),c=n(e("./ParseRole")),f=n(e("./ParseUser")),e=function(){function s(e){if((0,i.default)(this,s),(0,u.default)(this,"permissionsById",void 0),this.permissionsById={},e&&"object"===(0,o.default)(e))if(e instanceof f.default)this.setReadAccess(e,!0),this.setWriteAccess(e,!0);else for(var t in e){var r,n=e[t];for(r in this.permissionsById[t]={},n){var a=n[r];if("read"!==r&&"write"!==r)throw new TypeError("Tried to create an ACL with an invalid permission type.");if("boolean"!=typeof a)throw new TypeError("Tried to create an ACL with an invalid permission value.");this.permissionsById[t][r]=a}}else if("function"==typeof e)throw new TypeError("ParseACL constructed with a function. Did you forget ()?")}return(0,l.default)(s,[{key:"toJSON",value:function(){var e,t={};for(e in this.permissionsById)t[e]=this.permissionsById[e];return t}},{key:"equals",value:function(e){if(!(e instanceof s))return!1;var t,r=(0,a.default)(this.permissionsById),n=(0,a.default)(e.permissionsById);if(r.length!==n.length)return!1;for(t in this.permissionsById){if(!e.permissionsById[t])return!1;if(this.permissionsById[t].read!==e.permissionsById[t].read)return!1;if(this.permissionsById[t].write!==e.permissionsById[t].write)return!1}return!0}},{key:"_setAccess",value:function(e,t,r){if(t instanceof f.default)t=t.id;else if(t instanceof c.default){var n=t.getName();if(!n)throw new TypeError("Role must have a name");t="role:"+n}if("string"!=typeof t)throw new TypeError("userId must be a string.");if("boolean"!=typeof r)throw new TypeError("allowed must be either true or false.");n=this.permissionsById[t];if(!n){if(!r)return;n={},this.permissionsById[t]=n}r?this.permissionsById[t][e]=!0:(delete n[e],0===(0,a.default)(n).length&&delete this.permissionsById[t])}},{key:"_getAccess",value:function(e,t){if(t instanceof f.default){if(!(t=t.id))throw new Error("Cannot get access for a ParseUser without an ID")}else if(t instanceof c.default){var r=t.getName();if(!r)throw new TypeError("Role must have a name");t="role:"+r}t=this.permissionsById[t];return!!t&&!!t[e]}},{key:"setReadAccess",value:function(e,t){this._setAccess("read",e,t)}},{key:"getReadAccess",value:function(e){return this._getAccess("read",e)}},{key:"setWriteAccess",value:function(e,t){this._setAccess("write",e,t)}},{key:"getWriteAccess",value:function(e){return this._getAccess("write",e)}},{key:"setPublicReadAccess",value:function(e){this.setReadAccess("*",e)}},{key:"getPublicReadAccess",value:function(){return this.getReadAccess("*")}},{key:"setPublicWriteAccess",value:function(e){this.setWriteAccess("*",e)}},{key:"getPublicWriteAccess",value:function(){return this.getWriteAccess("*")}},{key:"getRoleReadAccess",value:function(e){if(e instanceof c.default&&(e=e.getName()),"string"!=typeof e)throw new TypeError("role must be a ParseRole or a String");return this.getReadAccess("role:"+e)}},{key:"getRoleWriteAccess",value:function(e){if(e instanceof c.default&&(e=e.getName()),"string"!=typeof e)throw new TypeError("role must be a ParseRole or a String");return this.getWriteAccess("role:"+e)}},{key:"setRoleReadAccess",value:function(e,t){if(e instanceof c.default&&(e=e.getName()),"string"!=typeof e)throw new TypeError("role must be a ParseRole or a String");this.setReadAccess("role:"+e,t)}},{key:"setRoleWriteAccess",value:function(e,t){if(e instanceof c.default&&(e=e.getName()),"string"!=typeof e)throw new TypeError("role must be a ParseRole or a String");this.setWriteAccess("role:"+e,t)}}]),s}();r.default=e},{"./ParseRole":29,"./ParseUser":32,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/object/keys":81,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/defineProperty":117,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/typeof":134}],18:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a=n(e("@babel/runtime-corejs3/core-js-stable/json/stringify")),s=n(e("@babel/runtime-corejs3/helpers/typeof")),o=n(e("@babel/runtime-corejs3/core-js-stable/promise")),i=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),l=n(e("@babel/runtime-corejs3/helpers/createClass")),u=n(e("@babel/runtime-corejs3/helpers/defineProperty")),c=n(e("./CoreManager")),f=n(e("./decode")),d=n(e("./encode")),p=n(e("./escape")),b=n(e("./ParseError")),h=n(e("./Storage")),y=function(){function e(){(0,i.default)(this,e),(0,u.default)(this,"attributes",void 0),(0,u.default)(this,"_escapedAttributes",void 0),this.attributes={},this._escapedAttributes={}}return(0,l.default)(e,[{key:"get",value:function(e){return this.attributes[e]}},{key:"escape",value:function(e){var t=this._escapedAttributes[e];if(t)return t;var r=this.attributes[e],t="";return null!=r&&(t=(0,p.default)(r.toString())),this._escapedAttributes[e]=t}}],[{key:"current",value:function(){return c.default.getConfigController().current()}},{key:"get",value:function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};return c.default.getConfigController().get(e)}},{key:"save",value:function(e,t){var r=c.default.getConfigController();return r.save(e,t).then(function(){return r.get({useMasterKey:!0})},function(e){return o.default.reject(e)})}},{key:"_clearCache",value:function(){m=null}}]),e}(),m=null,v="currentConfig";function j(e){try{var t=JSON.parse(e);if(t&&"object"===(0,s.default)(t))return(0,f.default)(t)}catch(e){return null}}e={current:function(){if(m)return m;var t=new y,e=h.default.generatePath(v);if(h.default.async())return h.default.getItemAsync(e).then(function(e){return!e||(e=j(e))&&(t.attributes=e,m=t),t});e=h.default.getItem(e);return!e||(e=j(e))&&(t.attributes=e,m=t),t},get:function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};return c.default.getRESTController().request("GET","config",{},e).then(function(e){if(!e||!e.params){var t=new b.default(b.default.INVALID_JSON,"Config JSON response invalid.");return o.default.reject(t)}var r,n=new y;for(r in n.attributes={},e.params)n.attributes[r]=(0,f.default)(e.params[r]);return m=n,h.default.setItemAsync(h.default.generatePath(v),(0,a.default)(e.params)).then(function(){return n})})},save:function(e,t){var r,n=c.default.getRESTController(),a={};for(r in e)a[r]=(0,d.default)(e[r]);return n.request("PUT","config",{params:a,masterKeyOnly:t},{useMasterKey:!0}).then(function(e){if(e&&e.result)return o.default.resolve();e=new b.default(b.default.INTERNAL_SERVER_ERROR,"Error occured updating Config.");return o.default.reject(e)})}};c.default.setConfigController(e),r.default=y},{"./CoreManager":4,"./ParseError":19,"./Storage":37,"./decode":44,"./encode":45,"./escape":47,"@babel/runtime-corejs3/core-js-stable/json/stringify":70,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/defineProperty":117,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/typeof":134}],19:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a=n(e("@babel/runtime-corejs3/core-js-stable/reflect/construct")),s=n(e("@babel/runtime-corejs3/core-js-stable/object/define-property")),o=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),i=n(e("@babel/runtime-corejs3/helpers/createClass")),l=n(e("@babel/runtime-corejs3/helpers/assertThisInitialized")),u=n(e("@babel/runtime-corejs3/helpers/inherits")),c=n(e("@babel/runtime-corejs3/helpers/possibleConstructorReturn")),f=n(e("@babel/runtime-corejs3/helpers/getPrototypeOf"));function d(r){var n=function(){if("undefined"==typeof Reflect||!a.default)return!1;if(a.default.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call((0,a.default)(Date,[],function(){})),!0}catch(e){return!1}}();return function(){var e,t=(0,f.default)(r);return t=n?(e=(0,f.default)(this).constructor,(0,a.default)(t,arguments,e)):t.apply(this,arguments),(0,c.default)(this,t)}}e=function(e){(0,u.default)(a,e);var n=d(a);function a(e,t){var r;return(0,o.default)(this,a),(r=n.call(this,t)).code=e,(0,s.default)((0,l.default)(r),"message",{enumerable:!0,value:t}),r}return(0,i.default)(a,[{key:"toString",value:function(){return"ParseError: "+this.code+" "+this.message}}]),a}((0,n(e("@babel/runtime-corejs3/helpers/wrapNativeSuper")).default)(Error));e.OTHER_CAUSE=-1,e.INTERNAL_SERVER_ERROR=1,e.CONNECTION_FAILED=100,e.OBJECT_NOT_FOUND=101,e.INVALID_QUERY=102,e.INVALID_CLASS_NAME=103,e.MISSING_OBJECT_ID=104,e.INVALID_KEY_NAME=105,e.INVALID_POINTER=106,e.INVALID_JSON=107,e.COMMAND_UNAVAILABLE=108,e.NOT_INITIALIZED=109,e.INCORRECT_TYPE=111,e.INVALID_CHANNEL_NAME=112,e.PUSH_MISCONFIGURED=115,e.OBJECT_TOO_LARGE=116,e.OPERATION_FORBIDDEN=119,e.CACHE_MISS=120,e.INVALID_NESTED_KEY=121,e.INVALID_FILE_NAME=122,e.INVALID_ACL=123,e.TIMEOUT=124,e.INVALID_EMAIL_ADDRESS=125,e.MISSING_CONTENT_TYPE=126,e.MISSING_CONTENT_LENGTH=127,e.INVALID_CONTENT_LENGTH=128,e.FILE_TOO_LARGE=129,e.FILE_SAVE_ERROR=130,e.DUPLICATE_VALUE=137,e.INVALID_ROLE_NAME=139,e.EXCEEDED_QUOTA=140,e.SCRIPT_FAILED=141,e.VALIDATION_ERROR=142,e.INVALID_IMAGE_DATA=143,e.UNSAVED_FILE_ERROR=151,e.INVALID_PUSH_TIME_ERROR=152,e.FILE_DELETE_ERROR=153,e.REQUEST_LIMIT_EXCEEDED=155,e.DUPLICATE_REQUEST=159,e.INVALID_EVENT_NAME=160,e.USERNAME_MISSING=200,e.PASSWORD_MISSING=201,e.USERNAME_TAKEN=202,e.EMAIL_TAKEN=203,e.EMAIL_MISSING=204,e.EMAIL_NOT_FOUND=205,e.SESSION_MISSING=206,e.MUST_CREATE_USER_THROUGH_SIGNUP=207,e.ACCOUNT_ALREADY_LINKED=208,e.INVALID_SESSION_TOKEN=209,e.LINKED_ID_MISSING=250,e.INVALID_LINKED_SESSION=251,e.UNSUPPORTED_SERVICE=252,e.INVALID_SCHEMA_OPERATION=255,e.AGGREGATE_ERROR=600,e.FILE_READ_ERROR=601,e.X_DOMAIN_REQUEST=602,r.default=e},{"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/reflect/construct":84,"@babel/runtime-corejs3/helpers/assertThisInitialized":112,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/getPrototypeOf":119,"@babel/runtime-corejs3/helpers/inherits":120,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/possibleConstructorReturn":129,"@babel/runtime-corejs3/helpers/wrapNativeSuper":136}],20:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a=n(e("@babel/runtime-corejs3/core-js-stable/object/define-property")),s=n(e("@babel/runtime-corejs3/core-js-stable/object/define-properties")),o=n(e("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptors")),i=n(e("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor")),l=n(e("@babel/runtime-corejs3/core-js-stable/instance/filter")),u=n(e("@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols")),c=n(e("@babel/runtime-corejs3/helpers/slicedToArray")),f=n(e("@babel/runtime-corejs3/core-js-stable/promise")),d=n(e("@babel/runtime-corejs3/core-js-stable/object/keys")),p=n(e("@babel/runtime-corejs3/core-js-stable/instance/for-each")),b=n(e("@babel/runtime-corejs3/helpers/typeof")),h=n(e("@babel/runtime-corejs3/regenerator")),y=n(e("@babel/runtime-corejs3/helpers/asyncToGenerator")),m=n(e("@babel/runtime-corejs3/core-js-stable/instance/slice")),v=n(e("@babel/runtime-corejs3/core-js-stable/instance/index-of")),j=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),g=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),_=n(e("@babel/runtime-corejs3/helpers/createClass")),w=n(e("@babel/runtime-corejs3/helpers/defineProperty")),x=n(e("./CoreManager"));function k(t,e){var r,n=(0,d.default)(t);return u.default&&(r=(0,u.default)(t),e&&(r=(0,l.default)(r).call(r,function(e){return(0,i.default)(t,e).enumerable})),n.push.apply(n,r)),n}function C(t){for(var e=1;e<arguments.length;e++){var r,n=null!=arguments[e]?arguments[e]:{};e%2?(0,p.default)(r=k(Object(n),!0)).call(r,function(e){(0,w.default)(t,e,n[e])}):o.default?(0,s.default)(t,(0,o.default)(n)):(0,p.default)(r=k(Object(n))).call(r,function(e){(0,a.default)(t,e,(0,i.default)(n,e))})}return t}var S=null;"undefined"!=typeof XMLHttpRequest&&(S=XMLHttpRequest),S=e("./Xhr.weapp");var E=/^data:([a-zA-Z]+\/[-a-zA-Z0-9+.]+)(;charset=[a-zA-Z0-9\-\/]*)?;base64,/;function O(e){if(e<26)return String.fromCharCode(65+e);if(e<52)return String.fromCharCode(e-26+97);if(e<62)return String.fromCharCode(e-52+48);if(62===e)return"+";if(63===e)return"/";throw new TypeError("Tried to encode large digit "+e+" in base64.")}var P,A=function(){function s(e,t,r,n,a){(0,g.default)(this,s),(0,w.default)(this,"_name",void 0),(0,w.default)(this,"_url",void 0),(0,w.default)(this,"_source",void 0),(0,w.default)(this,"_previousSave",void 0),(0,w.default)(this,"_data",void 0),(0,w.default)(this,"_requestTask",void 0),(0,w.default)(this,"_metadata",void 0),(0,w.default)(this,"_tags",void 0);r=r||"";if(this._name=e,this._metadata=n||{},this._tags=a||{},void 0!==t)if((0,j.default)(t))this._data=s.encodeBase64(t),this._source={format:"base64",base64:this._data,type:r};else if("undefined"!=typeof Blob&&t instanceof Blob)this._source={format:"file",file:t,type:r};else if(t&&"string"==typeof t.uri&&void 0!==t.uri)this._source={format:"uri",uri:t.uri,type:r};else{if(!t||"string"!=typeof t.base64)throw new TypeError("Cannot create a Parse.File with that data.");n=t.base64,a=(0,v.default)(n).call(n,",");-1!==a?(t=E.exec((0,m.default)(n).call(n,0,a+1)),this._data=(0,m.default)(n).call(n,a+1),this._source={format:"base64",base64:this._data,type:t[1]}):(this._data=n,this._source={format:"base64",base64:n,type:r})}}var e;return(0,_.default)(s,[{key:"getData",value:(e=(0,y.default)(h.default.mark(function e(){var t,r,n=this;return h.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this._data)return e.abrupt("return",this._data);e.next=2;break;case 2:if(this._url){e.next=4;break}throw new Error("Cannot retrieve data for unsaved ParseFile.");case 4:return r={requestTask:function(e){return n._requestTask=e}},t=x.default.getFileController(),e.next=8,t.download(this._url,r);case 8:return r=e.sent,this._data=r.base64,e.abrupt("return",this._data);case 11:case"end":return e.stop()}},e,this)})),function(){return e.apply(this,arguments)})},{key:"name",value:function(){return this._name}},{key:"url",value:function(e){if(e=e||{},this._url)return e.forceSecure?this._url.replace(/^http:\/\//i,"https://"):this._url}},{key:"metadata",value:function(){return this._metadata}},{key:"tags",value:function(){return this._tags}},{key:"save",value:function(r){var n=this;(r=r||{}).requestTask=function(e){return n._requestTask=e},r.metadata=this._metadata,r.tags=this._tags;var a=x.default.getFileController();if(this._previousSave||("file"===this._source.format?this._previousSave=a.saveFile(this._name,this._source,r).then(function(e){return n._name=e.name,n._url=e.url,n._data=null,n._requestTask=null,n}):"uri"===this._source.format?this._previousSave=a.download(this._source.uri,r).then(function(e){if(!e||!e.base64)return{};var t={format:"base64",base64:e.base64,type:e.contentType};return n._data=e.base64,n._requestTask=null,a.saveBase64(n._name,t,r)}).then(function(e){return n._name=e.name,n._url=e.url,n._requestTask=null,n}):this._previousSave=a.saveBase64(this._name,this._source,r).then(function(e){return n._name=e.name,n._url=e.url,n._requestTask=null,n})),this._previousSave)return this._previousSave}},{key:"cancel",value:function(){this._requestTask&&"function"==typeof this._requestTask.abort&&this._requestTask.abort(),this._requestTask=null}},{key:"destroy",value:function(){var e=this;if(!this._name)throw new Error("Cannot delete an unsaved ParseFile.");return x.default.getFileController().deleteFile(this._name).then(function(){return e._data=null,e._requestTask=null,e})}},{key:"toJSON",value:function(){return{__type:"File",name:this._name,url:this._url}}},{key:"equals",value:function(e){return this===e||e instanceof s&&this.name()===e.name()&&this.url()===e.url()&&void 0!==this.url()}},{key:"setMetadata",value:function(t){var e,r=this;t&&"object"===(0,b.default)(t)&&(0,p.default)(e=(0,d.default)(t)).call(e,function(e){r.addMetadata(e,t[e])})}},{key:"addMetadata",value:function(e,t){"string"==typeof e&&(this._metadata[e]=t)}},{key:"setTags",value:function(t){var e,r=this;t&&"object"===(0,b.default)(t)&&(0,p.default)(e=(0,d.default)(t)).call(e,function(e){r.addTag(e,t[e])})}},{key:"addTag",value:function(e,t){"string"==typeof e&&(this._tags[e]=t)}}],[{key:"fromJSON",value:function(e){if("File"!==e.__type)throw new TypeError("JSON object does not represent a ParseFile");var t=new s(e.name);return t._url=e.url,t}},{key:"encodeBase64",value:function(e){var t=[];t.length=Math.ceil(e.length/3);for(var r=0;r<t.length;r++){var n=e[3*r],a=e[3*r+1]||0,s=e[3*r+2]||0,o=3*r+1<e.length,i=3*r+2<e.length;t[r]=[O(n>>2&63),O(n<<4&48|a>>4&15),o?O(a<<2&60|s>>6&3):"=",i?O(63&s):"="].join("")}return t.join("")}}]),s}(),T={saveFile:(P=(0,y.default)(h.default.mark(function e(t,n,r){var a,s;return h.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if("file"!==n.format)throw new Error("saveFile can only be used with File-type sources.");e.next=2;break;case 2:return e.next=4,new f.default(function(e,t){var r=new FileReader;r.onload=function(){return e(r.result)},r.onerror=function(e){return t(e)},r.readAsDataURL(n.file)});case 4:return a=e.sent,s=a.split(","),a=(0,c.default)(s,2),s=a[0],a=a[1],s={format:"base64",base64:a||s,type:n.type||(n.file?n.file.type:null)},e.next=10,T.saveBase64(t,s,r);case 10:return e.abrupt("return",e.sent);case 11:case"end":return e.stop()}},e)})),function(){return P.apply(this,arguments)}),saveBase64:function(e,t,r){if("base64"!==t.format)throw new Error("saveBase64 can only be used with Base64-type sources.");var n={base64:t.base64,fileData:{metadata:C({},r.metadata),tags:C({},r.tags)}};return delete r.metadata,delete r.tags,t.type&&(n._ContentType=t.type),x.default.getRESTController().request("POST","files/"+e,n,r)},download:function(e,t){return S?this.downloadAjax(e,t):f.default.reject("Cannot make a request: No definition of XMLHttpRequest was found.")},downloadAjax:function(e,a){return new f.default(function(t,r){var n=new S;n.open("GET",e,!0),n.responseType="arraybuffer",n.onerror=function(e){r(e)},n.onreadystatechange=function(){if(n.readyState===n.DONE){if(!this.response)return t({});var e=new Uint8Array(this.response);t({base64:A.encodeBase64(e),contentType:n.getResponseHeader("content-type")})}},a.requestTask(n),n.send()})},deleteFile:function(e){var t={"X-Parse-Application-ID":x.default.get("APPLICATION_ID"),"X-Parse-Master-Key":x.default.get("MASTER_KEY")},r=x.default.get("SERVER_URL");return"/"!==r[r.length-1]&&(r+="/"),r+="files/"+e,x.default.getRESTController().ajax("DELETE",r,"",t).catch(function(e){return e&&"SyntaxError: Unexpected end of JSON input"!==e?x.default.getRESTController().handleError(e):f.default.resolve()})},_setXHR:function(e){S=e},_getXHR:function(){return S}};x.default.setFileController(T),r.default=A,r.b64Digit=O},{"./CoreManager":4,"./Xhr.weapp":41,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/instance/filter":57,"@babel/runtime-corejs3/core-js-stable/instance/for-each":59,"@babel/runtime-corejs3/core-js-stable/instance/index-of":61,"@babel/runtime-corejs3/core-js-stable/instance/slice":65,"@babel/runtime-corejs3/core-js-stable/object/define-properties":74,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor":78,"@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptors":79,"@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols":80,"@babel/runtime-corejs3/core-js-stable/object/keys":81,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/helpers/asyncToGenerator":113,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/defineProperty":117,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/slicedToArray":131,"@babel/runtime-corejs3/helpers/typeof":134,"@babel/runtime-corejs3/regenerator":137}],21:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a=n(e("@babel/runtime-corejs3/helpers/typeof")),s=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),o=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),i=n(e("@babel/runtime-corejs3/helpers/createClass")),l=n(e("@babel/runtime-corejs3/helpers/defineProperty")),e=function(){function r(e,t){(0,o.default)(this,r),(0,l.default)(this,"_latitude",void 0),(0,l.default)(this,"_longitude",void 0),(0,s.default)(e)?(r._validate(e[0],e[1]),this._latitude=e[0],this._longitude=e[1]):"object"===(0,a.default)(e)?(r._validate(e.latitude,e.longitude),this._latitude=e.latitude,this._longitude=e.longitude):void 0!==e&&void 0!==t?(r._validate(e,t),this._latitude=e,this._longitude=t):(this._latitude=0,this._longitude=0)}return(0,i.default)(r,[{key:"toJSON",value:function(){return r._validate(this._latitude,this._longitude),{__type:"GeoPoint",latitude:this._latitude,longitude:this._longitude}}},{key:"equals",value:function(e){return e instanceof r&&this.latitude===e.latitude&&this.longitude===e.longitude}},{key:"radiansTo",value:function(e){var t=Math.PI/180,r=this.latitude*t,n=this.longitude*t,a=e.latitude*t,e=e.longitude*t,t=Math.sin((r-a)/2),e=Math.sin((n-e)/2),e=t*t+Math.cos(r)*Math.cos(a)*e*e,e=Math.min(1,e);return 2*Math.asin(Math.sqrt(e))}},{key:"kilometersTo",value:function(e){return 6371*this.radiansTo(e)}},{key:"milesTo",value:function(e){return 3958.8*this.radiansTo(e)}},{key:"latitude",get:function(){return this._latitude},set:function(e){r._validate(e,this.longitude),this._latitude=e}},{key:"longitude",get:function(){return this._longitude},set:function(e){r._validate(this.latitude,e),this._longitude=e}}],[{key:"_validate",value:function(e,t){if(isNaN(e)||isNaN(t)||"number"!=typeof e||"number"!=typeof t)throw new TypeError("GeoPoint latitude and longitude must be valid numbers");if(e<-90)throw new TypeError("GeoPoint latitude out of bounds: "+e+" < -90.0.");if(90<e)throw new TypeError("GeoPoint latitude out of bounds: "+e+" > 90.0.");if(t<-180)throw new TypeError("GeoPoint longitude out of bounds: "+t+" < -180.0.");if(180<t)throw new TypeError("GeoPoint longitude out of bounds: "+t+" > 180.0.")}},{key:"current",value:function(){return navigator.geolocation.getCurrentPosition(function(e){return new r(e.coords.latitude,e.coords.longitude)})}}]),r}();r.default=e},{"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/defineProperty":117,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/typeof":134}],22:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a=n(e("@babel/runtime-corejs3/core-js-stable/reflect/construct")),s=n(e("@babel/runtime-corejs3/helpers/typeof")),o=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),i=n(e("@babel/runtime-corejs3/helpers/inherits")),l=n(e("@babel/runtime-corejs3/helpers/possibleConstructorReturn")),u=n(e("@babel/runtime-corejs3/helpers/getPrototypeOf")),n=n(e("./ParseObject"));function c(r){var n=function(){if("undefined"==typeof Reflect||!a.default)return!1;if(a.default.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call((0,a.default)(Date,[],function(){})),!0}catch(e){return!1}}();return function(){var e,t=(0,u.default)(r);return t=n?(e=(0,u.default)(this).constructor,(0,a.default)(t,arguments,e)):t.apply(this,arguments),(0,l.default)(this,t)}}e=function(e){(0,i.default)(n,e);var r=c(n);function n(e){var t;if((0,o.default)(this,n),t=r.call(this,"_Installation"),e&&"object"===(0,s.default)(e)&&!t.set(e||{}))throw new Error("Can't create an invalid Installation");return t}return n}(n.default);r.default=e,n.default.registerSubclass("_Installation",e)},{"./ParseObject":24,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/reflect/construct":84,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/getPrototypeOf":119,"@babel/runtime-corejs3/helpers/inherits":120,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/possibleConstructorReturn":129,"@babel/runtime-corejs3/helpers/typeof":134}],23:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var i=n(e("@babel/runtime-corejs3/core-js-stable/instance/index-of")),l=n(e("@babel/runtime-corejs3/core-js-stable/promise")),u=n(e("@babel/runtime-corejs3/helpers/slicedToArray")),c=n(e("@babel/runtime-corejs3/regenerator")),a=n(e("@babel/runtime-corejs3/helpers/asyncToGenerator")),s=n(e("./EventEmitter")),f=n(e("./LiveQueryClient")),d=n(e("./CoreManager"));function o(){return d.default.getLiveQueryController().getDefaultLiveQueryClient()}var p,b=new s.default;b.open=(0,a.default)(c.default.mark(function e(){return c.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,o();case 2:e.sent.open();case 4:case"end":return e.stop()}},e)})),b.close=(0,a.default)(c.default.mark(function e(){return c.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,o();case 2:e.sent.close();case 4:case"end":return e.stop()}},e)})),b.on("error",function(){}),r.default=b;r={setDefaultLiveQueryClient:function(e){p=e},getDefaultLiveQueryClient:function(){return(0,a.default)(c.default.mark(function e(){var t,r,n,a,s,o;return c.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(p)return e.abrupt("return",p);e.next=2;break;case 2:return e.next=4,l.default.all([d.default.getUserController().currentUserAsync(),d.default.getInstallationController().currentInstallationId()]);case 4:if(t=e.sent,r=(0,u.default)(t,2),n=r[0],t=r[1],r=n?n.getSessionToken():void 0,(n=d.default.get("LIVEQUERY_SERVER_URL"))&&0!==(0,i.default)(n).call(n,"ws"))throw new Error("You need to set a proper Parse LiveQuery server url before using LiveQueryClient");e.next=12;break;case 12:return n||(a=d.default.get("SERVER_URL"),s=0===(0,i.default)(a).call(a,"https")?"wss://":"ws://",o=a.replace(/^https?:\/\//,""),n=s+o,d.default.set("LIVEQUERY_SERVER_URL",n)),a=d.default.get("APPLICATION_ID"),s=d.default.get("JAVASCRIPT_KEY"),o=d.default.get("MASTER_KEY"),(p=new f.default({applicationId:a,serverURL:n,javascriptKey:s,masterKey:o,sessionToken:r,installationId:t})).on("error",function(e){b.emit("error",e)}),p.on("open",function(){b.emit("open")}),p.on("close",function(){b.emit("close")}),e.abrupt("return",p);case 21:case"end":return e.stop()}},e)}))()},_clearCachedDefaultClient:function(){p=null}};d.default.setLiveQueryController(r)},{"./CoreManager":4,"./EventEmitter":6,"./LiveQueryClient":9,"@babel/runtime-corejs3/core-js-stable/instance/index-of":61,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/helpers/asyncToGenerator":113,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/slicedToArray":131,"@babel/runtime-corejs3/regenerator":137}],24:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireWildcard"),a=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var b=a(e("@babel/runtime-corejs3/core-js-stable/instance/map")),i=a(e("@babel/runtime-corejs3/core-js-stable/instance/find")),l=a(e("@babel/runtime-corejs3/core-js/get-iterator")),u=a(e("@babel/runtime-corejs3/core-js/get-iterator-method")),c=a(e("@babel/runtime-corejs3/core-js-stable/symbol")),f=a(e("@babel/runtime-corejs3/core-js-stable/array/from")),d=a(e("@babel/runtime-corejs3/core-js-stable/instance/slice")),p=a(e("@babel/runtime-corejs3/core-js-stable/object/define-property")),h=a(e("@babel/runtime-corejs3/core-js-stable/object/create")),s=a(e("@babel/runtime-corejs3/core-js-stable/object/freeze")),y=a(e("@babel/runtime-corejs3/core-js-stable/promise")),m=a(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),v=a(e("@babel/runtime-corejs3/regenerator")),j=a(e("@babel/runtime-corejs3/helpers/asyncToGenerator")),g=a(e("@babel/runtime-corejs3/core-js-stable/instance/concat")),_=a(e("@babel/runtime-corejs3/core-js-stable/instance/includes")),o=a(e("@babel/runtime-corejs3/core-js-stable/json/stringify")),w=a(e("@babel/runtime-corejs3/core-js-stable/instance/for-each")),x=a(e("@babel/runtime-corejs3/core-js-stable/object/keys")),k=a(e("@babel/runtime-corejs3/helpers/typeof")),C=a(e("@babel/runtime-corejs3/helpers/classCallCheck")),S=a(e("@babel/runtime-corejs3/helpers/createClass")),E=a(e("@babel/runtime-corejs3/helpers/defineProperty")),O=a(e("@babel/runtime-corejs3/core-js-stable/instance/index-of")),P=a(e("./CoreManager")),A=a(e("./canBeSerialized")),T=a(e("./decode")),R=a(e("./encode")),I=a(e("./escape")),N=a(e("./ParseACL")),D=a(e("./parseDate")),L=a(e("./ParseError")),M=a(e("./ParseFile")),q=e("./promiseUtils"),U=e("./LocalDatastoreUtils"),F=e("./ParseOp"),K=a(e("./ParseQuery")),W=a(e("./ParseRelation")),z=n(e("./SingleInstanceStateController")),B=a(e("./unique")),J=n(e("./UniqueInstanceStateController")),Q=a(e("./unsavedChildren"));function V(e,t){var r;if(void 0===c.default||null==(0,u.default)(e)){if((0,m.default)(e)||(r=function(e,t){if(!e)return;if("string"==typeof e)return G(e,t);var r=(0,d.default)(r=Object.prototype.toString.call(e)).call(r,8,-1);"Object"===r&&e.constructor&&(r=e.constructor.name);if("Map"===r||"Set"===r)return(0,f.default)(e);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return G(e,t)}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var n=0,t=function(){};return{s:t,n:function(){return n>=e.length?{done:!0}:{done:!1,value:e[n++]}},e:function(e){throw e},f:t}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var a,s=!0,o=!1;return{s:function(){r=(0,l.default)(e)},n:function(){var e=r.next();return s=e.done,e},e:function(e){o=!0,a=e},f:function(){try{s||null==r.return||r.return()}finally{if(o)throw a}}}}function G(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}var $=e("uuid/v4"),H={},Y=0,X=!P.default.get("IS_NODE");function Z(){var e=P.default.get("SERVER_URL");"/"!==e[e.length-1]&&(e+="/");e=e.replace(/https?:\/\//,"");return e.substr((0,O.default)(e).call(e,"/"))}X?P.default.setObjectStateController(z):P.default.setObjectStateController(J);var ee=function(){function i(e,t,r){(0,C.default)(this,i),(0,E.default)(this,"id",void 0),(0,E.default)(this,"_localId",void 0),(0,E.default)(this,"_objCount",void 0),(0,E.default)(this,"className",void 0),"function"==typeof this.initialize&&this.initialize.apply(this,arguments);var n=null;if(this._objCount=Y++,"string"==typeof e)this.className=e,t&&"object"===(0,k.default)(t)&&(n=t);else if(e&&"object"===(0,k.default)(e)){for(var a in this.className=e.className,n={},e)"className"!==a&&(n[a]=e[a]);t&&"object"===(0,k.default)(t)&&(r=t)}if(n&&!this.set(n,r))throw new Error("Can't create an invalid Parse Object")}var e,t,r;return(0,S.default)(i,[{key:"_getId",value:function(){if("string"==typeof this.id)return this.id;if("string"==typeof this._localId)return this._localId;var e="local"+$();return this._localId=e}},{key:"_getStateIdentifier",value:function(){return X?{id:this.id||this._getId(),className:this.className}:this}},{key:"_getServerData",value:function(){return P.default.getObjectStateController().getServerData(this._getStateIdentifier())}},{key:"_clearServerData",value:function(){var e,t={};for(e in this._getServerData())t[e]=void 0;P.default.getObjectStateController().setServerData(this._getStateIdentifier(),t)}},{key:"_getPendingOps",value:function(){return P.default.getObjectStateController().getPendingOps(this._getStateIdentifier())}},{key:"_clearPendingOps",value:function(e){var t=this._getPendingOps(),r=t[t.length-1],e=e||(0,x.default)(r);(0,w.default)(e).call(e,function(e){delete r[e]})}},{key:"_getDirtyObjectAttributes",value:function(){var t,e=this.attributes,r=P.default.getObjectStateController().getObjectCache(this._getStateIdentifier()),n={};for(t in e){var a=e[t];if(a&&"object"===(0,k.default)(a)&&!(a instanceof i)&&!(a instanceof M.default)&&!(a instanceof W.default))try{var s=(0,R.default)(a,!1,!0),s=(0,o.default)(s);r[t]!==s&&(n[t]=a)}catch(e){n[t]=a}}return n}},{key:"_toFullJSON",value:function(e,t){t=this.toJSON(e,t);return t.__type="Object",t.className=this.className,t}},{key:"_getSaveJSON",value:function(){var e,t=this._getPendingOps(),r=this._getDirtyObjectAttributes(),n={};for(e in r){for(var a=!1,s=0;s<t.length;s+=1)for(var o in t[s]){if((0,_.default)(o).call(o,"."))if(o.split(".")[0]===e){a=!0;break}}a||(n[e]=new F.SetOp(r[e]).toJSON())}for(e in t[0])n[e]=t[0][e].toJSON();return n}},{key:"_getSaveParams",value:function(){var e=this.id?"PUT":"POST",t=this._getSaveJSON(),r="classes/"+this.className;return this.id?r+="/"+this.id:"_User"===this.className&&(r="users"),{method:e,body:t,path:r}}},{key:"_finishFetch",value:function(e){!this.id&&e.objectId&&(this.id=e.objectId);var t=P.default.getObjectStateController();t.initializeState(this._getStateIdentifier());var r,n={};for(r in e)"ACL"===r?n[r]=new N.default(e[r]):"objectId"!==r&&(n[r]=(0,T.default)(e[r]),n[r]instanceof W.default&&n[r]._ensureParentAndKey(this,r));n.createdAt&&"string"==typeof n.createdAt&&(n.createdAt=(0,D.default)(n.createdAt)),n.updatedAt&&"string"==typeof n.updatedAt&&(n.updatedAt=(0,D.default)(n.updatedAt)),!n.updatedAt&&n.createdAt&&(n.updatedAt=n.createdAt),t.commitServerChanges(this._getStateIdentifier(),n)}},{key:"_setExisted",value:function(e){var t=P.default.getObjectStateController().getState(this._getStateIdentifier());t&&(t.existed=e)}},{key:"_migrateId",value:function(e){var t,r;this._localId&&e&&(X?(r=(t=P.default.getObjectStateController()).removeState(this._getStateIdentifier()),this.id=e,delete this._localId,r&&t.initializeState(this._getStateIdentifier(),r)):(this.id=e,delete this._localId))}},{key:"_handleSaveResponse",value:function(e,t){var r,n={},a=P.default.getObjectStateController(),s=a.popPendingState(this._getStateIdentifier());for(r in s)s[r]instanceof F.RelationOp?n[r]=s[r].applyTo(void 0,this,r):r in e||(n[r]=s[r].applyTo(void 0));for(r in e)"createdAt"!==r&&"updatedAt"!==r||"string"!=typeof e[r]?"ACL"===r?n[r]=new N.default(e[r]):"objectId"!==r&&(n[r]=(0,T.default)(e[r]),n[r]instanceof F.UnsetOp&&(n[r]=void 0)):n[r]=(0,D.default)(e[r]);n.createdAt&&!n.updatedAt&&(n.updatedAt=n.createdAt),this._migrateId(e.objectId),201!==t&&this._setExisted(!0),a.commitServerChanges(this._getStateIdentifier(),n)}},{key:"_handleSaveError",value:function(){P.default.getObjectStateController().mergeFirstPendingState(this._getStateIdentifier())}},{key:"initialize",value:function(){}},{key:"toJSON",value:function(e,t){var r=this.id?this.className+":"+this.id:this;e=e||[r];var n,a={},s=this.attributes;for(n in s)"createdAt"!==n&&"updatedAt"!==n||!s[n].toJSON?a[n]=(0,R.default)(s[n],!1,!1,e,t):a[n]=s[n].toJSON();var o,i=this._getPendingOps();for(o in i[0])a[o]=i[0][o].toJSON(t);return this.id&&(a.objectId=this.id),a}},{key:"equals",value:function(e){return this===e||e instanceof i&&this.className===e.className&&this.id===e.id&&void 0!==this.id}},{key:"dirty",value:function(e){if(!this.id)return!0;var t=this._getPendingOps(),r=this._getDirtyObjectAttributes();if(e){if(r.hasOwnProperty(e))return!0;for(var n=0;n<t.length;n++)if(t[n].hasOwnProperty(e))return!0;return!1}return 0!==(0,x.default)(t[0]).length||0!==(0,x.default)(r).length}},{key:"dirtyKeys",value:function(){for(var e,t=this._getPendingOps(),r={},n=0;n<t.length;n++)for(var a in t[n])r[a]=!0;for(e in this._getDirtyObjectAttributes())r[e]=!0;return(0,x.default)(r)}},{key:"isDataAvailable",value:function(){var e=this._getServerData();return!!(0,x.default)(e).length}},{key:"toPointer",value:function(){if(!this.id)throw new Error("Cannot create a pointer to an unsaved ParseObject");return{__type:"Pointer",className:this.className,objectId:this.id}}},{key:"toOfflinePointer",value:function(){if(!this._localId)throw new Error("Cannot create a offline pointer to a saved ParseObject");return{__type:"Object",className:this.className,_localId:this._localId}}},{key:"get",value:function(e){return this.attributes[e]}},{key:"relation",value:function(e){var t=this.get(e);if(t){if(!(t instanceof W.default))throw new Error("Called relation() on non-relation field "+e);return t._ensureParentAndKey(this,e),t}return new W.default(this,e)}},{key:"escape",value:function(e){e=this.attributes[e];if(null==e)return"";if("string"!=typeof e){if("function"!=typeof e.toString)return"";e=e.toString()}return(0,I.default)(e)}},{key:"has",value:function(e){var t=this.attributes;return!!t.hasOwnProperty(e)&&null!=t[e]}},{key:"set",value:function(e,t,r){var n={},a={};if(e&&"object"===(0,k.default)(e))n=e,r=t;else{if("string"!=typeof e)return this;n[e]=t}r=r||{};var s,o,i=[];for(s in"function"==typeof this.constructor.readOnlyAttributes&&(i=(0,g.default)(i).call(i,this.constructor.readOnlyAttributes())),n)if("createdAt"!==s&&"updatedAt"!==s){if(-1<(0,O.default)(i).call(i,s))throw new Error("Cannot modify readonly attribute: "+s);r.unset?a[s]=new F.UnsetOp:n[s]instanceof F.Op?a[s]=n[s]:n[s]&&"object"===(0,k.default)(n[s])&&"string"==typeof n[s].__op?a[s]=(0,F.opFromJSON)(n[s]):"objectId"===s||"id"===s?"string"==typeof n[s]&&(this.id=n[s]):"ACL"!==s||"object"!==(0,k.default)(n[s])||n[s]instanceof N.default?n[s]instanceof W.default?((o=new W.default(this,s)).targetClassName=n[s].targetClassName,a[s]=new F.SetOp(o)):a[s]=new F.SetOp(n[s]):a[s]=new F.SetOp(new N.default(n[s]))}var l=this.attributes,t=this._getServerData();if("string"==typeof e&&(0,_.default)(e).call(e,".")&&!t[e.split(".")[0]])return this;var u,c={};for(u in a)a[u]instanceof F.RelationOp?c[u]=a[u].applyTo(l[u],this,u):a[u]instanceof F.UnsetOp||(c[u]=a[u].applyTo(l[u]));if(!r.ignoreValidation){e=this.validate(c);if(e)return"function"==typeof r.error&&r.error(this,e),!1}var f,d=this._getPendingOps(),p=d.length-1,b=P.default.getObjectStateController();for(f in a){var h=a[f].mergeWith(d[p][f]);b.setPendingOp(this._getStateIdentifier(),f,h)}return this}},{key:"unset",value:function(e,t){return(t=t||{}).unset=!0,this.set(e,null,t)}},{key:"increment",value:function(e,t){if(void 0===t&&(t=1),"number"!=typeof t)throw new Error("Cannot increment by a non-numeric amount.");return this.set(e,new F.IncrementOp(t))}},{key:"decrement",value:function(e,t){if(void 0===t&&(t=1),"number"!=typeof t)throw new Error("Cannot decrement by a non-numeric amount.");return this.set(e,new F.IncrementOp(-1*t))}},{key:"add",value:function(e,t){return this.set(e,new F.AddOp([t]))}},{key:"addAll",value:function(e,t){return this.set(e,new F.AddOp(t))}},{key:"addUnique",value:function(e,t){return this.set(e,new F.AddUniqueOp([t]))}},{key:"addAllUnique",value:function(e,t){return this.set(e,new F.AddUniqueOp(t))}},{key:"remove",value:function(e,t){return this.set(e,new F.RemoveOp([t]))}},{key:"removeAll",value:function(e,t){return this.set(e,new F.RemoveOp(t))}},{key:"op",value:function(e){for(var t=this._getPendingOps(),r=t.length;r--;)if(t[r][e])return t[r][e]}},{key:"clone",value:function(){var e=new this.constructor;e.className||(e.className=this.className);var t=this.attributes;if("function"==typeof this.constructor.readOnlyAttributes){var r,n=this.constructor.readOnlyAttributes()||[],a={};for(r in t)(0,O.default)(n).call(n,r)<0&&(a[r]=t[r]);t=a}return e.set&&e.set(t),e}},{key:"newInstance",value:function(){var e=new this.constructor;if(e.className||(e.className=this.className),e.id=this.id,X)return e;var t=P.default.getObjectStateController();return t&&t.duplicateState(this._getStateIdentifier(),e._getStateIdentifier()),e}},{key:"isNew",value:function(){return!this.id}},{key:"existed",value:function(){if(!this.id)return!1;var e=P.default.getObjectStateController().getState(this._getStateIdentifier());return!!e&&e.existed}},{key:"exists",value:(r=(0,j.default)(v.default.mark(function e(t){var r;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(this.id){e.next=2;break}return e.abrupt("return",!1);case 2:return e.prev=2,r=new K.default(this.className),e.next=6,r.get(this.id,t);case 6:return e.abrupt("return",!0);case 9:if(e.prev=9,e.t0=e.catch(2),e.t0.code===L.default.OBJECT_NOT_FOUND)return e.abrupt("return",!1);e.next=13;break;case 13:throw e.t0;case 14:case"end":return e.stop()}},e,this,[[2,9]])})),function(){return r.apply(this,arguments)})},{key:"isValid",value:function(){return!this.validate(this.attributes)}},{key:"validate",value:function(e){if(e.hasOwnProperty("ACL")&&!(e.ACL instanceof N.default))return new L.default(L.default.OTHER_CAUSE,"ACL must be a Parse ACL.");for(var t in e)if(!/^[A-Za-z][0-9A-Za-z_.]*$/.test(t))return new L.default(L.default.INVALID_KEY_NAME);return!1}},{key:"getACL",value:function(){var e=this.get("ACL");return e instanceof N.default?e:null}},{key:"setACL",value:function(e,t){return this.set("ACL",e,t)}},{key:"revert",value:function(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(r.length){e=[];var a=V(r);try{for(a.s();!(s=a.n()).done;){var s=s.value;if("string"!=typeof s)throw new Error("Parse.Object#revert expects either no, or a list of string, arguments.");e.push(s)}}catch(e){a.e(e)}finally{a.f()}}this._clearPendingOps(e)}},{key:"clear",value:function(){var e,t=this.attributes,r={},n=["createdAt","updatedAt"];for(e in"function"==typeof this.constructor.readOnlyAttributes&&(n=(0,g.default)(n).call(n,this.constructor.readOnlyAttributes())),t)(0,O.default)(n).call(n,e)<0&&(r[e]=!0);return this.set(r,{unset:!0})}},{key:"fetch",value:function(e){var t,r={};return(e=e||{}).hasOwnProperty("useMasterKey")&&(r.useMasterKey=e.useMasterKey),e.hasOwnProperty("sessionToken")&&(r.sessionToken=e.sessionToken),e.hasOwnProperty("context")&&"object"===(0,k.default)(e.context)&&(r.context=e.context),e.hasOwnProperty("include")&&(r.include=[],(0,m.default)(e.include)?(0,w.default)(t=e.include).call(t,function(e){var t;(0,m.default)(e)?r.include=(0,g.default)(t=r.include).call(t,e):r.include.push(e)}):r.include.push(e.include)),P.default.getObjectController().fetch(this,!0,r)}},{key:"fetchWithInclude",value:function(e,t){return(t=t||{}).include=e,this.fetch(t)}},{key:"save",value:function(e,t,r){var n,a=this;if("object"===(0,k.default)(e)||void 0===e?(n=e,"object"===(0,k.default)(t)&&(i=t)):((n={})[e]=t,i=r),n){r=this.validate(n);if(r)return y.default.reject(r);this.set(n,i)}var s={};(i=i||{}).hasOwnProperty("useMasterKey")&&(s.useMasterKey=!!i.useMasterKey),i.hasOwnProperty("sessionToken")&&"string"==typeof i.sessionToken&&(s.sessionToken=i.sessionToken),i.hasOwnProperty("installationId")&&"string"==typeof i.installationId&&(s.installationId=i.installationId),i.hasOwnProperty("context")&&"object"===(0,k.default)(i.context)&&(s.context=i.context);var o=P.default.getObjectController(),i=!1!==i.cascadeSave?(0,Q.default)(this):null;return o.save(i,s).then(function(){return o.save(a,s)})}},{key:"destroy",value:function(e){var t={};return(e=e||{}).hasOwnProperty("useMasterKey")&&(t.useMasterKey=e.useMasterKey),e.hasOwnProperty("sessionToken")&&(t.sessionToken=e.sessionToken),e.hasOwnProperty("context")&&"object"===(0,k.default)(e.context)&&(t.context=e.context),this.id?P.default.getObjectController().destroy(this,t):y.default.resolve()}},{key:"pin",value:function(){return i.pinAllWithName(U.DEFAULT_PIN,[this])}},{key:"unPin",value:function(){return i.unPinAllWithName(U.DEFAULT_PIN,[this])}},{key:"isPinned",value:(t=(0,j.default)(v.default.mark(function e(){var t,r;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if((t=P.default.getLocalDatastore()).isEnabled){e.next=3;break}return e.abrupt("return",y.default.reject("Parse.enableLocalDatastore() must be called first"));case 3:return r=t.getKeyForObject(this),e.next=6,t.fromPinWithName(r);case 6:return r=e.sent,e.abrupt("return",0<r.length);case 8:case"end":return e.stop()}},e,this)})),function(){return t.apply(this,arguments)})},{key:"pinWithName",value:function(e){return i.pinAllWithName(e,[this])}},{key:"unPinWithName",value:function(e){return i.unPinAllWithName(e,[this])}},{key:"fetchFromLocalDatastore",value:(e=(0,j.default)(v.default.mark(function e(){var t,r,n;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if((t=P.default.getLocalDatastore()).isEnabled){e.next=3;break}throw new Error("Parse.enableLocalDatastore() must be called first");case 3:return n=t.getKeyForObject(this),e.next=6,t._serializeObject(n);case 6:if(r=e.sent){e.next=9;break}throw new Error("Cannot fetch an unsaved ParseObject");case 9:return n=i.fromJSON(r),this._finishFetch(n.toJSON()),e.abrupt("return",this);case 12:case"end":return e.stop()}},e,this)})),function(){return e.apply(this,arguments)})},{key:"attributes",get:function(){var e=P.default.getObjectStateController();return(0,s.default)(e.estimateAttributes(this._getStateIdentifier()))}},{key:"createdAt",get:function(){return this._getServerData().createdAt}},{key:"updatedAt",get:function(){return this._getServerData().updatedAt}}],[{key:"_clearAllState",value:function(){P.default.getObjectStateController().clearAllState()}},{key:"fetchAll",value:function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r={};return t.hasOwnProperty("useMasterKey")&&(r.useMasterKey=t.useMasterKey),t.hasOwnProperty("sessionToken")&&(r.sessionToken=t.sessionToken),t.hasOwnProperty("include")&&(r.include=i.handleIncludeOptions(t)),P.default.getObjectController().fetch(e,!0,r)}},{key:"fetchAllWithInclude",value:function(e,t,r){return(r=r||{}).include=t,i.fetchAll(e,r)}},{key:"fetchAllIfNeededWithInclude",value:function(e,t,r){return(r=r||{}).include=t,i.fetchAllIfNeeded(e,r)}},{key:"fetchAllIfNeeded",value:function(e,t){var r={};return(t=t||{}).hasOwnProperty("useMasterKey")&&(r.useMasterKey=t.useMasterKey),t.hasOwnProperty("sessionToken")&&(r.sessionToken=t.sessionToken),t.hasOwnProperty("include")&&(r.include=i.handleIncludeOptions(t)),P.default.getObjectController().fetch(e,!1,r)}},{key:"handleIncludeOptions",value:function(e){var t,r=[];return(0,m.default)(e.include)?(0,w.default)(t=e.include).call(t,function(e){(0,m.default)(e)?r=(0,g.default)(r).call(r,e):r.push(e)}):r.push(e.include),r}},{key:"destroyAll",value:function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r={};return t.hasOwnProperty("useMasterKey")&&(r.useMasterKey=t.useMasterKey),t.hasOwnProperty("sessionToken")&&(r.sessionToken=t.sessionToken),t.hasOwnProperty("batchSize")&&"number"==typeof t.batchSize&&(r.batchSize=t.batchSize),t.hasOwnProperty("context")&&"object"===(0,k.default)(t.context)&&(r.context=t.context),P.default.getObjectController().destroy(e,r)}},{key:"saveAll",value:function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r={};return t.hasOwnProperty("useMasterKey")&&(r.useMasterKey=t.useMasterKey),t.hasOwnProperty("sessionToken")&&(r.sessionToken=t.sessionToken),t.hasOwnProperty("batchSize")&&"number"==typeof t.batchSize&&(r.batchSize=t.batchSize),t.hasOwnProperty("context")&&"object"===(0,k.default)(t.context)&&(r.context=t.context),P.default.getObjectController().save(e,r)}},{key:"createWithoutData",value:function(e){var t=new this;return t.id=e,t}},{key:"fromJSON",value:function(e,t){if(!e.className)throw new Error("Cannot create an object without a className");var r,n=H[e.className],n=n?new n:new i(e.className),a={};for(r in e)"className"!==r&&"__type"!==r&&(a[r]=e[r]);return t&&(a.objectId&&(n.id=a.objectId),t=null,"function"==typeof n._preserveFieldsOnFetch&&(t=n._preserveFieldsOnFetch()),n._clearServerData(),t&&n._finishFetch(t)),n._finishFetch(a),e.objectId&&n._setExisted(!0),n}},{key:"registerSubclass",value:function(e,t){if("string"!=typeof e)throw new TypeError("The first argument must be a valid class name.");if(void 0===t)throw new TypeError("You must supply a subclass constructor.");if("function"!=typeof t)throw new TypeError("You must register the subclass constructor. Did you attempt to register an instance of the subclass?");(H[e]=t).className||(t.className=e)}},{key:"extend",value:function(e,t,r){if("string"!=typeof e){if(e&&"string"==typeof e.className)return i.extend(e.className,e,t);throw new Error("Parse.Object.extend's first argument should be the className.")}var n=e;"User"===n&&P.default.get("PERFORM_USER_REWRITE")&&(n="_User");e=i.prototype;this.hasOwnProperty("__super__")&&this.__super__?e=this.prototype:H[n]&&(e=H[n].prototype);function a(e,t){if(this.className=n,this._objCount=Y++,"function"==typeof this.initialize&&this.initialize.apply(this,arguments),e&&"object"===(0,k.default)(e)&&!this.set(e||{},t))throw new Error("Can't create an invalid Parse Object")}if(a.className=n,a.__super__=e,a.prototype=(0,h.default)(e,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),t)for(var s in t)"className"!==s&&(0,p.default)(a.prototype,s,{value:t[s],enumerable:!1,writable:!0,configurable:!0});if(r)for(var o in r)"className"!==o&&(0,p.default)(a,o,{value:r[o],enumerable:!1,writable:!0,configurable:!0});return a.extend=function(e,t,r){return"string"==typeof e?i.extend.call(a,e,t,r):i.extend.call(a,n,e,t)},a.createWithoutData=i.createWithoutData,H[n]=a}},{key:"enableSingleInstance",value:function(){X=!0,P.default.setObjectStateController(z)}},{key:"disableSingleInstance",value:function(){X=!1,P.default.setObjectStateController(J)}},{key:"pinAll",value:function(e){return P.default.getLocalDatastore().isEnabled?i.pinAllWithName(U.DEFAULT_PIN,e):y.default.reject("Parse.enableLocalDatastore() must be called first")}},{key:"pinAllWithName",value:function(e,t){var r=P.default.getLocalDatastore();return r.isEnabled?r._handlePinAllWithName(e,t):y.default.reject("Parse.enableLocalDatastore() must be called first")}},{key:"unPinAll",value:function(e){return P.default.getLocalDatastore().isEnabled?i.unPinAllWithName(U.DEFAULT_PIN,e):y.default.reject("Parse.enableLocalDatastore() must be called first")}},{key:"unPinAllWithName",value:function(e,t){var r=P.default.getLocalDatastore();return r.isEnabled?r._handleUnPinAllWithName(e,t):y.default.reject("Parse.enableLocalDatastore() must be called first")}},{key:"unPinAllObjects",value:function(){var e=P.default.getLocalDatastore();return e.isEnabled?e.unPinWithName(U.DEFAULT_PIN):y.default.reject("Parse.enableLocalDatastore() must be called first")}},{key:"unPinAllObjectsWithName",value:function(e){var t=P.default.getLocalDatastore();return t.isEnabled?t.unPinWithName(U.PIN_PREFIX+e):y.default.reject("Parse.enableLocalDatastore() must be called first")}}]),i}(),e={fetch:function(r,u,e){var c=P.default.getLocalDatastore();if((0,m.default)(r)){if(r.length<1)return y.default.resolve([]);var f=[],t=[],n=null,d=[],a=null;if((0,w.default)(r).call(r,function(e){a||((n=n||e.className)!==e.className&&(a=new L.default(L.default.INVALID_CLASS_NAME,"All objects should be of the same class")),e.id||(a=new L.default(L.default.MISSING_OBJECT_ID,"All objects must have an ID")),!u&&e.isDataAvailable()||(t.push(e.id),f.push(e)),d.push(e))}),a)return y.default.reject(a);var s=new K.default(n);return s.containedIn("objectId",t),e&&e.include&&s.include(e.include),s._limit=t.length,(0,i.default)(s).call(s,e).then(function(){var e=(0,j.default)(v.default.mark(function e(t){var r,n,a,s,o,i,l;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:r={},(0,w.default)(t).call(t,function(e){r[e.id]=e}),n=0;case 3:if(!(n<f.length)){e.next=11;break}if((l=f[n])&&l.id&&r[l.id]){e.next=8;break}if(u)return e.abrupt("return",y.default.reject(new L.default(L.default.OBJECT_NOT_FOUND,"All objects must exist on the server.")));e.next=8;break;case 8:n++,e.next=3;break;case 11:if(!X)for(a=0;a<d.length;a++)(s=d[a])&&s.id&&r[s.id]&&(o=s.id,s._finishFetch(r[o].toJSON()),d[a]=r[o]);i=V(d),e.prev=13,i.s();case 15:if((l=i.n()).done){e.next=21;break}return l=l.value,e.next=19,c._updateObjectIfPinned(l);case 19:e.next=15;break;case 21:e.next=26;break;case 23:e.prev=23,e.t0=e.catch(13),i.e(e.t0);case 26:return e.prev=26,i.f(),e.finish(26);case 29:return e.abrupt("return",y.default.resolve(d));case 30:case"end":return e.stop()}},e,null,[[13,23,26,29]])}));return function(){return e.apply(this,arguments)}}())}if(r instanceof ee){if(!r.id)return y.default.reject(new L.default(L.default.MISSING_OBJECT_ID,"Object does not have an ID"));var o=P.default.getRESTController(),s={};return e&&e.include&&(s.include=e.include.join()),o.request("GET","classes/"+r.className+"/"+r._getId(),s,e).then(function(){var e=(0,j.default)(v.default.mark(function e(t){return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r._clearPendingOps(),r._clearServerData(),r._finishFetch(t),e.next=5,c._updateObjectIfPinned(r);case 5:return e.abrupt("return",r);case 6:case"end":return e.stop()}},e)}));return function(){return e.apply(this,arguments)}}())}return y.default.resolve()},destroy:function(i,l){return(0,j.default)(v.default.mark(function e(){var t,n,r,a,s,o;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(t=l&&l.batchSize?l.batchSize:P.default.get("REQUEST_BATCH_SIZE"),n=P.default.getLocalDatastore(),r=P.default.getRESTController(),!(0,m.default)(i)){e.next=15;break}if(i.length<1)return e.abrupt("return",y.default.resolve([]));e.next=6;break;case 6:return a=[[]],(0,w.default)(i).call(i,function(e){e.id&&(a[a.length-1].push(e),a[a.length-1].length>=t&&a.push([]))}),0===a[a.length-1].length&&a.pop(),s=y.default.resolve(),o=[],(0,w.default)(a).call(a,function(n){s=s.then(function(){return r.request("POST","batch",{requests:(0,b.default)(n).call(n,function(e){return{method:"DELETE",path:Z()+"classes/"+e.className+"/"+e._getId(),body:{}}})},l).then(function(e){for(var t,r=0;r<e.length;r++){e[r]&&e[r].hasOwnProperty("error")&&((t=new L.default(e[r].error.code,e[r].error.error)).object=n[r],o.push(t))}})})}),e.abrupt("return",s.then((0,j.default)(v.default.mark(function e(){var t,r;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(o.length)return(r=new L.default(L.default.AGGREGATE_ERROR)).errors=o,e.abrupt("return",y.default.reject(r));e.next=4;break;case 4:t=V(i),e.prev=5,t.s();case 7:if((r=t.n()).done){e.next=13;break}return r=r.value,e.next=11,n._destroyObjectIfPinned(r);case 11:e.next=7;break;case 13:e.next=18;break;case 15:e.prev=15,e.t0=e.catch(5),t.e(e.t0);case 18:return e.prev=18,t.f(),e.finish(18);case 21:return e.abrupt("return",y.default.resolve(i));case 22:case"end":return e.stop()}},e,null,[[5,15,18,21]])}))));case 15:if(i instanceof ee)return e.abrupt("return",r.request("DELETE","classes/"+i.className+"/"+i._getId(),{},l).then((0,j.default)(v.default.mark(function e(){return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n._destroyObjectIfPinned(i);case 2:return e.abrupt("return",y.default.resolve(i));case 3:case"end":return e.stop()}},e)}))));e.next=17;break;case 17:return e.abrupt("return",y.default.resolve(i));case 18:case"end":return e.stop()}},e)}))()},save:function(n,a){var u=a&&a.batchSize?a.batchSize:P.default.get("REQUEST_BATCH_SIZE"),s=P.default.getLocalDatastore(),c={},f=P.default.getRESTController(),d=P.default.getObjectStateController();if((a=a||{}).returnStatus=a.returnStatus||!0,(0,m.default)(n)){if(n.length<1)return y.default.resolve([]);for(var e=(0,g.default)(n).call(n),t=0;t<n.length;t++)n[t]instanceof ee&&(e=(0,g.default)(e).call(e,(0,Q.default)(n[t],!0)));e=(0,B.default)(e);var r=[],p=[];return(0,w.default)(e).call(e,function(e){e instanceof M.default?r.push(e.save(a)):e instanceof ee&&p.push(e)}),y.default.all(r).then(function(){var l=null;return(0,q.continueWhile)(function(){return 0<p.length},function(){var t=[],r=[];if((0,w.default)(p).call(p,function(e){(t.length<u&&(0,A.default)(e)?t:r).push(e)}),p=r,t.length<1)return y.default.reject(new L.default(L.default.OTHER_CAUSE,"Tried to save a batch with a cycle."));var s=new q.resolvingPromise,o=[],i=[];return(0,w.default)(t).call(t,function(n,a){var e=new q.resolvingPromise;o.push(e),d.pushPendingState(n._getStateIdentifier()),i.push(d.enqueueTask(n._getStateIdentifier(),function(){return e.resolve(),s.then(function(e){var t,r;e[a].hasOwnProperty("success")?(t=e[a].success.objectId,r=e[a]._status,delete e[a]._status,c[t]=n._localId,n._handleSaveResponse(e[a].success,r)):(!l&&e[a].hasOwnProperty("error")&&(e=e[a].error,l=new L.default(e.code,e.error),p=[]),n._handleSaveError())})}))}),(0,q.when)(o).then(function(){return f.request("POST","batch",{requests:(0,b.default)(t).call(t,function(e){e=e._getSaveParams();return e.path=Z()+e.path,e})},a)}).then(s.resolve,function(e){s.reject(new L.default(L.default.INCORRECT_TYPE,e.message))}),(0,q.when)(i)}).then((0,j.default)(v.default.mark(function e(){var t,r;return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:if(l)return e.abrupt("return",y.default.reject(l));e.next=2;break;case 2:t=V(n),e.prev=3,t.s();case 5:if((r=t.n()).done){e.next=13;break}return r=r.value,e.next=9,s._updateLocalIdForObject(c[r.id],r);case 9:return e.next=11,s._updateObjectIfPinned(r);case 11:e.next=5;break;case 13:e.next=18;break;case 15:e.prev=15,e.t0=e.catch(3),t.e(e.t0);case 18:return e.prev=18,t.f(),e.finish(18);case 21:return e.abrupt("return",y.default.resolve(n));case 22:case"end":return e.stop()}},e,null,[[3,15,18,21]])})))})}if(n instanceof ee){n._getId();var o=n._localId,i=n;return d.pushPendingState(n._getStateIdentifier()),d.enqueueTask(n._getStateIdentifier(),function(){var e=i._getSaveParams();return f.request(e.method,e.path,e.body,a).then(function(e){var t=e._status;delete e._status,i._handleSaveResponse(e,t)},function(e){return i._handleSaveError(),y.default.reject(e)})}).then((0,j.default)(v.default.mark(function e(){return v.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,s._updateLocalIdForObject(o,n);case 2:return e.next=4,s._updateObjectIfPinned(n);case 4:return e.abrupt("return",n);case 5:case"end":return e.stop()}},e)})),function(e){return y.default.reject(e)})}return y.default.resolve()}};P.default.setObjectController(e),r.default=ee},{"./CoreManager":4,"./LocalDatastoreUtils":13,"./ParseACL":17,"./ParseError":19,"./ParseFile":20,"./ParseOp":25,"./ParseQuery":27,"./ParseRelation":28,"./SingleInstanceStateController":35,"./UniqueInstanceStateController":40,"./canBeSerialized":43,"./decode":44,"./encode":45,"./escape":47,"./parseDate":49,"./promiseUtils":50,"./unique":51,"./unsavedChildren":52,"@babel/runtime-corejs3/core-js-stable/array/from":53,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/instance/concat":56,"@babel/runtime-corejs3/core-js-stable/instance/find":58,"@babel/runtime-corejs3/core-js-stable/instance/for-each":59,"@babel/runtime-corejs3/core-js-stable/instance/includes":60,"@babel/runtime-corejs3/core-js-stable/instance/index-of":61,"@babel/runtime-corejs3/core-js-stable/instance/map":63,"@babel/runtime-corejs3/core-js-stable/instance/slice":65,"@babel/runtime-corejs3/core-js-stable/json/stringify":70,"@babel/runtime-corejs3/core-js-stable/object/create":73,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/object/freeze":77,"@babel/runtime-corejs3/core-js-stable/object/keys":81,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/core-js-stable/symbol":87,"@babel/runtime-corejs3/core-js/get-iterator":92,"@babel/runtime-corejs3/core-js/get-iterator-method":91,"@babel/runtime-corejs3/helpers/asyncToGenerator":113,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/defineProperty":117,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/interopRequireWildcard":122,"@babel/runtime-corejs3/helpers/typeof":134,"@babel/runtime-corejs3/regenerator":137,"uuid/v4":476}],25:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.opFromJSON=function(e){if(!e||!e.__op)return null;switch(e.__op){case"Delete":return new E;case"Increment":return new O(e.amount);case"Add":return new P((0,j.default)(e.objects));case"AddUnique":return new A((0,j.default)(e.objects));case"Remove":return new T((0,j.default)(e.objects));case"AddRelation":var t=(0,j.default)(e.objects);return(0,m.default)(t)?new R(t,[]):new R([],[]);case"RemoveRelation":t=(0,j.default)(e.objects);return(0,m.default)(t)?new R([],t):new R([],[]);case"Batch":for(var r=[],n=[],a=0;a<e.ops.length;a++)"AddRelation"===e.ops[a].__op?r=(0,y.default)(r).call(r,(0,j.default)(e.ops[a].objects)):"RemoveRelation"===e.ops[a].__op&&(n=(0,y.default)(n).call(n,(0,j.default)(e.ops[a].objects)));return new R(r,n)}return null},r.RelationOp=r.RemoveOp=r.AddUniqueOp=r.AddOp=r.IncrementOp=r.UnsetOp=r.SetOp=r.Op=void 0;var a=n(e("@babel/runtime-corejs3/core-js-stable/reflect/construct")),s=n(e("@babel/runtime-corejs3/core-js-stable/instance/map")),o=n(e("@babel/runtime-corejs3/core-js-stable/instance/splice")),i=n(e("@babel/runtime-corejs3/core-js-stable/instance/index-of")),l=n(e("@babel/runtime-corejs3/core-js-stable/instance/for-each")),u=n(e("@babel/runtime-corejs3/helpers/assertThisInitialized")),c=n(e("@babel/runtime-corejs3/helpers/inherits")),f=n(e("@babel/runtime-corejs3/helpers/possibleConstructorReturn")),d=n(e("@babel/runtime-corejs3/helpers/getPrototypeOf")),p=n(e("@babel/runtime-corejs3/helpers/defineProperty")),b=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),h=n(e("@babel/runtime-corejs3/helpers/createClass")),y=n(e("@babel/runtime-corejs3/core-js-stable/instance/concat")),m=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),v=n(e("./arrayContainsObject")),j=n(e("./decode")),g=n(e("./encode")),_=n(e("./ParseObject")),w=n(e("./ParseRelation")),x=n(e("./unique"));function k(r){var n=function(){if("undefined"==typeof Reflect||!a.default)return!1;if(a.default.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call((0,a.default)(Date,[],function(){})),!0}catch(e){return!1}}();return function(){var e,t=(0,d.default)(r);return t=n?(e=(0,d.default)(this).constructor,(0,a.default)(t,arguments,e)):t.apply(this,arguments),(0,f.default)(this,t)}}var C=function(){function e(){(0,b.default)(this,e)}return(0,h.default)(e,[{key:"applyTo",value:function(){}},{key:"mergeWith",value:function(){}},{key:"toJSON",value:function(){}}]),e}();r.Op=C;var S=function(){(0,c.default)(n,C);var r=k(n);function n(e){var t;return(0,b.default)(this,n),t=r.call(this),(0,p.default)((0,u.default)(t),"_value",void 0),t._value=e,t}return(0,h.default)(n,[{key:"applyTo",value:function(){return this._value}},{key:"mergeWith",value:function(){return new n(this._value)}},{key:"toJSON",value:function(e){return(0,g.default)(this._value,!1,!0,void 0,e)}}]),n}();r.SetOp=S;var E=function(){(0,c.default)(t,C);var e=k(t);function t(){return(0,b.default)(this,t),e.apply(this,arguments)}return(0,h.default)(t,[{key:"applyTo",value:function(){}},{key:"mergeWith",value:function(){return new t}},{key:"toJSON",value:function(){return{__op:"Delete"}}}]),t}();r.UnsetOp=E;var O=function(){(0,c.default)(n,C);var r=k(n);function n(e){var t;if((0,b.default)(this,n),t=r.call(this),(0,p.default)((0,u.default)(t),"_amount",void 0),"number"!=typeof e)throw new TypeError("Increment Op must be initialized with a numeric amount.");return t._amount=e,t}return(0,h.default)(n,[{key:"applyTo",value:function(e){if(void 0===e)return this._amount;if("number"!=typeof e)throw new TypeError("Cannot increment a non-numeric value.");return this._amount+e}},{key:"mergeWith",value:function(e){if(!e)return this;if(e instanceof S)return new S(this.applyTo(e._value));if(e instanceof E)return new S(this._amount);if(e instanceof n)return new n(this.applyTo(e._amount));throw new Error("Cannot merge Increment Op with the previous Op")}},{key:"toJSON",value:function(){return{__op:"Increment",amount:this._amount}}}]),n}();r.IncrementOp=O;var P=function(){(0,c.default)(n,C);var r=k(n);function n(e){var t;return(0,b.default)(this,n),t=r.call(this),(0,p.default)((0,u.default)(t),"_value",void 0),t._value=(0,m.default)(e)?e:[e],t}return(0,h.default)(n,[{key:"applyTo",value:function(e){if(null==e)return this._value;if((0,m.default)(e))return(0,y.default)(e).call(e,this._value);throw new Error("Cannot add elements to a non-array value")}},{key:"mergeWith",value:function(e){if(!e)return this;if(e instanceof S)return new S(this.applyTo(e._value));if(e instanceof E)return new S(this._value);if(e instanceof n)return new n(this.applyTo(e._value));throw new Error("Cannot merge Add Op with the previous Op")}},{key:"toJSON",value:function(){return{__op:"Add",objects:(0,g.default)(this._value,!1,!0)}}}]),n}();r.AddOp=P;var A=function(){(0,c.default)(n,C);var r=k(n);function n(e){var t;return(0,b.default)(this,n),t=r.call(this),(0,p.default)((0,u.default)(t),"_value",void 0),t._value=(0,x.default)((0,m.default)(e)?e:[e]),t}return(0,h.default)(n,[{key:"applyTo",value:function(e){if(null==e)return this._value||[];if((0,m.default)(e)){var t,r=e,n=[];return(0,l.default)(t=this._value).call(t,function(e){e instanceof _.default?(0,v.default)(r,e)||n.push(e):(0,i.default)(r).call(r,e)<0&&n.push(e)}),(0,y.default)(e).call(e,n)}throw new Error("Cannot add elements to a non-array value")}},{key:"mergeWith",value:function(e){if(!e)return this;if(e instanceof S)return new S(this.applyTo(e._value));if(e instanceof E)return new S(this._value);if(e instanceof n)return new n(this.applyTo(e._value));throw new Error("Cannot merge AddUnique Op with the previous Op")}},{key:"toJSON",value:function(){return{__op:"AddUnique",objects:(0,g.default)(this._value,!1,!0)}}}]),n}();r.AddUniqueOp=A;var T=function(){(0,c.default)(n,C);var r=k(n);function n(e){var t;return(0,b.default)(this,n),t=r.call(this),(0,p.default)((0,u.default)(t),"_value",void 0),t._value=(0,x.default)((0,m.default)(e)?e:[e]),t}return(0,h.default)(n,[{key:"applyTo",value:function(e){if(null==e)return[];if((0,m.default)(e)){for(var t=(0,y.default)(e).call(e,[]),r=0;r<this._value.length;r++){for(var n=(0,i.default)(t).call(t,this._value[r]);-1<n;)(0,o.default)(t).call(t,n,1),n=(0,i.default)(t).call(t,this._value[r]);if(this._value[r]instanceof _.default&&this._value[r].id)for(var a=0;a<t.length;a++)t[a]instanceof _.default&&this._value[r].id===t[a].id&&((0,o.default)(t).call(t,a,1),a--)}return t}throw new Error("Cannot remove elements from a non-array value")}},{key:"mergeWith",value:function(e){if(!e)return this;if(e instanceof S)return new S(this.applyTo(e._value));if(e instanceof E)return new E;if(e instanceof n){for(var t=(0,y.default)(e=e._value).call(e,[]),r=0;r<this._value.length;r++)this._value[r]instanceof _.default?(0,v.default)(t,this._value[r])||t.push(this._value[r]):(0,i.default)(t).call(t,this._value[r])<0&&t.push(this._value[r]);return new n(t)}throw new Error("Cannot merge Remove Op with the previous Op")}},{key:"toJSON",value:function(){return{__op:"Remove",objects:(0,g.default)(this._value,!1,!0)}}}]),n}();r.RemoveOp=T;var R=function(){(0,c.default)(a,C);var n=k(a);function a(e,t){var r;return(0,b.default)(this,a),r=n.call(this),(0,p.default)((0,u.default)(r),"_targetClassName",void 0),(0,p.default)((0,u.default)(r),"relationsToAdd",void 0),(0,p.default)((0,u.default)(r),"relationsToRemove",void 0),(r._targetClassName=null,m.default)(e)&&(r.relationsToAdd=(0,x.default)((0,s.default)(e).call(e,r._extractId,(0,u.default)(r)))),(0,m.default)(t)&&(r.relationsToRemove=(0,x.default)((0,s.default)(t).call(t,r._extractId,(0,u.default)(r)))),r}return(0,h.default)(a,[{key:"_extractId",value:function(e){if("string"==typeof e)return e;if(!e.id)throw new Error("You cannot add or remove an unsaved Parse Object from a relation");if(this._targetClassName||(this._targetClassName=e.className),this._targetClassName!==e.className)throw new Error("Tried to create a Relation with 2 different object types: "+this._targetClassName+" and "+e.className+".");return e.id}},{key:"applyTo",value:function(e,t,r){if(!e){var n;if(!t||!r)throw new Error("Cannot apply a RelationOp without either a previous value, or an object and a key");var a=new _.default(t.className);t.id&&0===(0,i.default)(n=t.id).call(n,"local")?a._localId=t.id:t.id&&(a.id=t.id);r=new w.default(a,r);return r.targetClassName=this._targetClassName,r}if(e instanceof w.default){if(this._targetClassName)if(e.targetClassName){if(this._targetClassName!==e.targetClassName)throw new Error("Related object must be a "+e.targetClassName+", but a "+this._targetClassName+" was passed in.")}else e.targetClassName=this._targetClassName;return e}throw new Error("Relation cannot be applied to a non-relation field")}},{key:"mergeWith",value:function(e){if(!e)return this;if(e instanceof E)throw new Error("You cannot modify a relation after deleting it.");if(e instanceof S&&e._value instanceof w.default)return this;if(e instanceof a){var t;if(e._targetClassName&&e._targetClassName!==this._targetClassName)throw new Error("Related object must be of class "+e._targetClassName+", but "+(this._targetClassName||"null")+" was passed in.");var r=(0,y.default)(t=e.relationsToAdd).call(t,[]);(0,l.default)(t=this.relationsToRemove).call(t,function(e){e=(0,i.default)(r).call(r,e);-1<e&&(0,o.default)(r).call(r,e,1)}),(0,l.default)(t=this.relationsToAdd).call(t,function(e){(0,i.default)(r).call(r,e)<0&&r.push(e)});var n=(0,y.default)(e=e.relationsToRemove).call(e,[]);(0,l.default)(e=this.relationsToAdd).call(e,function(e){e=(0,i.default)(n).call(n,e);-1<e&&(0,o.default)(n).call(n,e,1)}),(0,l.default)(e=this.relationsToRemove).call(e,function(e){(0,i.default)(n).call(n,e)<0&&n.push(e)});e=new a(r,n);return e._targetClassName=this._targetClassName,e}throw new Error("Cannot merge Relation Op with the previous Op")}},{key:"toJSON",value:function(){function e(e){return{__type:"Pointer",className:r._targetClassName,objectId:e}}var t,r=this,n=null,a=null;return 0<this.relationsToAdd.length&&(n={__op:"AddRelation",objects:(0,s.default)(t=this.relationsToAdd).call(t,e)}),0<this.relationsToRemove.length&&(a={__op:"RemoveRelation",objects:(0,s.default)(t=this.relationsToRemove).call(t,e)}),n&&a?{__op:"Batch",ops:[n,a]}:n||a||{}}}]),a}();r.RelationOp=R},{"./ParseObject":24,"./ParseRelation":28,"./arrayContainsObject":42,"./decode":44,"./encode":45,"./unique":51,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/instance/concat":56,"@babel/runtime-corejs3/core-js-stable/instance/for-each":59,"@babel/runtime-corejs3/core-js-stable/instance/index-of":61,"@babel/runtime-corejs3/core-js-stable/instance/map":63,"@babel/runtime-corejs3/core-js-stable/instance/splice":67,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/reflect/construct":84,"@babel/runtime-corejs3/helpers/assertThisInitialized":112,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/defineProperty":117,"@babel/runtime-corejs3/helpers/getPrototypeOf":119,"@babel/runtime-corejs3/helpers/inherits":120,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/possibleConstructorReturn":129}],26:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var s=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),a=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),o=n(e("@babel/runtime-corejs3/helpers/createClass")),i=n(e("@babel/runtime-corejs3/helpers/defineProperty")),l=n(e("./ParseGeoPoint")),e=function(){function n(e){(0,a.default)(this,n),(0,i.default)(this,"_coordinates",void 0),this._coordinates=n._validate(e)}return(0,o.default)(n,[{key:"toJSON",value:function(){return n._validate(this._coordinates),{__type:"Polygon",coordinates:this._coordinates}}},{key:"equals",value:function(e){if(!(e instanceof n)||this.coordinates.length!==e.coordinates.length)return!1;for(var t=!0,r=1;r<this._coordinates.length;r+=1)if(this._coordinates[r][0]!=e.coordinates[r][0]||this._coordinates[r][1]!=e.coordinates[r][1]){t=!1;break}return t}},{key:"containsPoint",value:function(e){for(var t=this._coordinates[0][0],r=this._coordinates[0][0],n=this._coordinates[0][1],a=this._coordinates[0][1],s=1;s<this._coordinates.length;s+=1)var o=this._coordinates[s],t=Math.min(o[0],t),r=Math.max(o[0],r),n=Math.min(o[1],n),a=Math.max(o[1],a);if(e.latitude<t||e.latitude>r||e.longitude<n||e.longitude>a)return!1;for(var i=!1,l=0,u=this._coordinates.length-1;l<this._coordinates.length;u=l++){var c=this._coordinates[l][0],f=this._coordinates[l][1],d=this._coordinates[u][0],p=this._coordinates[u][1];f>e.longitude!=p>e.longitude&&e.latitude<(d-c)*(e.longitude-f)/(p-f)+c&&(i=!i)}return i}},{key:"coordinates",get:function(){return this._coordinates},set:function(e){this._coordinates=n._validate(e)}}],[{key:"_validate",value:function(e){if(!(0,s.default)(e))throw new TypeError("Coordinates must be an Array");if(e.length<3)throw new TypeError("Polygon must have at least 3 GeoPoints or Points");for(var t=[],r=0;r<e.length;r+=1){var n=e[r],a=void 0;if(n instanceof l.default)a=n;else{if(!(0,s.default)(n)||2!==n.length)throw new TypeError("Coordinates must be an Array of GeoPoints or Points");a=new l.default(n[0],n[1])}t.push([a.latitude,a.longitude])}return t}}]),n}();r.default=e},{"./ParseGeoPoint":21,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/defineProperty":117,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],27:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var o=n(e("@babel/runtime-corejs3/core-js-stable/object/entries")),d=n(e("@babel/runtime-corejs3/helpers/slicedToArray")),p=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),i=n(e("@babel/runtime-corejs3/helpers/toConsumableArray")),b=n(e("@babel/runtime-corejs3/core-js-stable/instance/find")),h=n(e("@babel/runtime-corejs3/core-js-stable/promise")),y=n(e("@babel/runtime-corejs3/regenerator")),u=n(e("@babel/runtime-corejs3/core-js-stable/instance/splice")),c=n(e("@babel/runtime-corejs3/core-js-stable/instance/sort")),m=n(e("@babel/runtime-corejs3/core-js-stable/instance/includes")),v=n(e("@babel/runtime-corejs3/core-js-stable/instance/concat")),j=n(e("@babel/runtime-corejs3/core-js-stable/instance/keys")),g=n(e("@babel/runtime-corejs3/core-js-stable/instance/filter")),_=n(e("@babel/runtime-corejs3/helpers/asyncToGenerator")),w=n(e("@babel/runtime-corejs3/core-js-stable/instance/map")),l=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),x=n(e("@babel/runtime-corejs3/helpers/createClass")),k=n(e("@babel/runtime-corejs3/helpers/defineProperty")),C=n(e("@babel/runtime-corejs3/core-js-stable/instance/slice")),S=n(e("@babel/runtime-corejs3/core-js-stable/object/keys")),E=n(e("@babel/runtime-corejs3/helpers/typeof")),O=n(e("@babel/runtime-corejs3/core-js-stable/instance/index-of")),P=n(e("@babel/runtime-corejs3/core-js-stable/instance/for-each")),A=n(e("./CoreManager")),T=n(e("./encode")),R=e("./promiseUtils"),I=n(e("./ParseError")),N=n(e("./ParseGeoPoint")),D=n(e("./ParseObject")),L=n(e("./OfflineQuery")),M=e("./LocalDatastoreUtils");function q(e){return"\\Q"+e.replace("\\E","\\E\\\\E\\Q")+"\\E"}function U(e){var t=null;return(0,P.default)(e).call(e,function(e){if((t=t||e.className)!==e.className)throw new Error("All queries must be for the same class.")}),t}function F(r,e){var s={};(0,P.default)(e).call(e,function(e){var n,a,t=-1!==(0,O.default)(e).call(e,".");t||r.hasOwnProperty(e)?t&&(t=e.split("."),n=r,a=s,(0,P.default)(t).call(t,function(e,t,r){n&&!n.hasOwnProperty(e)&&(n[e]=void 0),n&&"object"===(0,E.default)(n)&&(n=n[e]),t<r.length-1&&(a[e]||(a[e]={}),a=a[e])})):r[e]=void 0}),0<(0,S.default)(s).length&&function e(t,r,n,a){if(a)for(var s in t)t.hasOwnProperty(s)&&!r.hasOwnProperty(s)&&(r[s]=t[s]);for(var o in n)void 0!==r[o]&&null!==r[o]&&null!=t&&e(t[o],r[o],n[o],!0)}(A.default.getObjectStateController().getServerData({id:r.objectId,className:r.className}),r,s,!1)}n=function(){function f(e){if((0,l.default)(this,f),(0,k.default)(this,"className",void 0),(0,k.default)(this,"_where",void 0),(0,k.default)(this,"_include",void 0),(0,k.default)(this,"_exclude",void 0),(0,k.default)(this,"_select",void 0),(0,k.default)(this,"_limit",void 0),(0,k.default)(this,"_skip",void 0),(0,k.default)(this,"_count",void 0),(0,k.default)(this,"_order",void 0),(0,k.default)(this,"_readPreference",void 0),(0,k.default)(this,"_includeReadPreference",void 0),(0,k.default)(this,"_subqueryReadPreference",void 0),(0,k.default)(this,"_queriesLocalDatastore",void 0),(0,k.default)(this,"_localDatastorePinName",void 0),(0,k.default)(this,"_extraOptions",void 0),(0,k.default)(this,"_hint",void 0),(0,k.default)(this,"_explain",void 0),(0,k.default)(this,"_xhrRequest",void 0),"string"==typeof e)"User"===e&&A.default.get("PERFORM_USER_REWRITE")?this.className="_User":this.className=e;else if(e instanceof D.default)this.className=e.className;else{if("function"!=typeof e)throw new TypeError("A ParseQuery must be constructed with a ParseObject or class name.");"string"==typeof e.className?this.className=e.className:(e=new e,this.className=e.className)}this._where={},this._include=[],this._exclude=[],this._count=!1,this._limit=-1,this._skip=0,this._readPreference=null,this._includeReadPreference=null,this._subqueryReadPreference=null,this._queriesLocalDatastore=!1,this._localDatastorePinName=null,this._extraOptions={},this._xhrRequest={task:null,onchange:function(){}}}var e,t,r,n,a,s;return(0,x.default)(f,[{key:"_orQuery",value:function(e){e=(0,w.default)(e).call(e,function(e){return e.toJSON().where});return this._where.$or=e,this}},{key:"_andQuery",value:function(e){e=(0,w.default)(e).call(e,function(e){return e.toJSON().where});return this._where.$and=e,this}},{key:"_norQuery",value:function(e){e=(0,w.default)(e).call(e,function(e){return e.toJSON().where});return this._where.$nor=e,this}},{key:"_addCondition",value:function(e,t,r){return this._where[e]&&"string"!=typeof this._where[e]||(this._where[e]={}),this._where[e][t]=(0,T.default)(r,!1,!0),this}},{key:"_regexStartWith",value:function(e){return"^"+q(e)}},{key:"_handleOfflineQuery",value:(s=(0,_.default)(y.default.mark(function e(t){var r,n,a,s,o,i,l=this;return y.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return L.default.validateQuery(this),r=A.default.getLocalDatastore(),e.next=4,r._serializeObjectsFromPinName(this._localDatastorePinName);case 4:if(n=e.sent,n=(0,g.default)(n=(0,w.default)(n).call(n,function(e,t,r){var n=D.default.fromJSON(e,!1);return e._localId&&!e.objectId&&(n._localId=e._localId),L.default.matchesQuery(l.className,n,r,l)?n:null})).call(n,function(e){return null!==e}),(0,j.default)(t)&&(a=(0,j.default)(t).split(","),i=["className","objectId","createdAt","updatedAt","ACL"],a=(0,v.default)(a).call(a,i),n=(0,w.default)(n).call(n,function(e){var t=e._toFullJSON();return(0,P.default)(e=(0,S.default)(t)).call(e,function(e){(0,m.default)(a).call(a,e)||delete t[e]}),D.default.fromJSON(t,!1)})),t.order&&(s=t.order.split(","),(0,c.default)(n).call(n,function(e,t){return function e(t,r,n){var a=n[0],s="-"===(0,C.default)(a).call(a,0,1);if(s&&(a=a.substring(1)),"_created_at"===a&&(a="createdAt"),"_updated_at"===a&&(a="updatedAt"),!/^[A-Za-z][0-9A-Za-z_]*$/.test(a)||"password"===a)throw new I.default(I.default.INVALID_KEY_NAME,"Invalid Key: ".concat(a));var o=t.get(a),a=r.get(a);return o<a?s?1:-1:a<o?s?-1:1:1<n.length?e(t,r,(0,C.default)(n).call(n,1)):0}(e,t,s)})),t.count&&(o=n.length),t.skip&&(n=t.skip>=n.length?[]:(0,u.default)(n).call(n,t.skip,n.length)),i=n.length,0!==t.limit&&t.limit<n.length&&(i=t.limit),n=(0,u.default)(n).call(n,0,i),"number"==typeof o)return e.abrupt("return",{results:n,count:o});e.next=15;break;case 15:return e.abrupt("return",n);case 16:case"end":return e.stop()}},e,this)})),function(){return s.apply(this,arguments)})},{key:"toJSON",value:function(){var e,t={where:this._where};for(e in this._include.length&&(t.include=this._include.join(",")),this._exclude.length&&(t.excludeKeys=this._exclude.join(",")),this._select&&(t.keys=this._select.join(",")),this._count&&(t.count=1),0<=this._limit&&(t.limit=this._limit),0<this._skip&&(t.skip=this._skip),this._order&&(t.order=this._order.join(",")),this._readPreference&&(t.readPreference=this._readPreference),this._includeReadPreference&&(t.includeReadPreference=this._includeReadPreference),this._subqueryReadPreference&&(t.subqueryReadPreference=this._subqueryReadPreference),this._hint&&(t.hint=this._hint),this._explain&&(t.explain=!0),this._extraOptions)t[e]=this._extraOptions[e];return t}},{key:"withJSON",value:function(e){for(var t in e.where&&(this._where=e.where),e.include&&(this._include=e.include.split(",")),(0,j.default)(e)&&(this._select=(0,j.default)(e).split(",")),e.excludeKeys&&(this._exclude=e.excludeKeys.split(",")),e.count&&(this._count=1===e.count),e.limit&&(this._limit=e.limit),e.skip&&(this._skip=e.skip),e.order&&(this._order=e.order.split(",")),e.readPreference&&(this._readPreference=e.readPreference),e.includeReadPreference&&(this._includeReadPreference=e.includeReadPreference),e.subqueryReadPreference&&(this._subqueryReadPreference=e.subqueryReadPreference),e.hint&&(this._hint=e.hint),e.explain&&(this._explain=!!e.explain),e){var r;e.hasOwnProperty(t)&&-1===(0,O.default)(r=["where","include","keys","count","limit","skip","order","readPreference","includeReadPreference","subqueryReadPreference","hint","explain"]).call(r,t)&&(this._extraOptions[t]=e[t])}return this}},{key:"get",value:function(e,t){this.equalTo("objectId",e);e={};return t&&t.hasOwnProperty("useMasterKey")&&(e.useMasterKey=t.useMasterKey),t&&t.hasOwnProperty("sessionToken")&&(e.sessionToken=t.sessionToken),t&&t.hasOwnProperty("context")&&"object"===(0,E.default)(t.context)&&(e.context=t.context),this.first(e).then(function(e){if(e)return e;e=new I.default(I.default.OBJECT_NOT_FOUND,"Object not found.");return h.default.reject(e)})}},{key:"find",value:function(e){var n=this,t={};(e=e||{}).hasOwnProperty("useMasterKey")&&(t.useMasterKey=e.useMasterKey),e.hasOwnProperty("sessionToken")&&(t.sessionToken=e.sessionToken),e.hasOwnProperty("context")&&"object"===(0,E.default)(e.context)&&(t.context=e.context),this._setRequestTask(t);var e=A.default.getQueryController(),a=this._select;return this._queriesLocalDatastore?this._handleOfflineQuery(this.toJSON()):(0,b.default)(e).call(e,this.className,this.toJSON(),t).then(function(r){if(n._explain)return r.results;var e=(0,w.default)(t=r.results).call(t,function(e){var t=r.className||n.className;return e.className||(e.className=t),a&&F(e,a),D.default.fromJSON(e,!a)}),t=r.count;return"number"==typeof t?{results:e,count:t}:e})}},{key:"findAll",value:(a=(0,_.default)(y.default.mark(function e(t){var r;return y.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return r=[],e.next=3,this.eachBatch(function(e){var t;r=(0,v.default)(t=[]).call(t,(0,i.default)(r),(0,i.default)(e))},t);case 3:return e.abrupt("return",r);case 4:case"end":return e.stop()}},e,this)})),function(){return a.apply(this,arguments)})},{key:"count",value:function(e){var t={};(e=e||{}).hasOwnProperty("useMasterKey")&&(t.useMasterKey=e.useMasterKey),e.hasOwnProperty("sessionToken")&&(t.sessionToken=e.sessionToken),this._setRequestTask(t);var r=A.default.getQueryController(),e=this.toJSON();return e.limit=0,e.count=1,(0,b.default)(r).call(r,this.className,e,t).then(function(e){return e.count})}},{key:"distinct",value:function(e,t){var r={useMasterKey:!0};(t=t||{}).hasOwnProperty("sessionToken")&&(r.sessionToken=t.sessionToken),this._setRequestTask(r);t=A.default.getQueryController(),e={distinct:e,where:this._where,hint:this._hint};return t.aggregate(this.className,e,r).then(function(e){return e.results})}},{key:"aggregate",value:function(e,t){var r={useMasterKey:!0};(t=t||{}).hasOwnProperty("sessionToken")&&(r.sessionToken=t.sessionToken),this._setRequestTask(r);t=A.default.getQueryController();if(!(0,p.default)(e)&&"object"!==(0,E.default)(e))throw new Error("Invalid pipeline must be Array or Object");(0,S.default)(this._where||{}).length&&((0,p.default)(e)||(e=[e]),e.unshift({match:this._where}));e={pipeline:e,hint:this._hint,explain:this._explain,readPreference:this._readPreference};return t.aggregate(this.className,e,r).then(function(e){return e.results})}},{key:"first",value:function(e){var t=this,r={};(e=e||{}).hasOwnProperty("useMasterKey")&&(r.useMasterKey=e.useMasterKey),e.hasOwnProperty("sessionToken")&&(r.sessionToken=e.sessionToken),e.hasOwnProperty("context")&&"object"===(0,E.default)(e.context)&&(r.context=e.context),this._setRequestTask(r);var n=A.default.getQueryController(),e=this.toJSON();e.limit=1;var a=this._select;return this._queriesLocalDatastore?this._handleOfflineQuery(e).then(function(e){if(e[0])return e[0]}):(0,b.default)(n).call(n,this.className,e,r).then(function(e){e=e.results;if(e[0])return e[0].className||(e[0].className=t.className),a&&F(e[0],a),D.default.fromJSON(e[0],!a)})}},{key:"eachBatch",value:function(r,e){if(e=e||{},this._order||this._skip||0<=this._limit)return h.default.reject("Cannot iterate on a query with sort, skip, or limit.");var t,n,a=new f(this.className);for(n in a._limit=e.batchSize||100,a._include=(0,w.default)(t=this._include).call(t,function(e){return e}),this._select&&(a._select=(0,w.default)(t=this._select).call(t,function(e){return e})),a._hint=this._hint,a._where={},this._where){var s=this._where[n];if((0,p.default)(s))a._where[n]=(0,w.default)(s).call(s,function(e){return e});else if(s&&"object"===(0,E.default)(s)){var o,i={};for(o in a._where[n]=i,s)i[o]=s[o]}else a._where[n]=s}a.ascending("objectId");var l={};e.hasOwnProperty("useMasterKey")&&(l.useMasterKey=e.useMasterKey),e.hasOwnProperty("sessionToken")&&(l.sessionToken=e.sessionToken),e.hasOwnProperty("context")&&"object"===(0,E.default)(e.context)&&(l.context=e.context);var u=!1,c=[];return(0,R.continueWhile)(function(){return!u},(0,_.default)(y.default.mark(function e(){var t;return y.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,h.default.all([(0,b.default)(a).call(a,l),h.default.resolve(0<c.length&&r(c))]);case 2:if(t=e.sent,t=(0,d.default)(t,1),!((t=t[0]).length>=a._limit)){e.next=10;break}a.greaterThan("objectId",t[t.length-1].id),c=t,e.next=17;break;case 10:if(0<t.length)return e.next=13,h.default.resolve(r(t));e.next=16;break;case 13:u=!0,e.next=17;break;case 16:u=!0;case 17:case"end":return e.stop()}},e)})))}},{key:"each",value:function(r,e){return this.eachBatch(function(e){var t=h.default.resolve();return(0,P.default)(e).call(e,function(e){t=t.then(function(){return r(e)})}),t},e)}},{key:"hint",value:function(e){return void 0===e&&delete this._hint,this._hint=e,this}},{key:"explain",value:function(){var e=!(0<arguments.length&&void 0!==arguments[0])||arguments[0];if("boolean"!=typeof e)throw new Error("You can only set explain to a boolean value");return this._explain=e,this}},{key:"map",value:(n=(0,_.default)(y.default.mark(function e(t,r){var n,a,s=this;return y.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=[],a=0,e.next=4,this.each(function(e){return h.default.resolve(t(e,a,s)).then(function(e){n.push(e),a+=1})},r);case 4:return e.abrupt("return",n);case 5:case"end":return e.stop()}},e,this)})),function(){return n.apply(this,arguments)})},{key:"reduce",value:(r=(0,_.default)(y.default.mark(function e(t,r,n){var a,s;return y.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return a=r,s=0,e.next=4,this.each(function(e){return 0===s&&void 0===r?(a=e,void(s+=1)):h.default.resolve(t(a,e,s)).then(function(e){a=e,s+=1})},n);case 4:if(0===s&&void 0===r)throw new TypeError("Reducing empty query result set with no initial value");e.next=6;break;case 6:return e.abrupt("return",a);case 7:case"end":return e.stop()}},e,this)})),function(){return r.apply(this,arguments)})},{key:"filter",value:(t=(0,_.default)(y.default.mark(function e(r,t){var n,a,s=this;return y.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return n=[],a=0,e.next=4,this.each(function(t){return h.default.resolve(r(t,a,s)).then(function(e){e&&n.push(t),a+=1})},t);case 4:return e.abrupt("return",n);case 5:case"end":return e.stop()}},e,this)})),function(){return t.apply(this,arguments)})},{key:"equalTo",value:function(e,t){var r,n=this;return e&&"object"===(0,E.default)(e)?((0,P.default)(r=(0,o.default)(e)).call(r,function(e){var t=(0,d.default)(e,2),e=t[0],t=t[1];return n.equalTo(e,t)}),this):void 0===t?this.doesNotExist(e):(this._where[e]=(0,T.default)(t,!1,!0),this)}},{key:"notEqualTo",value:function(e,t){var r,n=this;return e&&"object"===(0,E.default)(e)?((0,P.default)(r=(0,o.default)(e)).call(r,function(e){var t=(0,d.default)(e,2),e=t[0],t=t[1];return n.notEqualTo(e,t)}),this):this._addCondition(e,"$ne",t)}},{key:"lessThan",value:function(e,t){return this._addCondition(e,"$lt",t)}},{key:"greaterThan",value:function(e,t){return this._addCondition(e,"$gt",t)}},{key:"lessThanOrEqualTo",value:function(e,t){return this._addCondition(e,"$lte",t)}},{key:"greaterThanOrEqualTo",value:function(e,t){return this._addCondition(e,"$gte",t)}},{key:"containedIn",value:function(e,t){return this._addCondition(e,"$in",t)}},{key:"notContainedIn",value:function(e,t){return this._addCondition(e,"$nin",t)}},{key:"containedBy",value:function(e,t){return this._addCondition(e,"$containedBy",t)}},{key:"containsAll",value:function(e,t){return this._addCondition(e,"$all",t)}},{key:"containsAllStartingWith",value:function(e,t){var r=this;(0,p.default)(t)||(t=[t]);t=(0,w.default)(t).call(t,function(e){return{$regex:r._regexStartWith(e)}});return this.containsAll(e,t)}},{key:"exists",value:function(e){return this._addCondition(e,"$exists",!0)}},{key:"doesNotExist",value:function(e){return this._addCondition(e,"$exists",!1)}},{key:"matches",value:function(e,t,r){return this._addCondition(e,"$regex",t),r=r||"",t.ignoreCase&&(r+="i"),t.multiline&&(r+="m"),r.length&&this._addCondition(e,"$options",r),this}},{key:"matchesQuery",value:function(e,t){var r=t.toJSON();return r.className=t.className,this._addCondition(e,"$inQuery",r)}},{key:"doesNotMatchQuery",value:function(e,t){var r=t.toJSON();return r.className=t.className,this._addCondition(e,"$notInQuery",r)}},{key:"matchesKeyInQuery",value:function(e,t,r){var n=r.toJSON();return n.className=r.className,this._addCondition(e,"$select",{key:t,query:n})}},{key:"doesNotMatchKeyInQuery",value:function(e,t,r){var n=r.toJSON();return n.className=r.className,this._addCondition(e,"$dontSelect",{key:t,query:n})}},{key:"contains",value:function(e,t){if("string"!=typeof t)throw new Error("The value being searched for must be a string.");return this._addCondition(e,"$regex",q(t))}},{key:"fullText",value:function(e,t,r){if(r=r||{},!e)throw new Error("A key is required.");if(!t)throw new Error("A search term is required");if("string"!=typeof t)throw new Error("The value being searched for must be a string.");var n,a={};for(n in a.$term=t,r)switch(n){case"language":a.$language=r[n];break;case"caseSensitive":a.$caseSensitive=r[n];break;case"diacriticSensitive":a.$diacriticSensitive=r[n];break;default:throw new Error("Unknown option: ".concat(n))}return this._addCondition(e,"$text",{$search:a})}},{key:"sortByTextScore",value:function(){return this.ascending("$score"),this.select(["$score"]),this}},{key:"startsWith",value:function(e,t){if("string"!=typeof t)throw new Error("The value being searched for must be a string.");return this._addCondition(e,"$regex",this._regexStartWith(t))}},{key:"endsWith",value:function(e,t){if("string"!=typeof t)throw new Error("The value being searched for must be a string.");return this._addCondition(e,"$regex",q(t)+"$")}},{key:"near",value:function(e,t){return t instanceof N.default||(t=new N.default(t)),this._addCondition(e,"$nearSphere",t)}},{key:"withinRadians",value:function(e,t,r,n){return n||void 0===n?(this.near(e,t),this._addCondition(e,"$maxDistance",r)):this._addCondition(e,"$geoWithin",{$centerSphere:[[t.longitude,t.latitude],r]})}},{key:"withinMiles",value:function(e,t,r,n){return this.withinRadians(e,t,r/3958.8,n)}},{key:"withinKilometers",value:function(e,t,r,n){return this.withinRadians(e,t,r/6371,n)}},{key:"withinGeoBox",value:function(e,t,r){return t instanceof N.default||(t=new N.default(t)),r instanceof N.default||(r=new N.default(r)),this._addCondition(e,"$within",{$box:[t,r]}),this}},{key:"withinPolygon",value:function(e,t){return this._addCondition(e,"$geoWithin",{$polygon:t})}},{key:"polygonContains",value:function(e,t){return this._addCondition(e,"$geoIntersects",{$point:t})}},{key:"ascending",value:function(){this._order=[];for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.addAscending.apply(this,t)}},{key:"addAscending",value:function(){var r=this;this._order||(this._order=[]);for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return(0,P.default)(t).call(t,function(e){var t;(0,p.default)(e)&&(e=e.join()),r._order=(0,v.default)(t=r._order).call(t,e.replace(/\s/g,"").split(","))}),this}},{key:"descending",value:function(){this._order=[];for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return this.addDescending.apply(this,t)}},{key:"addDescending",value:function(){var r=this;this._order||(this._order=[]);for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return(0,P.default)(t).call(t,function(e){var t;(0,p.default)(e)&&(e=e.join()),r._order=(0,v.default)(t=r._order).call(t,(0,w.default)(e=e.replace(/\s/g,"").split(",")).call(e,function(e){return"-"+e}))}),this}},{key:"skip",value:function(e){if("number"!=typeof e||e<0)throw new Error("You can only skip by a positive number");return this._skip=e,this}},{key:"limit",value:function(e){if("number"!=typeof e)throw new Error("You can only set the limit to a numeric value");return this._limit=e,this}},{key:"withCount",value:function(){var e=!(0<arguments.length&&void 0!==arguments[0])||arguments[0];if("boolean"!=typeof e)throw new Error("You can only set withCount to a boolean value");return this._count=e,this}},{key:"include",value:function(){for(var r=this,e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return(0,P.default)(t).call(t,function(e){var t;(0,p.default)(e)?r._include=(0,v.default)(t=r._include).call(t,e):r._include.push(e)}),this}},{key:"includeAll",value:function(){return this.include("*")}},{key:"select",value:function(){var r=this;this._select||(this._select=[]);for(var e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return(0,P.default)(t).call(t,function(e){var t;(0,p.default)(e)?r._select=(0,v.default)(t=r._select).call(t,e):r._select.push(e)}),this}},{key:"exclude",value:function(){for(var r=this,e=arguments.length,t=new Array(e),n=0;n<e;n++)t[n]=arguments[n];return(0,P.default)(t).call(t,function(e){var t;(0,p.default)(e)?r._exclude=(0,v.default)(t=r._exclude).call(t,e):r._exclude.push(e)}),this}},{key:"readPreference",value:function(e,t,r){return this._readPreference=e,this._includeReadPreference=t,this._subqueryReadPreference=r,this}},{key:"subscribe",value:(e=(0,_.default)(y.default.mark(function e(t){var r,n;return y.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,A.default.getUserController().currentUserAsync();case 2:return r=e.sent,t=t||(r?r.getSessionToken():void 0),e.next=6,A.default.getLiveQueryController().getDefaultLiveQueryClient();case 6:return(r=e.sent).shouldOpen()&&r.open(),n=r.subscribe(this,t),e.abrupt("return",n.subscribePromise.then(function(){return n}));case 10:case"end":return e.stop()}},e,this)})),function(){return e.apply(this,arguments)})},{key:"fromNetwork",value:function(){return this._queriesLocalDatastore=!1,this._localDatastorePinName=null,this}},{key:"fromLocalDatastore",value:function(){return this.fromPinWithName(null)}},{key:"fromPin",value:function(){return this.fromPinWithName(M.DEFAULT_PIN)}},{key:"fromPinWithName",value:function(e){return A.default.getLocalDatastore().checkIfEnabled()&&(this._queriesLocalDatastore=!0,this._localDatastorePinName=e),this}},{key:"cancel",value:function(){var e=this;return this._xhrRequest.task&&"function"==typeof this._xhrRequest.task.abort?(this._xhrRequest.task._aborted=!0,this._xhrRequest.task.abort(),this._xhrRequest.task=null,this._xhrRequest.onchange=function(){},this):this._xhrRequest.onchange=function(){return e.cancel()}}},{key:"_setRequestTask",value:function(e){var t=this;e.requestTask=function(e){t._xhrRequest.task=e,t._xhrRequest.onchange()}}}],[{key:"fromJSON",value:function(e,t){return new f(e).withJSON(t)}},{key:"or",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=new f(U(t));return n._orQuery(t),n}},{key:"and",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=new f(U(t));return n._andQuery(t),n}},{key:"nor",value:function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=new f(U(t));return n._norQuery(t),n}}]),f}(),e={find:function(e,t,r){return A.default.getRESTController().request("GET","classes/"+e,t,r)},aggregate:function(e,t,r){return A.default.getRESTController().request("GET","aggregate/"+e,t,r)}};A.default.setQueryController(e),r.default=n},{"./CoreManager":4,"./LocalDatastoreUtils":13,"./OfflineQuery":15,"./ParseError":19,"./ParseGeoPoint":21,"./ParseObject":24,"./encode":45,"./promiseUtils":50,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/instance/concat":56,"@babel/runtime-corejs3/core-js-stable/instance/filter":57,"@babel/runtime-corejs3/core-js-stable/instance/find":58,"@babel/runtime-corejs3/core-js-stable/instance/for-each":59,"@babel/runtime-corejs3/core-js-stable/instance/includes":60,"@babel/runtime-corejs3/core-js-stable/instance/index-of":61,"@babel/runtime-corejs3/core-js-stable/instance/keys":62,"@babel/runtime-corejs3/core-js-stable/instance/map":63,"@babel/runtime-corejs3/core-js-stable/instance/slice":65,"@babel/runtime-corejs3/core-js-stable/instance/sort":66,"@babel/runtime-corejs3/core-js-stable/instance/splice":67,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/object/entries":76,"@babel/runtime-corejs3/core-js-stable/object/keys":81,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/helpers/asyncToGenerator":113,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/defineProperty":117,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/slicedToArray":131,"@babel/runtime-corejs3/helpers/toConsumableArray":133,"@babel/runtime-corejs3/helpers/typeof":134,"@babel/runtime-corejs3/regenerator":137}],28:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),s=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),o=n(e("@babel/runtime-corejs3/helpers/createClass")),i=n(e("@babel/runtime-corejs3/helpers/defineProperty")),l=e("./ParseOp"),u=(n(e("./ParseObject")),n(e("./ParseQuery"))),e=function(){function r(e,t){(0,s.default)(this,r),(0,i.default)(this,"parent",void 0),(0,i.default)(this,"key",void 0),(0,i.default)(this,"targetClassName",void 0),this.parent=e,this.key=t,this.targetClassName=null}return(0,o.default)(r,[{key:"_ensureParentAndKey",value:function(e,t){if(this.key=this.key||t,this.key!==t)throw new Error("Internal Error. Relation retrieved from two different keys.");if(this.parent){if(this.parent.className!==e.className)throw new Error("Internal Error. Relation retrieved from two different Objects.");if(this.parent.id){if(this.parent.id!==e.id)throw new Error("Internal Error. Relation retrieved from two different Objects.")}else e.id&&(this.parent=e)}else this.parent=e}},{key:"add",value:function(e){(0,a.default)(e)||(e=[e]);var t=new l.RelationOp(e,[]),r=this.parent;if(!r)throw new Error("Cannot add to a Relation without a parent");return 0===e.length||(r.set(this.key,t),this.targetClassName=t._targetClassName),r}},{key:"remove",value:function(e){(0,a.default)(e)||(e=[e]);var t=new l.RelationOp([],e);if(!this.parent)throw new Error("Cannot remove from a Relation without a parent");0!==e.length&&(this.parent.set(this.key,t),this.targetClassName=t._targetClassName)}},{key:"toJSON",value:function(){return{__type:"Relation",className:this.targetClassName}}},{key:"query",value:function(){var e,t=this.parent;if(!t)throw new Error("Cannot construct a query for a Relation without a parent");return this.targetClassName?e=new u.default(this.targetClassName):(e=new u.default(t.className),e._extraOptions.redirectClassNameForKey=this.key),e._addCondition("$relatedTo","object",{__type:"Pointer",className:t.className,objectId:t.id}),e._addCondition("$relatedTo","key",this.key),e}}]),r}();r.default=e},{"./ParseObject":24,"./ParseOp":25,"./ParseQuery":27,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/defineProperty":117,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],29:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a=n(e("@babel/runtime-corejs3/core-js-stable/reflect/construct")),s=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),o=n(e("@babel/runtime-corejs3/helpers/createClass")),i=n(e("@babel/runtime-corejs3/helpers/get")),l=n(e("@babel/runtime-corejs3/helpers/inherits")),u=n(e("@babel/runtime-corejs3/helpers/possibleConstructorReturn")),c=n(e("@babel/runtime-corejs3/helpers/getPrototypeOf")),f=n(e("./ParseACL")),d=n(e("./ParseError")),n=n(e("./ParseObject"));function p(r){var n=function(){if("undefined"==typeof Reflect||!a.default)return!1;if(a.default.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call((0,a.default)(Date,[],function(){})),!0}catch(e){return!1}}();return function(){var e,t=(0,c.default)(r);return t=n?(e=(0,c.default)(this).constructor,(0,a.default)(t,arguments,e)):t.apply(this,arguments),(0,u.default)(this,t)}}e=function(e){(0,l.default)(a,e);var n=p(a);function a(e,t){var r;return(0,s.default)(this,a),r=n.call(this,"_Role"),"string"==typeof e&&t instanceof f.default&&(r.setName(e),r.setACL(t)),r}return(0,o.default)(a,[{key:"getName",value:function(){var e=this.get("name");return null==e||"string"==typeof e?e:""}},{key:"setName",value:function(e,t){return this.set("name",e,t)}},{key:"getUsers",value:function(){return this.relation("users")}},{key:"getRoles",value:function(){return this.relation("roles")}},{key:"validate",value:function(e,t){t=(0,i.default)((0,c.default)(a.prototype),"validate",this).call(this,e,t);if(t)return t;if("name"in e&&e.name!==this.getName()){t=e.name;if(this.id&&this.id!==e.objectId)return new d.default(d.default.OTHER_CAUSE,"A role's name can only be set before it has been saved.");if("string"!=typeof t)return new d.default(d.default.OTHER_CAUSE,"A role's name must be a String.");if(!/^[0-9a-zA-Z\-_ ]+$/.test(t))return new d.default(d.default.OTHER_CAUSE,"A role's name can be only contain alphanumeric characters, _, -, and spaces.")}return!1}}]),a}(n.default);n.default.registerSubclass("_Role",e),r.default=e},{"./ParseACL":17,"./ParseError":19,"./ParseObject":24,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/reflect/construct":84,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/get":118,"@babel/runtime-corejs3/helpers/getPrototypeOf":119,"@babel/runtime-corejs3/helpers/inherits":120,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/possibleConstructorReturn":129}],30:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a=n(e("@babel/runtime-corejs3/core-js-stable/instance/index-of")),s=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),o=n(e("@babel/runtime-corejs3/helpers/createClass")),i=n(e("@babel/runtime-corejs3/helpers/defineProperty")),l=n(e("./CoreManager")),u=n(e("./ParseObject")),c=["String","Number","Boolean","Date","File","GeoPoint","Polygon","Array","Object","Pointer","Relation"],n=function(){function t(e){(0,s.default)(this,t),(0,i.default)(this,"className",void 0),(0,i.default)(this,"_fields",void 0),(0,i.default)(this,"_indexes",void 0),(0,i.default)(this,"_clp",void 0),"string"==typeof e&&("User"===e&&l.default.get("PERFORM_USER_REWRITE")?this.className="_User":this.className=e),this._fields={},this._indexes={}}return(0,o.default)(t,[{key:"get",value:function(){return this.assertClassName(),l.default.getSchemaController().get(this.className).then(function(e){if(!e)throw new Error("Schema not found.");return e})}},{key:"save",value:function(){this.assertClassName();var e=l.default.getSchemaController(),t={className:this.className,fields:this._fields,indexes:this._indexes,classLevelPermissions:this._clp};return e.create(this.className,t)}},{key:"update",value:function(){this.assertClassName();var e=l.default.getSchemaController(),t={className:this.className,fields:this._fields,indexes:this._indexes,classLevelPermissions:this._clp};return this._fields={},this._indexes={},e.update(this.className,t)}},{key:"delete",value:function(){return this.assertClassName(),l.default.getSchemaController().delete(this.className)}},{key:"purge",value:function(){return this.assertClassName(),l.default.getSchemaController().purge(this.className)}},{key:"assertClassName",value:function(){if(!this.className)throw new Error("You must set a Class Name before making any request.")}},{key:"setCLP",value:function(e){return this._clp=e,this}},{key:"addField",value:function(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};if(t=t||"String",!e)throw new Error("field name may not be null.");if(-1===(0,a.default)(c).call(c,t))throw new Error("".concat(t," is not a valid type."));t={type:t};return"boolean"==typeof r.required&&(t.required=r.required),void 0!==r.defaultValue&&(t.defaultValue=r.defaultValue),this._fields[e]=t,this}},{key:"addIndex",value:function(e,t){if(!e)throw new Error("index name may not be null.");if(!t)throw new Error("index may not be null.");return this._indexes[e]=t,this}},{key:"addString",value:function(e,t){return this.addField(e,"String",t)}},{key:"addNumber",value:function(e,t){return this.addField(e,"Number",t)}},{key:"addBoolean",value:function(e,t){return this.addField(e,"Boolean",t)}},{key:"addDate",value:function(e,t){return t&&t.defaultValue&&(t.defaultValue={__type:"Date",iso:new Date(t.defaultValue)}),this.addField(e,"Date",t)}},{key:"addFile",value:function(e,t){return this.addField(e,"File",t)}},{key:"addGeoPoint",value:function(e,t){return this.addField(e,"GeoPoint",t)}},{key:"addPolygon",value:function(e,t){return this.addField(e,"Polygon",t)}},{key:"addArray",value:function(e,t){return this.addField(e,"Array",t)}},{key:"addObject",value:function(e,t){return this.addField(e,"Object",t)}},{key:"addPointer",value:function(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};if(!e)throw new Error("field name may not be null.");if(!t)throw new Error("You need to set the targetClass of the Pointer.");t={type:"Pointer",targetClass:t};return"boolean"==typeof r.required&&(t.required=r.required),void 0!==r.defaultValue&&(t.defaultValue=r.defaultValue,r.defaultValue instanceof u.default&&(t.defaultValue=r.defaultValue.toPointer())),this._fields[e]=t,this}},{key:"addRelation",value:function(e,t){if(!e)throw new Error("field name may not be null.");if(!t)throw new Error("You need to set the targetClass of the Relation.");return this._fields[e]={type:"Relation",targetClass:t},this}},{key:"deleteField",value:function(e){return this._fields[e]={__op:"Delete"},this}},{key:"deleteIndex",value:function(e){return this._indexes[e]={__op:"Delete"},this}}],[{key:"all",value:function(){return l.default.getSchemaController().get("").then(function(e){if(0===e.results.length)throw new Error("Schema not found.");return e.results})}}]),t}(),e={send:function(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};return l.default.getRESTController().request(t,"schemas/".concat(e),r,{useMasterKey:!0})},get:function(e){return this.send(e,"GET")},create:function(e,t){return this.send(e,"POST",t)},update:function(e,t){return this.send(e,"PUT",t)},delete:function(e){return this.send(e,"DELETE")},purge:function(e){return l.default.getRESTController().request("DELETE","purge/".concat(e),{},{useMasterKey:!0})}};l.default.setSchemaController(e),r.default=n},{"./CoreManager":4,"./ParseObject":24,"@babel/runtime-corejs3/core-js-stable/instance/index-of":61,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/defineProperty":117,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],31:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a=n(e("@babel/runtime-corejs3/core-js-stable/reflect/construct")),s=n(e("@babel/runtime-corejs3/core-js-stable/promise")),o=n(e("@babel/runtime-corejs3/helpers/typeof")),i=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),l=n(e("@babel/runtime-corejs3/helpers/createClass")),u=n(e("@babel/runtime-corejs3/helpers/inherits")),c=n(e("@babel/runtime-corejs3/helpers/possibleConstructorReturn")),f=n(e("@babel/runtime-corejs3/helpers/getPrototypeOf")),d=n(e("./CoreManager")),p=n(e("./isRevocableSession")),b=n(e("./ParseObject")),h=n(e("./ParseUser"));function y(r){var n=function(){if("undefined"==typeof Reflect||!a.default)return!1;if(a.default.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call((0,a.default)(Date,[],function(){})),!0}catch(e){return!1}}();return function(){var e,t=(0,f.default)(r);return t=n?(e=(0,f.default)(this).constructor,(0,a.default)(t,arguments,e)):t.apply(this,arguments),(0,c.default)(this,t)}}var m=function(e){(0,u.default)(n,e);var r=y(n);function n(e){var t;if((0,i.default)(this,n),t=r.call(this,"_Session"),e&&"object"===(0,o.default)(e)&&!t.set(e||{}))throw new Error("Can't create an invalid Session");return t}return(0,l.default)(n,[{key:"getSessionToken",value:function(){var e=this.get("sessionToken");return"string"==typeof e?e:""}}],[{key:"readOnlyAttributes",value:function(){return["createdWith","expiresAt","installationId","restricted","sessionToken","user"]}},{key:"current",value:function(e){e=e||{};var t=d.default.getSessionController(),r={};return e.hasOwnProperty("useMasterKey")&&(r.useMasterKey=e.useMasterKey),h.default.currentAsync().then(function(e){return e?(r.sessionToken=e.getSessionToken(),t.getSession(r)):s.default.reject("There is no current user.")})}},{key:"isCurrentSessionRevocable",value:function(){var e=h.default.current();return!!e&&(0,p.default)(e.getSessionToken()||"")}}]),n}(b.default);b.default.registerSubclass("_Session",m);b={getSession:function(e){var t=d.default.getRESTController(),r=new m;return t.request("GET","sessions/me",{},e).then(function(e){return r._finishFetch(e),r._setExisted(!0),r})}};d.default.setSessionController(b),r.default=m},{"./CoreManager":4,"./ParseObject":24,"./ParseUser":32,"./isRevocableSession":48,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/core-js-stable/reflect/construct":84,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/getPrototypeOf":119,"@babel/runtime-corejs3/helpers/inherits":120,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/possibleConstructorReturn":129,"@babel/runtime-corejs3/helpers/typeof":134}],32:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=void 0;var a=n(e("@babel/runtime-corejs3/regenerator")),s=n(e("@babel/runtime-corejs3/helpers/asyncToGenerator")),o=n(e("@babel/runtime-corejs3/core-js-stable/json/stringify")),i=n(e("@babel/runtime-corejs3/core-js-stable/reflect/construct")),l=n(e("@babel/runtime-corejs3/core-js-stable/object/define-property")),u=n(e("@babel/runtime-corejs3/core-js-stable/promise")),c=n(e("@babel/runtime-corejs3/helpers/typeof")),f=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),d=n(e("@babel/runtime-corejs3/helpers/createClass")),p=n(e("@babel/runtime-corejs3/helpers/get")),b=n(e("@babel/runtime-corejs3/helpers/inherits")),h=n(e("@babel/runtime-corejs3/helpers/possibleConstructorReturn")),y=n(e("@babel/runtime-corejs3/helpers/getPrototypeOf")),m=n(e("./AnonymousUtils")),v=n(e("./CoreManager")),j=n(e("./isRevocableSession")),g=n(e("./ParseError")),_=n(e("./ParseObject")),w=n(e("./ParseSession")),x=n(e("./Storage"));function k(r){var n=function(){if("undefined"==typeof Reflect||!i.default)return!1;if(i.default.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call((0,i.default)(Date,[],function(){})),!0}catch(e){return!1}}();return function(){var e,t=(0,y.default)(r);return t=n?(e=(0,y.default)(this).constructor,(0,i.default)(t,arguments,e)):t.apply(this,arguments),(0,h.default)(this,t)}}var C="currentUser",S=!v.default.get("IS_NODE"),E=!1,O=null,P={},e=function(e){(0,b.default)(a,e);var r=k(a);function a(e){var t;if((0,f.default)(this,a),t=r.call(this,"_User"),e&&"object"===(0,c.default)(e)&&!t.set(e||{}))throw new Error("Can't create an invalid Parse User");return t}return(0,d.default)(a,[{key:"_upgradeToRevocableSession",value:function(e){var t={};return(e=e||{}).hasOwnProperty("useMasterKey")&&(t.useMasterKey=e.useMasterKey),v.default.getUserController().upgradeToRevocableSession(this,t)}},{key:"linkWith",value:function(e,t){var r,s=this,o=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};if(o.sessionToken=o.sessionToken||this.getSessionToken()||"","string"==typeof e?e=P[r=e]?P[e]:P[(n={restoreAuthentication:function(){return!0},getAuthType:function(){return r}}).getAuthType()]=n:r=e.getAuthType(),t&&t.hasOwnProperty("authData")){var n=this.get("authData")||{};if("object"!==(0,c.default)(n))throw new Error("Invalid type: authData field should be an object");return n[r]=t.authData,v.default.getUserController().linkWith(this,n,o)}return new u.default(function(n,a){e.authenticate({success:function(e,t){var r={};r.authData=t,s.linkWith(e,r,o).then(function(){n(s)},function(e){a(e)})},error:function(e,t){a(t)}})})}},{key:"_linkWith",value:function(e,t){var r=2<arguments.length&&void 0!==arguments[2]?arguments[2]:{};return this.linkWith(e,t,r)}},{key:"_synchronizeAuthData",value:function(e){var t,r;this.isCurrent()&&e&&("string"==typeof e?e=P[t=e]:t=e.getAuthType(),r=this.get("authData"),e&&r&&"object"===(0,c.default)(r)&&(e.restoreAuthentication(r[t])||this._unlinkFrom(e)))}},{key:"_synchronizeAllAuthData",value:function(){var e=this.get("authData");if("object"===(0,c.default)(e))for(var t in e)this._synchronizeAuthData(t)}},{key:"_cleanupAuthData",value:function(){if(this.isCurrent()){var e=this.get("authData");if("object"===(0,c.default)(e))for(var t in e)e[t]||delete e[t]}}},{key:"_unlinkFrom",value:function(e,t){var r=this;return this.linkWith(e,{authData:null},t).then(function(){return r._synchronizeAuthData(e),u.default.resolve(r)})}},{key:"_isLinked",value:function(e){var t="string"==typeof e?e:e.getAuthType(),e=this.get("authData")||{};return"object"===(0,c.default)(e)&&!!e[t]}},{key:"_logOutWithAll",value:function(){var e=this.get("authData");if("object"===(0,c.default)(e))for(var t in e)this._logOutWith(t)}},{key:"_logOutWith",value:function(e){this.isCurrent()&&("string"==typeof e&&(e=P[e]),e&&e.deauthenticate&&e.deauthenticate())}},{key:"_preserveFieldsOnFetch",value:function(){return{sessionToken:this.get("sessionToken")}}},{key:"isCurrent",value:function(){var e=a.current();return!!e&&e.id===this.id}},{key:"getUsername",value:function(){var e=this.get("username");return null==e||"string"==typeof e?e:""}},{key:"setUsername",value:function(e){var t=this.get("authData");t&&"object"===(0,c.default)(t)&&t.hasOwnProperty("anonymous")&&(t.anonymous=null),this.set("username",e)}},{key:"setPassword",value:function(e){this.set("password",e)}},{key:"getEmail",value:function(){var e=this.get("email");return null==e||"string"==typeof e?e:""}},{key:"setEmail",value:function(e){return this.set("email",e)}},{key:"getSessionToken",value:function(){var e=this.get("sessionToken");return null==e||"string"==typeof e?e:""}},{key:"authenticated",value:function(){var e=a.current();return!!this.get("sessionToken")&&!!e&&e.id===this.id}},{key:"signUp",value:function(e,t){var r={};return(t=t||{}).hasOwnProperty("useMasterKey")&&(r.useMasterKey=t.useMasterKey),t.hasOwnProperty("installationId")&&(r.installationId=t.installationId),v.default.getUserController().signUp(this,e,r)}},{key:"logIn",value:function(e){var t={};return(e=e||{}).hasOwnProperty("useMasterKey")&&(t.useMasterKey=e.useMasterKey),e.hasOwnProperty("installationId")&&(t.installationId=e.installationId),e.hasOwnProperty("usePost")&&(t.usePost=e.usePost),v.default.getUserController().logIn(this,t)}},{key:"save",value:function(){for(var e=this,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return(0,p.default)((0,y.default)(a.prototype),"save",this).apply(this,r).then(function(){return e.isCurrent()?v.default.getUserController().updateUserOnDisk(e):e})}},{key:"destroy",value:function(){for(var e=this,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return(0,p.default)((0,y.default)(a.prototype),"destroy",this).apply(this,r).then(function(){return e.isCurrent()?v.default.getUserController().removeUserFromDisk():e})}},{key:"fetch",value:function(){for(var e=this,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return(0,p.default)((0,y.default)(a.prototype),"fetch",this).apply(this,r).then(function(){return e.isCurrent()?v.default.getUserController().updateUserOnDisk(e):e})}},{key:"fetchWithInclude",value:function(){for(var e=this,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];return(0,p.default)((0,y.default)(a.prototype),"fetchWithInclude",this).apply(this,r).then(function(){return e.isCurrent()?v.default.getUserController().updateUserOnDisk(e):e})}},{key:"verifyPassword",value:function(e,t){var r=this.getUsername()||"";return a.verifyPassword(r,e,t)}}],[{key:"readOnlyAttributes",value:function(){return["sessionToken"]}},{key:"extend",value:function(e,t){if(e)for(var r in e)"className"!==r&&(0,l.default)(a.prototype,r,{value:e[r],enumerable:!1,writable:!0,configurable:!0});if(t)for(var n in t)"className"!==n&&(0,l.default)(a,n,{value:t[n],enumerable:!1,writable:!0,configurable:!0});return a}},{key:"current",value:function(){return S?v.default.getUserController().currentUser():null}},{key:"currentAsync",value:function(){return S?v.default.getUserController().currentUserAsync():u.default.resolve(null)}},{key:"signUp",value:function(e,t,r,n){return(r=r||{}).username=e,r.password=t,new this(r).signUp({},n)}},{key:"logIn",value:function(e,t,r){if("string"!=typeof e)return u.default.reject(new g.default(g.default.OTHER_CAUSE,"Username must be a string."));if("string"!=typeof t)return u.default.reject(new g.default(g.default.OTHER_CAUSE,"Password must be a string."));var n=new this;return n._finishFetch({username:e,password:t}),n.logIn(r)}},{key:"become",value:function(e,t){if(!S)throw new Error("It is not memory-safe to become a user in a server environment");var r={sessionToken:e};(t=t||{}).hasOwnProperty("useMasterKey")&&(r.useMasterKey=t.useMasterKey);e=v.default.getUserController(),t=new this;return e.become(t,r)}},{key:"me",value:function(e){var t=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},r=v.default.getUserController(),e={sessionToken:e};t.useMasterKey&&(e.useMasterKey=t.useMasterKey);t=new this;return r.me(t,e)}},{key:"hydrate",value:function(e){var t=v.default.getUserController(),r=new this;return t.hydrate(r,e)}},{key:"logInWith",value:function(e,t,r){return(new this).linkWith(e,t,r)}},{key:"logOut",value:function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:{};return v.default.getUserController().logOut(e)}},{key:"requestPasswordReset",value:function(e,t){var r={};return(t=t||{}).hasOwnProperty("useMasterKey")&&(r.useMasterKey=t.useMasterKey),v.default.getUserController().requestPasswordReset(e,r)}},{key:"requestEmailVerification",value:function(e,t){var r={};return(t=t||{}).hasOwnProperty("useMasterKey")&&(r.useMasterKey=t.useMasterKey),v.default.getUserController().requestEmailVerification(e,r)}},{key:"verifyPassword",value:function(e,t,r){if("string"!=typeof e)return u.default.reject(new g.default(g.default.OTHER_CAUSE,"Username must be a string."));if("string"!=typeof t)return u.default.reject(new g.default(g.default.OTHER_CAUSE,"Password must be a string."));var n={};return(r=r||{}).hasOwnProperty("useMasterKey")&&(n.useMasterKey=r.useMasterKey),v.default.getUserController().verifyPassword(e,t,n)}},{key:"allowCustomUserClass",value:function(e){v.default.set("PERFORM_USER_REWRITE",!e)}},{key:"enableRevocableSession",value:function(e){if(e=e||{},v.default.set("FORCE_REVOCABLE_SESSION",!0),S){var t=a.current();if(t)return t._upgradeToRevocableSession(e)}return u.default.resolve()}},{key:"enableUnsafeCurrentUser",value:function(){S=!0}},{key:"disableUnsafeCurrentUser",value:function(){S=!1}},{key:"_registerAuthenticationProvider",value:function(t){P[t.getAuthType()]=t,a.currentAsync().then(function(e){e&&e._synchronizeAuthData(t.getAuthType())})}},{key:"_logInWith",value:function(e,t,r){return(new this).linkWith(e,t,r)}},{key:"_clearCache",value:function(){O=null,E=!1}},{key:"_setCurrentUserCache",value:function(e){O=e}}]),a}(_.default);_.default.registerSubclass("_User",e);var A={updateUserOnDisk:function(e){var t=x.default.generatePath(C),r=e.toJSON();delete r.password,r.className="_User";var n=(0,o.default)(r);return v.default.get("ENCRYPTED_USER")&&(n=v.default.getCryptoController().encrypt(r,v.default.get("ENCRYPTED_KEY"))),x.default.setItemAsync(t,n).then(function(){return e})},removeUserFromDisk:function(){var e=x.default.generatePath(C);return E=!0,O=null,x.default.removeItemAsync(e)},setCurrentUser:function(r){var n=this;return(0,s.default)(a.default.mark(function e(){var t;return a.default.wrap(function(e){for(;;)switch(e.prev=e.next){case 0:return e.next=2,n.currentUserAsync();case 2:if((t=e.sent)&&!r.equals(t)&&m.default.isLinked(t))return e.next=6,t.destroy({sessionToken:t.getSessionToken()});e.next=6;break;case 6:return(O=r)._cleanupAuthData(),r._synchronizeAllAuthData(),e.abrupt("return",A.updateUserOnDisk(r));case 10:case"end":return e.stop()}},e)}))()},currentUser:function(){if(O)return O;if(E)return null;if(x.default.async())throw new Error("Cannot call currentUser() when using a platform with an async storage system. Call currentUserAsync() instead.");var e=x.default.generatePath(C),e=x.default.getItem(e);if(E=!0,!e)return O=null;v.default.get("ENCRYPTED_USER")&&(e=v.default.getCryptoController().decrypt(e,v.default.get("ENCRYPTED_KEY"))),(e=JSON.parse(e)).className||(e.className="_User"),e._id&&(e.objectId!==e._id&&(e.objectId=e._id),delete e._id),e._sessionToken&&(e.sessionToken=e._sessionToken,delete e._sessionToken);e=_.default.fromJSON(e);return(O=e)._synchronizeAllAuthData(),e},currentUserAsync:function(){if(O)return u.default.resolve(O);if(E)return u.default.resolve(null);var e=x.default.generatePath(C);return x.default.getItemAsync(e).then(function(e){if(E=!0,!e)return O=null,u.default.resolve(null);v.default.get("ENCRYPTED_USER")&&(e=v.default.getCryptoController().decrypt(e.toString(),v.default.get("ENCRYPTED_KEY"))),(e=JSON.parse(e)).className||(e.className="_User"),e._id&&(e.objectId!==e._id&&(e.objectId=e._id),delete e._id),e._sessionToken&&(e.sessionToken=e._sessionToken,delete e._sessionToken);e=_.default.fromJSON(e);return(O=e)._synchronizeAllAuthData(),u.default.resolve(e)})},signUp:function(e,t,r){var n=t&&t.username||e.get("username"),a=t&&t.password||e.get("password");return n&&n.length?a&&a.length?e.save(t,r).then(function(){return e._finishFetch({password:void 0}),S?A.setCurrentUser(e):e}):u.default.reject(new g.default(g.default.OTHER_CAUSE,"Cannot sign up user with an empty password.")):u.default.reject(new g.default(g.default.OTHER_CAUSE,"Cannot sign up user with an empty username."))},logIn:function(t,e){var r=v.default.getRESTController(),n=v.default.getObjectStateController(),a={username:t.get("username"),password:t.get("password")};return r.request(e.usePost?"POST":"GET","login",a,e).then(function(e){return t._migrateId(e.objectId),t._setExisted(!0),n.setPendingOp(t._getStateIdentifier(),"username",void 0),n.setPendingOp(t._getStateIdentifier(),"password",void 0),e.password=void 0,t._finishFetch(e),S?A.setCurrentUser(t):u.default.resolve(t)})},become:function(t,e){return v.default.getRESTController().request("GET","users/me",{},e).then(function(e){return t._finishFetch(e),t._setExisted(!0),A.setCurrentUser(t)})},hydrate:function(e,t){return e._finishFetch(t),e._setExisted(!0),t.sessionToken&&S?A.setCurrentUser(e):u.default.resolve(e)},me:function(t,e){return v.default.getRESTController().request("GET","users/me",{},e).then(function(e){return t._finishFetch(e),t._setExisted(!0),t})},logOut:function(e){var a=v.default.getRESTController();return e.sessionToken?a.request("POST","logout",{},e):A.currentUserAsync().then(function(e){var t,r,n=x.default.generatePath(C),n=x.default.removeItemAsync(n);return null!==e&&(t=m.default.isLinked(e),(r=e.getSessionToken())&&(0,j.default)(r)&&(n=n.then(function(){if(t)return e.destroy({sessionToken:r})}).then(function(){return a.request("POST","logout",{},{sessionToken:r})})),e._logOutWithAll(),e._finishFetch({sessionToken:void 0})),E=!0,O=null,n})},requestPasswordReset:function(e,t){return v.default.getRESTController().request("POST","requestPasswordReset",{email:e},t)},upgradeToRevocableSession:function(r,e){var t=r.getSessionToken();return t?(e.sessionToken=t,v.default.getRESTController().request("POST","upgradeToRevocableSession",{},e).then(function(e){var t=new w.default;return t._finishFetch(e),r._finishFetch({sessionToken:t.getSessionToken()}),r.isCurrent()?A.setCurrentUser(r):u.default.resolve(r)})):u.default.reject(new g.default(g.default.SESSION_MISSING,"Cannot upgrade a user with no session token"))},linkWith:function(e,t,r){return e.save({authData:t},r).then(function(){return S?A.setCurrentUser(e):e})},verifyPassword:function(e,t,r){return v.default.getRESTController().request("GET","verifyPassword",{username:e,password:t},r)},requestEmailVerification:function(e,t){return v.default.getRESTController().request("POST","verificationEmailRequest",{email:e},t)}};v.default.setUserController(A),r.default=e},{"./AnonymousUtils":2,"./CoreManager":4,"./ParseError":19,"./ParseObject":24,"./ParseSession":31,"./Storage":37,"./isRevocableSession":48,"@babel/runtime-corejs3/core-js-stable/json/stringify":70,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/core-js-stable/reflect/construct":84,"@babel/runtime-corejs3/helpers/asyncToGenerator":113,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/get":118,"@babel/runtime-corejs3/helpers/getPrototypeOf":119,"@babel/runtime-corejs3/helpers/inherits":120,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/possibleConstructorReturn":129,"@babel/runtime-corejs3/helpers/typeof":134,"@babel/runtime-corejs3/regenerator":137}],33:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.send=function(e){e.where&&e.where instanceof o.default&&(e.where=e.where.toJSON().where);e.push_time&&"object"===(0,a.default)(e.push_time)&&(e.push_time=e.push_time.toJSON());e.expiration_time&&"object"===(0,a.default)(e.expiration_time)&&(e.expiration_time=e.expiration_time.toJSON());if(e.expiration_time&&e.expiration_interval)throw new Error("expiration_time and expiration_interval cannot both be set.");return s.default.getPushController().send(e)};var a=n(e("@babel/runtime-corejs3/helpers/typeof")),s=n(e("./CoreManager")),o=n(e("./ParseQuery"));e={send:function(e){return s.default.getRESTController().request("POST","push",e,{useMasterKey:!0})}};s.default.setPushController(e)},{"./CoreManager":4,"./ParseQuery":27,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/typeof":134}],34:[function(C,S,e){(function(m){"use strict";var e=C("@babel/runtime-corejs3/helpers/interopRequireDefault"),a=e(C("@babel/runtime-corejs3/core-js-stable/object/define-property")),s=e(C("@babel/runtime-corejs3/core-js-stable/object/define-properties")),o=e(C("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptors")),i=e(C("@babel/runtime-corejs3/core-js-stable/instance/for-each")),l=e(C("@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor")),u=e(C("@babel/runtime-corejs3/core-js-stable/instance/filter")),c=e(C("@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols")),f=e(C("@babel/runtime-corejs3/core-js-stable/object/keys")),d=e(C("@babel/runtime-corejs3/helpers/defineProperty")),p=e(C("@babel/runtime-corejs3/helpers/typeof")),v=e(C("@babel/runtime-corejs3/core-js-stable/set-timeout")),j=e(C("@babel/runtime-corejs3/core-js-stable/instance/includes")),g=e(C("@babel/runtime-corejs3/core-js-stable/json/stringify")),_=e(C("@babel/runtime-corejs3/core-js-stable/promise")),w=e(C("./CoreManager")),x=e(C("./ParseError")),t=C("./promiseUtils");function b(t,e){var r,n=(0,f.default)(t);return c.default&&(r=(0,c.default)(t),e&&(r=(0,u.default)(r).call(r,function(e){return(0,l.default)(t,e).enumerable})),n.push.apply(n,r)),n}function h(t){for(var e=1;e<arguments.length;e++){var r,n=null!=arguments[e]?arguments[e]:{};e%2?(0,i.default)(r=b(Object(n),!0)).call(r,function(e){(0,d.default)(t,e,n[e])}):o.default?(0,s.default)(t,(0,o.default)(n)):(0,i.default)(r=b(Object(n))).call(r,function(e){(0,a.default)(t,e,(0,l.default)(n,e))})}return t}var r=C("uuid/v4"),k=null;"undefined"!=typeof XMLHttpRequest&&(k=XMLHttpRequest),k=C("./Xhr.weapp");var n=!1;"undefined"==typeof XDomainRequest||"withCredentials"in new XMLHttpRequest||(n=!0);var y={ajax:function(i,l,u,c,f){var e,a,s,o,d;if(n)return a=i,s=l,o=u,d=f,new _.default(function(t,r){var n=new XDomainRequest;n.onload=function(){var e;try{e=JSON.parse(n.responseText)}catch(e){r(e)}e&&t({response:e})},n.onerror=n.ontimeout=function(){var e={responseText:(0,g.default)({code:x.default.X_DOMAIN_REQUEST,error:"IE's XDomainRequest does not supply error info."})};r(e)},n.onprogress=function(){d&&"function"==typeof d.progress&&d.progress(n.responseText)},n.open(a,s),n.send(o),d&&"function"==typeof d.requestTask&&d.requestTask(n)});var p=(0,t.resolvingPromise)(),b=w.default.get("IDEMPOTENCY")&&(0,j.default)(e=["POST","PUT"]).call(e,i),h=b?r():"",y=0;return function n(){if(null==k)throw new Error("Cannot make a request: No definition of XMLHttpRequest was found.");var a=!1,s=new k;s.onreadystatechange=function(){if(4===s.readyState&&!a&&!s._aborted)if(a=!0,200<=s.status&&s.status<300){try{var e,t=JSON.parse(s.responseText);"function"==typeof s.getResponseHeader&&(0,j.default)(e=s.getAllResponseHeaders()||"").call(e,"x-parse-job-status-id: ")&&(t=s.getResponseHeader("x-parse-job-status-id"))}catch(e){p.reject(e.toString())}t&&p.resolve({response:t,status:s.status,xhr:s})}else{var r;500<=s.status||0===s.status?++y<w.default.get("REQUEST_ATTEMPT_LIMIT")?(r=Math.round(125*Math.random()*Math.pow(2,y)),(0,v.default)(n,r)):0===s.status?p.reject("Unable to connect to the Parse API"):p.reject(s):p.reject(s)}},"string"!=typeof(c=c||{})["Content-Type"]&&(c["Content-Type"]="text/plain"),w.default.get("IS_NODE")&&(c["User-Agent"]="Parse/"+w.default.get("VERSION")+" (NodeJS "+m.versions.node+")"),b&&(c["X-Parse-Request-Id"]=h),w.default.get("SERVER_AUTH_TYPE")&&w.default.get("SERVER_AUTH_TOKEN")&&(c.Authorization=w.default.get("SERVER_AUTH_TYPE")+" "+w.default.get("SERVER_AUTH_TOKEN"));var e,t,r=w.default.get("REQUEST_HEADERS");for(e in r)c[e]=r[e];function o(e,t){f&&"function"==typeof f.progress&&(t.lengthComputable?f.progress(t.loaded/t.total,t.loaded,t.total,{type:e}):f.progress(null,null,null,{type:e}))}for(t in s.onprogress=function(e){o("download",e)},s.upload&&(s.upload.onprogress=function(e){o("upload",e)}),s.open(i,l,!0),c)s.setRequestHeader(t,c[t]);s.onabort=function(){p.resolve({response:{results:[]},status:0,xhr:s})},s.send(u),f&&"function"==typeof f.requestTask&&f.requestTask(s)}(),p},request:function(t,e,r,n){n=n||{};var a=w.default.get("SERVER_URL");"/"!==a[a.length-1]&&(a+="/"),a+=e;var s={};if(r&&"object"===(0,p.default)(r))for(var o in r)s[o]=r[o];e=n.context;void 0!==e&&(s._context=e),"POST"!==t&&(s._method=t,t="POST"),s._ApplicationId=w.default.get("APPLICATION_ID");e=w.default.get("JAVASCRIPT_KEY");e&&(s._JavaScriptKey=e),s._ClientVersion=w.default.get("VERSION");e=n.useMasterKey;if(void 0===e&&(e=w.default.get("USE_MASTER_KEY")),e){if(!w.default.get("MASTER_KEY"))throw new Error("Cannot use the Master Key, it has not been provided.");delete s._JavaScriptKey,s._MasterKey=w.default.get("MASTER_KEY")}w.default.get("FORCE_REVOCABLE_SESSION")&&(s._RevocableSession="1");e=n.installationId;return(e&&"string"==typeof e?_.default.resolve(e):w.default.getInstallationController().currentInstallationId()).then(function(e){s._InstallationId=e;e=w.default.getUserController();return n&&"string"==typeof n.sessionToken?_.default.resolve(n.sessionToken):e?e.currentUserAsync().then(function(e){return e?_.default.resolve(e.getSessionToken()):_.default.resolve(null)}):_.default.resolve(null)}).then(function(e){e&&(s._SessionToken=e);e=(0,g.default)(s);return y.ajax(t,a,e,{},n).then(function(e){var t=e.response,e=e.status;return n.returnStatus?h(h({},t),{},{_status:e}):t})}).catch(y.handleError)},handleError:function(t){if(t&&t.responseText)try{var e=JSON.parse(t.responseText),r=new x.default(e.code,e.error)}catch(e){r=new x.default(x.default.INVALID_JSON,"Received an error with invalid JSON from Parse: "+t.responseText)}else{var n=t.message?t.message:t;r=new x.default(x.default.CONNECTION_FAILED,"XMLHttpRequest failed: "+(0,g.default)(n))}return _.default.reject(r)},_setXHR:function(e){k=e},_getXHR:function(){return k}};S.exports=y}).call(this,C("_process"))},{"./CoreManager":4,"./ParseError":19,"./Xhr.weapp":41,"./promiseUtils":50,"@babel/runtime-corejs3/core-js-stable/instance/filter":57,"@babel/runtime-corejs3/core-js-stable/instance/for-each":59,"@babel/runtime-corejs3/core-js-stable/instance/includes":60,"@babel/runtime-corejs3/core-js-stable/json/stringify":70,"@babel/runtime-corejs3/core-js-stable/object/define-properties":74,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptor":78,"@babel/runtime-corejs3/core-js-stable/object/get-own-property-descriptors":79,"@babel/runtime-corejs3/core-js-stable/object/get-own-property-symbols":80,"@babel/runtime-corejs3/core-js-stable/object/keys":81,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/core-js-stable/set-timeout":85,"@babel/runtime-corejs3/helpers/defineProperty":117,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/typeof":134,_process:138,"uuid/v4":476}],35:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireWildcard");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.getState=o,r.initializeState=i,r.removeState=function(e){var t=o(e);return null!==t?(delete s[e.className][e.id],t):null},r.getServerData=l,r.setServerData=function(e,t){e=i(e).serverData;a.setServerData(e,t)},r.getPendingOps=u,r.setPendingOp=function(e,t,r){e=i(e).pendingOps;a.setPendingOp(e,t,r)},r.pushPendingState=function(e){e=i(e).pendingOps;a.pushPendingState(e)},r.popPendingState=function(e){e=i(e).pendingOps;return a.popPendingState(e)},r.mergeFirstPendingState=function(e){e=u(e);a.mergeFirstPendingState(e)},r.getObjectCache=function(e){e=o(e);if(e)return e.objectCache;return{}},r.estimateAttribute=function(e,t){var r=l(e),n=u(e);return a.estimateAttribute(r,n,e.className,e.id,t)},r.estimateAttributes=function(e){var t=l(e),r=u(e);return a.estimateAttributes(t,r,e.className,e.id)},r.commitServerChanges=function(e,t){e=i(e);a.commitServerChanges(e.serverData,e.objectCache,t)},r.enqueueTask=function(e,t){return i(e).tasks.enqueue(t)},r.clearAllState=function(){s={}},r.duplicateState=function(e,t){t.id=e.id};var a=n(e("./ObjectStateMutations")),s={};function o(e){var t=s[e.className];return t&&t[e.id]||null}function i(e,t){var r=o(e);return r||(s[e.className]||(s[e.className]={}),t=t||a.defaultState(),r=s[e.className][e.id]=t)}function l(e){e=o(e);return e?e.serverData:{}}function u(e){e=o(e);return e?e.pendingOps:[{}]}},{"./ObjectStateMutations":14,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/interopRequireWildcard":122}],36:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault"),a=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),s=n(e("@babel/runtime-corejs3/helpers/createClass"));t.exports=function(){function r(e){var t=this;(0,a.default)(this,r),this.onopen=function(){},this.onmessage=function(){},this.onclose=function(){},this.onerror=function(){},wx.onSocketOpen(function(){t.onopen()}),wx.onSocketMessage(function(e){t.onmessage(e)}),wx.onSocketClose(function(){t.onclose()}),wx.onSocketError(function(e){t.onerror(e)}),wx.connectSocket({url:e})}return(0,s.default)(r,[{key:"send",value:function(e){wx.sendSocketMessage({data:e})}},{key:"close",value:function(){wx.closeSocket()}}]),r}()},{"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],37:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault"),a=n(e("@babel/runtime-corejs3/core-js-stable/promise")),s=n(e("./CoreManager")),n={async:function(){return!!s.default.getStorageController().async},getItem:function(e){var t=s.default.getStorageController();if(1===t.async)throw new Error("Synchronous storage is not supported by the current storage controller");return t.getItem(e)},getItemAsync:function(e){var t=s.default.getStorageController();return 1===t.async?t.getItemAsync(e):a.default.resolve(t.getItem(e))},setItem:function(e,t){var r=s.default.getStorageController();if(1===r.async)throw new Error("Synchronous storage is not supported by the current storage controller");return r.setItem(e,t)},setItemAsync:function(e,t){var r=s.default.getStorageController();return 1===r.async?r.setItemAsync(e,t):a.default.resolve(r.setItem(e,t))},removeItem:function(e){var t=s.default.getStorageController();if(1===t.async)throw new Error("Synchronous storage is not supported by the current storage controller");return t.removeItem(e)},removeItemAsync:function(e){var t=s.default.getStorageController();return 1===t.async?t.removeItemAsync(e):a.default.resolve(t.removeItem(e))},getAllKeys:function(){var e=s.default.getStorageController();if(1===e.async)throw new Error("Synchronous storage is not supported by the current storage controller");return e.getAllKeys()},getAllKeysAsync:function(){var e=s.default.getStorageController();return 1===e.async?e.getAllKeysAsync():a.default.resolve(e.getAllKeys())},generatePath:function(e){if(!s.default.get("APPLICATION_ID"))throw new Error("You need to call Parse.initialize before using Parse.");if("string"!=typeof e)throw new Error("Tried to get a Storage path that was not a String.");return"/"===e[0]&&(e=e.substr(1)),"Parse/"+s.default.get("APPLICATION_ID")+"/"+e},_clear:function(){var e=s.default.getStorageController();e.hasOwnProperty("clear")&&e.clear()}};t.exports=n,s.default.setStorageController(e("./StorageController.weapp"))},{"./CoreManager":4,"./StorageController.weapp":38,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],38:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault")(e("@babel/runtime-corejs3/core-js-stable/instance/keys")),e={async:0,getItem:function(e){return wx.getStorageSync(e)},setItem:function(e,t){try{wx.setStorageSync(e,t)}catch(e){}},removeItem:function(e){wx.removeStorageSync(e)},getAllKeys:function(){var e=wx.getStorageInfoSync();return(0,n.default)(e)},clear:function(){wx.clearStorageSync()}};t.exports=e},{"@babel/runtime-corejs3/core-js-stable/instance/keys":62,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],39:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault"),a=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),s=n(e("@babel/runtime-corejs3/helpers/createClass")),o=n(e("@babel/runtime-corejs3/helpers/defineProperty")),i=e("./promiseUtils"),e=function(){function e(){(0,a.default)(this,e),(0,o.default)(this,"queue",void 0),this.queue=[]}return(0,s.default)(e,[{key:"enqueue",value:function(e){var t=this,r=new i.resolvingPromise;return this.queue.push({task:e,_completion:r}),1===this.queue.length&&e().then(function(){t._dequeue(),r.resolve()},function(e){t._dequeue(),r.reject(e)}),r}},{key:"_dequeue",value:function(){var t,r=this;this.queue.shift(),this.queue.length&&(t=this.queue[0]).task().then(function(){r._dequeue(),t._completion.resolve()},function(e){r._dequeue(),t._completion.reject(e)})}}]),e}();t.exports=e},{"./promiseUtils":50,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/defineProperty":117,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],40:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireWildcard"),a=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.getState=u,r.initializeState=c,r.removeState=function(e){var t=u(e);return null!==t?(l.delete(e),t):null},r.getServerData=f,r.setServerData=function(e,t){e=c(e).serverData;o.setServerData(e,t)},r.getPendingOps=d,r.setPendingOp=function(e,t,r){e=c(e).pendingOps;o.setPendingOp(e,t,r)},r.pushPendingState=function(e){e=c(e).pendingOps;o.pushPendingState(e)},r.popPendingState=function(e){e=c(e).pendingOps;return o.popPendingState(e)},r.mergeFirstPendingState=function(e){e=d(e);o.mergeFirstPendingState(e)},r.getObjectCache=function(e){e=u(e);if(e)return e.objectCache;return{}},r.estimateAttribute=function(e,t){var r=f(e),n=d(e);return o.estimateAttribute(r,n,e.className,e.id,t)},r.estimateAttributes=function(e){var t=f(e),r=d(e);return o.estimateAttributes(t,r,e.className,e.id)},r.commitServerChanges=function(e,t){e=c(e);o.commitServerChanges(e.serverData,e.objectCache,t)},r.enqueueTask=function(e,t){return c(e).tasks.enqueue(t)},r.duplicateState=function(e,t){var r,n=c(e),a=c(t);for(r in n.serverData)a.serverData[r]=n.serverData[r];for(var s,o=0;o<n.pendingOps.length;o++)for(var i in n.pendingOps[o])a.pendingOps[o][i]=n.pendingOps[o][i];for(s in n.objectCache)a.objectCache[s]=n.objectCache[s];a.existed=n.existed},r.clearAllState=function(){l=new s.default};var s=a(e("@babel/runtime-corejs3/core-js-stable/weak-map")),o=n(e("./ObjectStateMutations")),i=a(e("./TaskQueue")),l=new s.default;function u(e){return l.get(e)||null}function c(e,t){var r=u(e);return r||(r=t=t||{serverData:{},pendingOps:[{}],objectCache:{},tasks:new i.default,existed:!1},l.set(e,r),r)}function f(e){e=u(e);return e?e.serverData:{}}function d(e){e=u(e);return e?e.pendingOps:[{}]}},{"./ObjectStateMutations":14,"./TaskQueue":39,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/weak-map":88,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/interopRequireWildcard":122}],41:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault"),a=n(e("@babel/runtime-corejs3/core-js-stable/json/stringify")),s=n(e("@babel/runtime-corejs3/helpers/classCallCheck")),o=n(e("@babel/runtime-corejs3/helpers/createClass"));t.exports=function(){function e(){(0,s.default)(this,e),this.UNSENT=0,this.OPENED=1,this.HEADERS_RECEIVED=2,this.LOADING=3,this.DONE=4,this.header={},this.readyState=this.DONE,this.status=0,this.response="",this.responseType="",this.responseText="",this.responseHeader={},this.method="",this.url="",this.onabort=function(){},this.onprogress=function(){},this.onerror=function(){},this.onreadystatechange=function(){},this.requestTask=null}return(0,o.default)(e,[{key:"getAllResponseHeaders",value:function(){var e,t="";for(e in this.responseHeader)t+=e+":"+this.getResponseHeader(e)+"\r\n";return t}},{key:"getResponseHeader",value:function(e){return this.responseHeader[e]}},{key:"setRequestHeader",value:function(e,t){this.header[e]=t}},{key:"open",value:function(e,t){this.method=e,this.url=t}},{key:"abort",value:function(){this.requestTask&&(this.requestTask.abort(),this.status=0,this.response=void 0,this.onabort(),this.onreadystatechange())}},{key:"send",value:function(e){var t=this;this.requestTask=wx.request({url:this.url,method:this.method,data:e,header:this.header,responseType:this.responseType,success:function(e){t.status=e.statusCode,t.response=e.data,t.responseHeader=e.header,t.responseText=(0,a.default)(e.data),t.requestTask=null,t.onreadystatechange()},fail:function(e){t.requestTask=null,t.onerror(e)}}),this.requestTask.onProgressUpdate(function(e){e={lengthComputable:0!==e.totalBytesExpectedToWrite,loaded:e.totalBytesWritten,total:e.totalBytesExpectedToWrite};t.onprogress(e)})}}]),e}()},{"@babel/runtime-corejs3/core-js-stable/json/stringify":70,"@babel/runtime-corejs3/helpers/classCallCheck":114,"@babel/runtime-corejs3/helpers/createClass":116,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],42:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=function(e,t){if(-1<(0,a.default)(e).call(e,t))return!0;for(var r=0;r<e.length;r++)if(e[r]instanceof s.default&&e[r].className===t.className&&e[r]._getId()===t._getId())return!0;return!1};var a=n(e("@babel/runtime-corejs3/core-js-stable/instance/index-of")),s=n(e("./ParseObject"))},{"./ParseObject":24,"@babel/runtime-corejs3/core-js-stable/instance/index-of":61,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],43:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=function(e){if(!(e instanceof i.default))return!0;var t,r=e.attributes;for(t in r){if(!function e(t){if("object"!==(0,s.default)(t))return!0;if(t instanceof l.default)return!0;if(t instanceof i.default)return!!t.id;if(t instanceof o.default)return!!t.url();if((0,a.default)(t)){for(var r=0;r<t.length;r++)if(!e(t[r]))return!1;return!0}for(var n in t)if(!e(t[n]))return!1;return!0}(r[t]))return!1}return!0};var a=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),s=n(e("@babel/runtime-corejs3/helpers/typeof")),o=n(e("./ParseFile")),i=n(e("./ParseObject")),l=n(e("./ParseRelation"))},{"./ParseFile":20,"./ParseObject":24,"./ParseRelation":28,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/typeof":134}],44:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=function r(e){if(null===e||"object"!==(0,l.default)(e))return e;if((0,i.default)(e)){var n=[];return(0,o.default)(e).call(e,function(e,t){n[t]=r(e)}),n}if("string"==typeof e.__op)return(0,p.opFromJSON)(e);if("Pointer"===e.__type&&e.className)return d.default.fromJSON(e);if("Object"===e.__type&&e.className)return d.default.fromJSON(e);if("Relation"===e.__type){var t=new b.default(null,null);return t.targetClassName=e.className,t}if("Date"===e.__type)return new Date(e.iso);if("File"===e.__type)return u.default.fromJSON(e);if("GeoPoint"===e.__type)return new c.default({latitude:e.latitude,longitude:e.longitude});if("Polygon"===e.__type)return new f.default(e.coordinates);var a={};for(var s in e)a[s]=r(e[s]);return a};var o=n(e("@babel/runtime-corejs3/core-js-stable/instance/for-each")),i=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),l=n(e("@babel/runtime-corejs3/helpers/typeof")),u=(n(e("./ParseACL")),n(e("./ParseFile"))),c=n(e("./ParseGeoPoint")),f=n(e("./ParsePolygon")),d=n(e("./ParseObject")),p=e("./ParseOp"),b=n(e("./ParseRelation"))},{"./ParseACL":17,"./ParseFile":20,"./ParseGeoPoint":21,"./ParseObject":24,"./ParseOp":25,"./ParsePolygon":26,"./ParseRelation":28,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/instance/for-each":59,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/typeof":134}],45:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=function(e,t,r,n,a){return function t(e,r,n,a,s){if(e instanceof _.default){if(r)throw new Error("Parse Objects not allowed here");var o,i=e.id?e.className+":"+e.id:e;return n||!a||-1<(0,y.default)(a).call(a,i)||e.dirty()||(0,h.default)(e._getServerData()).length<1?s&&(0,b.default)(o=e._getId()).call(o,"local")?e.toOfflinePointer():e.toPointer():(a=(0,p.default)(a).call(a,i),e._toFullJSON(a,s))}if(e instanceof w.Op||e instanceof m.default||e instanceof j.default||e instanceof g.default||e instanceof x.default)return e.toJSON();if(e instanceof v.default){if(!e.url())throw new Error("Tried to encode an unsaved file.");return e.toJSON()}if("[object Date]"===Object.prototype.toString.call(e)){if(isNaN(e))throw new Error("Tried to encode an invalid date.");return{__type:"Date",iso:e.toJSON()}}if("[object RegExp]"===Object.prototype.toString.call(e)&&"string"==typeof e.source)return e.source;if((0,d.default)(e))return(0,f.default)(e).call(e,function(e){return t(e,r,n,a,s)});if(e&&"object"===(0,c.default)(e)){var l,u={};for(l in e)u[l]=t(e[l],r,n,a,s);return u}return e}(e,!!t,!!r,n||[],a)};var c=n(e("@babel/runtime-corejs3/helpers/typeof")),f=n(e("@babel/runtime-corejs3/core-js-stable/instance/map")),d=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),p=n(e("@babel/runtime-corejs3/core-js-stable/instance/concat")),b=n(e("@babel/runtime-corejs3/core-js-stable/instance/starts-with")),h=n(e("@babel/runtime-corejs3/core-js-stable/object/keys")),y=n(e("@babel/runtime-corejs3/core-js-stable/instance/index-of")),m=n(e("./ParseACL")),v=n(e("./ParseFile")),j=n(e("./ParseGeoPoint")),g=n(e("./ParsePolygon")),_=n(e("./ParseObject")),w=e("./ParseOp"),x=n(e("./ParseRelation"))},{"./ParseACL":17,"./ParseFile":20,"./ParseGeoPoint":21,"./ParseObject":24,"./ParseOp":25,"./ParsePolygon":26,"./ParseRelation":28,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/instance/concat":56,"@babel/runtime-corejs3/core-js-stable/instance/index-of":61,"@babel/runtime-corejs3/core-js-stable/instance/map":63,"@babel/runtime-corejs3/core-js-stable/instance/starts-with":68,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/object/keys":81,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/typeof":134}],46:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=function e(t,r){var n=Object.prototype.toString;if("[object Date]"===n.call(t)||"[object Date]"===n.call(r)){var a=new Date(t),n=new Date(r);return+a==+n}if((0,u.default)(t)!==(0,u.default)(r))return!1;if(!t||"object"!==(0,u.default)(t))return t===r;if((0,l.default)(t)||(0,l.default)(r)){if(!(0,l.default)(t)||!(0,l.default)(r))return!1;if(t.length!==r.length)return!1;for(var s=t.length;s--;)if(!e(t[s],r[s]))return!1;return!0}if(t instanceof c.default||t instanceof f.default||t instanceof d.default||t instanceof p.default)return t.equals(r);if(r instanceof p.default&&("Object"===t.__type||"Pointer"===t.__type))return t.objectId===r.id&&t.className===r.className;if((0,i.default)(t).length!==(0,i.default)(r).length)return!1;for(var o in t)if(!e(t[o],r[o]))return!1;return!0};var i=n(e("@babel/runtime-corejs3/core-js-stable/object/keys")),l=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),u=n(e("@babel/runtime-corejs3/helpers/typeof")),c=n(e("./ParseACL")),f=n(e("./ParseFile")),d=n(e("./ParseGeoPoint")),p=n(e("./ParseObject"))},{"./ParseACL":17,"./ParseFile":20,"./ParseGeoPoint":21,"./ParseObject":24,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/object/keys":81,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/typeof":134}],47:[function(e,t,r){"use strict";e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=function(e){return e.replace(/[&<>\/'"]/g,function(e){return n[e]})};var n={"&":"&amp;","<":"&lt;",">":"&gt;","/":"&#x2F;","'":"&#x27;",'"':"&quot;"}},{"@babel/runtime-corejs3/core-js-stable/object/define-property":75}],48:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=function(e){return-1<(0,a.default)(e).call(e,"r:")};var a=n(e("@babel/runtime-corejs3/core-js-stable/instance/index-of"))},{"@babel/runtime-corejs3/core-js-stable/instance/index-of":61,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],49:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=function(e){var t=new RegExp("^([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2})T([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})(.([0-9]+))?Z$").exec(e);if(!t)return null;var r=(0,i.default)(t[1])||0,n=((0,i.default)(t[2])||1)-1,a=(0,i.default)(t[3])||0,s=(0,i.default)(t[4])||0,o=(0,i.default)(t[5])||0,e=(0,i.default)(t[6])||0,t=(0,i.default)(t[8])||0;return new Date(Date.UTC(r,n,a,s,o,e,t))};var i=n(e("@babel/runtime-corejs3/core-js-stable/parse-int"))},{"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/parse-int":82,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],50:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.resolvingPromise=p,r.when=function(e){var t,r=(0,f.default)(e);t=r?e:arguments;var n=t.length,a=!1,s=[],o=r?[s]:s,i=[];if(s.length=t.length,i.length=t.length,0===n)return d.default.resolve(o);for(var l=new p,u=function(){--n<=0&&(a?l.reject(i):l.resolve(o))},c=0;c<t.length;c++)!function(e,t){e&&"function"==typeof e.then?e.then(function(e){s[t]=e,u()},function(e){i[t]=e,a=!0,u()}):(s[t]=e,u())}(t[c],c);return l},r.continueWhile=function e(t,r){if(t())return r().then(function(){return e(t,r)});return d.default.resolve()};var f=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),d=n(e("@babel/runtime-corejs3/core-js-stable/promise"));function p(){var r,n,e=new d.default(function(e,t){r=e,n=t});return e.resolve=r,e.reject=n,e}},{"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/core-js-stable/promise":83,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],51:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=function(e){var t=[];return(0,s.default)(e).call(e,function(e){e instanceof i.default?(0,o.default)(t,e)||t.push(e):(0,a.default)(t).call(t,e)<0&&t.push(e)}),t};var a=n(e("@babel/runtime-corejs3/core-js-stable/instance/index-of")),s=n(e("@babel/runtime-corejs3/core-js-stable/instance/for-each")),o=n(e("./arrayContainsObject")),i=n(e("./ParseObject"))},{"./ParseObject":24,"./arrayContainsObject":42,"@babel/runtime-corejs3/core-js-stable/instance/for-each":59,"@babel/runtime-corejs3/core-js-stable/instance/index-of":61,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/interopRequireDefault":121}],52:[function(e,t,r){"use strict";var n=e("@babel/runtime-corejs3/helpers/interopRequireDefault");e("@babel/runtime-corejs3/core-js-stable/object/define-property")(r,"__esModule",{value:!0}),r.default=function(e,t){var r={objects:{},files:[]},n=e.className+":"+e._getId();r.objects[n]=!e.dirty()||e;var a,s=e.attributes;for(a in s)"object"===(0,d.default)(s[a])&&!function t(e,r,n,a){if(e instanceof b.default){if(!e.id&&n)throw new Error("Cannot create a pointer to an unsaved Object.");var s=e.className+":"+e._getId();if(!r.objects[s]){r.objects[s]=!e.dirty()||e;var o,i=e.attributes;for(o in i)"object"===(0,d.default)(i[o])&&t(i[o],r,!a,a)}return}if(e instanceof p.default){return void(!e.url()&&(0,f.default)(s=r.files).call(s,e)<0&&r.files.push(e))}if(e instanceof h.default)return;(0,c.default)(e)&&(0,u.default)(e).call(e,function(e){"object"===(0,d.default)(e)&&t(e,r,n,a)});for(var l in e)"object"===(0,d.default)(e[l])&&t(e[l],r,n,a)}(s[a],r,!1,!!t);var o,i=[];for(o in r.objects)o!==n&&!0!==r.objects[o]&&i.push(r.objects[o]);return(0,l.default)(i).call(i,r.files)};var u=n(e("@babel/runtime-corejs3/core-js-stable/instance/for-each")),c=n(e("@babel/runtime-corejs3/core-js-stable/array/is-array")),f=n(e("@babel/runtime-corejs3/core-js-stable/instance/index-of")),l=n(e("@babel/runtime-corejs3/core-js-stable/instance/concat")),d=n(e("@babel/runtime-corejs3/helpers/typeof")),p=n(e("./ParseFile")),b=n(e("./ParseObject")),h=n(e("./ParseRelation"))},{"./ParseFile":20,"./ParseObject":24,"./ParseRelation":28,"@babel/runtime-corejs3/core-js-stable/array/is-array":54,"@babel/runtime-corejs3/core-js-stable/instance/concat":56,"@babel/runtime-corejs3/core-js-stable/instance/for-each":59,"@babel/runtime-corejs3/core-js-stable/instance/index-of":61,"@babel/runtime-corejs3/core-js-stable/object/define-property":75,"@babel/runtime-corejs3/helpers/interopRequireDefault":121,"@babel/runtime-corejs3/helpers/typeof":134}],53:[function(e,t,r){t.exports=e("core-js-pure/stable/array/from")},{"core-js-pure/stable/array/from":424}],54:[function(e,t,r){t.exports=e("core-js-pure/stable/array/is-array")},{"core-js-pure/stable/array/is-array":425}],55:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/bind")},{"core-js-pure/stable/instance/bind":429}],56:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/concat")},{"core-js-pure/stable/instance/concat":430}],57:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/filter")},{"core-js-pure/stable/instance/filter":431}],58:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/find")},{"core-js-pure/stable/instance/find":432}],59:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/for-each")},{"core-js-pure/stable/instance/for-each":433}],60:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/includes")},{"core-js-pure/stable/instance/includes":434}],61:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/index-of")},{"core-js-pure/stable/instance/index-of":435}],62:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/keys")},{"core-js-pure/stable/instance/keys":436}],63:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/map")},{"core-js-pure/stable/instance/map":437}],64:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/reduce")},{"core-js-pure/stable/instance/reduce":438}],65:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/slice")},{"core-js-pure/stable/instance/slice":439}],66:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/sort")},{"core-js-pure/stable/instance/sort":440}],67:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/splice")},{"core-js-pure/stable/instance/splice":441}],68:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/starts-with")},{"core-js-pure/stable/instance/starts-with":442}],69:[function(e,t,r){t.exports=e("core-js-pure/stable/instance/values")},{"core-js-pure/stable/instance/values":443}],70:[function(e,t,r){t.exports=e("core-js-pure/stable/json/stringify")},{"core-js-pure/stable/json/stringify":444}],71:[function(e,t,r){t.exports=e("core-js-pure/stable/map")},{"core-js-pure/stable/map":445}],72:[function(e,t,r){t.exports=e("core-js-pure/stable/object/assign")},{"core-js-pure/stable/object/assign":446}],73:[function(e,t,r){t.exports=e("core-js-pure/stable/object/create")},{"core-js-pure/stable/object/create":447}],74:[function(e,t,r){t.exports=e("core-js-pure/stable/object/define-properties")},{"core-js-pure/stable/object/define-properties":448}],75:[function(e,t,r){t.exports=e("core-js-pure/stable/object/define-property")},{"core-js-pure/stable/object/define-property":449}],76:[function(e,t,r){t.exports=e("core-js-pure/stable/object/entries")},{"core-js-pure/stable/object/entries":450}],77:[function(e,t,r){t.exports=e("core-js-pure/stable/object/freeze")},{"core-js-pure/stable/object/freeze":451}],78:[function(e,t,r){t.exports=e("core-js-pure/stable/object/get-own-property-descriptor")},{"core-js-pure/stable/object/get-own-property-descriptor":452}],79:[function(e,t,r){t.exports=e("core-js-pure/stable/object/get-own-property-descriptors")},{"core-js-pure/stable/object/get-own-property-descriptors":453}],80:[function(e,t,r){t.exports=e("core-js-pure/stable/object/get-own-property-symbols")},{"core-js-pure/stable/object/get-own-property-symbols":454}],81:[function(e,t,r){t.exports=e("core-js-pure/stable/object/keys")},{"core-js-pure/stable/object/keys":455}],82:[function(e,t,r){t.exports=e("core-js-pure/stable/parse-int")},{"core-js-pure/stable/parse-int":456}],83:[function(e,t,r){t.exports=e("core-js-pure/stable/promise")},{"core-js-pure/stable/promise":457}],84:[function(e,t,r){t.exports=e("core-js-pure/stable/reflect/construct")},{"core-js-pure/stable/reflect/construct":458}],85:[function(e,t,r){t.exports=e("core-js-pure/stable/set-timeout")},{"core-js-pure/stable/set-timeout":459}],86:[function(e,t,r){t.exports=e("core-js-pure/stable/set")},{"core-js-pure/stable/set":460}],87:[function(e,t,r){t.exports=e("core-js-pure/stable/symbol")},{"core-js-pure/stable/symbol":461}],88:[function(e,t,r){t.exports=e("core-js-pure/stable/weak-map")},{"core-js-pure/stable/weak-map":462}],89:[function(e,t,r){t.exports=e("core-js-pure/features/array/from")},{"core-js-pure/features/array/from":191}],90:[function(e,t,r){t.exports=e("core-js-pure/features/array/is-array")},{"core-js-pure/features/array/is-array":192}],91:[function(e,t,r){t.exports=e("core-js-pure/features/get-iterator-method")},{"core-js-pure/features/get-iterator-method":193}],92:[function(e,t,r){t.exports=e("core-js-pure/features/get-iterator")},{"core-js-pure/features/get-iterator":194}],93:[function(e,t,r){t.exports=e("core-js-pure/features/instance/bind")},{"core-js-pure/features/instance/bind":195}],94:[function(e,t,r){t.exports=e("core-js-pure/features/instance/index-of")},{"core-js-pure/features/instance/index-of":196}],95:[function(e,t,r){t.exports=e("core-js-pure/features/instance/slice")},{"core-js-pure/features/instance/slice":197}],96:[function(e,t,r){t.exports=e("core-js-pure/features/is-iterable")},{"core-js-pure/features/is-iterable":198}],97:[function(e,t,r){t.exports=e("core-js-pure/features/map")},{"core-js-pure/features/map":199}],98:[function(e,t,r){t.exports=e("core-js-pure/features/object/create")},{"core-js-pure/features/object/create":200}],99:[function(e,t,r){t.exports=e("core-js-pure/features/object/define-property")},{"core-js-pure/features/object/define-property":201}],100:[function(e,t,r){t.exports=e("core-js-pure/features/object/get-own-property-descriptor")},{"core-js-pure/features/object/get-own-property-descriptor":202}],101:[function(e,t,r){t.exports=e("core-js-pure/features/object/get-prototype-of")},{"core-js-pure/features/object/get-prototype-of":203}],102:[function(e,t,r){t.exports=e("core-js-pure/features/object/set-prototype-of")},{"core-js-pure/features/object/set-prototype-of":204}],103:[function(e,t,r){t.exports=e("core-js-pure/features/promise")},{"core-js-pure/features/promise":205}],104:[function(e,t,r){t.exports=e("core-js-pure/features/reflect/construct")},{"core-js-pure/features/reflect/construct":206}],105:[function(e,t,r){t.exports=e("core-js-pure/features/reflect/get")},{"core-js-pure/features/reflect/get":207}],106:[function(e,t,r){t.exports=e("core-js-pure/features/symbol")},{"core-js-pure/features/symbol":208}],107:[function(e,t,r){t.exports=e("core-js-pure/features/symbol/iterator")},{"core-js-pure/features/symbol/iterator":209}],108:[function(e,t,r){t.exports=e("core-js-pure/features/weak-map")},{"core-js-pure/features/weak-map":210}],109:[function(e,t,r){t.exports=function(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r<t;r++)n[r]=e[r];return n}},{}],110:[function(e,t,r){var n=e("@babel/runtime-corejs3/core-js/array/is-array");t.exports=function(e){if(n(e))return e}},{"@babel/runtime-corejs3/core-js/array/is-array":90}],111:[function(e,t,r){var n=e("@babel/runtime-corejs3/core-js/array/is-array"),a=e("./arrayLikeToArray");t.exports=function(e){if(n(e))return a(e)}},{"./arrayLikeToArray":109,"@babel/runtime-corejs3/core-js/array/is-array":90}],112:[function(e,t,r){t.exports=function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}},{}],113:[function(e,t,r){var u=e("@babel/runtime-corejs3/core-js/promise");function l(e,t,r,n,a,s,o){try{var i=e[s](o),l=i.value}catch(e){return void r(e)}i.done?t(l):u.resolve(l).then(n,a)}t.exports=function(i){return function(){var e=this,o=arguments;return new u(function(t,r){var n=i.apply(e,o);function a(e){l(n,t,r,a,s,"next",e)}function s(e){l(n,t,r,a,s,"throw",e)}a(void 0)})}}},{"@babel/runtime-corejs3/core-js/promise":103}],114:[function(e,t,r){t.exports=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}},{}],115:[function(e,n,t){var a=e("@babel/runtime-corejs3/core-js/instance/bind"),s=e("@babel/runtime-corejs3/core-js/reflect/construct"),o=e("./setPrototypeOf"),i=e("./isNativeReflectConstruct");function l(e,t,r){return i()?n.exports=l=s:n.exports=l=function(e,t,r){var n=[null];n.push.apply(n,t);n=new(a(Function).apply(e,n));return r&&o(n,r.prototype),n},l.apply(null,arguments)}n.exports=l},{"./isNativeReflectConstruct":124,"./setPrototypeOf":130,"@babel/runtime-corejs3/core-js/instance/bind":93,"@babel/runtime-corejs3/core-js/reflect/construct":104}],116:[function(e,t,r){var a=e("@babel/runtime-corejs3/core-js/object/define-property");function n(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),a(e,n.key,n)}}t.exports=function(e,t,r){return t&&n(e.prototype,t),r&&n(e,r),e}},{"@babel/runtime-corejs3/core-js/object/define-property":99}],117:[function(e,t,r){var n=e("@babel/runtime-corejs3/core-js/object/define-property");t.exports=function(e,t,r){return t in e?n(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}},{"@babel/runtime-corejs3/core-js/object/define-property":99}],118:[function(e,n,t){var a=e("@babel/runtime-corejs3/core-js/object/get-own-property-descriptor"),s=e("@babel/runtime-corejs3/core-js/reflect/get"),o=e("./superPropBase");function i(e,t,r){return"undefined"!=typeof Reflect&&s?n.exports=i=s:n.exports=i=function(e,t,r){e=o(e,t);if(e){t=a(e,t);return t.get?t.get.call(r):t.value}},i(e,t,r||e)}n.exports=i},{"./superPropBase":132,"@babel/runtime-corejs3/core-js/object/get-own-property-descriptor":100,"@babel/runtime-corejs3/core-js/reflect/get":105}],119:[function(e,t,r){var n=e("@babel/runtime-corejs3/core-js/object/get-prototype-of"),a=e("@babel/runtime-corejs3/core-js/object/set-prototype-of");function s(e){return t.exports=s=a?n:function(e){return e.__proto__||n(e)},s(e)}t.exports=s},{"@babel/runtime-corejs3/core-js/object/get-prototype-of":101,"@babel/runtime-corejs3/core-js/object/set-prototype-of":102}],120:[function(e,t,r){var n=e("@babel/runtime-corejs3/core-js/object/create"),a=e("./setPrototypeOf");t.exports=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=n(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&a(e,t)}},{"./setPrototypeOf":130,"@babel/runtime-corejs3/core-js/object/create":98}],121:[function(e,t,r){t.exports=function(e){return e&&e.__esModule?e:{default:e}}},{}],122:[function(e,t,r){var o=e("@babel/runtime-corejs3/core-js/object/get-own-property-descriptor"),i=e("@babel/runtime-corejs3/core-js/object/define-property"),l=e("@babel/runtime-corejs3/helpers/typeof"),n=e("@babel/runtime-corejs3/core-js/weak-map");function u(){if("function"!=typeof n)return null;var e=new n;return u=function(){return e},e}t.exports=function(e){if(e&&e.__esModule)return e;if(null===e||"object"!==l(e)&&"function"!=typeof e)return{default:e};var t=u();if(t&&t.has(e))return t.get(e);var r,n,a={},s=i&&o;for(r in e){Object.prototype.hasOwnProperty.call(e,r)&&((n=s?o(e,r):null)&&(n.get||n.set)?i(a,r,n):a[r]=e[r])}return a.default=e,t&&t.set(e,a),a}},{"@babel/runtime-corejs3/core-js/object/define-property":99,"@babel/runtime-corejs3/core-js/object/get-own-property-descriptor":100,"@babel/runtime-corejs3/core-js/weak-map":108,"@babel/runtime-corejs3/helpers/typeof":134}],123:[function(e,t,r){var n=e("@babel/runtime-corejs3/core-js/instance/index-of");t.exports=function(e){return-1!==n(e=Function.toString.call(e)).call(e,"[native code]")}},{"@babel/runtime-corejs3/core-js/instance/index-of":94}],124:[function(e,t,r){var n=e("@babel/runtime-corejs3/core-js/reflect/construct");t.exports=function(){if("undefined"==typeof Reflect||!n)return!1;if(n.sham)return!1;if("function"==typeof Proxy)return!0;try{return Date.prototype.toString.call(n(Date,[],function(){})),!0}catch(e){return!1}}},{"@babel/runtime-corejs3/core-js/reflect/construct":104}],125:[function(e,t,r){var n=e("@babel/runtime-corejs3/core-js/array/from"),a=e("@babel/runtime-corejs3/core-js/is-iterable"),s=e("@babel/runtime-corejs3/core-js/symbol");t.exports=function(e){if(void 0!==s&&a(Object(e)))return n(e)}},{"@babel/runtime-corejs3/core-js/array/from":89,"@babel/runtime-corejs3/core-js/is-iterable":96,"@babel/runtime-corejs3/core-js/symbol":106}],126:[function(e,t,r){var l=e("@babel/runtime-corejs3/core-js/get-iterator"),u=e("@babel/runtime-corejs3/core-js/is-iterable"),c=e("@babel/runtime-corejs3/core-js/symbol");t.exports=function(e,t){if(void 0!==c&&u(Object(e))){var r=[],n=!0,a=!1,s=void 0;try{for(var o,i=l(e);!(n=(o=i.next()).done)&&(r.push(o.value),!t||r.length!==t);n=!0);}catch(e){a=!0,s=e}finally{try{n||null==i.return||i.return()}finally{if(a)throw s}}return r}}},{"@babel/runtime-corejs3/core-js/get-iterator":92,"@babel/runtime-corejs3/core-js/is-iterable":96,"@babel/runtime-corejs3/core-js/symbol":106}],127:[function(e,t,r){t.exports=function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}},{}],128:[function(e,t,r){t.exports=function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}},{}],129:[function(e,t,r){var n=e("@babel/runtime-corejs3/helpers/typeof"),a=e("./assertThisInitialized");t.exports=function(e,t){return!t||"object"!==n(t)&&"function"!=typeof t?a(e):t}},{"./assertThisInitialized":112,"@babel/runtime-corejs3/helpers/typeof":134}],130:[function(e,r,t){var n=e("@babel/runtime-corejs3/core-js/object/set-prototype-of");function a(e,t){return r.exports=a=n||function(e,t){return e.__proto__=t,e},a(e,t)}r.exports=a},{"@babel/runtime-corejs3/core-js/object/set-prototype-of":102}],131:[function(e,t,r){var n=e("./arrayWithHoles"),a=e("./iterableToArrayLimit"),s=e("./unsupportedIterableToArray"),o=e("./nonIterableRest");t.exports=function(e,t){return n(e)||a(e,t)||s(e,t)||o()}},{"./arrayWithHoles":110,"./iterableToArrayLimit":126,"./nonIterableRest":127,"./unsupportedIterableToArray":135}],132:[function(e,t,r){var n=e("./getPrototypeOf");t.exports=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=n(e)););return e}},{"./getPrototypeOf":119}],133:[function(e,t,r){var n=e("./arrayWithoutHoles"),a=e("./iterableToArray"),s=e("./unsupportedIterableToArray"),o=e("./nonIterableSpread");t.exports=function(e){return n(e)||a(e)||s(e)||o()}},{"./arrayWithoutHoles":111,"./iterableToArray":125,"./nonIterableSpread":128,"./unsupportedIterableToArray":135}],134:[function(e,t,r){var n=e("@babel/runtime-corejs3/core-js/symbol/iterator"),a=e("@babel/runtime-corejs3/core-js/symbol");function s(e){return t.exports=s="function"==typeof a&&"symbol"==typeof n?function(e){return typeof e}:function(e){return e&&"function"==typeof a&&e.constructor===a&&e!==a.prototype?"symbol":typeof e},s(e)}t.exports=s},{"@babel/runtime-corejs3/core-js/symbol":106,"@babel/runtime-corejs3/core-js/symbol/iterator":107}],135:[function(e,t,r){var n=e("@babel/runtime-corejs3/core-js/array/from"),a=e("@babel/runtime-corejs3/core-js/instance/slice"),s=e("./arrayLikeToArray");t.exports=function(e,t){if(e){if("string"==typeof e)return s(e,t);var r=a(r=Object.prototype.toString.call(e)).call(r,8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?n(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?s(e,t):void 0}}},{"./arrayLikeToArray":109,"@babel/runtime-corejs3/core-js/array/from":89,"@babel/runtime-corejs3/core-js/instance/slice":95}],136:[function(e,t,r){var n=e("@babel/runtime-corejs3/core-js/object/create"),a=e("@babel/runtime-corejs3/core-js/map"),s=e("./getPrototypeOf"),o=e("./setPrototypeOf"),i=e("./isNativeFunction"),l=e("./construct");function u(e){var r="function"==typeof a?new a:void 0;return t.exports=u=function(e){if(null===e||!i(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==r){if(r.has(e))return r.get(e);r.set(e,t)}function t(){return l(e,arguments,s(this).constructor)}return t.prototype=n(e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),o(t,e)},u(e)}t.exports=u},{"./construct":115,"./getPrototypeOf":119,"./isNativeFunction":123,"./setPrototypeOf":130,"@babel/runtime-corejs3/core-js/map":97,"@babel/runtime-corejs3/core-js/object/create":98}],137:[function(e,t,r){t.exports=e("regenerator-runtime")},{"regenerator-runtime":473}],138:[function(e,t,r){},{}],139:[function(e,t,r){e("../../modules/es.string.iterator"),e("../../modules/es.array.from");e=e("../../internals/path");t.exports=e.Array.from},{"../../internals/path":304,"../../modules/es.array.from":337,"../../modules/es.string.iterator":372}],140:[function(e,t,r){e("../../modules/es.array.is-array");e=e("../../internals/path");t.exports=e.Array.isArray},{"../../internals/path":304,"../../modules/es.array.is-array":340}],141:[function(e,t,r){e("../../../modules/es.array.concat");e=e("../../../internals/entry-virtual");t.exports=e("Array").concat},{"../../../internals/entry-virtual":249,"../../../modules/es.array.concat":333}],142:[function(e,t,r){e("../../../modules/es.array.filter");e=e("../../../internals/entry-virtual");t.exports=e("Array").filter},{"../../../internals/entry-virtual":249,"../../../modules/es.array.filter":334}],143:[function(e,t,r){e("../../../modules/es.array.find");e=e("../../../internals/entry-virtual");t.exports=e("Array").find},{"../../../internals/entry-virtual":249,"../../../modules/es.array.find":335}],144:[function(e,t,r){e("../../../modules/es.array.for-each");e=e("../../../internals/entry-virtual");t.exports=e("Array").forEach},{"../../../internals/entry-virtual":249,"../../../modules/es.array.for-each":336}],145:[function(e,t,r){e("../../../modules/es.array.includes");e=e("../../../internals/entry-virtual");t.exports=e("Array").includes},{"../../../internals/entry-virtual":249,"../../../modules/es.array.includes":338}],146:[function(e,t,r){e("../../../modules/es.array.index-of");e=e("../../../internals/entry-virtual");t.exports=e("Array").indexOf},{"../../../internals/entry-virtual":249,"../../../modules/es.array.index-of":339}],147:[function(e,t,r){e("../../../modules/es.array.iterator");e=e("../../../internals/entry-virtual");t.exports=e("Array").keys},{"../../../internals/entry-virtual":249,"../../../modules/es.array.iterator":341}],148:[function(e,t,r){e("../../../modules/es.array.map");e=e("../../../internals/entry-virtual");t.exports=e("Array").map},{"../../../internals/entry-virtual":249,"../../../modules/es.array.map":342}],149:[function(e,t,r){e("../../../modules/es.array.reduce");e=e("../../../internals/entry-virtual");t.exports=e("Array").reduce},{"../../../internals/entry-virtual":249,"../../../modules/es.array.reduce":343}],150:[function(e,t,r){e("../../../modules/es.array.slice");e=e("../../../internals/entry-virtual");t.exports=e("Array").slice},{"../../../internals/entry-virtual":249,"../../../modules/es.array.slice":344}],151:[function(e,t,r){e("../../../modules/es.array.sort");e=e("../../../internals/entry-virtual");t.exports=e("Array").sort},{"../../../internals/entry-virtual":249,"../../../modules/es.array.sort":345}],152:[function(e,t,r){e("../../../modules/es.array.splice");e=e("../../../internals/entry-virtual");t.exports=e("Array").splice},{"../../../internals/entry-virtual":249,"../../../modules/es.array.splice":346}],153:[function(e,t,r){e("../../../modules/es.array.iterator");e=e("../../../internals/entry-virtual");t.exports=e("Array").values},{"../../../internals/entry-virtual":249,"../../../modules/es.array.iterator":341}],154:[function(e,t,r){e("../../../modules/es.function.bind");e=e("../../../internals/entry-virtual");t.exports=e("Function").bind},{"../../../internals/entry-virtual":249,"../../../modules/es.function.bind":347}],155:[function(e,t,r){var n=e("../function/virtual/bind"),a=Function.prototype;t.exports=function(e){var t=e.bind;return e===a||e instanceof Function&&t===a.bind?n:t}},{"../function/virtual/bind":154}],156:[function(e,t,r){var n=e("../array/virtual/concat"),a=Array.prototype;t.exports=function(e){var t=e.concat;return e===a||e instanceof Array&&t===a.concat?n:t}},{"../array/virtual/concat":141}],157:[function(e,t,r){var n=e("../array/virtual/filter"),a=Array.prototype;t.exports=function(e){var t=e.filter;return e===a||e instanceof Array&&t===a.filter?n:t}},{"../array/virtual/filter":142}],158:[function(e,t,r){var n=e("../array/virtual/find"),a=Array.prototype;t.exports=function(e){var t=e.find;return e===a||e instanceof Array&&t===a.find?n:t}},{"../array/virtual/find":143}],159:[function(e,t,r){var n=e("../array/virtual/includes"),a=e("../string/virtual/includes"),s=Array.prototype,o=String.prototype;t.exports=function(e){var t=e.includes;return e===s||e instanceof Array&&t===s.includes?n:"string"==typeof e||e===o||e instanceof String&&t===o.includes?a:t}},{"../array/virtual/includes":145,"../string/virtual/includes":186}],160:[function(e,t,r){var n=e("../array/virtual/index-of"),a=Array.prototype;t.exports=function(e){var t=e.indexOf;return e===a||e instanceof Array&&t===a.indexOf?n:t}},{"../array/virtual/index-of":146}],161:[function(e,t,r){var n=e("../array/virtual/map"),a=Array.prototype;t.exports=function(e){var t=e.map;return e===a||e instanceof Array&&t===a.map?n:t}},{"../array/virtual/map":148}],162:[function(e,t,r){var n=e("../array/virtual/reduce"),a=Array.prototype;t.exports=function(e){var t=e.reduce;return e===a||e instanceof Array&&t===a.reduce?n:t}},{"../array/virtual/reduce":149}],163:[function(e,t,r){var n=e("../array/virtual/slice"),a=Array.prototype;t.exports=function(e){var t=e.slice;return e===a||e instanceof Array&&t===a.slice?n:t}},{"../array/virtual/slice":150}],164:[function(e,t,r){var n=e("../array/virtual/sort"),a=Array.prototype;t.exports=function(e){var t=e.sort;return e===a||e instanceof Array&&t===a.sort?n:t}},{"../array/virtual/sort":151}],165:[function(e,t,r){var n=e("../array/virtual/splice"),a=Array.prototype;t.exports=function(e){var t=e.splice;return e===a||e instanceof Array&&t===a.splice?n:t}},{"../array/virtual/splice":152}],166:[function(e,t,r){var n=e("../string/virtual/starts-with"),a=String.prototype;t.exports=function(e){var t=e.startsWith;return"string"==typeof e||e===a||e instanceof String&&t===a.startsWith?n:t}},{"../string/virtual/starts-with":187}],167:[function(e,t,r){e("../../modules/es.json.stringify");var n=e("../../internals/path");n.JSON||(n.JSON={stringify:JSON.stringify}),t.exports=function(e,t,r){return n.JSON.stringify.apply(null,arguments)}},{"../../internals/path":304,"../../modules/es.json.stringify":348}],168:[function(e,t,r){e("../../modules/es.map"),e("../../modules/es.object.to-string"),e("../../modules/es.string.iterator"),e("../../modules/web.dom-collections.iterator");e=e("../../internals/path");t.exports=e.Map},{"../../internals/path":304,"../../modules/es.map":350,"../../modules/es.object.to-string":363,"../../modules/es.string.iterator":372,"../../modules/web.dom-collections.iterator":422}],169:[function(e,t,r){e("../../modules/es.object.assign");e=e("../../internals/path");t.exports=e.Object.assign},{"../../internals/path":304,"../../modules/es.object.assign":352}],170:[function(e,t,r){e("../../modules/es.object.create");var n=e("../../internals/path").Object;t.exports=function(e,t){return n.create(e,t)}},{"../../internals/path":304,"../../modules/es.object.create":353}],171:[function(e,t,r){e("../../modules/es.object.define-properties");var n=e("../../internals/path").Object,t=t.exports=function(e,t){return n.defineProperties(e,t)};n.defineProperties.sham&&(t.sham=!0)},{"../../internals/path":304,"../../modules/es.object.define-properties":354}],172:[function(e,t,r){e("../../modules/es.object.define-property");var n=e("../../internals/path").Object,t=t.exports=function(e,t,r){return n.defineProperty(e,t,r)};n.defineProperty.sham&&(t.sham=!0)},{"../../internals/path":304,"../../modules/es.object.define-property":355}],173:[function(e,t,r){e("../../modules/es.object.entries");e=e("../../internals/path");t.exports=e.Object.entries},{"../../internals/path":304,"../../modules/es.object.entries":356}],174:[function(e,t,r){e("../../modules/es.object.freeze");e=e("../../internals/path");t.exports=e.Object.freeze},{"../../internals/path":304,"../../modules/es.object.freeze":357}],175:[function(e,t,r){e("../../modules/es.object.get-own-property-descriptor");var n=e("../../internals/path").Object,t=t.exports=function(e,t){return n.getOwnPropertyDescriptor(e,t)};n.getOwnPropertyDescriptor.sham&&(t.sham=!0)},{"../../internals/path":304,"../../modules/es.object.get-own-property-descriptor":358}],176:[function(e,t,r){e("../../modules/es.object.get-own-property-descriptors");e=e("../../internals/path");t.exports=e.Object.getOwnPropertyDescriptors},{"../../internals/path":304,"../../modules/es.object.get-own-property-descriptors":359}],177:[function(e,t,r){e("../../modules/es.symbol");e=e("../../internals/path");t.exports=e.Object.getOwnPropertySymbols},{"../../internals/path":304,"../../modules/es.symbol":379}],178:[function(e,t,r){e("../../modules/es.object.get-prototype-of");e=e("../../internals/path");t.exports=e.Object.getPrototypeOf},{"../../internals/path":304,"../../modules/es.object.get-prototype-of":360}],179:[function(e,t,r){e("../../modules/es.object.keys");e=e("../../internals/path");t.exports=e.Object.keys},{"../../internals/path":304,"../../modules/es.object.keys":361}],180:[function(e,t,r){e("../../modules/es.object.set-prototype-of");e=e("../../internals/path");t.exports=e.Object.setPrototypeOf},{"../../internals/path":304,"../../modules/es.object.set-prototype-of":362}],181:[function(e,t,r){e("../modules/es.parse-int");e=e("../internals/path");t.exports=e.parseInt},{"../internals/path":304,"../modules/es.parse-int":364}],182:[function(e,t,r){e("../../modules/es.object.to-string"),e("../../modules/es.string.iterator"),e("../../modules/web.dom-collections.iterator"),e("../../modules/es.promise"),e("../../modules/es.promise.all-settled"),e("../../modules/es.promise.finally");e=e("../../internals/path");t.exports=e.Promise},{"../../internals/path":304,"../../modules/es.object.to-string":363,"../../modules/es.promise":367,"../../modules/es.promise.all-settled":365,"../../modules/es.promise.finally":366,"../../modules/es.string.iterator":372,"../../modules/web.dom-collections.iterator":422}],183:[function(e,t,r){e("../../modules/es.reflect.construct");e=e("../../internals/path");t.exports=e.Reflect.construct},{"../../internals/path":304,"../../modules/es.reflect.construct":368}],184:[function(e,t,r){e("../../modules/es.reflect.get");e=e("../../internals/path");t.exports=e.Reflect.get},{"../../internals/path":304,"../../modules/es.reflect.get":369}],185:[function(e,t,r){e("../../modules/es.set"),e("../../modules/es.object.to-string"),e("../../modules/es.string.iterator"),e("../../modules/web.dom-collections.iterator");e=e("../../internals/path");t.exports=e.Set},{"../../internals/path":304,"../../modules/es.object.to-string":363,"../../modules/es.set":370,"../../modules/es.string.iterator":372,"../../modules/web.dom-collections.iterator":422}],186:[function(e,t,r){e("../../../modules/es.string.includes");e=e("../../../internals/entry-virtual");t.exports=e("String").includes},{"../../../internals/entry-virtual":249,"../../../modules/es.string.includes":371}],187:[function(e,t,r){e("../../../modules/es.string.starts-with");e=e("../../../internals/entry-virtual");t.exports=e("String").startsWith},{"../../../internals/entry-virtual":249,"../../../modules/es.string.starts-with":373}],188:[function(e,t,r){e("../../modules/es.array.concat"),e("../../modules/es.object.to-string"),e("../../modules/es.symbol"),e("../../modules/es.symbol.async-iterator"),e("../../modules/es.symbol.description"),e("../../modules/es.symbol.has-instance"),e("../../modules/es.symbol.is-concat-spreadable"),e("../../modules/es.symbol.iterator"),e("../../modules/es.symbol.match"),e("../../modules/es.symbol.match-all"),e("../../modules/es.symbol.replace"),e("../../modules/es.symbol.search"),e("../../modules/es.symbol.species"),e("../../modules/es.symbol.split"),e("../../modules/es.symbol.to-primitive"),e("../../modules/es.symbol.to-string-tag"),e("../../modules/es.symbol.unscopables"),e("../../modules/es.math.to-string-tag"),e("../../modules/es.json.to-string-tag");e=e("../../internals/path");t.exports=e.Symbol},{"../../internals/path":304,"../../modules/es.array.concat":333,"../../modules/es.json.to-string-tag":349,"../../modules/es.math.to-string-tag":351,"../../modules/es.object.to-string":363,"../../modules/es.symbol":379,"../../modules/es.symbol.async-iterator":374,"../../modules/es.symbol.description":375,"../../modules/es.symbol.has-instance":376,"../../modules/es.symbol.is-concat-spreadable":377,"../../modules/es.symbol.iterator":378,"../../modules/es.symbol.match":381,"../../modules/es.symbol.match-all":380,"../../modules/es.symbol.replace":382,"../../modules/es.symbol.search":383,"../../modules/es.symbol.species":384,"../../modules/es.symbol.split":385,"../../modules/es.symbol.to-primitive":386,"../../modules/es.symbol.to-string-tag":387,"../../modules/es.symbol.unscopables":388}],189:[function(e,t,r){e("../../modules/es.symbol.iterator"),e("../../modules/es.string.iterator"),e("../../modules/web.dom-collections.iterator");e=e("../../internals/well-known-symbol-wrapped");t.exports=e.f("iterator")},{"../../internals/well-known-symbol-wrapped":330,"../../modules/es.string.iterator":372,"../../modules/es.symbol.iterator":378,"../../modules/web.dom-collections.iterator":422}],190:[function(e,t,r){e("../../modules/es.object.to-string"),e("../../modules/es.weak-map"),e("../../modules/web.dom-collections.iterator");e=e("../../internals/path");t.exports=e.WeakMap},{"../../internals/path":304,"../../modules/es.object.to-string":363,"../../modules/es.weak-map":389,"../../modules/web.dom-collections.iterator":422}],191:[function(e,t,r){e=e("../../es/array/from");t.exports=e},{"../../es/array/from":139}],192:[function(e,t,r){e=e("../../es/array/is-array");t.exports=e},{"../../es/array/is-array":140}],193:[function(e,t,r){e("../modules/web.dom-collections.iterator"),e("../modules/es.string.iterator");e=e("../internals/get-iterator-method");t.exports=e},{"../internals/get-iterator-method":257,"../modules/es.string.iterator":372,"../modules/web.dom-collections.iterator":422}],194:[function(e,t,r){e("../modules/web.dom-collections.iterator"),e("../modules/es.string.iterator");e=e("../internals/get-iterator");t.exports=e},{"../internals/get-iterator":258,"../modules/es.string.iterator":372,"../modules/web.dom-collections.iterator":422}],195:[function(e,t,r){e=e("../../es/instance/bind");t.exports=e},{"../../es/instance/bind":155}],196:[function(e,t,r){e=e("../../es/instance/index-of");t.exports=e},{"../../es/instance/index-of":160}],197:[function(e,t,r){e=e("../../es/instance/slice");t.exports=e},{"../../es/instance/slice":163}],198:[function(e,t,r){e("../modules/web.dom-collections.iterator"),e("../modules/es.string.iterator");e=e("../internals/is-iterable");t.exports=e},{"../internals/is-iterable":273,"../modules/es.string.iterator":372,"../modules/web.dom-collections.iterator":422}],199:[function(e,t,r){var n=e("../../es/map");e("../../modules/esnext.map.from"),e("../../modules/esnext.map.of"),e("../../modules/esnext.map.delete-all"),e("../../modules/esnext.map.every"),e("../../modules/esnext.map.filter"),e("../../modules/esnext.map.find"),e("../../modules/esnext.map.find-key"),e("../../modules/esnext.map.group-by"),e("../../modules/esnext.map.includes"),e("../../modules/esnext.map.key-by"),e("../../modules/esnext.map.key-of"),e("../../modules/esnext.map.map-keys"),e("../../modules/esnext.map.map-values"),e("../../modules/esnext.map.merge"),e("../../modules/esnext.map.reduce"),e("../../modules/esnext.map.some"),e("../../modules/esnext.map.update"),e("../../modules/esnext.map.upsert"),e("../../modules/esnext.map.update-or-insert"),t.exports=n},{"../../es/map":168,"../../modules/esnext.map.delete-all":391,"../../modules/esnext.map.every":392,"../../modules/esnext.map.filter":393,"../../modules/esnext.map.find":395,"../../modules/esnext.map.find-key":394,"../../modules/esnext.map.from":396,"../../modules/esnext.map.group-by":397,"../../modules/esnext.map.includes":398,"../../modules/esnext.map.key-by":399,"../../modules/esnext.map.key-of":400,"../../modules/esnext.map.map-keys":401,"../../modules/esnext.map.map-values":402,"../../modules/esnext.map.merge":403,"../../modules/esnext.map.of":404,"../../modules/esnext.map.reduce":405,"../../modules/esnext.map.some":406,"../../modules/esnext.map.update":408,"../../modules/esnext.map.update-or-insert":407,"../../modules/esnext.map.upsert":409}],200:[function(e,t,r){e=e("../../es/object/create");t.exports=e},{"../../es/object/create":170}],201:[function(e,t,r){e=e("../../es/object/define-property");t.exports=e},{"../../es/object/define-property":172}],202:[function(e,t,r){e=e("../../es/object/get-own-property-descriptor");t.exports=e},{"../../es/object/get-own-property-descriptor":175}],203:[function(e,t,r){e=e("../../es/object/get-prototype-of");t.exports=e},{"../../es/object/get-prototype-of":178}],204:[function(e,t,r){e=e("../../es/object/set-prototype-of");t.exports=e},{"../../es/object/set-prototype-of":180}],205:[function(e,t,r){var n=e("../../es/promise");e("../../modules/esnext.aggregate-error"),e("../../modules/esnext.promise.all-settled"),e("../../modules/esnext.promise.try"),e("../../modules/esnext.promise.any"),t.exports=n},{"../../es/promise":182,"../../modules/esnext.aggregate-error":390,"../../modules/esnext.promise.all-settled":410,"../../modules/esnext.promise.any":411,"../../modules/esnext.promise.try":412}],206:[function(e,t,r){e=e("../../es/reflect/construct");t.exports=e},{"../../es/reflect/construct":183}],207:[function(e,t,r){e=e("../../es/reflect/get");t.exports=e},{"../../es/reflect/get":184}],208:[function(e,t,r){var n=e("../../es/symbol");e("../../modules/esnext.symbol.async-dispose"),e("../../modules/esnext.symbol.dispose"),e("../../modules/esnext.symbol.observable"),e("../../modules/esnext.symbol.pattern-match"),e("../../modules/esnext.symbol.replace-all"),t.exports=n},{"../../es/symbol":188,"../../modules/esnext.symbol.async-dispose":413,"../../modules/esnext.symbol.dispose":414,"../../modules/esnext.symbol.observable":415,"../../modules/esnext.symbol.pattern-match":416,"../../modules/esnext.symbol.replace-all":417}],209:[function(e,t,r){e=e("../../es/symbol/iterator");t.exports=e},{"../../es/symbol/iterator":189}],210:[function(e,t,r){var n=e("../../es/weak-map");e("../../modules/esnext.weak-map.from"),e("../../modules/esnext.weak-map.of"),e("../../modules/esnext.weak-map.delete-all"),e("../../modules/esnext.weak-map.upsert"),t.exports=n},{"../../es/weak-map":190,"../../modules/esnext.weak-map.delete-all":418,"../../modules/esnext.weak-map.from":419,"../../modules/esnext.weak-map.of":420,"../../modules/esnext.weak-map.upsert":421}],211:[function(e,t,r){t.exports=function(e){if("function"!=typeof e)throw TypeError(String(e)+" is not a function");return e}},{}],212:[function(e,t,r){var n=e("../internals/is-object");t.exports=function(e){if(!n(e)&&null!==e)throw TypeError("Can't set "+String(e)+" as a prototype");return e}},{"../internals/is-object":274}],213:[function(e,t,r){t.exports=function(){}},{}],214:[function(e,t,r){t.exports=function(e,t,r){if(!(e instanceof t))throw TypeError("Incorrect "+(r?r+" ":"")+"invocation");return e}},{}],215:[function(e,t,r){var n=e("../internals/is-object");t.exports=function(e){if(!n(e))throw TypeError(String(e)+" is not an object");return e}},{"../internals/is-object":274}],216:[function(e,t,r){"use strict";var n=e("../internals/array-iteration").forEach,a=e("../internals/array-method-is-strict"),e=e("../internals/array-method-uses-to-length"),a=a("forEach"),e=e("forEach");t.exports=a&&e?[].forEach:function(e,t){return n(this,e,1<arguments.length?t:void 0)}},{"../internals/array-iteration":219,"../internals/array-method-is-strict":221,"../internals/array-method-uses-to-length":222}],217:[function(e,t,r){"use strict";var b=e("../internals/function-bind-context"),h=e("../internals/to-object"),y=e("../internals/call-with-safe-iteration-closing"),m=e("../internals/is-array-iterator-method"),v=e("../internals/to-length"),j=e("../internals/create-property"),g=e("../internals/get-iterator-method");t.exports=function(e,t,r){var n,a,s,o,i,l,u=h(e),c="function"==typeof this?this:Array,e=arguments.length,f=1<e?t:void 0,d=void 0!==f,t=g(u),p=0;if(d&&(f=b(f,2<e?r:void 0,2)),null==t||c==Array&&m(t))for(a=new c(n=v(u.length));p<n;p++)l=d?f(u[p],p):u[p],j(a,p,l);else for(i=(o=t.call(u)).next,a=new c;!(s=i.call(o)).done;p++)l=d?y(o,f,[s.value,p],!0):s.value,j(a,p,l);return a.length=p,a}},{"../internals/call-with-safe-iteration-closing":225,"../internals/create-property":240,"../internals/function-bind-context":254,"../internals/get-iterator-method":257,"../internals/is-array-iterator-method":270,"../internals/to-length":324,"../internals/to-object":325}],218:[function(e,t,r){var l=e("../internals/to-indexed-object"),u=e("../internals/to-length"),c=e("../internals/to-absolute-index"),e=function(i){return function(e,t,r){var n,a=l(e),s=u(a.length),o=c(r,s);if(i&&t!=t){for(;o<s;)if((n=a[o++])!=n)return!0}else for(;o<s;o++)if((i||o in a)&&a[o]===t)return i||o||0;return!i&&-1}};t.exports={includes:e(!0),indexOf:e(!1)}},{"../internals/to-absolute-index":321,"../internals/to-indexed-object":322,"../internals/to-length":324}],219:[function(e,t,r){var j=e("../internals/function-bind-context"),g=e("../internals/indexed-object"),_=e("../internals/to-object"),w=e("../internals/to-length"),x=e("../internals/array-species-create"),k=[].push,e=function(d){var p=1==d,b=2==d,h=3==d,y=4==d,m=6==d,v=5==d||m;return function(e,t,r,n){for(var a,s,o=_(e),i=g(o),l=j(t,r,3),u=w(i.length),c=0,n=n||x,f=p?n(e,u):b?n(e,0):void 0;c<u;c++)if((v||c in i)&&(s=l(a=i[c],c,o),d))if(p)f[c]=s;else if(s)switch(d){case 3:return!0;case 5:return a;case 6:return c;case 2:k.call(f,a)}else if(y)return!1;return m?-1:h||y?y:f}};t.exports={forEach:e(0),map:e(1),filter:e(2),some:e(3),every:e(4),find:e(5),findIndex:e(6)}},{"../internals/array-species-create":224,"../internals/function-bind-context":254,"../internals/indexed-object":266,"../internals/to-length":324,"../internals/to-object":325}],220:[function(e,t,r){var n=e("../internals/fails"),a=e("../internals/well-known-symbol"),s=e("../internals/engine-v8-version"),o=a("species");t.exports=function(t){return 51<=s||!n(function(){var e=[];return(e.constructor={})[o]=function(){return{foo:1}},1!==e[t](Boolean).foo})}},{"../internals/engine-v8-version":248,"../internals/fails":252,"../internals/well-known-symbol":331}],221:[function(e,t,r){"use strict";var n=e("../internals/fails");t.exports=function(e,t){var r=[][e];return!!r&&n(function(){r.call(null,t||function(){throw 1},1)})}},{"../internals/fails":252}],222:[function(e,t,r){function o(e){throw e}var i=e("../internals/descriptors"),l=e("../internals/fails"),u=e("../internals/has"),c=Object.defineProperty,f={};t.exports=function(e,t){if(u(f,e))return f[e];var r=[][e],n=!!u(t=t||{},"ACCESSORS")&&t.ACCESSORS,a=u(t,0)?t[0]:o,s=u(t,1)?t[1]:void 0;return f[e]=!!r&&!l(function(){if(n&&!i)return!0;var e={length:-1};n?c(e,1,{enumerable:!0,get:o}):e[1]=1,r.call(e,a,s)})}},{"../internals/descriptors":243,"../internals/fails":252,"../internals/has":261}],223:[function(e,t,r){var c=e("../internals/a-function"),f=e("../internals/to-object"),d=e("../internals/indexed-object"),p=e("../internals/to-length"),e=function(u){return function(e,t,r,n){c(t);var a=f(e),s=d(a),o=p(a.length),i=u?o-1:0,l=u?-1:1;if(r<2)for(;;){if(i in s){n=s[i],i+=l;break}if(i+=l,u?i<0:o<=i)throw TypeError("Reduce of empty array with no initial value")}for(;u?0<=i:i<o;i+=l)i in s&&(n=t(n,s[i],i,a));return n}};t.exports={left:e(!1),right:e(!0)}},{"../internals/a-function":211,"../internals/indexed-object":266,"../internals/to-length":324,"../internals/to-object":325}],224:[function(e,t,r){var n=e("../internals/is-object"),a=e("../internals/is-array"),s=e("../internals/well-known-symbol")("species");t.exports=function(e,t){var r;return a(e)&&("function"==typeof(r=e.constructor)&&(r===Array||a(r.prototype))||n(r)&&null===(r=r[s]))&&(r=void 0),new(void 0===r?Array:r)(0===t?0:t)}},{"../internals/is-array":271,"../internals/is-object":274,"../internals/well-known-symbol":331}],225:[function(e,t,r){var s=e("../internals/an-object");t.exports=function(t,e,r,n){try{return n?e(s(r)[0],r[1]):e(r)}catch(e){var a=t.return;throw void 0!==a&&s(a.call(t)),e}}},{"../internals/an-object":215}],226:[function(e,t,r){var a=e("../internals/well-known-symbol")("iterator"),s=!1;try{var n=0,o={next:function(){return{done:!!n++}},return:function(){s=!0}};o[a]=function(){return this},Array.from(o,function(){throw 2})}catch(e){}t.exports=function(e,t){if(!t&&!s)return!1;var r=!1;try{var n={};n[a]=function(){return{next:function(){return{done:r=!0}}}},e(n)}catch(e){}return r}},{"../internals/well-known-symbol":331}],227:[function(e,t,r){var n={}.toString;t.exports=function(e){return n.call(e).slice(8,-1)}},{}],228:[function(e,t,r){var n=e("../internals/to-string-tag-support"),a=e("../internals/classof-raw"),s=e("../internals/well-known-symbol")("toStringTag"),o="Arguments"==a(function(){return arguments}());t.exports=n?a:function(e){var t;return void 0===e?"Undefined":null===e?"Null":"string"==typeof(e=function(e,t){try{return e[t]}catch(e){}}(t=Object(e),s))?e:o?a(t):"Object"==(e=a(t))&&"function"==typeof t.callee?"Arguments":e}},{"../internals/classof-raw":227,"../internals/to-string-tag-support":327,"../internals/well-known-symbol":331}],229:[function(e,t,r){"use strict";var o=e("../internals/an-object"),i=e("../internals/a-function");t.exports=function(){for(var e,t=o(this),r=i(t.delete),n=!0,a=0,s=arguments.length;a<s;a++)e=r.call(t,arguments[a]),n=n&&e;return!!n}},{"../internals/a-function":211,"../internals/an-object":215}],230:[function(e,t,r){"use strict";var l=e("../internals/a-function"),u=e("../internals/function-bind-context"),c=e("../internals/iterate");t.exports=function(e,t,r){var n,a,s,o=arguments.length,i=1<o?t:void 0;return l(this),(t=void 0!==i)&&l(i),null==e?new this:(n=[],t?(a=0,s=u(i,2<o?r:void 0,2),c(e,function(e){n.push(s(e,a++))})):c(e,n.push,n),new this(n))}},{"../internals/a-function":211,"../internals/function-bind-context":254,"../internals/iterate":277}],231:[function(e,t,r){"use strict";t.exports=function(){for(var e=arguments.length,t=new Array(e);e--;)t[e]=arguments[e];return new this(t)}},{}],232:[function(e,t,r){"use strict";var u=e("../internals/object-define-property").f,c=e("../internals/object-create"),f=e("../internals/redefine-all"),d=e("../internals/function-bind-context"),p=e("../internals/an-instance"),b=e("../internals/iterate"),o=e("../internals/define-iterator"),i=e("../internals/set-species"),h=e("../internals/descriptors"),y=e("../internals/internal-metadata").fastKey,e=e("../internals/internal-state"),m=e.set,v=e.getterFor;t.exports={getConstructor:function(e,r,n,a){function s(e,t,r){var n,a=i(e),s=l(e,t);return s?s.value=r:(a.last=s={index:n=y(t,!0),key:t,value:r,previous:r=a.last,next:void 0,removed:!1},a.first||(a.first=s),r&&(r.next=s),h?a.size++:e.size++,"F"!==n&&(a.index[n]=s)),e}var o=e(function(e,t){p(e,o,r),m(e,{type:r,index:c(null),first:void 0,last:void 0,size:0}),h||(e.size=0),null!=t&&b(t,e[a],e,n)}),i=v(r),l=function(e,t){var r,n=i(e),e=y(t);if("F"!==e)return n.index[e];for(r=n.first;r;r=r.next)if(r.key==t)return r};return f(o.prototype,{clear:function(){for(var e=i(this),t=e.index,r=e.first;r;)r.removed=!0,r.previous&&(r.previous=r.previous.next=void 0),delete t[r.index],r=r.next;e.first=e.last=void 0,h?e.size=0:this.size=0},delete:function(e){var t,r=i(this),n=l(this,e);return n&&(t=n.next,e=n.previous,delete r.index[n.index],n.removed=!0,e&&(e.next=t),t&&(t.previous=e),r.first==n&&(r.first=t),r.last==n&&(r.last=e),h?r.size--:this.size--),!!n},forEach:function(e,t){for(var r,n=i(this),a=d(e,1<arguments.length?t:void 0,3);r=r?r.next:n.first;)for(a(r.value,r.key,this);r&&r.removed;)r=r.previous},has:function(e){return!!l(this,e)}}),f(o.prototype,n?{get:function(e){e=l(this,e);return e&&e.value},set:function(e,t){return s(this,0===e?0:e,t)}}:{add:function(e){return s(this,e=0===e?0:e,e)}}),h&&u(o.prototype,"size",{get:function(){return i(this).size}}),o},setStrong:function(e,t,r){var n=t+" Iterator",a=v(t),s=v(n);o(e,t,function(e,t){m(this,{type:n,target:e,state:a(e),kind:t,last:void 0})},function(){for(var e=s(this),t=e.kind,r=e.last;r&&r.removed;)r=r.previous;return e.target&&(e.last=r=r?r.next:e.state.first)?"keys"==t?{value:r.key,done:!1}:"values"==t?{value:r.value,done:!1}:{value:[r.key,r.value],done:!1}:{value:e.target=void 0,done:!0}},r?"entries":"values",!r,!0),i(t)}}},{"../internals/an-instance":214,"../internals/define-iterator":241,"../internals/descriptors":243,"../internals/function-bind-context":254,"../internals/internal-metadata":268,"../internals/internal-state":269,"../internals/iterate":277,"../internals/object-create":289,"../internals/object-define-property":291,"../internals/redefine-all":307,"../internals/set-species":312}],233:[function(e,t,r){"use strict";function l(e){return e.frozen||(e.frozen=new i)}function n(e,t){return s(e.entries,function(e){return e[0]===t})}var u=e("../internals/redefine-all"),c=e("../internals/internal-metadata").getWeakData,f=e("../internals/an-object"),d=e("../internals/is-object"),p=e("../internals/an-instance"),b=e("../internals/iterate"),a=e("../internals/array-iteration"),h=e("../internals/has"),e=e("../internals/internal-state"),y=e.set,m=e.getterFor,s=a.find,o=a.findIndex,v=0,i=function(){this.entries=[]};i.prototype={get:function(e){e=n(this,e);if(e)return e[1]},has:function(e){return!!n(this,e)},set:function(e,t){var r=n(this,e);r?r[1]=t:this.entries.push([e,t])},delete:function(t){var e=o(this.entries,function(e){return e[0]===t});return~e&&this.entries.splice(e,1),!!~e}},t.exports={getConstructor:function(e,r,n,a){function s(e,t,r){var n=i(e),a=c(f(t),!0);return!0===a?l(n).set(t,r):a[n.id]=r,e}var o=e(function(e,t){p(e,o,r),y(e,{type:r,id:v++,frozen:void 0}),null!=t&&b(t,e[a],e,n)}),i=m(r);return u(o.prototype,{delete:function(e){var t=i(this);if(!d(e))return!1;var r=c(e);return!0===r?l(t).delete(e):r&&h(r,t.id)&&delete r[t.id]},has:function(e){var t=i(this);if(!d(e))return!1;var r=c(e);return!0===r?l(t).has(e):r&&h(r,t.id)}}),u(o.prototype,n?{get:function(e){var t=i(this);if(d(e)){var r=c(e);return!0===r?l(t).get(e):r?r[t.id]:void 0}},set:function(e,t){return s(this,e,t)}}:{add:function(e){return s(this,e,!0)}}),o}}},{"../internals/an-instance":214,"../internals/an-object":215,"../internals/array-iteration":219,"../internals/has":261,"../internals/internal-metadata":268,"../internals/internal-state":269,"../internals/is-object":274,"../internals/iterate":277,"../internals/redefine-all":307}],234:[function(e,t,r){"use strict";var f=e("./export"),d=e("../internals/global"),p=e("../internals/internal-metadata"),b=e("../internals/fails"),h=e("../internals/create-non-enumerable-property"),y=e("../internals/iterate"),m=e("../internals/an-instance"),v=e("../internals/is-object"),j=e("../internals/set-to-string-tag"),g=e("../internals/object-define-property").f,_=e("../internals/array-iteration").forEach,w=e("../internals/descriptors"),e=e("../internals/internal-state"),x=e.set,k=e.getterFor;t.exports=function(r,e,t){var s,o,n=-1!==r.indexOf("Map"),i=-1!==r.indexOf("Weak"),a=n?"set":"add",l=d[r],u=l&&l.prototype,c={};return w&&"function"==typeof l&&(i||u.forEach&&!b(function(){(new l).entries().next()}))?(s=e(function(e,t){x(m(e,s,r),{type:r,collection:new l}),null!=t&&y(t,e[a],e,n)}),o=k(r),_(["add","clear","delete","forEach","get","has","set","keys","values","entries"],function(n){var a="add"==n||"set"==n;n in u&&(!i||"clear"!=n)&&h(s.prototype,n,function(e,t){var r=o(this).collection;if(!a&&i&&!v(e))return"get"==n&&void 0;t=r[n](0===e?0:e,t);return a?this:t})}),i||g(s.prototype,"size",{configurable:!0,get:function(){return o(this).collection.size}})):(s=t.getConstructor(e,r,n,a),p.REQUIRED=!0),j(s,r,!1,!0),c[r]=s,f({global:!0,forced:!0},c),i||t.setStrong(s,r,n),s}},{"../internals/an-instance":214,"../internals/array-iteration":219,"../internals/create-non-enumerable-property":238,"../internals/descriptors":243,"../internals/fails":252,"../internals/global":260,"../internals/internal-metadata":268,"../internals/internal-state":269,"../internals/is-object":274,"../internals/iterate":277,"../internals/object-define-property":291,"../internals/set-to-string-tag":313,"./export":251}],235:[function(e,t,r){var n=e("../internals/well-known-symbol")("match");t.exports=function(t){var r=/./;try{"/./"[t](r)}catch(e){try{return r[n]=!1,"/./"[t](r)}catch(e){}}return!1}},{"../internals/well-known-symbol":331}],236:[function(e,t,r){e=e("../internals/fails");t.exports=!e(function(){function e(){}return e.prototype.constructor=null,Object.getPrototypeOf(new e)!==e.prototype})},{"../internals/fails":252}],237:[function(e,t,r){"use strict";function n(){return this}var a=e("../internals/iterators-core").IteratorPrototype,s=e("../internals/object-create"),o=e("../internals/create-property-descriptor"),i=e("../internals/set-to-string-tag"),l=e("../internals/iterators");t.exports=function(e,t,r){t+=" Iterator";return e.prototype=s(a,{next:o(1,r)}),i(e,t,!1,!0),l[t]=n,e}},{"../internals/create-property-descriptor":239,"../internals/iterators":279,"../internals/iterators-core":278,"../internals/object-create":289,"../internals/set-to-string-tag":313}],238:[function(e,t,r){var n=e("../internals/descriptors"),a=e("../internals/object-define-property"),s=e("../internals/create-property-descriptor");t.exports=n?function(e,t,r){return a.f(e,t,s(1,r))}:function(e,t,r){return e[t]=r,e}},{"../internals/create-property-descriptor":239,"../internals/descriptors":243,"../internals/object-define-property":291}],239:[function(e,t,r){t.exports=function(e,t){return{enumerable:!(1&e),configurable:!(2&e),writable:!(4&e),value:t}}},{}],240:[function(e,t,r){"use strict";var n=e("../internals/to-primitive"),a=e("../internals/object-define-property"),s=e("../internals/create-property-descriptor");t.exports=function(e,t,r){t=n(t);t in e?a.f(e,t,s(0,r)):e[t]=r}},{"../internals/create-property-descriptor":239,"../internals/object-define-property":291,"../internals/to-primitive":326}],241:[function(e,t,r){"use strict";function h(){return this}var y=e("../internals/export"),m=e("../internals/create-iterator-constructor"),v=e("../internals/object-get-prototype-of"),j=e("../internals/object-set-prototype-of"),g=e("../internals/set-to-string-tag"),_=e("../internals/create-non-enumerable-property"),w=e("../internals/redefine"),n=e("../internals/well-known-symbol"),x=e("../internals/is-pure"),k=e("../internals/iterators"),e=e("../internals/iterators-core"),C=e.IteratorPrototype,S=e.BUGGY_SAFARI_ITERATORS,E=n("iterator"),O="values";t.exports=function(e,t,r,n,a,s,o){m(r,t,n);function i(e){if(e===a&&b)return b;if(!S&&e in d)return d[e];switch(e){case"keys":case O:case"entries":return function(){return new r(this,e)}}return function(){return new r(this)}}var l,u,c=t+" Iterator",f=!1,d=e.prototype,p=d[E]||d["@@iterator"]||a&&d[a],b=!S&&p||i(a),n="Array"==t&&d.entries||p;if(n&&(e=v(n.call(new e)),C!==Object.prototype&&e.next&&(x||v(e)===C||(j?j(e,C):"function"!=typeof e[E]&&_(e,E,h)),g(e,c,!0,!0),x&&(k[c]=h))),a==O&&p&&p.name!==O&&(f=!0,b=function(){return p.call(this)}),x&&!o||d[E]===b||_(d,E,b),k[t]=b,a)if(l={values:i(O),keys:s?b:i("keys"),entries:i("entries")},o)for(u in l)!S&&!f&&u in d||w(d,u,l[u]);else y({target:t,proto:!0,forced:S||f},l);return l}},{"../internals/create-iterator-constructor":237,"../internals/create-non-enumerable-property":238,"../internals/export":251,"../internals/is-pure":275,"../internals/iterators":279,"../internals/iterators-core":278,"../internals/object-get-prototype-of":296,"../internals/object-set-prototype-of":300,"../internals/redefine":308,"../internals/set-to-string-tag":313,"../internals/well-known-symbol":331}],242:[function(e,t,r){var n=e("../internals/path"),a=e("../internals/has"),s=e("../internals/well-known-symbol-wrapped"),o=e("../internals/object-define-property").f;t.exports=function(e){var t=n.Symbol||(n.Symbol={});a(t,e)||o(t,e,{value:s.f(e)})}},{"../internals/has":261,"../internals/object-define-property":291,"../internals/path":304,"../internals/well-known-symbol-wrapped":330}],243:[function(e,t,r){e=e("../internals/fails");t.exports=!e(function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})},{"../internals/fails":252}],244:[function(e,t,r){var n=e("../internals/global"),e=e("../internals/is-object"),a=n.document,s=e(a)&&e(a.createElement);t.exports=function(e){return s?a.createElement(e):{}}},{"../internals/global":260,"../internals/is-object":274}],245:[function(e,t,r){t.exports={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0}},{}],246:[function(e,t,r){e=e("../internals/engine-user-agent");t.exports=/(iphone|ipod|ipad).*applewebkit/i.test(e)},{"../internals/engine-user-agent":247}],247:[function(e,t,r){e=e("../internals/get-built-in");t.exports=e("navigator","userAgent")||""},{"../internals/get-built-in":256}],248:[function(e,t,r){var n,a,s=e("../internals/global"),e=e("../internals/engine-user-agent"),s=s.process,s=s&&s.versions,s=s&&s.v8;s?a=(n=s.split("."))[0]+n[1]:e&&(!(n=e.match(/Edge\/(\d+)/))||74<=n[1])&&(n=e.match(/Chrome\/(\d+)/))&&(a=n[1]),t.exports=a&&+a},{"../internals/engine-user-agent":247,"../internals/global":260}],249:[function(e,t,r){var n=e("../internals/path");t.exports=function(e){return n[e+"Prototype"]}},{"../internals/path":304}],250:[function(e,t,r){t.exports=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"]},{}],251:[function(e,t,r){"use strict";function b(n){function e(e,t,r){if(this instanceof n){switch(arguments.length){case 0:return new n;case 1:return new n(e);case 2:return new n(e,t)}return new n(e,t,r)}return n.apply(this,arguments)}return e.prototype=n.prototype,e}var h=e("../internals/global"),y=e("../internals/object-get-own-property-descriptor").f,m=e("../internals/is-forced"),v=e("../internals/path"),j=e("../internals/function-bind-context"),g=e("../internals/create-non-enumerable-property"),_=e("../internals/has");t.exports=function(e,t){var r,n,a,s,o,i=e.target,l=e.global,u=e.stat,c=e.proto,f=l?h:u?h[i]:(h[i]||{}).prototype,d=l?v:v[i]||(v[i]={}),p=d.prototype;for(r in t)s=!m(l?r:i+(u?".":"#")+r,e.forced)&&f&&_(f,r),n=d[r],s&&(a=e.noTargetGet?(o=y(f,r))&&o.value:f[r]),o=s&&a?a:t[r],s&&typeof n==typeof o||(s=e.bind&&s?j(o,h):e.wrap&&s?b(o):c&&"function"==typeof o?j(Function.call,o):o,(e.sham||o&&o.sham||n&&n.sham)&&g(s,"sham",!0),d[r]=s,c&&(_(v,s=i+"Prototype")||g(v,s,{}),v[s][r]=o,e.real&&p&&!p[r]&&g(p,r,o)))}},{"../internals/create-non-enumerable-property":238,"../internals/function-bind-context":254,"../internals/global":260,"../internals/has":261,"../internals/is-forced":272,"../internals/object-get-own-property-descriptor":292,"../internals/path":304}],252:[function(e,t,r){t.exports=function(e){try{return!!e()}catch(e){return!0}}},{}],253:[function(e,t,r){e=e("../internals/fails");t.exports=!e(function(){return Object.isExtensible(Object.preventExtensions({}))})},{"../internals/fails":252}],254:[function(e,t,r){var s=e("../internals/a-function");t.exports=function(n,a,e){if(s(n),void 0===a)return n;switch(e){case 0:return function(){return n.call(a)};case 1:return function(e){return n.call(a,e)};case 2:return function(e,t){return n.call(a,e,t)};case 3:return function(e,t,r){return n.call(a,e,t,r)}}return function(){return n.apply(a,arguments)}}},{"../internals/a-function":211}],255:[function(e,t,r){"use strict";var s=e("../internals/a-function"),o=e("../internals/is-object"),i=[].slice,l={};t.exports=Function.bind||function(t){var r=s(this),n=i.call(arguments,1),a=function(){var e=n.concat(i.call(arguments));return this instanceof a?function(e,t,r){if(!(t in l)){for(var n=[],a=0;a<t;a++)n[a]="a["+a+"]";l[t]=Function("C,a","return new C("+n.join(",")+")")}return l[t](e,r)}(r,e.length,e):r.apply(t,e)};return o(r.prototype)&&(a.prototype=r.prototype),a}},{"../internals/a-function":211,"../internals/is-object":274}],256:[function(e,t,r){function n(e){return"function"==typeof e?e:void 0}var a=e("../internals/path"),s=e("../internals/global");t.exports=function(e,t){return arguments.length<2?n(a[e])||n(s[e]):a[e]&&a[e][t]||s[e]&&s[e][t]}},{"../internals/global":260,"../internals/path":304}],257:[function(e,t,r){var n=e("../internals/classof"),a=e("../internals/iterators"),s=e("../internals/well-known-symbol")("iterator");t.exports=function(e){if(null!=e)return e[s]||e["@@iterator"]||a[n(e)]}},{"../internals/classof":228,"../internals/iterators":279,"../internals/well-known-symbol":331}],258:[function(e,t,r){var n=e("../internals/an-object"),a=e("../internals/get-iterator-method");t.exports=function(e){var t=a(e);if("function"!=typeof t)throw TypeError(String(e)+" is not iterable");return n(t.call(e))}},{"../internals/an-object":215,"../internals/get-iterator-method":257}],259:[function(e,t,r){var n=e("../internals/is-pure"),e=e("../internals/get-iterator");t.exports=n?e:function(e){return Map.prototype.entries.call(e)}},{"../internals/get-iterator":258,"../internals/is-pure":275}],260:[function(e,r,t){(function(e){function t(e){return e&&e.Math==Math&&e}r.exports=t("object"==typeof globalThis&&globalThis)||t("object"==typeof window&&window)||t("object"==typeof self&&self)||t("object"==typeof e&&e)||Function("return this")()}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],261:[function(e,t,r){var n={}.hasOwnProperty;t.exports=function(e,t){return n.call(e,t)}},{}],262:[function(e,t,r){t.exports={}},{}],263:[function(e,t,r){var n=e("../internals/global");t.exports=function(e,t){var r=n.console;r&&r.error&&(1===arguments.length?r.error(e):r.error(e,t))}},{"../internals/global":260}],264:[function(e,t,r){e=e("../internals/get-built-in");t.exports=e("document","documentElement")},{"../internals/get-built-in":256}],265:[function(e,t,r){var n=e("../internals/descriptors"),a=e("../internals/fails"),s=e("../internals/document-create-element");t.exports=!n&&!a(function(){return 7!=Object.defineProperty(s("div"),"a",{get:function(){return 7}}).a})},{"../internals/descriptors":243,"../internals/document-create-element":244,"../internals/fails":252}],266:[function(e,t,r){var n=e("../internals/fails"),a=e("../internals/classof-raw"),s="".split;t.exports=n(function(){return!Object("z").propertyIsEnumerable(0)})?function(e){return"String"==a(e)?s.call(e,""):Object(e)}:Object},{"../internals/classof-raw":227,"../internals/fails":252}],267:[function(e,t,r){var e=e("../internals/shared-store"),n=Function.toString;"function"!=typeof e.inspectSource&&(e.inspectSource=function(e){return n.call(e)}),t.exports=e.inspectSource},{"../internals/shared-store":315}],268:[function(e,t,r){function n(e){i(e,c,{value:{objectID:"O"+ ++f,weakData:{}}})}var a=e("../internals/hidden-keys"),s=e("../internals/is-object"),o=e("../internals/has"),i=e("../internals/object-define-property").f,l=e("../internals/uid"),u=e("../internals/freezing"),c=l("meta"),f=0,d=Object.isExtensible||function(){return!0},p=t.exports={REQUIRED:!1,fastKey:function(e,t){if(!s(e))return"symbol"==typeof e?e:("string"==typeof e?"S":"P")+e;if(!o(e,c)){if(!d(e))return"F";if(!t)return"E";n(e)}return e[c].objectID},getWeakData:function(e,t){if(!o(e,c)){if(!d(e))return!0;if(!t)return!1;n(e)}return e[c].weakData},onFreeze:function(e){return u&&p.REQUIRED&&d(e)&&!o(e,c)&&n(e),e}};a[c]=!0},{"../internals/freezing":253,"../internals/has":261,"../internals/hidden-keys":262,"../internals/is-object":274,"../internals/object-define-property":291,"../internals/uid":328}],269:[function(e,t,r){var n,a,s,o,i,l,u,c,f=e("../internals/native-weak-map"),d=e("../internals/global"),p=e("../internals/is-object"),b=e("../internals/create-non-enumerable-property"),h=e("../internals/has"),y=e("../internals/shared-key"),e=e("../internals/hidden-keys"),d=d.WeakMap;u=f?(n=new d,a=n.get,s=n.has,o=n.set,i=function(e,t){return o.call(n,e,t),t},l=function(e){return a.call(n,e)||{}},function(e){return s.call(n,e)}):(e[c=y("state")]=!0,i=function(e,t){return b(e,c,t),t},l=function(e){return h(e,c)?e[c]:{}},function(e){return h(e,c)}),t.exports={set:i,get:l,has:u,enforce:function(e){return u(e)?l(e):i(e,{})},getterFor:function(r){return function(e){var t;if(!p(e)||(t=l(e)).type!==r)throw TypeError("Incompatible receiver, "+r+" required");return t}}}},{"../internals/create-non-enumerable-property":238,"../internals/global":260,"../internals/has":261,"../internals/hidden-keys":262,"../internals/is-object":274,"../internals/native-weak-map":284,"../internals/shared-key":314}],270:[function(e,t,r){var n=e("../internals/well-known-symbol"),a=e("../internals/iterators"),s=n("iterator"),o=Array.prototype;t.exports=function(e){return void 0!==e&&(a.Array===e||o[s]===e)}},{"../internals/iterators":279,"../internals/well-known-symbol":331}],271:[function(e,t,r){var n=e("../internals/classof-raw");t.exports=Array.isArray||function(e){return"Array"==n(e)}},{"../internals/classof-raw":227}],272:[function(e,t,r){var n=e("../internals/fails"),a=/#|\.prototype\./,e=function(e,t){e=o[s(e)];return e==l||e!=i&&("function"==typeof t?n(t):!!t)},s=e.normalize=function(e){return String(e).replace(a,".").toLowerCase()},o=e.data={},i=e.NATIVE="N",l=e.POLYFILL="P";t.exports=e},{"../internals/fails":252}],273:[function(e,t,r){var n=e("../internals/classof"),a=e("../internals/well-known-symbol"),s=e("../internals/iterators"),o=a("iterator");t.exports=function(e){e=Object(e);return void 0!==e[o]||"@@iterator"in e||s.hasOwnProperty(n(e))}},{"../internals/classof":228,"../internals/iterators":279,"../internals/well-known-symbol":331}],274:[function(e,t,r){t.exports=function(e){return"object"==typeof e?null!==e:"function"==typeof e}},{}],275:[function(e,t,r){t.exports=!0},{}],276:[function(e,t,r){var n=e("../internals/is-object"),a=e("../internals/classof-raw"),s=e("../internals/well-known-symbol")("match");t.exports=function(e){var t;return n(e)&&(void 0!==(t=e[s])?!!t:"RegExp"==a(e))}},{"../internals/classof-raw":227,"../internals/is-object":274,"../internals/well-known-symbol":331}],277:[function(e,t,r){function d(e,t){this.stopped=e,this.result=t}var p=e("../internals/an-object"),b=e("../internals/is-array-iterator-method"),h=e("../internals/to-length"),y=e("../internals/function-bind-context"),m=e("../internals/get-iterator-method"),v=e("../internals/call-with-safe-iteration-closing");(t.exports=function(e,t,r,n,a){var s,o,i,l,u,c,f=y(t,r,n?2:1);if(a)s=e;else{if("function"!=typeof(a=m(e)))throw TypeError("Target is not iterable");if(b(a)){for(o=0,i=h(e.length);o<i;o++)if((l=n?f(p(c=e[o])[0],c[1]):f(e[o]))&&l instanceof d)return l;return new d(!1)}s=a.call(e)}for(u=s.next;!(c=u.call(s)).done;)if("object"==typeof(l=v(s,f,c.value,n))&&l&&l instanceof d)return l;return new d(!1)}).stop=function(e){return new d(!0,e)}},{"../internals/an-object":215,"../internals/call-with-safe-iteration-closing":225,"../internals/function-bind-context":254,"../internals/get-iterator-method":257,"../internals/is-array-iterator-method":270,"../internals/to-length":324}],278:[function(e,t,r){"use strict";var n,a=e("../internals/object-get-prototype-of"),s=e("../internals/create-non-enumerable-property"),o=e("../internals/has"),i=e("../internals/well-known-symbol"),l=e("../internals/is-pure"),u=i("iterator"),e=!1;[].keys&&("next"in(i=[].keys())?(i=a(a(i)))!==Object.prototype&&(n=i):e=!0),null==n&&(n={}),l||o(n,u)||s(n,u,function(){return this}),t.exports={IteratorPrototype:n,BUGGY_SAFARI_ITERATORS:e}},{"../internals/create-non-enumerable-property":238,"../internals/has":261,"../internals/is-pure":275,"../internals/object-get-prototype-of":296,"../internals/well-known-symbol":331}],279:[function(e,t,r){arguments[4][262][0].apply(r,arguments)},{dup:262}],280:[function(e,t,r){"use strict";var s=e("../internals/an-object");t.exports=function(e,t,r){var n,a=s(this),r=2<arguments.length?r:void 0;if("function"!=typeof t&&"function"!=typeof r)throw TypeError("At least one callback required");return a.has(e)?(n=a.get(e),"function"==typeof t&&(n=t(n),a.set(e,n))):"function"==typeof r&&(n=r(),a.set(e,n)),n}},{"../internals/an-object":215}],281:[function(e,t,r){var n,a,s,o,i,l,u,c,f=e("../internals/global"),d=e("../internals/object-get-own-property-descriptor").f,p=e("../internals/classof-raw"),b=e("../internals/task").set,h=e("../internals/engine-is-ios"),y=f.MutationObserver||f.WebKitMutationObserver,m=f.process,e=f.Promise,v="process"==p(m),d=d(f,"queueMicrotask"),d=d&&d.value;d||(n=function(){var e,t;for(v&&(e=m.domain)&&e.exit();a;){t=a.fn,a=a.next;try{t()}catch(e){throw a?o():s=void 0,e}}s=void 0,e&&e.enter()},o=v?function(){m.nextTick(n)}:y&&!h?(i=!0,l=document.createTextNode(""),new y(n).observe(l,{characterData:!0}),function(){l.data=i=!i}):e&&e.resolve?(u=e.resolve(void 0),c=u.then,function(){c.call(u,n)}):function(){b.call(f,n)}),t.exports=d||function(e){e={fn:e,next:void 0};s&&(s.next=e),a||(a=e,o()),s=e}},{"../internals/classof-raw":227,"../internals/engine-is-ios":246,"../internals/global":260,"../internals/object-get-own-property-descriptor":292,"../internals/task":320}],282:[function(e,t,r){e=e("../internals/global");t.exports=e.Promise},{"../internals/global":260}],283:[function(e,t,r){e=e("../internals/fails");t.exports=!!Object.getOwnPropertySymbols&&!e(function(){return!String(Symbol())})},{"../internals/fails":252}],284:[function(e,t,r){var n=e("../internals/global"),e=e("../internals/inspect-source"),n=n.WeakMap;t.exports="function"==typeof n&&/native code/.test(e(n))},{"../internals/global":260,"../internals/inspect-source":267}],285:[function(e,t,r){"use strict";function n(e){var r,n;this.promise=new e(function(e,t){if(void 0!==r||void 0!==n)throw TypeError("Bad Promise constructor");r=e,n=t}),this.resolve=a(r),this.reject=a(n)}var a=e("../internals/a-function");t.exports.f=function(e){return new n(e)}},{"../internals/a-function":211}],286:[function(e,t,r){var n=e("../internals/is-regexp");t.exports=function(e){if(n(e))throw TypeError("The method doesn't accept regular expressions");return e}},{"../internals/is-regexp":276}],287:[function(e,t,r){var n=e("../internals/global"),a=e("../internals/string-trim").trim,e=e("../internals/whitespaces"),s=n.parseInt,o=/^[+-]?0[Xx]/,e=8!==s(e+"08")||22!==s(e+"0x16");t.exports=e?function(e,t){e=a(String(e));return s(e,t>>>0||(o.test(e)?16:10))}:s},{"../internals/global":260,"../internals/string-trim":319,"../internals/whitespaces":332}],288:[function(e,t,r){"use strict";var f=e("../internals/descriptors"),n=e("../internals/fails"),d=e("../internals/object-keys"),p=e("../internals/object-get-own-property-symbols"),b=e("../internals/object-property-is-enumerable"),h=e("../internals/to-object"),y=e("../internals/indexed-object"),a=Object.assign,s=Object.defineProperty;t.exports=!a||n(function(){if(f&&1!==a({b:1},a(s({},"a",{enumerable:!0,get:function(){s(this,"b",{value:3,enumerable:!1})}}),{b:2})).b)return!0;var e={},t={},r=Symbol(),n="abcdefghijklmnopqrst";return e[r]=7,n.split("").forEach(function(e){t[e]=e}),7!=a({},e)[r]||d(a({},t)).join("")!=n})?function(e){for(var t=h(e),r=arguments.length,n=1,a=p.f,s=b.f;n<r;)for(var o,i=y(arguments[n++]),l=a?d(i).concat(a(i)):d(i),u=l.length,c=0;c<u;)o=l[c++],f&&!s.call(i,o)||(t[o]=i[o]);return t}:a},{"../internals/descriptors":243,"../internals/fails":252,"../internals/indexed-object":266,"../internals/object-get-own-property-symbols":295,"../internals/object-keys":298,"../internals/object-property-is-enumerable":299,"../internals/to-object":325}],289:[function(e,t,r){function n(){}function a(e){return"<script>"+e+"</"+p+">"}var s,o=e("../internals/an-object"),i=e("../internals/object-define-properties"),l=e("../internals/enum-bug-keys"),u=e("../internals/hidden-keys"),c=e("../internals/html"),f=e("../internals/document-create-element"),e=e("../internals/shared-key"),d="prototype",p="script",b=e("IE_PROTO"),h=function(){try{s=document.domain&&new ActiveXObject("htmlfile")}catch(e){}var e;h=s?function(e){e.write(a("")),e.close();var t=e.parentWindow.Object;return e=null,t}(s):((e=f("iframe")).style.display="none",c.appendChild(e),e.src=String("javascript:"),(e=e.contentWindow.document).open(),e.write(a("document.F=Object")),e.close(),e.F);for(var t=l.length;t--;)delete h[d][l[t]];return h()};u[b]=!0,t.exports=Object.create||function(e,t){var r;return null!==e?(n[d]=o(e),r=new n,n[d]=null,r[b]=e):r=h(),void 0===t?r:i(r,t)}},{"../internals/an-object":215,"../internals/document-create-element":244,"../internals/enum-bug-keys":250,"../internals/hidden-keys":262,"../internals/html":264,"../internals/object-define-properties":290,"../internals/shared-key":314}],290:[function(e,t,r){var n=e("../internals/descriptors"),o=e("../internals/object-define-property"),i=e("../internals/an-object"),l=e("../internals/object-keys");t.exports=n?Object.defineProperties:function(e,t){i(e);for(var r,n=l(t),a=n.length,s=0;s<a;)o.f(e,r=n[s++],t[r]);return e}},{"../internals/an-object":215,"../internals/descriptors":243,"../internals/object-define-property":291,"../internals/object-keys":298}],291:[function(e,t,r){var n=e("../internals/descriptors"),a=e("../internals/ie8-dom-define"),s=e("../internals/an-object"),o=e("../internals/to-primitive"),i=Object.defineProperty;r.f=n?i:function(e,t,r){if(s(e),t=o(t,!0),s(r),a)try{return i(e,t,r)}catch(e){}if("get"in r||"set"in r)throw TypeError("Accessors not supported");return"value"in r&&(e[t]=r.value),e}},{"../internals/an-object":215,"../internals/descriptors":243,"../internals/ie8-dom-define":265,"../internals/to-primitive":326}],292:[function(e,t,r){var n=e("../internals/descriptors"),a=e("../internals/object-property-is-enumerable"),s=e("../internals/create-property-descriptor"),o=e("../internals/to-indexed-object"),i=e("../internals/to-primitive"),l=e("../internals/has"),u=e("../internals/ie8-dom-define"),c=Object.getOwnPropertyDescriptor;r.f=n?c:function(e,t){if(e=o(e),t=i(t,!0),u)try{return c(e,t)}catch(e){}if(l(e,t))return s(!a.f.call(e,t),e[t])}},{"../internals/create-property-descriptor":239,"../internals/descriptors":243,"../internals/has":261,"../internals/ie8-dom-define":265,"../internals/object-property-is-enumerable":299,"../internals/to-indexed-object":322,"../internals/to-primitive":326}],293:[function(e,t,r){var n=e("../internals/to-indexed-object"),a=e("../internals/object-get-own-property-names").f,s={}.toString,o="object"==typeof window&&window&&Object.getOwnPropertyNames?Object.getOwnPropertyNames(window):[];t.exports.f=function(e){return o&&"[object Window]"==s.call(e)?function(e){try{return a(e)}catch(e){return o.slice()}}(e):a(n(e))}},{"../internals/object-get-own-property-names":294,"../internals/to-indexed-object":322}],294:[function(e,t,r){var n=e("../internals/object-keys-internal"),a=e("../internals/enum-bug-keys").concat("length","prototype");r.f=Object.getOwnPropertyNames||function(e){return n(e,a)}},{"../internals/enum-bug-keys":250,"../internals/object-keys-internal":297}],295:[function(e,t,r){r.f=Object.getOwnPropertySymbols},{}],296:[function(e,t,r){var n=e("../internals/has"),a=e("../internals/to-object"),s=e("../internals/shared-key"),e=e("../internals/correct-prototype-getter"),o=s("IE_PROTO"),i=Object.prototype;t.exports=e?Object.getPrototypeOf:function(e){return e=a(e),n(e,o)?e[o]:"function"==typeof e.constructor&&e instanceof e.constructor?e.constructor.prototype:e instanceof Object?i:null}},{"../internals/correct-prototype-getter":236,"../internals/has":261,"../internals/shared-key":314,"../internals/to-object":325}],297:[function(e,t,r){var o=e("../internals/has"),i=e("../internals/to-indexed-object"),l=e("../internals/array-includes").indexOf,u=e("../internals/hidden-keys");t.exports=function(e,t){var r,n=i(e),a=0,s=[];for(r in n)!o(u,r)&&o(n,r)&&s.push(r);for(;t.length>a;)o(n,r=t[a++])&&(~l(s,r)||s.push(r));return s}},{"../internals/array-includes":218,"../internals/has":261,"../internals/hidden-keys":262,"../internals/to-indexed-object":322}],298:[function(e,t,r){var n=e("../internals/object-keys-internal"),a=e("../internals/enum-bug-keys");t.exports=Object.keys||function(e){return n(e,a)}},{"../internals/enum-bug-keys":250,"../internals/object-keys-internal":297}],299:[function(e,t,r){"use strict";var n={}.propertyIsEnumerable,a=Object.getOwnPropertyDescriptor,s=a&&!n.call({1:2},1);r.f=s?function(e){e=a(this,e);return!!e&&e.enumerable}:n},{}],300:[function(e,t,r){var a=e("../internals/an-object"),s=e("../internals/a-possible-prototype");t.exports=Object.setPrototypeOf||("__proto__"in{}?function(){var r,n=!1,e={};try{(r=Object.getOwnPropertyDescriptor(Object.prototype,"__proto__").set).call(e,[]),n=e instanceof Array}catch(e){}return function(e,t){return a(e),s(t),n?r.call(e,t):e.__proto__=t,e}}():void 0)},{"../internals/a-possible-prototype":212,"../internals/an-object":215}],301:[function(e,t,r){var l=e("../internals/descriptors"),u=e("../internals/object-keys"),c=e("../internals/to-indexed-object"),f=e("../internals/object-property-is-enumerable").f,e=function(i){return function(e){for(var t,r=c(e),n=u(r),a=n.length,s=0,o=[];s<a;)t=n[s++],l&&!f.call(r,t)||o.push(i?[t,r[t]]:r[t]);return o}};t.exports={entries:e(!0),values:e(!1)}},{"../internals/descriptors":243,"../internals/object-keys":298,"../internals/object-property-is-enumerable":299,"../internals/to-indexed-object":322}],302:[function(e,t,r){"use strict";var n=e("../internals/to-string-tag-support"),a=e("../internals/classof");t.exports=n?{}.toString:function(){return"[object "+a(this)+"]"}},{"../internals/classof":228,"../internals/to-string-tag-support":327}],303:[function(e,t,r){var n=e("../internals/get-built-in"),a=e("../internals/object-get-own-property-names"),s=e("../internals/object-get-own-property-symbols"),o=e("../internals/an-object");t.exports=n("Reflect","ownKeys")||function(e){var t=a.f(o(e)),r=s.f;return r?t.concat(r(e)):t}},{"../internals/an-object":215,"../internals/get-built-in":256,"../internals/object-get-own-property-names":294,"../internals/object-get-own-property-symbols":295}],304:[function(e,t,r){arguments[4][262][0].apply(r,arguments)},{dup:262}],305:[function(e,t,r){t.exports=function(e){try{return{error:!1,value:e()}}catch(e){return{error:!0,value:e}}}},{}],306:[function(e,t,r){var n=e("../internals/an-object"),a=e("../internals/is-object"),s=e("../internals/new-promise-capability");t.exports=function(e,t){if(n(e),a(t)&&t.constructor===e)return t;e=s.f(e);return(0,e.resolve)(t),e.promise}},{"../internals/an-object":215,"../internals/is-object":274,"../internals/new-promise-capability":285}],307:[function(e,t,r){var a=e("../internals/redefine");t.exports=function(e,t,r){for(var n in t)r&&r.unsafe&&e[n]?e[n]=t[n]:a(e,n,t[n],r);return e}},{"../internals/redefine":308}],308:[function(e,t,r){var a=e("../internals/create-non-enumerable-property");t.exports=function(e,t,r,n){n&&n.enumerable?e[t]=r:a(e,t,r)}},{"../internals/create-non-enumerable-property":238}],309:[function(e,t,r){t.exports=function(e){if(null==e)throw TypeError("Can't call method on "+e);return e}},{}],310:[function(e,t,r){t.exports=function(e,t){return e===t||e!=e&&t!=t}},{}],311:[function(e,t,r){var n=e("../internals/global"),a=e("../internals/create-non-enumerable-property");t.exports=function(t,r){try{a(n,t,r)}catch(e){n[t]=r}return r}},{"../internals/create-non-enumerable-property":238,"../internals/global":260}],312:[function(e,t,r){"use strict";var n=e("../internals/get-built-in"),a=e("../internals/object-define-property"),s=e("../internals/well-known-symbol"),o=e("../internals/descriptors"),i=s("species");t.exports=function(e){var t=n(e),e=a.f;o&&t&&!t[i]&&e(t,i,{configurable:!0,get:function(){return this}})}},{"../internals/descriptors":243,"../internals/get-built-in":256,"../internals/object-define-property":291,"../internals/well-known-symbol":331}],313:[function(e,t,r){var a=e("../internals/to-string-tag-support"),s=e("../internals/object-define-property").f,o=e("../internals/create-non-enumerable-property"),i=e("../internals/has"),l=e("../internals/object-to-string"),u=e("../internals/well-known-symbol")("toStringTag");t.exports=function(e,t,r,n){e&&(e=r?e:e.prototype,i(e,u)||s(e,u,{configurable:!0,value:t}),n&&!a&&o(e,"toString",l))}},{"../internals/create-non-enumerable-property":238,"../internals/has":261,"../internals/object-define-property":291,"../internals/object-to-string":302,"../internals/to-string-tag-support":327,"../internals/well-known-symbol":331}],314:[function(e,t,r){var n=e("../internals/shared"),a=e("../internals/uid"),s=n("keys");t.exports=function(e){return s[e]||(s[e]=a(e))}},{"../internals/shared":316,"../internals/uid":328}],315:[function(e,t,r){var n=e("../internals/global"),a=e("../internals/set-global"),e="__core-js_shared__",e=n[e]||a(e,{});t.exports=e},{"../internals/global":260,"../internals/set-global":311}],316:[function(e,t,r){var n=e("../internals/is-pure"),a=e("../internals/shared-store");(t.exports=function(e,t){return a[e]||(a[e]=void 0!==t?t:{})})("versions",[]).push({version:"3.6.4",mode:n?"pure":"global",copyright:"© 2020 Denis Pushkarev (zloirock.ru)"})},{"../internals/is-pure":275,"../internals/shared-store":315}],317:[function(e,t,r){var n=e("../internals/an-object"),a=e("../internals/a-function"),s=e("../internals/well-known-symbol")("species");t.exports=function(e,t){var r,e=n(e).constructor;return void 0===e||null==(r=n(e)[s])?t:a(r)}},{"../internals/a-function":211,"../internals/an-object":215,"../internals/well-known-symbol":331}],318:[function(e,t,r){var o=e("../internals/to-integer"),i=e("../internals/require-object-coercible"),e=function(s){return function(e,t){var r,n=String(i(e)),a=o(t),e=n.length;return a<0||e<=a?s?"":void 0:(t=n.charCodeAt(a))<55296||56319<t||a+1===e||(r=n.charCodeAt(a+1))<56320||57343<r?s?n.charAt(a):t:s?n.slice(a,a+2):r-56320+(t-55296<<10)+65536}};t.exports={codeAt:e(!1),charAt:e(!0)}},{"../internals/require-object-coercible":309,"../internals/to-integer":323}],319:[function(e,t,r){var n=e("../internals/require-object-coercible"),e="["+e("../internals/whitespaces")+"]",a=RegExp("^"+e+e+"*"),s=RegExp(e+e+"*$"),e=function(t){return function(e){e=String(n(e));return 1&t&&(e=e.replace(a,"")),2&t&&(e=e.replace(s,"")),e}};t.exports={start:e(1),end:e(2),trim:e(3)}},{"../internals/require-object-coercible":309,"../internals/whitespaces":332}],320:[function(e,t,r){function n(e){var t;_.hasOwnProperty(e)&&(t=_[e],delete _[e],t())}function a(e){return function(){n(e)}}function s(e){n(e.data)}var o,i=e("../internals/global"),l=e("../internals/fails"),u=e("../internals/classof-raw"),c=e("../internals/function-bind-context"),f=e("../internals/html"),d=e("../internals/document-create-element"),p=e("../internals/engine-is-ios"),b=i.location,h=i.setImmediate,y=i.clearImmediate,m=i.process,v=i.MessageChannel,j=i.Dispatch,g=0,_={},w="onreadystatechange",e=function(e){i.postMessage(e+"",b.protocol+"//"+b.host)};h&&y||(h=function(e){for(var t=[],r=1;r<arguments.length;)t.push(arguments[r++]);return _[++g]=function(){("function"==typeof e?e:Function(e)).apply(void 0,t)},o(g),g},y=function(e){delete _[e]},"process"==u(m)?o=function(e){m.nextTick(a(e))}:j&&j.now?o=function(e){j.now(a(e))}:v&&!p?(v=(p=new v).port2,p.port1.onmessage=s,o=c(v.postMessage,v,1)):!i.addEventListener||"function"!=typeof postMessage||i.importScripts||l(e)||"file:"===b.protocol?o=w in d("script")?function(e){f.appendChild(d("script"))[w]=function(){f.removeChild(this),n(e)}}:function(e){setTimeout(a(e),0)}:(o=e,i.addEventListener("message",s,!1))),t.exports={set:h,clear:y}},{"../internals/classof-raw":227,"../internals/document-create-element":244,"../internals/engine-is-ios":246,"../internals/fails":252,"../internals/function-bind-context":254,"../internals/global":260,"../internals/html":264}],321:[function(e,t,r){var n=e("../internals/to-integer"),a=Math.max,s=Math.min;t.exports=function(e,t){e=n(e);return e<0?a(e+t,0):s(e,t)}},{"../internals/to-integer":323}],322:[function(e,t,r){var n=e("../internals/indexed-object"),a=e("../internals/require-object-coercible");t.exports=function(e){return n(a(e))}},{"../internals/indexed-object":266,"../internals/require-object-coercible":309}],323:[function(e,t,r){var n=Math.ceil,a=Math.floor;t.exports=function(e){return isNaN(e=+e)?0:(0<e?a:n)(e)}},{}],324:[function(e,t,r){var n=e("../internals/to-integer"),a=Math.min;t.exports=function(e){return 0<e?a(n(e),9007199254740991):0}},{"../internals/to-integer":323}],325:[function(e,t,r){var n=e("../internals/require-object-coercible");t.exports=function(e){return Object(n(e))}},{"../internals/require-object-coercible":309}],326:[function(e,t,r){var a=e("../internals/is-object");t.exports=function(e,t){if(!a(e))return e;var r,n;if(t&&"function"==typeof(r=e.toString)&&!a(n=r.call(e)))return n;if("function"==typeof(r=e.valueOf)&&!a(n=r.call(e)))return n;if(!t&&"function"==typeof(r=e.toString)&&!a(n=r.call(e)))return n;throw TypeError("Can't convert object to primitive value")}},{"../internals/is-object":274}],327:[function(e,t,r){var n={};n[e("../internals/well-known-symbol")("toStringTag")]="z",t.exports="[object z]"===String(n)},{"../internals/well-known-symbol":331}],328:[function(e,t,r){var n=0,a=Math.random();t.exports=function(e){return"Symbol("+String(void 0===e?"":e)+")_"+(++n+a).toString(36)}},{}],329:[function(e,t,r){e=e("../internals/native-symbol");t.exports=e&&!Symbol.sham&&"symbol"==typeof Symbol.iterator},{"../internals/native-symbol":283}],330:[function(e,t,r){e=e("../internals/well-known-symbol");r.f=e},{"../internals/well-known-symbol":331}],331:[function(e,t,r){var n=e("../internals/global"),a=e("../internals/shared"),s=e("../internals/has"),o=e("../internals/uid"),i=e("../internals/native-symbol"),e=e("../internals/use-symbol-as-uid"),l=a("wks"),u=n.Symbol,c=e?u:u&&u.withoutSetter||o;t.exports=function(e){return s(l,e)||(i&&s(u,e)?l[e]=u[e]:l[e]=c("Symbol."+e)),l[e]}},{"../internals/global":260,"../internals/has":261,"../internals/native-symbol":283,"../internals/shared":316,"../internals/uid":328,"../internals/use-symbol-as-uid":329}],332:[function(e,t,r){t.exports="\t\n\v\f\r                 \u2028\u2029\ufeff"},{}],333:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/fails"),l=e("../internals/is-array"),u=e("../internals/is-object"),c=e("../internals/to-object"),f=e("../internals/to-length"),d=e("../internals/create-property"),p=e("../internals/array-species-create"),s=e("../internals/array-method-has-species-support"),o=e("../internals/well-known-symbol"),e=e("../internals/engine-v8-version"),b=o("isConcatSpreadable"),h=9007199254740991,y="Maximum allowed index exceeded",a=51<=e||!a(function(){var e=[];return e[b]=!1,e.concat()[0]!==e}),s=s("concat");n({target:"Array",proto:!0,forced:!a||!s},{concat:function(){for(var e,t,r,n=c(this),a=p(n,0),s=0,o=-1,i=arguments.length;o<i;o++)if(function(e){if(!u(e))return!1;var t=e[b];return void 0!==t?!!t:l(e)}(r=-1===o?n:arguments[o])){if(t=f(r.length),h<s+t)throw TypeError(y);for(e=0;e<t;e++,s++)e in r&&d(a,s,r[e])}else{if(h<=s)throw TypeError(y);d(a,s++,r)}return a.length=s,a}})},{"../internals/array-method-has-species-support":220,"../internals/array-species-create":224,"../internals/create-property":240,"../internals/engine-v8-version":248,"../internals/export":251,"../internals/fails":252,"../internals/is-array":271,"../internals/is-object":274,"../internals/to-length":324,"../internals/to-object":325,"../internals/well-known-symbol":331}],334:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/array-iteration").filter,s=e("../internals/array-method-has-species-support"),e=e("../internals/array-method-uses-to-length"),s=s("filter"),e=e("filter");n({target:"Array",proto:!0,forced:!s||!e},{filter:function(e,t){return a(this,e,1<arguments.length?t:void 0)}})},{"../internals/array-iteration":219,"../internals/array-method-has-species-support":220,"../internals/array-method-uses-to-length":222,"../internals/export":251}],335:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/array-iteration").find,s=e("../internals/add-to-unscopables"),o=e("../internals/array-method-uses-to-length"),e="find",i=!0,o=o(e);e in[]&&Array(1).find(function(){i=!1}),n({target:"Array",proto:!0,forced:i||!o},{find:function(e,t){return a(this,e,1<arguments.length?t:void 0)}}),s(e)},{"../internals/add-to-unscopables":213,"../internals/array-iteration":219,"../internals/array-method-uses-to-length":222,"../internals/export":251}],336:[function(e,t,r){"use strict";var n=e("../internals/export"),e=e("../internals/array-for-each");n({target:"Array",proto:!0,forced:[].forEach!=e},{forEach:e})},{"../internals/array-for-each":216,"../internals/export":251}],337:[function(e,t,r){var n=e("../internals/export"),a=e("../internals/array-from");n({target:"Array",stat:!0,forced:!e("../internals/check-correctness-of-iteration")(function(e){Array.from(e)})},{from:a})},{"../internals/array-from":217,"../internals/check-correctness-of-iteration":226,"../internals/export":251}],338:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/array-includes").includes,s=e("../internals/add-to-unscopables");n({target:"Array",proto:!0,forced:!e("../internals/array-method-uses-to-length")("indexOf",{ACCESSORS:!0,1:0})},{includes:function(e,t){return a(this,e,1<arguments.length?t:void 0)}}),s("includes")},{"../internals/add-to-unscopables":213,"../internals/array-includes":218,"../internals/array-method-uses-to-length":222,"../internals/export":251}],339:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/array-includes").indexOf,s=e("../internals/array-method-is-strict"),e=e("../internals/array-method-uses-to-length"),o=[].indexOf,i=!!o&&1/[1].indexOf(1,-0)<0,s=s("indexOf"),e=e("indexOf",{ACCESSORS:!0,1:0});n({target:"Array",proto:!0,forced:i||!s||!e},{indexOf:function(e,t){return i?o.apply(this,arguments)||0:a(this,e,1<arguments.length?t:void 0)}})},{"../internals/array-includes":218,"../internals/array-method-is-strict":221,"../internals/array-method-uses-to-length":222,"../internals/export":251}],340:[function(e,t,r){e("../internals/export")({target:"Array",stat:!0},{isArray:e("../internals/is-array")})},{"../internals/export":251,"../internals/is-array":271}],341:[function(e,t,r){"use strict";var n=e("../internals/to-indexed-object"),a=e("../internals/add-to-unscopables"),s=e("../internals/iterators"),o=e("../internals/internal-state"),e=e("../internals/define-iterator"),i="Array Iterator",l=o.set,u=o.getterFor(i);t.exports=e(Array,"Array",function(e,t){l(this,{type:i,target:n(e),index:0,kind:t})},function(){var e=u(this),t=e.target,r=e.kind,n=e.index++;return!t||n>=t.length?{value:e.target=void 0,done:!0}:"keys"==r?{value:n,done:!1}:"values"==r?{value:t[n],done:!1}:{value:[n,t[n]],done:!1}},"values"),s.Arguments=s.Array,a("keys"),a("values"),a("entries")},{"../internals/add-to-unscopables":213,"../internals/define-iterator":241,"../internals/internal-state":269,"../internals/iterators":279,"../internals/to-indexed-object":322}],342:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/array-iteration").map,s=e("../internals/array-method-has-species-support"),e=e("../internals/array-method-uses-to-length"),s=s("map"),e=e("map");n({target:"Array",proto:!0,forced:!s||!e},{map:function(e,t){return a(this,e,1<arguments.length?t:void 0)}})},{"../internals/array-iteration":219,"../internals/array-method-has-species-support":220,"../internals/array-method-uses-to-length":222,"../internals/export":251}],343:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/array-reduce").left,s=e("../internals/array-method-is-strict"),e=e("../internals/array-method-uses-to-length"),s=s("reduce"),e=e("reduce",{1:0});n({target:"Array",proto:!0,forced:!s||!e},{reduce:function(e,t){return a(this,e,arguments.length,1<arguments.length?t:void 0)}})},{"../internals/array-method-is-strict":221,"../internals/array-method-uses-to-length":222,"../internals/array-reduce":223,"../internals/export":251}],344:[function(e,t,r){"use strict";var n=e("../internals/export"),u=e("../internals/is-object"),c=e("../internals/is-array"),f=e("../internals/to-absolute-index"),d=e("../internals/to-length"),p=e("../internals/to-indexed-object"),b=e("../internals/create-property"),a=e("../internals/well-known-symbol"),s=e("../internals/array-method-has-species-support"),e=e("../internals/array-method-uses-to-length"),s=s("slice"),e=e("slice",{ACCESSORS:!0,0:0,1:2}),h=a("species"),y=[].slice,m=Math.max;n({target:"Array",proto:!0,forced:!s||!e},{slice:function(e,t){var r,n,a,s=p(this),o=d(s.length),i=f(e,o),l=f(void 0===t?o:t,o);if(c(s)&&(("function"==typeof(r=s.constructor)&&(r===Array||c(r.prototype))||u(r)&&null===(r=r[h]))&&(r=void 0),r===Array||void 0===r))return y.call(s,i,l);for(n=new(void 0===r?Array:r)(m(l-i,0)),a=0;i<l;i++,a++)i in s&&b(n,a,s[i]);return n.length=a,n}})},{"../internals/array-method-has-species-support":220,"../internals/array-method-uses-to-length":222,"../internals/create-property":240,"../internals/export":251,"../internals/is-array":271,"../internals/is-object":274,"../internals/to-absolute-index":321,"../internals/to-indexed-object":322,"../internals/to-length":324,"../internals/well-known-symbol":331}],345:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/a-function"),s=e("../internals/to-object"),o=e("../internals/fails"),i=e("../internals/array-method-is-strict"),l=[],u=l.sort,e=o(function(){l.sort(void 0)}),o=o(function(){l.sort(null)}),i=i("sort");n({target:"Array",proto:!0,forced:e||!o||!i},{sort:function(e){return void 0===e?u.call(s(this)):u.call(s(this),a(e))}})},{"../internals/a-function":211,"../internals/array-method-is-strict":221,"../internals/export":251,"../internals/fails":252,"../internals/to-object":325}],346:[function(e,t,r){"use strict";var n=e("../internals/export"),f=e("../internals/to-absolute-index"),d=e("../internals/to-integer"),p=e("../internals/to-length"),b=e("../internals/to-object"),h=e("../internals/array-species-create"),y=e("../internals/create-property"),a=e("../internals/array-method-has-species-support"),e=e("../internals/array-method-uses-to-length"),a=a("splice"),e=e("splice",{ACCESSORS:!0,0:0,1:2}),m=Math.max,v=Math.min;n({target:"Array",proto:!0,forced:!a||!e},{splice:function(e,t){var r,n,a,s,o,i,l=b(this),u=p(l.length),c=f(e,u),e=arguments.length;if(0===e?r=n=0:n=1===e?(r=0,u-c):(r=e-2,v(m(d(t),0),u-c)),9007199254740991<u+r-n)throw TypeError("Maximum allowed length exceeded");for(a=h(l,n),s=0;s<n;s++)(o=c+s)in l&&y(a,s,l[o]);if(r<(a.length=n)){for(s=c;s<u-n;s++)i=s+r,(o=s+n)in l?l[i]=l[o]:delete l[i];for(s=u;u-n+r<s;s--)delete l[s-1]}else if(n<r)for(s=u-n;c<s;s--)i=s+r-1,(o=s+n-1)in l?l[i]=l[o]:delete l[i];for(s=0;s<r;s++)l[s+c]=arguments[s+2];return l.length=u-n+r,a}})},{"../internals/array-method-has-species-support":220,"../internals/array-method-uses-to-length":222,"../internals/array-species-create":224,"../internals/create-property":240,"../internals/export":251,"../internals/to-absolute-index":321,"../internals/to-integer":323,"../internals/to-length":324,"../internals/to-object":325}],347:[function(e,t,r){e("../internals/export")({target:"Function",proto:!0},{bind:e("../internals/function-bind")})},{"../internals/export":251,"../internals/function-bind":255}],348:[function(e,t,r){function a(e,t,r){var n=r.charAt(t-1),t=r.charAt(t+1);return l.test(e)&&!u.test(t)||u.test(e)&&!l.test(n)?"\\u"+e.charCodeAt(0).toString(16):e}var n=e("../internals/export"),s=e("../internals/get-built-in"),e=e("../internals/fails"),o=s("JSON","stringify"),i=/[\uD800-\uDFFF]/g,l=/^[\uD800-\uDBFF]$/,u=/^[\uDC00-\uDFFF]$/,e=e(function(){return'"\\udf06\\ud834"'!==o("\udf06\ud834")||'"\\udead"'!==o("\udead")});o&&n({target:"JSON",stat:!0,forced:e},{stringify:function(e,t,r){var n=o.apply(null,arguments);return"string"==typeof n?n.replace(i,a):n}})},{"../internals/export":251,"../internals/fails":252,"../internals/get-built-in":256}],349:[function(e,t,r){var n=e("../internals/global");e("../internals/set-to-string-tag")(n.JSON,"JSON",!0)},{"../internals/global":260,"../internals/set-to-string-tag":313}],350:[function(e,t,r){"use strict";var n=e("../internals/collection"),e=e("../internals/collection-strong");t.exports=n("Map",function(t){return function(e){return t(this,arguments.length?e:void 0)}},e)},{"../internals/collection":234,"../internals/collection-strong":232}],351:[function(e,t,r){e("../internals/set-to-string-tag")(Math,"Math",!0)},{"../internals/set-to-string-tag":313}],352:[function(e,t,r){var n=e("../internals/export"),e=e("../internals/object-assign");n({target:"Object",stat:!0,forced:Object.assign!==e},{assign:e})},{"../internals/export":251,"../internals/object-assign":288}],353:[function(e,t,r){e("../internals/export")({target:"Object",stat:!0,sham:!e("../internals/descriptors")},{create:e("../internals/object-create")})},{"../internals/descriptors":243,"../internals/export":251,"../internals/object-create":289}],354:[function(e,t,r){var n=e("../internals/export"),a=e("../internals/descriptors");n({target:"Object",stat:!0,forced:!a,sham:!a},{defineProperties:e("../internals/object-define-properties")})},{"../internals/descriptors":243,"../internals/export":251,"../internals/object-define-properties":290}],355:[function(e,t,r){var n=e("../internals/export"),a=e("../internals/descriptors");n({target:"Object",stat:!0,forced:!a,sham:!a},{defineProperty:e("../internals/object-define-property").f})},{"../internals/descriptors":243,"../internals/export":251,"../internals/object-define-property":291}],356:[function(e,t,r){var n=e("../internals/export"),a=e("../internals/object-to-array").entries;n({target:"Object",stat:!0},{entries:function(e){return a(e)}})},{"../internals/export":251,"../internals/object-to-array":301}],357:[function(e,t,r){var n=e("../internals/export"),a=e("../internals/freezing"),s=e("../internals/fails"),o=e("../internals/is-object"),i=e("../internals/internal-metadata").onFreeze,l=Object.freeze;n({target:"Object",stat:!0,forced:s(function(){l(1)}),sham:!a},{freeze:function(e){return l&&o(e)?l(i(e)):e}})},{"../internals/export":251,"../internals/fails":252,"../internals/freezing":253,"../internals/internal-metadata":268,"../internals/is-object":274}],358:[function(e,t,r){var n=e("../internals/export"),a=e("../internals/fails"),s=e("../internals/to-indexed-object"),o=e("../internals/object-get-own-property-descriptor").f,e=e("../internals/descriptors"),a=a(function(){o(1)});n({target:"Object",stat:!0,forced:!e||a,sham:!e},{getOwnPropertyDescriptor:function(e,t){return o(s(e),t)}})},{"../internals/descriptors":243,"../internals/export":251,"../internals/fails":252,"../internals/object-get-own-property-descriptor":292,"../internals/to-indexed-object":322}],359:[function(e,t,r){var n=e("../internals/export"),a=e("../internals/descriptors"),l=e("../internals/own-keys"),u=e("../internals/to-indexed-object"),c=e("../internals/object-get-own-property-descriptor"),f=e("../internals/create-property");n({target:"Object",stat:!0,sham:!a},{getOwnPropertyDescriptors:function(e){for(var t,r,n=u(e),a=c.f,s=l(n),o={},i=0;s.length>i;)void 0!==(r=a(n,t=s[i++]))&&f(o,t,r);return o}})},{"../internals/create-property":240,"../internals/descriptors":243,"../internals/export":251,"../internals/object-get-own-property-descriptor":292,"../internals/own-keys":303,"../internals/to-indexed-object":322}],360:[function(e,t,r){var n=e("../internals/export"),a=e("../internals/fails"),s=e("../internals/to-object"),o=e("../internals/object-get-prototype-of"),e=e("../internals/correct-prototype-getter");n({target:"Object",stat:!0,forced:a(function(){o(1)}),sham:!e},{getPrototypeOf:function(e){return o(s(e))}})},{"../internals/correct-prototype-getter":236,"../internals/export":251,"../internals/fails":252,"../internals/object-get-prototype-of":296,"../internals/to-object":325}],361:[function(e,t,r){var n=e("../internals/export"),a=e("../internals/to-object"),s=e("../internals/object-keys");n({target:"Object",stat:!0,forced:e("../internals/fails")(function(){s(1)})},{keys:function(e){return s(a(e))}})},{"../internals/export":251,"../internals/fails":252,"../internals/object-keys":298,"../internals/to-object":325}],362:[function(e,t,r){e("../internals/export")({target:"Object",stat:!0},{setPrototypeOf:e("../internals/object-set-prototype-of")})},{"../internals/export":251,"../internals/object-set-prototype-of":300}],363:[function(e,t,r){},{}],364:[function(e,t,r){var n=e("../internals/export"),e=e("../internals/number-parse-int");n({global:!0,forced:parseInt!=e},{parseInt:e})},{"../internals/export":251,"../internals/number-parse-int":287}],365:[function(e,t,r){"use strict";var n=e("../internals/export"),u=e("../internals/a-function"),a=e("../internals/new-promise-capability"),s=e("../internals/perform"),c=e("../internals/iterate");n({target:"Promise",stat:!0},{allSettled:function(e){var i=this,t=a.f(i),l=t.resolve,r=t.reject,n=s(function(){var n=u(i.resolve),a=[],s=0,o=1;c(e,function(e){var t=s++,r=!1;a.push(void 0),o++,n.call(i,e).then(function(e){r||(r=!0,a[t]={status:"fulfilled",value:e},--o||l(a))},function(e){r||(r=!0,a[t]={status:"rejected",reason:e},--o||l(a))})}),--o||l(a)});return n.error&&r(n.value),t.promise}})},{"../internals/a-function":211,"../internals/export":251,"../internals/iterate":277,"../internals/new-promise-capability":285,"../internals/perform":305}],366:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),s=e("../internals/native-promise-constructor"),o=e("../internals/fails"),i=e("../internals/get-built-in"),l=e("../internals/species-constructor"),u=e("../internals/promise-resolve"),e=e("../internals/redefine");n({target:"Promise",proto:!0,real:!0,forced:!!s&&o(function(){s.prototype.finally.call({then:function(){}},function(){})})},{finally:function(t){var r=l(this,i("Promise")),e="function"==typeof t;return this.then(e?function(e){return u(r,t()).then(function(){return e})}:t,e?function(e){return u(r,t()).then(function(){throw e})}:t)}}),a||"function"!=typeof s||s.prototype.finally||e(s.prototype,"finally",i("Promise").prototype.finally)},{"../internals/export":251,"../internals/fails":252,"../internals/get-built-in":256,"../internals/is-pure":275,"../internals/native-promise-constructor":282,"../internals/promise-resolve":306,"../internals/redefine":308,"../internals/species-constructor":317}],367:[function(e,t,r){"use strict";function h(e){var t;return!(!_(e)||"function"!=typeof(t=e.then))&&t}function s(f,d,p){var b;d.notified||(d.notified=!0,b=d.reactions,A(function(){for(var e=d.value,t=1==d.state,r=0;b.length>r;){var n,a,s,o=b[r++],i=t?o.ok:o.fail,l=o.resolve,u=o.reject,c=o.domain;try{i?(t||(2===d.rejection&&re(f,d),d.rejection=1),!0===i?n=e:(c&&c.enter(),n=i(e),c&&(c.exit(),s=!0)),n===o.promise?u(J("Promise-chain cycle")):(a=h(n))?a.call(n,l,u):l(n)):u(e)}catch(e){c&&!s&&c.exit(),u(e)}}d.reactions=[],d.notified=!1,p&&!d.rejection&&ee(f,d)}))}function a(e,t,r){var n;X?((n=Q.createEvent("Event")).promise=t,n.reason=r,n.initEvent(e,!1,!0),p.dispatchEvent(n)):n={promise:t,reason:r},(t=p["on"+e])?t(n):e===Z&&R("Unhandled promise rejection",r)}function o(t,r,n,a){return function(e){t(r,n,e,a)}}function i(e,t,r,n){t.done||(t.done=!0,n&&(t=n),t.value=r,t.state=2,s(e,t,!0))}var n,l,u,c,f=e("../internals/export"),d=e("../internals/is-pure"),p=e("../internals/global"),b=e("../internals/get-built-in"),y=e("../internals/native-promise-constructor"),m=e("../internals/redefine"),v=e("../internals/redefine-all"),j=e("../internals/set-to-string-tag"),g=e("../internals/set-species"),_=e("../internals/is-object"),w=e("../internals/a-function"),x=e("../internals/an-instance"),k=e("../internals/classof-raw"),C=e("../internals/inspect-source"),S=e("../internals/iterate"),E=e("../internals/check-correctness-of-iteration"),O=e("../internals/species-constructor"),P=e("../internals/task").set,A=e("../internals/microtask"),T=e("../internals/promise-resolve"),R=e("../internals/host-report-errors"),I=e("../internals/new-promise-capability"),N=e("../internals/perform"),D=e("../internals/internal-state"),L=e("../internals/is-forced"),M=e("../internals/well-known-symbol"),q=e("../internals/engine-v8-version"),U=M("species"),F="Promise",K=D.get,W=D.set,z=D.getterFor(F),B=y,J=p.TypeError,Q=p.document,V=p.process,G=b("fetch"),$=I.f,H=$,Y="process"==k(V),X=!!(Q&&Q.createEvent&&p.dispatchEvent),Z="unhandledrejection",L=L(F,function(){if(!(C(B)!==String(B))){if(66===q)return!0;if(!Y&&"function"!=typeof PromiseRejectionEvent)return!0}if(d&&!B.prototype.finally)return!0;if(51<=q&&/native code/.test(B))return!1;function e(e){e(function(){},function(){})}var t=B.resolve(1);return(t.constructor={})[U]=e,!(t.then(function(){})instanceof e)}),E=L||!E(function(e){B.all(e).catch(function(){})}),ee=function(r,n){P.call(p,function(){var e,t=n.value;if(te(n)&&(e=N(function(){Y?V.emit("unhandledRejection",t,r):a(Z,r,t)}),n.rejection=Y||te(n)?2:1,e.error))throw e.value})},te=function(e){return 1!==e.rejection&&!e.parent},re=function(e,t){P.call(p,function(){Y?V.emit("rejectionHandled",e):a("rejectionhandled",e,t.value)})},ne=function(r,n,e,t){if(!n.done){n.done=!0,t&&(n=t);try{if(r===e)throw J("Promise can't be resolved itself");var a=h(e);a?A(function(){var t={done:!1};try{a.call(e,o(ne,r,t,n),o(i,r,t,n))}catch(e){i(r,t,e,n)}}):(n.value=e,n.state=1,s(r,n,!1))}catch(e){i(r,{done:!1},e,n)}}};L&&(B=function(e){x(this,B,F),w(e),n.call(this);var t=K(this);try{e(o(ne,this,t),o(i,this,t))}catch(e){i(this,t,e)}},(n=function(){W(this,{type:F,done:!1,notified:!1,parent:!1,reactions:[],rejection:!1,state:0,value:void 0})}).prototype=v(B.prototype,{then:function(e,t){var r=z(this),n=$(O(this,B));return n.ok="function"!=typeof e||e,n.fail="function"==typeof t&&t,n.domain=Y?V.domain:void 0,r.parent=!0,r.reactions.push(n),0!=r.state&&s(this,r,!1),n.promise},catch:function(e){return this.then(void 0,e)}}),l=function(){var e=new n,t=K(e);this.promise=e,this.resolve=o(ne,e,t),this.reject=o(i,e,t)},I.f=$=function(e){return e===B||e===u?new l:H(e)},d||"function"!=typeof y||(c=y.prototype.then,m(y.prototype,"then",function(e,t){var r=this;return new B(function(e,t){c.call(r,e,t)}).then(e,t)},{unsafe:!0}),"function"==typeof G&&f({global:!0,enumerable:!0,forced:!0},{fetch:function(){return T(B,G.apply(p,arguments))}}))),f({global:!0,wrap:!0,forced:L},{Promise:B}),j(B,F,!1,!0),g(F),u=b(F),f({target:F,stat:!0,forced:L},{reject:function(e){var t=$(this);return t.reject.call(void 0,e),t.promise}}),f({target:F,stat:!0,forced:d||L},{resolve:function(e){return T(d&&this===u?B:this,e)}}),f({target:F,stat:!0,forced:E},{all:function(e){var i=this,t=$(i),l=t.resolve,u=t.reject,r=N(function(){var n=w(i.resolve),a=[],s=0,o=1;S(e,function(e){var t=s++,r=!1;a.push(void 0),o++,n.call(i,e).then(function(e){r||(r=!0,a[t]=e,--o||l(a))},u)}),--o||l(a)});return r.error&&u(r.value),t.promise},race:function(e){var r=this,n=$(r),a=n.reject,t=N(function(){var t=w(r.resolve);S(e,function(e){t.call(r,e).then(n.resolve,a)})});return t.error&&a(t.value),n.promise}})},{"../internals/a-function":211,"../internals/an-instance":214,"../internals/check-correctness-of-iteration":226,"../internals/classof-raw":227,"../internals/engine-v8-version":248,"../internals/export":251,"../internals/get-built-in":256,"../internals/global":260,"../internals/host-report-errors":263,"../internals/inspect-source":267,"../internals/internal-state":269,"../internals/is-forced":272,"../internals/is-object":274,"../internals/is-pure":275,"../internals/iterate":277,"../internals/microtask":281,"../internals/native-promise-constructor":282,"../internals/new-promise-capability":285,"../internals/perform":305,"../internals/promise-resolve":306,"../internals/redefine":308,"../internals/redefine-all":307,"../internals/set-species":312,"../internals/set-to-string-tag":313,"../internals/species-constructor":317,"../internals/task":320,"../internals/well-known-symbol":331}],368:[function(e,t,r){var n=e("../internals/export"),a=e("../internals/get-built-in"),s=e("../internals/a-function"),o=e("../internals/an-object"),i=e("../internals/is-object"),l=e("../internals/object-create"),u=e("../internals/function-bind"),e=e("../internals/fails"),c=a("Reflect","construct"),f=e(function(){function e(){}return!(c(function(){},[],e)instanceof e)}),d=!e(function(){c(function(){})}),e=f||d;n({target:"Reflect",stat:!0,forced:e,sham:e},{construct:function(e,t,r){s(e),o(t);var n=arguments.length<3?e:s(r);if(d&&!f)return c(e,t,n);if(e==n){switch(t.length){case 0:return new e;case 1:return new e(t[0]);case 2:return new e(t[0],t[1]);case 3:return new e(t[0],t[1],t[2]);case 4:return new e(t[0],t[1],t[2],t[3])}var a=[null];return a.push.apply(a,t),new(u.apply(e,a))}a=n.prototype,n=l(i(a)?a:Object.prototype),a=Function.apply.call(e,n,t);return i(a)?a:n}})},{"../internals/a-function":211,"../internals/an-object":215,"../internals/export":251,"../internals/fails":252,"../internals/function-bind":255,"../internals/get-built-in":256,"../internals/is-object":274,"../internals/object-create":289}],369:[function(e,t,r){var n=e("../internals/export"),s=e("../internals/is-object"),o=e("../internals/an-object"),i=e("../internals/has"),l=e("../internals/object-get-own-property-descriptor"),u=e("../internals/object-get-prototype-of");n({target:"Reflect",stat:!0},{get:function e(t,r){var n,a=arguments.length<3?t:arguments[2];return o(t)===a?t[r]:(n=l.f(t,r))?i(n,"value")?n.value:void 0===n.get?void 0:n.get.call(a):s(n=u(t))?e(n,r,a):void 0}})},{"../internals/an-object":215,"../internals/export":251,"../internals/has":261,"../internals/is-object":274,"../internals/object-get-own-property-descriptor":292,"../internals/object-get-prototype-of":296}],370:[function(e,t,r){"use strict";var n=e("../internals/collection"),e=e("../internals/collection-strong");t.exports=n("Set",function(t){return function(e){return t(this,arguments.length?e:void 0)}},e)},{"../internals/collection":234,"../internals/collection-strong":232}],371:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/not-a-regexp"),s=e("../internals/require-object-coercible");n({target:"String",proto:!0,forced:!e("../internals/correct-is-regexp-logic")("includes")},{includes:function(e,t){return!!~String(s(this)).indexOf(a(e),1<arguments.length?t:void 0)}})},{"../internals/correct-is-regexp-logic":235,"../internals/export":251,"../internals/not-a-regexp":286,"../internals/require-object-coercible":309}],372:[function(e,t,r){"use strict";var n=e("../internals/string-multibyte").charAt,a=e("../internals/internal-state"),e=e("../internals/define-iterator"),s="String Iterator",o=a.set,i=a.getterFor(s);e(String,"String",function(e){o(this,{type:s,string:String(e),index:0})},function(){var e=i(this),t=e.string,r=e.index;return r>=t.length?{value:void 0,done:!0}:(r=n(t,r),e.index+=r.length,{value:r,done:!1})})},{"../internals/define-iterator":241,"../internals/internal-state":269,"../internals/string-multibyte":318}],373:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/object-get-own-property-descriptor").f,s=e("../internals/to-length"),o=e("../internals/not-a-regexp"),i=e("../internals/require-object-coercible"),l=e("../internals/correct-is-regexp-logic"),e=e("../internals/is-pure"),u="".startsWith,c=Math.min,l=l("startsWith");n({target:"String",proto:!0,forced:!!(e||l||(!(a=a(String.prototype,"startsWith"))||a.writable))&&!l},{startsWith:function(e,t){var r=String(i(this));o(e);t=s(c(1<arguments.length?t:void 0,r.length)),e=String(e);return u?u.call(r,e,t):r.slice(t,t+e.length)===e}})},{"../internals/correct-is-regexp-logic":235,"../internals/export":251,"../internals/is-pure":275,"../internals/not-a-regexp":286,"../internals/object-get-own-property-descriptor":292,"../internals/require-object-coercible":309,"../internals/to-length":324}],374:[function(e,t,r){e("../internals/define-well-known-symbol")("asyncIterator")},{"../internals/define-well-known-symbol":242}],375:[function(e,t,r){arguments[4][363][0].apply(r,arguments)},{dup:363}],376:[function(e,t,r){e("../internals/define-well-known-symbol")("hasInstance")},{"../internals/define-well-known-symbol":242}],377:[function(e,t,r){e("../internals/define-well-known-symbol")("isConcatSpreadable")},{"../internals/define-well-known-symbol":242}],378:[function(e,t,r){e("../internals/define-well-known-symbol")("iterator")},{"../internals/define-well-known-symbol":242}],379:[function(e,t,r){"use strict";function n(e,t){var r=Z[e]=_(V[z]);return B(r,{type:W,tag:e,description:t}),u||(r.description=t),r}function a(t,e){y(t);var r=v(e),e=w(r).concat(le(r));return F(e,function(e){u&&!ie.call(r,e)||oe(t,e,r[e])}),t}var s=e("../internals/export"),o=e("../internals/global"),i=e("../internals/get-built-in"),l=e("../internals/is-pure"),u=e("../internals/descriptors"),c=e("../internals/native-symbol"),f=e("../internals/use-symbol-as-uid"),d=e("../internals/fails"),p=e("../internals/has"),b=e("../internals/is-array"),h=e("../internals/is-object"),y=e("../internals/an-object"),m=e("../internals/to-object"),v=e("../internals/to-indexed-object"),j=e("../internals/to-primitive"),g=e("../internals/create-property-descriptor"),_=e("../internals/object-create"),w=e("../internals/object-keys"),x=e("../internals/object-get-own-property-names"),k=e("../internals/object-get-own-property-names-external"),C=e("../internals/object-get-own-property-symbols"),S=e("../internals/object-get-own-property-descriptor"),E=e("../internals/object-define-property"),O=e("../internals/object-property-is-enumerable"),P=e("../internals/create-non-enumerable-property"),A=e("../internals/redefine"),T=e("../internals/shared"),R=e("../internals/shared-key"),I=e("../internals/hidden-keys"),N=e("../internals/uid"),D=e("../internals/well-known-symbol"),L=e("../internals/well-known-symbol-wrapped"),M=e("../internals/define-well-known-symbol"),q=e("../internals/set-to-string-tag"),U=e("../internals/internal-state"),F=e("../internals/array-iteration").forEach,K=R("hidden"),W="Symbol",z="prototype",R=D("toPrimitive"),B=U.set,J=U.getterFor(W),Q=Object[z],V=o.Symbol,G=i("JSON","stringify"),$=S.f,H=E.f,Y=k.f,X=O.f,Z=T("symbols"),ee=T("op-symbols"),te=T("string-to-symbol-registry"),re=T("symbol-to-string-registry"),T=T("wks"),o=o.QObject,ne=!o||!o[z]||!o[z].findChild,ae=u&&d(function(){return 7!=_(H({},"a",{get:function(){return H(this,"a",{value:7}).a}})).a})?function(e,t,r){var n=$(Q,t);n&&delete Q[t],H(e,t,r),n&&e!==Q&&H(Q,t,n)}:H,se=f?function(e){return"symbol"==typeof e}:function(e){return Object(e)instanceof V},oe=function(e,t,r){e===Q&&oe(ee,t,r),y(e);t=j(t,!0);return y(r),p(Z,t)?(r.enumerable?(p(e,K)&&e[K][t]&&(e[K][t]=!1),r=_(r,{enumerable:g(0,!1)})):(p(e,K)||H(e,K,g(1,{})),e[K][t]=!0),ae(e,t,r)):H(e,t,r)},ie=function(e){var t=j(e,!0),e=X.call(this,t);return!(this===Q&&p(Z,t)&&!p(ee,t))&&(!(e||!p(this,t)||!p(Z,t)||p(this,K)&&this[K][t])||e)},o=function(e,t){var r=v(e),e=j(t,!0);if(r!==Q||!p(Z,e)||p(ee,e)){t=$(r,e);return!t||!p(Z,e)||p(r,K)&&r[K][e]||(t.enumerable=!0),t}},f=function(e){var e=Y(v(e)),t=[];return F(e,function(e){p(Z,e)||p(I,e)||t.push(e)}),t},le=function(e){var t=e===Q,e=Y(t?ee:v(e)),r=[];return F(e,function(e){!p(Z,e)||t&&!p(Q,e)||r.push(Z[e])}),r};c||(A((V=function(e){if(this instanceof V)throw TypeError("Symbol is not a constructor");var e=arguments.length&&void 0!==e?String(e):void 0,t=N(e),r=function(e){this===Q&&r.call(ee,e),p(this,K)&&p(this[K],t)&&(this[K][t]=!1),ae(this,t,g(1,e))};return u&&ne&&ae(Q,t,{configurable:!0,set:r}),n(t,e)})[z],"toString",function(){return J(this).tag}),A(V,"withoutSetter",function(e){return n(N(e),e)}),O.f=ie,E.f=oe,S.f=o,x.f=k.f=f,C.f=le,L.f=function(e){return n(D(e),e)},u&&(H(V[z],"description",{configurable:!0,get:function(){return J(this).description}}),l||A(Q,"propertyIsEnumerable",ie,{unsafe:!0}))),s({global:!0,wrap:!0,forced:!c,sham:!c},{Symbol:V}),F(w(T),function(e){M(e)}),s({target:W,stat:!0,forced:!c},{for:function(e){var t=String(e);if(p(te,t))return te[t];e=V(t);return te[t]=e,re[e]=t,e},keyFor:function(e){if(!se(e))throw TypeError(e+" is not a symbol");if(p(re,e))return re[e]},useSetter:function(){ne=!0},useSimple:function(){ne=!1}}),s({target:"Object",stat:!0,forced:!c,sham:!u},{create:function(e,t){return void 0===t?_(e):a(_(e),t)},defineProperty:oe,defineProperties:a,getOwnPropertyDescriptor:o}),s({target:"Object",stat:!0,forced:!c},{getOwnPropertyNames:f,getOwnPropertySymbols:le}),s({target:"Object",stat:!0,forced:d(function(){C.f(1)})},{getOwnPropertySymbols:function(e){return C.f(m(e))}}),G&&s({target:"JSON",stat:!0,forced:!c||d(function(){var e=V();return"[null]"!=G([e])||"{}"!=G({a:e})||"{}"!=G(Object(e))})},{stringify:function(e,t){for(var r,n=[e],a=1;a<arguments.length;)n.push(arguments[a++]);if((h(r=t)||void 0!==e)&&!se(e))return b(t)||(t=function(e,t){if("function"==typeof r&&(t=r.call(this,e,t)),!se(t))return t}),n[1]=t,G.apply(null,n)}}),V[z][R]||P(V[z],R,V[z].valueOf),q(V,W),I[K]=!0},{"../internals/an-object":215,"../internals/array-iteration":219,"../internals/create-non-enumerable-property":238,"../internals/create-property-descriptor":239,"../internals/define-well-known-symbol":242,"../internals/descriptors":243,"../internals/export":251,"../internals/fails":252,"../internals/get-built-in":256,"../internals/global":260,"../internals/has":261,"../internals/hidden-keys":262,"../internals/internal-state":269,"../internals/is-array":271,"../internals/is-object":274,"../internals/is-pure":275,"../internals/native-symbol":283,"../internals/object-create":289,"../internals/object-define-property":291,"../internals/object-get-own-property-descriptor":292,"../internals/object-get-own-property-names":294,"../internals/object-get-own-property-names-external":293,"../internals/object-get-own-property-symbols":295,"../internals/object-keys":298,"../internals/object-property-is-enumerable":299,"../internals/redefine":308,"../internals/set-to-string-tag":313,"../internals/shared":316,"../internals/shared-key":314,"../internals/to-indexed-object":322,"../internals/to-object":325,"../internals/to-primitive":326,"../internals/uid":328,"../internals/use-symbol-as-uid":329,"../internals/well-known-symbol":331,"../internals/well-known-symbol-wrapped":330}],380:[function(e,t,r){e("../internals/define-well-known-symbol")("matchAll")},{"../internals/define-well-known-symbol":242}],381:[function(e,t,r){e("../internals/define-well-known-symbol")("match")},{"../internals/define-well-known-symbol":242}],382:[function(e,t,r){e("../internals/define-well-known-symbol")("replace")},{"../internals/define-well-known-symbol":242}],383:[function(e,t,r){e("../internals/define-well-known-symbol")("search")},{"../internals/define-well-known-symbol":242}],384:[function(e,t,r){e("../internals/define-well-known-symbol")("species")},{"../internals/define-well-known-symbol":242}],385:[function(e,t,r){e("../internals/define-well-known-symbol")("split")},{"../internals/define-well-known-symbol":242}],386:[function(e,t,r){e("../internals/define-well-known-symbol")("toPrimitive")},{"../internals/define-well-known-symbol":242}],387:[function(e,t,r){e("../internals/define-well-known-symbol")("toStringTag")},{"../internals/define-well-known-symbol":242}],388:[function(e,t,r){e("../internals/define-well-known-symbol")("unscopables")},{"../internals/define-well-known-symbol":242}],389:[function(e,t,r){"use strict";var n,a,s,o,i,l=e("../internals/global"),u=e("../internals/redefine-all"),c=e("../internals/internal-metadata"),f=e("../internals/collection"),d=e("../internals/collection-weak"),p=e("../internals/is-object"),b=e("../internals/internal-state").enforce,h=e("../internals/native-weak-map"),e=!l.ActiveXObject&&"ActiveXObject"in l,y=Object.isExtensible,l=function(t){return function(e){return t(this,arguments.length?e:void 0)}},f=t.exports=f("WeakMap",l,d);h&&e&&(n=d.getConstructor(l,"WeakMap",!0),c.REQUIRED=!0,f=f.prototype,a=f.delete,s=f.has,o=f.get,i=f.set,u(f,{delete:function(e){if(!p(e)||y(e))return a.call(this,e);var t=b(this);return t.frozen||(t.frozen=new n),a.call(this,e)||t.frozen.delete(e)},has:function(e){if(!p(e)||y(e))return s.call(this,e);var t=b(this);return t.frozen||(t.frozen=new n),s.call(this,e)||t.frozen.has(e)},get:function(e){if(!p(e)||y(e))return o.call(this,e);var t=b(this);return t.frozen||(t.frozen=new n),s.call(this,e)?o.call(this,e):t.frozen.get(e)},set:function(e,t){var r;return p(e)&&!y(e)?((r=b(this)).frozen||(r.frozen=new n),s.call(this,e)?i.call(this,e,t):r.frozen.set(e,t)):i.call(this,e,t),this}}))},{"../internals/collection":234,"../internals/collection-weak":233,"../internals/global":260,"../internals/internal-metadata":268,"../internals/internal-state":269,"../internals/is-object":274,"../internals/native-weak-map":284,"../internals/redefine-all":307}],390:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/descriptors"),s=e("../internals/object-get-prototype-of"),o=e("../internals/object-set-prototype-of"),i=e("../internals/object-create"),l=e("../internals/object-define-property"),u=e("../internals/create-property-descriptor"),c=e("../internals/iterate"),f=e("../internals/create-non-enumerable-property"),e=e("../internals/internal-state"),d=e.set,p=e.getterFor("AggregateError"),b=function(e,t){var r=this;if(!(r instanceof b))return new b(e,t);o&&(r=o(new Error(t),s(r)));var n=[];return c(e,n.push,n),a?d(r,{errors:n,type:"AggregateError"}):r.errors=n,void 0!==t&&f(r,"message",String(t)),r};b.prototype=i(Error.prototype,{constructor:u(5,b),message:u(5,""),name:u(5,"AggregateError")}),a&&l.f(b.prototype,"errors",{get:function(){return p(this).errors},configurable:!0}),n({global:!0},{AggregateError:b})},{"../internals/create-non-enumerable-property":238,"../internals/create-property-descriptor":239,"../internals/descriptors":243,"../internals/export":251,"../internals/internal-state":269,"../internals/iterate":277,"../internals/object-create":289,"../internals/object-define-property":291,"../internals/object-get-prototype-of":296,"../internals/object-set-prototype-of":300}],391:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),s=e("../internals/collection-delete-all");n({target:"Map",proto:!0,real:!0,forced:a},{deleteAll:function(){return s.apply(this,arguments)}})},{"../internals/collection-delete-all":229,"../internals/export":251,"../internals/is-pure":275}],392:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),s=e("../internals/an-object"),o=e("../internals/function-bind-context"),i=e("../internals/get-map-iterator"),l=e("../internals/iterate");n({target:"Map",proto:!0,real:!0,forced:a},{every:function(e,t){var r=s(this),n=i(r),a=o(e,1<arguments.length?t:void 0,3);return!l(n,function(e,t){if(!a(t,e,r))return l.stop()},void 0,!0,!0).stopped}})},{"../internals/an-object":215,"../internals/export":251,"../internals/function-bind-context":254,"../internals/get-map-iterator":259,"../internals/is-pure":275,"../internals/iterate":277}],393:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),i=e("../internals/get-built-in"),l=e("../internals/an-object"),u=e("../internals/a-function"),c=e("../internals/function-bind-context"),f=e("../internals/species-constructor"),d=e("../internals/get-map-iterator"),p=e("../internals/iterate");n({target:"Map",proto:!0,real:!0,forced:a},{filter:function(e,t){var r=l(this),n=d(r),a=c(e,1<arguments.length?t:void 0,3),s=new(f(r,i("Map"))),o=u(s.set);return p(n,function(e,t){a(t,e,r)&&o.call(s,e,t)},void 0,!0,!0),s}})},{"../internals/a-function":211,"../internals/an-object":215,"../internals/export":251,"../internals/function-bind-context":254,"../internals/get-built-in":256,"../internals/get-map-iterator":259,"../internals/is-pure":275,"../internals/iterate":277,"../internals/species-constructor":317}],394:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),s=e("../internals/an-object"),o=e("../internals/function-bind-context"),i=e("../internals/get-map-iterator"),l=e("../internals/iterate");n({target:"Map",proto:!0,real:!0,forced:a},{findKey:function(e,t){var r=s(this),n=i(r),a=o(e,1<arguments.length?t:void 0,3);return l(n,function(e,t){if(a(t,e,r))return l.stop(e)},void 0,!0,!0).result}})},{"../internals/an-object":215,"../internals/export":251,"../internals/function-bind-context":254,"../internals/get-map-iterator":259,"../internals/is-pure":275,"../internals/iterate":277}],395:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),s=e("../internals/an-object"),o=e("../internals/function-bind-context"),i=e("../internals/get-map-iterator"),l=e("../internals/iterate");n({target:"Map",proto:!0,real:!0,forced:a},{find:function(e,t){var r=s(this),n=i(r),a=o(e,1<arguments.length?t:void 0,3);return l(n,function(e,t){if(a(t,e,r))return l.stop(t)},void 0,!0,!0).result}})},{"../internals/an-object":215,"../internals/export":251,"../internals/function-bind-context":254,"../internals/get-map-iterator":259,"../internals/is-pure":275,"../internals/iterate":277}],396:[function(e,t,r){e("../internals/export")({target:"Map",stat:!0},{from:e("../internals/collection-from")})},{"../internals/collection-from":230,"../internals/export":251}],397:[function(e,t,r){"use strict";var n=e("../internals/export"),i=e("../internals/iterate"),l=e("../internals/a-function");n({target:"Map",stat:!0},{groupBy:function(e,r){var n=new this;l(r);var a=l(n.has),s=l(n.get),o=l(n.set);return i(e,function(e){var t=r(e);a.call(n,t)?s.call(n,t).push(e):o.call(n,t,[e])}),n}})},{"../internals/a-function":211,"../internals/export":251,"../internals/iterate":277}],398:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),s=e("../internals/an-object"),o=e("../internals/get-map-iterator"),i=e("../internals/same-value-zero"),l=e("../internals/iterate");n({target:"Map",proto:!0,real:!0,forced:a},{includes:function(r){return l(o(s(this)),function(e,t){if(i(t,r))return l.stop()},void 0,!0,!0).stopped}})},{"../internals/an-object":215,"../internals/export":251,"../internals/get-map-iterator":259,"../internals/is-pure":275,"../internals/iterate":277,"../internals/same-value-zero":310}],399:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/iterate"),s=e("../internals/a-function");n({target:"Map",stat:!0},{keyBy:function(e,t){var r=new this;s(t);var n=s(r.set);return a(e,function(e){n.call(r,t(e),e)}),r}})},{"../internals/a-function":211,"../internals/export":251,"../internals/iterate":277}],400:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),s=e("../internals/an-object"),o=e("../internals/get-map-iterator"),i=e("../internals/iterate");n({target:"Map",proto:!0,real:!0,forced:a},{keyOf:function(r){return i(o(s(this)),function(e,t){if(t===r)return i.stop(e)},void 0,!0,!0).result}})},{"../internals/an-object":215,"../internals/export":251,"../internals/get-map-iterator":259,"../internals/is-pure":275,"../internals/iterate":277}],401:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),i=e("../internals/get-built-in"),l=e("../internals/an-object"),u=e("../internals/a-function"),c=e("../internals/function-bind-context"),f=e("../internals/species-constructor"),d=e("../internals/get-map-iterator"),p=e("../internals/iterate");n({target:"Map",proto:!0,real:!0,forced:a},{mapKeys:function(e,t){var r=l(this),n=d(r),a=c(e,1<arguments.length?t:void 0,3),s=new(f(r,i("Map"))),o=u(s.set);return p(n,function(e,t){o.call(s,a(t,e,r),t)},void 0,!0,!0),s}})},{"../internals/a-function":211,"../internals/an-object":215,"../internals/export":251,"../internals/function-bind-context":254,"../internals/get-built-in":256,"../internals/get-map-iterator":259,"../internals/is-pure":275,"../internals/iterate":277,"../internals/species-constructor":317}],402:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),i=e("../internals/get-built-in"),l=e("../internals/an-object"),u=e("../internals/a-function"),c=e("../internals/function-bind-context"),f=e("../internals/species-constructor"),d=e("../internals/get-map-iterator"),p=e("../internals/iterate");n({target:"Map",proto:!0,real:!0,forced:a},{mapValues:function(e,t){var r=l(this),n=d(r),a=c(e,1<arguments.length?t:void 0,3),s=new(f(r,i("Map"))),o=u(s.set);return p(n,function(e,t){o.call(s,e,a(t,e,r))},void 0,!0,!0),s}})},{"../internals/a-function":211,"../internals/an-object":215,"../internals/export":251,"../internals/function-bind-context":254,"../internals/get-built-in":256,"../internals/get-map-iterator":259,"../internals/is-pure":275,"../internals/iterate":277,"../internals/species-constructor":317}],403:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),s=e("../internals/an-object"),o=e("../internals/a-function"),i=e("../internals/iterate");n({target:"Map",proto:!0,real:!0,forced:a},{merge:function(){for(var e=s(this),t=o(e.set),r=0;r<arguments.length;)i(arguments[r++],t,e,!0);return e}})},{"../internals/a-function":211,"../internals/an-object":215,"../internals/export":251,"../internals/is-pure":275,"../internals/iterate":277}],404:[function(e,t,r){e("../internals/export")({target:"Map",stat:!0},{of:e("../internals/collection-of")})},{"../internals/collection-of":231,"../internals/export":251}],405:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),o=e("../internals/an-object"),i=e("../internals/a-function"),l=e("../internals/get-map-iterator"),u=e("../internals/iterate");n({target:"Map",proto:!0,real:!0,forced:a},{reduce:function(r,e){var n=o(this),t=l(n),a=arguments.length<2,s=a?void 0:e;if(i(r),u(t,function(e,t){s=a?(a=!1,t):r(s,t,e,n)},void 0,!0,!0),a)throw TypeError("Reduce of empty map with no initial value");return s}})},{"../internals/a-function":211,"../internals/an-object":215,"../internals/export":251,"../internals/get-map-iterator":259,"../internals/is-pure":275,"../internals/iterate":277}],406:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),s=e("../internals/an-object"),o=e("../internals/function-bind-context"),i=e("../internals/get-map-iterator"),l=e("../internals/iterate");n({target:"Map",proto:!0,real:!0,forced:a},{some:function(e,t){var r=s(this),n=i(r),a=o(e,1<arguments.length?t:void 0,3);return l(n,function(e,t){if(a(t,e,r))return l.stop()},void 0,!0,!0).stopped}})},{"../internals/an-object":215,"../internals/export":251,"../internals/function-bind-context":254,"../internals/get-map-iterator":259,"../internals/is-pure":275,"../internals/iterate":277}],407:[function(e,t,r){"use strict";e("../internals/export")({target:"Map",proto:!0,real:!0,forced:e("../internals/is-pure")},{updateOrInsert:e("../internals/map-upsert")})},{"../internals/export":251,"../internals/is-pure":275,"../internals/map-upsert":280}],408:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),o=e("../internals/an-object"),i=e("../internals/a-function");n({target:"Map",proto:!0,real:!0,forced:a},{update:function(e,t,r){var n=o(this),a=arguments.length;i(t);var s=n.has(e);if(!s&&a<3)throw TypeError("Updating absent value");r=s?n.get(e):i(2<a?r:void 0)(e,n);return n.set(e,t(r,e,n)),n}})},{"../internals/a-function":211,"../internals/an-object":215,"../internals/export":251,"../internals/is-pure":275}],409:[function(e,t,r){"use strict";e("../internals/export")({target:"Map",proto:!0,real:!0,forced:e("../internals/is-pure")},{upsert:e("../internals/map-upsert")})},{"../internals/export":251,"../internals/is-pure":275,"../internals/map-upsert":280}],410:[function(e,t,r){e("./es.promise.all-settled.js")},{"./es.promise.all-settled.js":365}],411:[function(e,t,r){"use strict";var n=e("../internals/export"),f=e("../internals/a-function"),d=e("../internals/get-built-in"),a=e("../internals/new-promise-capability"),s=e("../internals/perform"),p=e("../internals/iterate"),b="No one promise resolved";n({target:"Promise",stat:!0},{any:function(e){var l=this,t=a.f(l),u=t.resolve,c=t.reject,r=s(function(){var n=f(l.resolve),a=[],s=0,o=1,i=!1;p(e,function(e){var t=s++,r=!1;a.push(void 0),o++,n.call(l,e).then(function(e){r||i||(i=!0,u(e))},function(e){r||i||(r=!0,a[t]=e,--o||c(new(d("AggregateError"))(a,b)))})}),--o||c(new(d("AggregateError"))(a,b))});return r.error&&c(r.value),t.promise}})},{"../internals/a-function":211,"../internals/export":251,"../internals/get-built-in":256,"../internals/iterate":277,"../internals/new-promise-capability":285,"../internals/perform":305}],412:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/new-promise-capability"),s=e("../internals/perform");n({target:"Promise",stat:!0},{try:function(e){var t=a.f(this),e=s(e);return(e.error?t.reject:t.resolve)(e.value),t.promise}})},{"../internals/export":251,"../internals/new-promise-capability":285,"../internals/perform":305}],413:[function(e,t,r){e("../internals/define-well-known-symbol")("asyncDispose")},{"../internals/define-well-known-symbol":242}],414:[function(e,t,r){e("../internals/define-well-known-symbol")("dispose")},{"../internals/define-well-known-symbol":242}],415:[function(e,t,r){e("../internals/define-well-known-symbol")("observable")},{"../internals/define-well-known-symbol":242}],416:[function(e,t,r){e("../internals/define-well-known-symbol")("patternMatch")},{"../internals/define-well-known-symbol":242}],417:[function(e,t,r){e("../internals/define-well-known-symbol")("replaceAll")},{"../internals/define-well-known-symbol":242}],418:[function(e,t,r){"use strict";var n=e("../internals/export"),a=e("../internals/is-pure"),s=e("../internals/collection-delete-all");n({target:"WeakMap",proto:!0,real:!0,forced:a},{deleteAll:function(){return s.apply(this,arguments)}})},{"../internals/collection-delete-all":229,"../internals/export":251,"../internals/is-pure":275}],419:[function(e,t,r){e("../internals/export")({target:"WeakMap",stat:!0},{from:e("../internals/collection-from")})},{"../internals/collection-from":230,"../internals/export":251}],420:[function(e,t,r){e("../internals/export")({target:"WeakMap",stat:!0},{of:e("../internals/collection-of")})},{"../internals/collection-of":231,"../internals/export":251}],421:[function(e,t,r){"use strict";e("../internals/export")({target:"WeakMap",proto:!0,real:!0,forced:e("../internals/is-pure")},{upsert:e("../internals/map-upsert")})},{"../internals/export":251,"../internals/is-pure":275,"../internals/map-upsert":280}],422:[function(e,t,r){e("./es.array.iterator");var n,a=e("../internals/dom-iterables"),s=e("../internals/global"),o=e("../internals/classof"),i=e("../internals/create-non-enumerable-property"),l=e("../internals/iterators"),u=e("../internals/well-known-symbol")("toStringTag");for(n in a){var c=s[n],c=c&&c.prototype;c&&o(c)!==u&&i(c,u,n),l[n]=l.Array}},{"../internals/classof":228,"../internals/create-non-enumerable-property":238,"../internals/dom-iterables":245,"../internals/global":260,"../internals/iterators":279,"../internals/well-known-symbol":331,"./es.array.iterator":341}],423:[function(e,t,r){var n=e("../internals/export"),a=e("../internals/global"),s=e("../internals/engine-user-agent"),o=[].slice,e=function(a){return function(e,t){var r=2<arguments.length,n=r?o.call(arguments,2):void 0;return a(r?function(){("function"==typeof e?e:Function(e)).apply(this,n)}:e,t)}};n({global:!0,bind:!0,forced:/MSIE .\./.test(s)},{setTimeout:e(a.setTimeout),setInterval:e(a.setInterval)})},{"../internals/engine-user-agent":247,"../internals/export":251,"../internals/global":260}],424:[function(e,t,r){arguments[4][191][0].apply(r,arguments)},{"../../es/array/from":139,dup:191}],425:[function(e,t,r){arguments[4][192][0].apply(r,arguments)},{"../../es/array/is-array":140,dup:192}],426:[function(e,t,r){e=e("../../../es/array/virtual/for-each");t.exports=e},{"../../../es/array/virtual/for-each":144}],427:[function(e,t,r){e=e("../../../es/array/virtual/keys");t.exports=e},{"../../../es/array/virtual/keys":147}],428:[function(e,t,r){e=e("../../../es/array/virtual/values");t.exports=e},{"../../../es/array/virtual/values":153}],429:[function(e,t,r){arguments[4][195][0].apply(r,arguments)},{"../../es/instance/bind":155,dup:195}],430:[function(e,t,r){e=e("../../es/instance/concat");t.exports=e},{"../../es/instance/concat":156}],431:[function(e,t,r){e=e("../../es/instance/filter");t.exports=e},{"../../es/instance/filter":157}],432:[function(e,t,r){e=e("../../es/instance/find");t.exports=e},{"../../es/instance/find":158}],433:[function(e,t,r){e("../../modules/web.dom-collections.iterator");var n=e("../array/virtual/for-each"),a=e("../../internals/classof"),s=Array.prototype,o={DOMTokenList:!0,NodeList:!0};t.exports=function(e){var t=e.forEach;return e===s||e instanceof Array&&t===s.forEach||o.hasOwnProperty(a(e))?n:t}},{"../../internals/classof":228,"../../modules/web.dom-collections.iterator":422,"../array/virtual/for-each":426}],434:[function(e,t,r){e=e("../../es/instance/includes");t.exports=e},{"../../es/instance/includes":159}],435:[function(e,t,r){arguments[4][196][0].apply(r,arguments)},{"../../es/instance/index-of":160,dup:196}],436:[function(e,t,r){e("../../modules/web.dom-collections.iterator");var n=e("../array/virtual/keys"),a=e("../../internals/classof"),s=Array.prototype,o={DOMTokenList:!0,NodeList:!0};t.exports=function(e){var t=e.keys;return e===s||e instanceof Array&&t===s.keys||o.hasOwnProperty(a(e))?n:t}},{"../../internals/classof":228,"../../modules/web.dom-collections.iterator":422,"../array/virtual/keys":427}],437:[function(e,t,r){e=e("../../es/instance/map");t.exports=e},{"../../es/instance/map":161}],438:[function(e,t,r){e=e("../../es/instance/reduce");t.exports=e},{"../../es/instance/reduce":162}],439:[function(e,t,r){arguments[4][197][0].apply(r,arguments)},{"../../es/instance/slice":163,dup:197}],440:[function(e,t,r){e=e("../../es/instance/sort");t.exports=e},{"../../es/instance/sort":164}],441:[function(e,t,r){e=e("../../es/instance/splice");t.exports=e},{"../../es/instance/splice":165}],442:[function(e,t,r){e=e("../../es/instance/starts-with");t.exports=e},{"../../es/instance/starts-with":166}],443:[function(e,t,r){e("../../modules/web.dom-collections.iterator");var n=e("../array/virtual/values"),a=e("../../internals/classof"),s=Array.prototype,o={DOMTokenList:!0,NodeList:!0};t.exports=function(e){var t=e.values;return e===s||e instanceof Array&&t===s.values||o.hasOwnProperty(a(e))?n:t}},{"../../internals/classof":228,"../../modules/web.dom-collections.iterator":422,"../array/virtual/values":428}],444:[function(e,t,r){e=e("../../es/json/stringify");t.exports=e},{"../../es/json/stringify":167}],445:[function(e,t,r){e=e("../../es/map");t.exports=e},{"../../es/map":168}],446:[function(e,t,r){e=e("../../es/object/assign");t.exports=e},{"../../es/object/assign":169}],447:[function(e,t,r){arguments[4][200][0].apply(r,arguments)},{"../../es/object/create":170,dup:200}],448:[function(e,t,r){e=e("../../es/object/define-properties");t.exports=e},{"../../es/object/define-properties":171}],449:[function(e,t,r){arguments[4][201][0].apply(r,arguments)},{"../../es/object/define-property":172,dup:201}],450:[function(e,t,r){e=e("../../es/object/entries");t.exports=e},{"../../es/object/entries":173}],451:[function(e,t,r){e=e("../../es/object/freeze");t.exports=e},{"../../es/object/freeze":174}],452:[function(e,t,r){arguments[4][202][0].apply(r,arguments)},{"../../es/object/get-own-property-descriptor":175,dup:202}],453:[function(e,t,r){e=e("../../es/object/get-own-property-descriptors");t.exports=e},{"../../es/object/get-own-property-descriptors":176}],454:[function(e,t,r){e=e("../../es/object/get-own-property-symbols");t.exports=e},{"../../es/object/get-own-property-symbols":177}],455:[function(e,t,r){e=e("../../es/object/keys");t.exports=e},{"../../es/object/keys":179}],456:[function(e,t,r){e=e("../es/parse-int");t.exports=e},{"../es/parse-int":181}],457:[function(e,t,r){e=e("../../es/promise");t.exports=e},{"../../es/promise":182}],458:[function(e,t,r){arguments[4][206][0].apply(r,arguments)},{"../../es/reflect/construct":183,dup:206}],459:[function(e,t,r){e("../modules/web.timers");e=e("../internals/path");t.exports=e.setTimeout},{"../internals/path":304,"../modules/web.timers":423}],460:[function(e,t,r){e=e("../../es/set");t.exports=e},{"../../es/set":185}],461:[function(e,t,r){e=e("../../es/symbol");t.exports=e},{"../../es/symbol":188}],462:[function(e,t,r){e=e("../../es/weak-map");t.exports=e},{"../../es/weak-map":190}],463:[function(e,t,r){var n,a;n=this,a=function(n){return function(){var e=n,t=e.lib.BlockCipher,r=e.algo,u=[],c=[],f=[],d=[],p=[],b=[],h=[],y=[],m=[],v=[];!function(){for(var e=[],t=0;t<256;t++)e[t]=t<128?t<<1:t<<1^283;for(var r=0,n=0,t=0;t<256;t++){var a=(a=n^n<<1^n<<2^n<<3^n<<4)>>>8^255&a^99;u[r]=a;var s=e[c[a]=r],o=e[s],i=e[o],l=257*e[a]^16843008*a;f[r]=l<<24|l>>>8,d[r]=l<<16|l>>>16,p[r]=l<<8|l>>>24,b[r]=l;l=16843009*i^65537*o^257*s^16843008*r;h[a]=l<<24|l>>>8,y[a]=l<<16|l>>>16,m[a]=l<<8|l>>>24,v[a]=l,r?(r=s^e[e[e[i^s]]],n^=e[e[n]]):r=n=1}}();var j=[0,1,2,4,8,16,32,64,128,27,54],r=r.AES=t.extend({_doReset:function(){if(!this._nRounds||this._keyPriorReset!==this._key){for(var e=this._keyPriorReset=this._key,t=e.words,r=e.sigBytes/4,n=4*(1+(this._nRounds=6+r)),a=this._keySchedule=[],s=0;s<n;s++)s<r?a[s]=t[s]:(l=a[s-1],s%r?6<r&&s%r==4&&(l=u[l>>>24]<<24|u[l>>>16&255]<<16|u[l>>>8&255]<<8|u[255&l]):(l=u[(l=l<<8|l>>>24)>>>24]<<24|u[l>>>16&255]<<16|u[l>>>8&255]<<8|u[255&l],l^=j[s/r|0]<<24),a[s]=a[s-r]^l);for(var o=this._invKeySchedule=[],i=0;i<n;i++){var l,s=n-i;l=i%4?a[s]:a[s-4],o[i]=i<4||s<=4?l:h[u[l>>>24]]^y[u[l>>>16&255]]^m[u[l>>>8&255]]^v[u[255&l]]}}},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,f,d,p,b,u)},decryptBlock:function(e,t){var r=e[t+1];e[t+1]=e[t+3],e[t+3]=r,this._doCryptBlock(e,t,this._invKeySchedule,h,y,m,v,c);r=e[t+1];e[t+1]=e[t+3],e[t+3]=r},_doCryptBlock:function(e,t,r,n,a,s,o,i){for(var l=this._nRounds,u=e[t]^r[0],c=e[t+1]^r[1],f=e[t+2]^r[2],d=e[t+3]^r[3],p=4,b=1;b<l;b++)var h=n[u>>>24]^a[c>>>16&255]^s[f>>>8&255]^o[255&d]^r[p++],y=n[c>>>24]^a[f>>>16&255]^s[d>>>8&255]^o[255&u]^r[p++],m=n[f>>>24]^a[d>>>16&255]^s[u>>>8&255]^o[255&c]^r[p++],v=n[d>>>24]^a[u>>>16&255]^s[c>>>8&255]^o[255&f]^r[p++],u=h,c=y,f=m,d=v;h=(i[u>>>24]<<24|i[c>>>16&255]<<16|i[f>>>8&255]<<8|i[255&d])^r[p++],y=(i[c>>>24]<<24|i[f>>>16&255]<<16|i[d>>>8&255]<<8|i[255&u])^r[p++],m=(i[f>>>24]<<24|i[d>>>16&255]<<16|i[u>>>8&255]<<8|i[255&c])^r[p++],v=(i[d>>>24]<<24|i[u>>>16&255]<<16|i[c>>>8&255]<<8|i[255&f])^r[p++];e[t]=h,e[t+1]=y,e[t+2]=m,e[t+3]=v},keySize:8});e.AES=t._createHelper(r)}(),n.AES},"object"==typeof r?t.exports=r=a(e("./core"),e("./enc-base64"),e("./md5"),e("./evpkdf"),e("./cipher-core")):a(n.CryptoJS)},{"./cipher-core":464,"./core":465,"./enc-base64":466,"./evpkdf":468,"./md5":470}],464:[function(e,t,r){var n,a;n=this,a=function(h){h.lib.Cipher||function(){var e=h,t=e.lib,r=t.Base,o=t.WordArray,n=t.BufferedBlockAlgorithm,a=e.enc,s=(a.Utf8,a.Base64),i=e.algo.EvpKDF,l=t.Cipher=n.extend({cfg:r.extend(),createEncryptor:function(e,t){return this.create(this._ENC_XFORM_MODE,e,t)},createDecryptor:function(e,t){return this.create(this._DEC_XFORM_MODE,e,t)},init:function(e,t,r){this.cfg=this.cfg.extend(r),this._xformMode=e,this._key=t,this.reset()},reset:function(){n.reset.call(this),this._doReset()},process:function(e){return this._append(e),this._process()},finalize:function(e){return e&&this._append(e),this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(n){return{encrypt:function(e,t,r){return u(t).encrypt(n,e,t,r)},decrypt:function(e,t,r){return u(t).decrypt(n,e,t,r)}}}});function u(e){return"string"==typeof e?b:p}t.StreamCipher=l.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var c=e.mode={},a=t.BlockCipherMode=r.extend({createEncryptor:function(e,t){return this.Encryptor.create(e,t)},createDecryptor:function(e,t){return this.Decryptor.create(e,t)},init:function(e,t){this._cipher=e,this._iv=t}}),a=c.CBC=((c=a.extend()).Encryptor=c.extend({processBlock:function(e,t){var r=this._cipher,n=r.blockSize;f.call(this,e,t,n),r.encryptBlock(e,t),this._prevBlock=e.slice(t,t+n)}}),c.Decryptor=c.extend({processBlock:function(e,t){var r=this._cipher,n=r.blockSize,a=e.slice(t,t+n);r.decryptBlock(e,t),f.call(this,e,t,n),this._prevBlock=a}}),c);function f(e,t,r){var n,a=this._iv;a?(n=a,this._iv=void 0):n=this._prevBlock;for(var s=0;s<r;s++)e[t+s]^=n[s]}var c=(e.pad={}).Pkcs7={pad:function(e,t){for(var t=4*t,r=t-e.sigBytes%t,n=r<<24|r<<16|r<<8|r,a=[],s=0;s<r;s+=4)a.push(n);t=o.create(a,r);e.concat(t)},unpad:function(e){var t=255&e.words[e.sigBytes-1>>>2];e.sigBytes-=t}},d=(t.BlockCipher=l.extend({cfg:l.cfg.extend({mode:a,padding:c}),reset:function(){var e;l.reset.call(this);var t=this.cfg,r=t.iv,t=t.mode;this._xformMode==this._ENC_XFORM_MODE?e=t.createEncryptor:(e=t.createDecryptor,this._minBufferSize=1),this._mode&&this._mode.__creator==e?this._mode.init(this,r&&r.words):(this._mode=e.call(t,this,r&&r.words),this._mode.__creator=e)},_doProcessBlock:function(e,t){this._mode.processBlock(e,t)},_doFinalize:function(){var e,t=this.cfg.padding;return this._xformMode==this._ENC_XFORM_MODE?(t.pad(this._data,this.blockSize),e=this._process(!0)):(e=this._process(!0),t.unpad(e)),e},blockSize:4}),t.CipherParams=r.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}})),c=(e.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext,e=e.salt,t=e?o.create([1398893684,1701076831]).concat(e).concat(t):t;return t.toString(s)},parse:function(e){var t,r=s.parse(e),e=r.words;return 1398893684==e[0]&&1701076831==e[1]&&(t=o.create(e.slice(2,4)),e.splice(0,4),r.sigBytes-=16),d.create({ciphertext:r,salt:t})}},p=t.SerializableCipher=r.extend({cfg:r.extend({format:c}),encrypt:function(e,t,r,n){n=this.cfg.extend(n);var a=e.createEncryptor(r,n),t=a.finalize(t),a=a.cfg;return d.create({ciphertext:t,key:r,iv:a.iv,algorithm:e,mode:a.mode,padding:a.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,r,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(r,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}}),e=(e.kdf={}).OpenSSL={execute:function(e,t,r,n){n=n||o.random(8);e=i.create({keySize:t+r}).compute(e,n),r=o.create(e.words.slice(t),4*r);return e.sigBytes=4*t,d.create({key:e,iv:r,salt:n})}},b=t.PasswordBasedCipher=p.extend({cfg:p.cfg.extend({kdf:e}),encrypt:function(e,t,r,n){r=(n=this.cfg.extend(n)).kdf.execute(r,e.keySize,e.ivSize);n.iv=r.iv;n=p.encrypt.call(this,e,t,r.key,n);return n.mixIn(r),n},decrypt:function(e,t,r,n){n=this.cfg.extend(n),t=this._parse(t,n.format);r=n.kdf.execute(r,e.keySize,e.ivSize,t.salt);return n.iv=r.iv,p.decrypt.call(this,e,t,r.key,n)}})}()},"object"==typeof r?t.exports=r=a(e("./core"),e("./evpkdf")):a(n.CryptoJS)},{"./core":465,"./evpkdf":468}],465:[function(h,r,n){(function(b){var e,t;e=this,t=function(){return function(u){var n;if("undefined"!=typeof window&&window.crypto&&(n=window.crypto),!n&&"undefined"!=typeof window&&window.msCrypto&&(n=window.msCrypto),!n&&void 0!==b&&b.crypto&&(n=b.crypto),!n&&"function"==typeof h)try{n=h("crypto")}catch(e){}var r=Object.create||function(e){return t.prototype=e,e=new t,t.prototype=null,e};function t(){}var e={},a=e.lib={},s=a.Base={extend:function(e){var t=r(this);return e&&t.mixIn(e),t.hasOwnProperty("init")&&this.init!==t.init||(t.init=function(){t.$super.init.apply(this,arguments)}),(t.init.prototype=t).$super=this,t},create:function(){var e=this.extend();return e.init.apply(e,arguments),e},init:function(){},mixIn:function(e){for(var t in e)e.hasOwnProperty(t)&&(this[t]=e[t]);e.hasOwnProperty("toString")&&(this.toString=e.toString)},clone:function(){return this.init.prototype.extend(this)}},c=a.WordArray=s.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||i).stringify(this)},concat:function(e){var t=this.words,r=e.words,n=this.sigBytes,a=e.sigBytes;if(this.clamp(),n%4)for(var s=0;s<a;s++){var o=r[s>>>2]>>>24-s%4*8&255;t[n+s>>>2]|=o<<24-(n+s)%4*8}else for(s=0;s<a;s+=4)t[n+s>>>2]=r[s>>>2];return this.sigBytes+=a,this},clamp:function(){var e=this.words,t=this.sigBytes;e[t>>>2]&=4294967295<<32-t%4*8,e.length=u.ceil(t/4)},clone:function(){var e=s.clone.call(this);return e.words=this.words.slice(0),e},random:function(e){for(var t=[],r=0;r<e;r+=4)t.push(function(){if(n){if("function"==typeof n.getRandomValues)try{return n.getRandomValues(new Uint32Array(1))[0]}catch(e){}if("function"==typeof n.randomBytes)try{return n.randomBytes(4).readInt32LE()}catch(e){}}throw new Error("Native crypto module could not be used to get secure random number.")}());return new c.init(t,e)}}),o=e.enc={},i=o.Hex={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],a=0;a<r;a++){var s=t[a>>>2]>>>24-a%4*8&255;n.push((s>>>4).toString(16)),n.push((15&s).toString(16))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n<t;n+=2)r[n>>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new c.init(r,t/2)}},l=o.Latin1={stringify:function(e){for(var t=e.words,r=e.sigBytes,n=[],a=0;a<r;a++){var s=t[a>>>2]>>>24-a%4*8&255;n.push(String.fromCharCode(s))}return n.join("")},parse:function(e){for(var t=e.length,r=[],n=0;n<t;n++)r[n>>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new c.init(r,t)}},f=o.Utf8={stringify:function(e){try{return decodeURIComponent(escape(l.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return l.parse(unescape(encodeURIComponent(e)))}},d=a.BufferedBlockAlgorithm=s.extend({reset:function(){this._data=new c.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=f.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(e){var t,r=this._data,n=r.words,a=r.sigBytes,s=this.blockSize,o=a/(4*s),i=(o=e?u.ceil(o):u.max((0|o)-this._minBufferSize,0))*s,a=u.min(4*i,a);if(i){for(var l=0;l<i;l+=s)this._doProcessBlock(n,l);t=n.splice(0,i),r.sigBytes-=a}return new c.init(t,a)},clone:function(){var e=s.clone.call(this);return e._data=this._data.clone(),e},_minBufferSize:0}),p=(a.Hasher=d.extend({cfg:s.extend(),init:function(e){this.cfg=this.cfg.extend(e),this.reset()},reset:function(){d.reset.call(this),this._doReset()},update:function(e){return this._append(e),this._process(),this},finalize:function(e){return e&&this._append(e),this._doFinalize()},blockSize:16,_createHelper:function(r){return function(e,t){return new r.init(t).finalize(e)}},_createHmacHelper:function(r){return function(e,t){return new p.HMAC.init(r,t).finalize(e)}}}),e.algo={});return e}(Math)},"object"==typeof n?r.exports=n=t():e.CryptoJS=t()}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{crypto:void 0}],466:[function(e,t,r){var n,a;n=this,a=function(e){var l;return l=e.lib.WordArray,e.enc.Base64={stringify:function(e){var t=e.words,r=e.sigBytes,n=this._map;e.clamp();for(var a=[],s=0;s<r;s+=3)for(var o=(t[s>>>2]>>>24-s%4*8&255)<<16|(t[s+1>>>2]>>>24-(s+1)%4*8&255)<<8|t[s+2>>>2]>>>24-(s+2)%4*8&255,i=0;i<4&&s+.75*i<r;i++)a.push(n.charAt(o>>>6*(3-i)&63));var l=n.charAt(64);if(l)for(;a.length%4;)a.push(l);return a.join("")},parse:function(e){var t=e.length,r=this._map,n=this._reverseMap;if(!n){n=this._reverseMap=[];for(var a=0;a<r.length;a++)n[r.charCodeAt(a)]=a}var s=r.charAt(64);return!s||-1!==(s=e.indexOf(s))&&(t=s),function(e,t,r){for(var n=[],a=0,s=0;s<t;s++){var o,i;s%4&&(o=r[e.charCodeAt(s-1)]<<s%4*2,i=r[e.charCodeAt(s)]>>>6-s%4*2,i=o|i,n[a>>>2]|=i<<24-a%4*8,a++)}return l.create(n,a)}(e,t,n)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},e.enc.Base64},"object"==typeof r?t.exports=r=a(e("./core")):a(n.CryptoJS)},{"./core":465}],467:[function(e,t,r){var n,a;n=this,a=function(e){return e.enc.Utf8},"object"==typeof r?t.exports=r=a(e("./core")):a(n.CryptoJS)},{"./core":465}],468:[function(e,t,r){var n,a;n=this,a=function(e){var t,r,n,c,a,s;return r=(t=e).lib,n=r.Base,c=r.WordArray,a=t.algo,r=a.MD5,s=a.EvpKDF=n.extend({cfg:n.extend({keySize:4,hasher:r,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var r,n=this.cfg,a=n.hasher.create(),s=c.create(),o=s.words,i=n.keySize,l=n.iterations;o.length<i;){r&&a.update(r),r=a.update(e).finalize(t),a.reset();for(var u=1;u<l;u++)r=a.finalize(r),a.reset();s.concat(r)}return s.sigBytes=4*i,s}}),t.EvpKDF=function(e,t,r){return s.create(r).compute(e,t)},e.EvpKDF},"object"==typeof r?t.exports=r=a(e("./core"),e("./sha1"),e("./hmac")):a(n.CryptoJS)},{"./core":465,"./hmac":469,"./sha1":471}],469:[function(e,t,r){var n,a;n=this,a=function(e){var t,i;t=e.lib.Base,i=e.enc.Utf8,e.algo.HMAC=t.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=i.parse(t));var r=e.blockSize,n=4*r;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var e=this._oKey=t.clone(),t=this._iKey=t.clone(),a=e.words,s=t.words,o=0;o<r;o++)a[o]^=1549556828,s[o]^=909522486;e.sigBytes=t.sigBytes=n,this.reset()},reset:function(){var e=this._hasher;e.reset(),e.update(this._iKey)},update:function(e){return this._hasher.update(e),this},finalize:function(e){var t=this._hasher,e=t.finalize(e);return t.reset(),t.finalize(this._oKey.clone().concat(e))}})},"object"==typeof r?t.exports=r=a(e("./core")):a(n.CryptoJS)},{"./core":465}],470:[function(e,t,r){var n,a;n=this,a=function(a){return function(l){var e=a,t=e.lib,r=t.WordArray,n=t.Hasher,t=e.algo,S=[];!function(){for(var e=0;e<64;e++)S[e]=4294967296*l.abs(l.sin(e+1))|0}();t=t.MD5=n.extend({_doReset:function(){this._hash=new r.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,t){for(var r=0;r<16;r++){var n=t+r,a=e[n];e[n]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8)}var s=this._hash.words,o=e[t+0],i=e[t+1],l=e[t+2],u=e[t+3],c=e[t+4],f=e[t+5],d=e[t+6],p=e[t+7],b=e[t+8],h=e[t+9],y=e[t+10],m=e[t+11],v=e[t+12],j=e[t+13],g=e[t+14],_=e[t+15],w=E(w=s[0],C=s[1],k=s[2],x=s[3],o,7,S[0]),x=E(x,w,C,k,i,12,S[1]),k=E(k,x,w,C,l,17,S[2]),C=E(C,k,x,w,u,22,S[3]);w=E(w,C,k,x,c,7,S[4]),x=E(x,w,C,k,f,12,S[5]),k=E(k,x,w,C,d,17,S[6]),C=E(C,k,x,w,p,22,S[7]),w=E(w,C,k,x,b,7,S[8]),x=E(x,w,C,k,h,12,S[9]),k=E(k,x,w,C,y,17,S[10]),C=E(C,k,x,w,m,22,S[11]),w=E(w,C,k,x,v,7,S[12]),x=E(x,w,C,k,j,12,S[13]),k=E(k,x,w,C,g,17,S[14]),w=O(w,C=E(C,k,x,w,_,22,S[15]),k,x,i,5,S[16]),x=O(x,w,C,k,d,9,S[17]),k=O(k,x,w,C,m,14,S[18]),C=O(C,k,x,w,o,20,S[19]),w=O(w,C,k,x,f,5,S[20]),x=O(x,w,C,k,y,9,S[21]),k=O(k,x,w,C,_,14,S[22]),C=O(C,k,x,w,c,20,S[23]),w=O(w,C,k,x,h,5,S[24]),x=O(x,w,C,k,g,9,S[25]),k=O(k,x,w,C,u,14,S[26]),C=O(C,k,x,w,b,20,S[27]),w=O(w,C,k,x,j,5,S[28]),x=O(x,w,C,k,l,9,S[29]),k=O(k,x,w,C,p,14,S[30]),w=P(w,C=O(C,k,x,w,v,20,S[31]),k,x,f,4,S[32]),x=P(x,w,C,k,b,11,S[33]),k=P(k,x,w,C,m,16,S[34]),C=P(C,k,x,w,g,23,S[35]),w=P(w,C,k,x,i,4,S[36]),x=P(x,w,C,k,c,11,S[37]),k=P(k,x,w,C,p,16,S[38]),C=P(C,k,x,w,y,23,S[39]),w=P(w,C,k,x,j,4,S[40]),x=P(x,w,C,k,o,11,S[41]),k=P(k,x,w,C,u,16,S[42]),C=P(C,k,x,w,d,23,S[43]),w=P(w,C,k,x,h,4,S[44]),x=P(x,w,C,k,v,11,S[45]),k=P(k,x,w,C,_,16,S[46]),w=A(w,C=P(C,k,x,w,l,23,S[47]),k,x,o,6,S[48]),x=A(x,w,C,k,p,10,S[49]),k=A(k,x,w,C,g,15,S[50]),C=A(C,k,x,w,f,21,S[51]),w=A(w,C,k,x,v,6,S[52]),x=A(x,w,C,k,u,10,S[53]),k=A(k,x,w,C,y,15,S[54]),C=A(C,k,x,w,i,21,S[55]),w=A(w,C,k,x,b,6,S[56]),x=A(x,w,C,k,_,10,S[57]),k=A(k,x,w,C,d,15,S[58]),C=A(C,k,x,w,j,21,S[59]),w=A(w,C,k,x,c,6,S[60]),x=A(x,w,C,k,m,10,S[61]),k=A(k,x,w,C,l,15,S[62]),C=A(C,k,x,w,h,21,S[63]),s[0]=s[0]+w|0,s[1]=s[1]+C|0,s[2]=s[2]+k|0,s[3]=s[3]+x|0},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;t[n>>>5]|=128<<24-n%32;var a=l.floor(r/4294967296),r=r;t[15+(64+n>>>9<<4)]=16711935&(a<<8|a>>>24)|4278255360&(a<<24|a>>>8),t[14+(64+n>>>9<<4)]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8),e.sigBytes=4*(t.length+1),this._process();for(var t=this._hash,s=t.words,o=0;o<4;o++){var i=s[o];s[o]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}return t},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});function E(e,t,r,n,a,s,o){o=e+(t&r|~t&n)+a+o;return(o<<s|o>>>32-s)+t}function O(e,t,r,n,a,s,o){o=e+(t&n|r&~n)+a+o;return(o<<s|o>>>32-s)+t}function P(e,t,r,n,a,s,o){o=e+(t^r^n)+a+o;return(o<<s|o>>>32-s)+t}function A(e,t,r,n,a,s,o){o=e+(r^(t|~n))+a+o;return(o<<s|o>>>32-s)+t}e.MD5=n._createHelper(t),e.HmacMD5=n._createHmacHelper(t)}(Math),a.MD5},"object"==typeof r?t.exports=r=a(e("./core")):a(n.CryptoJS)},{"./core":465}],471:[function(e,t,r){var n,a;n=this,a=function(e){var t,r,n,a,c;return r=(t=e).lib,n=r.WordArray,a=r.Hasher,r=t.algo,c=[],r=r.SHA1=a.extend({_doReset:function(){this._hash=new n.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,t){for(var r=this._hash.words,n=r[0],a=r[1],s=r[2],o=r[3],i=r[4],l=0;l<80;l++){l<16?c[l]=0|e[t+l]:(u=c[l-3]^c[l-8]^c[l-14]^c[l-16],c[l]=u<<1|u>>>31);var u=(n<<5|n>>>27)+i+c[l];u+=l<20?1518500249+(a&s|~a&o):l<40?1859775393+(a^s^o):l<60?(a&s|a&o|s&o)-1894007588:(a^s^o)-899497514,i=o,o=s,s=a<<30|a>>>2,a=n,n=u}r[0]=r[0]+n|0,r[1]=r[1]+a|0,r[2]=r[2]+s|0,r[3]=r[3]+o|0,r[4]=r[4]+i|0},_doFinalize:function(){var e=this._data,t=e.words,r=8*this._nDataBytes,n=8*e.sigBytes;return t[n>>>5]|=128<<24-n%32,t[14+(64+n>>>9<<4)]=Math.floor(r/4294967296),t[15+(64+n>>>9<<4)]=r,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=a.clone.call(this);return e._hash=this._hash.clone(),e}}),t.SHA1=a._createHelper(r),t.HmacSHA1=a._createHmacHelper(r),e.SHA1},"object"==typeof r?t.exports=r=a(e("./core")):a(n.CryptoJS)},{"./core":465}],472:[function(e,t,r){var i=Object.create||function(e){function t(){}return t.prototype=e,new t},o=Object.keys||function(e){var t,r=[];for(t in e)Object.prototype.hasOwnProperty.call(e,t)&&r.push(t);return t},n=Function.prototype.bind||function(e){var t=this;return function(){return t.apply(e,arguments)}};function a(){this._events&&Object.prototype.hasOwnProperty.call(this,"_events")||(this._events=i(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0}((t.exports=a).EventEmitter=a).prototype._events=void 0,a.prototype._maxListeners=void 0;var s,l=10;try{var u={};Object.defineProperty&&Object.defineProperty(u,"x",{value:0}),s=0===u.x}catch(e){s=!1}function c(e){return void 0===e._maxListeners?a.defaultMaxListeners:e._maxListeners}function f(e,t,r,n){var a,s;if("function"!=typeof r)throw new TypeError('"listener" argument must be a function');return(a=e._events)?(a.newListener&&(e.emit("newListener",t,r.listener?r.listener:r),a=e._events),s=a[t]):(a=e._events=i(null),e._eventsCount=0),s?("function"==typeof s?s=a[t]=n?[r,s]:[s,r]:n?s.unshift(r):s.push(r),s.warned||(n=c(e))&&0<n&&s.length>n&&(s.warned=!0,(n=new Error("Possible EventEmitter memory leak detected. "+s.length+' "'+String(t)+'" listeners added. Use emitter.setMaxListeners() to increase limit.')).name="MaxListenersExceededWarning",n.emitter=e,n.type=t,n.count=s.length,"object"==typeof console&&console.warn&&console.warn("%s: %s",n.name,n.message))):(s=a[t]=r,++e._eventsCount),e}function d(){if(!this.fired)switch(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length){case 0:return this.listener.call(this.target);case 1:return this.listener.call(this.target,arguments[0]);case 2:return this.listener.call(this.target,arguments[0],arguments[1]);case 3:return this.listener.call(this.target,arguments[0],arguments[1],arguments[2]);default:for(var e=new Array(arguments.length),t=0;t<e.length;++t)e[t]=arguments[t];this.listener.apply(this.target,e)}}function p(e,t,r){e={fired:!1,wrapFn:void 0,target:e,type:t,listener:r},t=n.call(d,e);return t.listener=r,e.wrapFn=t}function b(e,t,r){e=e._events;if(!e)return[];t=e[t];return t?"function"==typeof t?r?[t.listener||t]:[t]:r?function(e){for(var t=new Array(e.length),r=0;r<t.length;++r)t[r]=e[r].listener||e[r];return t}(t):y(t,t.length):[]}function h(e){var t=this._events;if(t){e=t[e];if("function"==typeof e)return 1;if(e)return e.length}return 0}function y(e,t){for(var r=new Array(t),n=0;n<t;++n)r[n]=e[n];return r}s?Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return l},set:function(e){if("number"!=typeof e||e<0||e!=e)throw new TypeError('"defaultMaxListeners" must be a positive number');l=e}}):a.defaultMaxListeners=l,a.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw new TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},a.prototype.getMaxListeners=function(){return c(this)},a.prototype.emit=function(e,t,r,n){var a,s,o,i="error"===e,l=this._events;if(l)i=i&&null==l.error;else if(!i)return!1;if(i){if(1<arguments.length&&(a=t),a instanceof Error)throw a;var u=new Error('Unhandled "error" event. ('+a+")");throw u.context=a,u}if(!(u=l[e]))return!1;var c,l="function"==typeof u;switch(c=arguments.length){case 1:!function(e,t,r){if(t)e.call(r);else for(var n=e.length,a=y(e,n),s=0;s<n;++s)a[s].call(r)}(u,l,this);break;case 2:!function(e,t,r,n){if(t)e.call(r,n);else for(var a=e.length,s=y(e,a),o=0;o<a;++o)s[o].call(r,n)}(u,l,this,t);break;case 3:!function(e,t,r,n,a){if(t)e.call(r,n,a);else for(var s=e.length,o=y(e,s),i=0;i<s;++i)o[i].call(r,n,a)}(u,l,this,t,r);break;case 4:!function(e,t,r,n,a,s){if(t)e.call(r,n,a,s);else for(var o=e.length,i=y(e,o),l=0;l<o;++l)i[l].call(r,n,a,s)}(u,l,this,t,r,n);break;default:for(s=new Array(c-1),o=1;o<c;o++)s[o-1]=arguments[o];!function(e,t,r,n){if(t)e.apply(r,n);else for(var a=e.length,s=y(e,a),o=0;o<a;++o)s[o].apply(r,n)}(u,l,this,s)}return!0},a.prototype.on=a.prototype.addListener=function(e,t){return f(this,e,t,!1)},a.prototype.prependListener=function(e,t){return f(this,e,t,!0)},a.prototype.once=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.on(e,p(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');return this.prependListener(e,p(this,e,t)),this},a.prototype.removeListener=function(e,t){var r,n,a,s,o;if("function"!=typeof t)throw new TypeError('"listener" argument must be a function');if(!(n=this._events))return this;if(!(r=n[e]))return this;if(r===t||r.listener===t)0==--this._eventsCount?this._events=i(null):(delete n[e],n.removeListener&&this.emit("removeListener",e,r.listener||t));else if("function"!=typeof r){for(a=-1,s=r.length-1;0<=s;s--)if(r[s]===t||r[s].listener===t){o=r[s].listener,a=s;break}if(a<0)return this;0===a?r.shift():function(e,t){for(var r=t,n=r+1,a=e.length;n<a;r+=1,n+=1)e[r]=e[n];e.pop()}(r,a),1===r.length&&(n[e]=r[0]),n.removeListener&&this.emit("removeListener",e,o||t)}return this},a.prototype.removeAllListeners=function(e){var t,r=this._events;if(!r)return this;if(!r.removeListener)return 0===arguments.length?(this._events=i(null),this._eventsCount=0):r[e]&&(0==--this._eventsCount?this._events=i(null):delete r[e]),this;if(0===arguments.length){for(var n,a=o(r),s=0;s<a.length;++s)"removeListener"!==(n=a[s])&&this.removeAllListeners(n);return this.removeAllListeners("removeListener"),this._events=i(null),this._eventsCount=0,this}if("function"==typeof(t=r[e]))this.removeListener(e,t);else if(t)for(s=t.length-1;0<=s;s--)this.removeListener(e,t[s]);return this},a.prototype.listeners=function(e){return b(this,e,!0)},a.prototype.rawListeners=function(e){return b(this,e,!1)},a.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):h.call(e,t)},a.prototype.listenerCount=h,a.prototype.eventNames=function(){return 0<this._eventsCount?Reflect.ownKeys(this._events):[]}},{}],473:[function(e,t,r){var n=function(o){"use strict";var l,e=Object.prototype,u=e.hasOwnProperty,t="function"==typeof Symbol?Symbol:{},n=t.iterator||"@@iterator",r=t.asyncIterator||"@@asyncIterator",a=t.toStringTag||"@@toStringTag";function i(e,t,r,n){var a,s,o,i,t=t&&t.prototype instanceof y?t:y,t=Object.create(t.prototype),n=new k(n||[]);return t._invoke=(a=e,s=r,o=n,i=f,function(e,t){if(i===p)throw new Error("Generator is already running");if(i===b){if("throw"===e)throw t;return S()}for(o.method=e,o.arg=t;;){var r=o.delegate;if(r){var n=function e(t,r){var n=t.iterator[r.method];if(n===l){if(r.delegate=null,"throw"===r.method){if(t.iterator.return&&(r.method="return",r.arg=l,e(t,r),"throw"===r.method))return h;r.method="throw",r.arg=new TypeError("The iterator does not provide a 'throw' method")}return h}n=c(n,t.iterator,r.arg);if("throw"===n.type)return r.method="throw",r.arg=n.arg,r.delegate=null,h;var n=n.arg;if(!n)return r.method="throw",r.arg=new TypeError("iterator result is not an object"),r.delegate=null,h;{if(!n.done)return n;r[t.resultName]=n.value,r.next=t.nextLoc,"return"!==r.method&&(r.method="next",r.arg=l)}r.delegate=null;return h}(r,o);if(n){if(n===h)continue;return n}}if("next"===o.method)o.sent=o._sent=o.arg;else if("throw"===o.method){if(i===f)throw i=b,o.arg;o.dispatchException(o.arg)}else"return"===o.method&&o.abrupt("return",o.arg);i=p;n=c(a,s,o);if("normal"===n.type){if(i=o.done?b:d,n.arg!==h)return{value:n.arg,done:o.done}}else"throw"===n.type&&(i=b,o.method="throw",o.arg=n.arg)}}),t}function c(e,t,r){try{return{type:"normal",arg:e.call(t,r)}}catch(e){return{type:"throw",arg:e}}}o.wrap=i;var f="suspendedStart",d="suspendedYield",p="executing",b="completed",h={};function y(){}function s(){}function m(){}var v={};v[n]=function(){return this};t=Object.getPrototypeOf,t=t&&t(t(C([])));t&&t!==e&&u.call(t,n)&&(v=t);var j=m.prototype=y.prototype=Object.create(v);function g(e){["next","throw","return"].forEach(function(t){e[t]=function(e){return this._invoke(t,e)}})}function _(o,i){var t;this._invoke=function(r,n){function e(){return new i(function(e,t){!function t(e,r,n,a){e=c(o[e],o,r);if("throw"!==e.type){var s=e.arg,r=s.value;return r&&"object"==typeof r&&u.call(r,"__await")?i.resolve(r.__await).then(function(e){t("next",e,n,a)},function(e){t("throw",e,n,a)}):i.resolve(r).then(function(e){s.value=e,n(s)},function(e){return t("throw",e,n,a)})}a(e.arg)}(r,n,e,t)})}return t=t?t.then(e,e):e()}}function w(e){var t={tryLoc:e[0]};1 in e&&(t.catchLoc=e[1]),2 in e&&(t.finallyLoc=e[2],t.afterLoc=e[3]),this.tryEntries.push(t)}function x(e){var t=e.completion||{};t.type="normal",delete t.arg,e.completion=t}function k(e){this.tryEntries=[{tryLoc:"root"}],e.forEach(w,this),this.reset(!0)}function C(t){if(t){var e=t[n];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var r=-1,e=function e(){for(;++r<t.length;)if(u.call(t,r))return e.value=t[r],e.done=!1,e;return e.value=l,e.done=!0,e};return e.next=e}}return{next:S}}function S(){return{value:l,done:!0}}return(s.prototype=j.constructor=m).constructor=s,m[a]=s.displayName="GeneratorFunction",o.isGeneratorFunction=function(e){e="function"==typeof e&&e.constructor;return!!e&&(e===s||"GeneratorFunction"===(e.displayName||e.name))},o.mark=function(e){return Object.setPrototypeOf?Object.setPrototypeOf(e,m):(e.__proto__=m,a in e||(e[a]="GeneratorFunction")),e.prototype=Object.create(j),e},o.awrap=function(e){return{__await:e}},g(_.prototype),_.prototype[r]=function(){return this},o.AsyncIterator=_,o.async=function(e,t,r,n,a){void 0===a&&(a=Promise);var s=new _(i(e,t,r,n),a);return o.isGeneratorFunction(t)?s:s.next().then(function(e){return e.done?e.value:s.next()})},g(j),j[a]="Generator",j[n]=function(){return this},j.toString=function(){return"[object Generator]"},o.keys=function(r){var e,n=[];for(e in r)n.push(e);return n.reverse(),function e(){for(;n.length;){var t=n.pop();if(t in r)return e.value=t,e.done=!1,e}return e.done=!0,e}},o.values=C,k.prototype={constructor:k,reset:function(e){if(this.prev=0,this.next=0,this.sent=this._sent=l,this.done=!1,this.delegate=null,this.method="next",this.arg=l,this.tryEntries.forEach(x),!e)for(var t in this)"t"===t.charAt(0)&&u.call(this,t)&&!isNaN(+t.slice(1))&&(this[t]=l)},stop:function(){this.done=!0;var e=this.tryEntries[0].completion;if("throw"===e.type)throw e.arg;return this.rval},dispatchException:function(r){if(this.done)throw r;var n=this;function e(e,t){return s.type="throw",s.arg=r,n.next=e,t&&(n.method="next",n.arg=l),!!t}for(var t=this.tryEntries.length-1;0<=t;--t){var a=this.tryEntries[t],s=a.completion;if("root"===a.tryLoc)return e("end");if(a.tryLoc<=this.prev){var o=u.call(a,"catchLoc"),i=u.call(a,"finallyLoc");if(o&&i){if(this.prev<a.catchLoc)return e(a.catchLoc,!0);if(this.prev<a.finallyLoc)return e(a.finallyLoc)}else if(o){if(this.prev<a.catchLoc)return e(a.catchLoc,!0)}else{if(!i)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return e(a.finallyLoc)}}}},abrupt:function(e,t){for(var r=this.tryEntries.length-1;0<=r;--r){var n=this.tryEntries[r];if(n.tryLoc<=this.prev&&u.call(n,"finallyLoc")&&this.prev<n.finallyLoc){var a=n;break}}a&&("break"===e||"continue"===e)&&a.tryLoc<=t&&t<=a.finallyLoc&&(a=null);var s=a?a.completion:{};return s.type=e,s.arg=t,a?(this.method="next",this.next=a.finallyLoc,h):this.complete(s)},complete:function(e,t){if("throw"===e.type)throw e.arg;return"break"===e.type||"continue"===e.type?this.next=e.arg:"return"===e.type?(this.rval=this.arg=e.arg,this.method="return",this.next="end"):"normal"===e.type&&t&&(this.next=t),h},finish:function(e){for(var t=this.tryEntries.length-1;0<=t;--t){var r=this.tryEntries[t];if(r.finallyLoc===e)return this.complete(r.completion,r.afterLoc),x(r),h}},catch:function(e){for(var t=this.tryEntries.length-1;0<=t;--t){var r=this.tryEntries[t];if(r.tryLoc===e){var n,a=r.completion;return"throw"===a.type&&(n=a.arg,x(r)),n}}throw new Error("illegal catch attempt")},delegateYield:function(e,t,r){return this.delegate={iterator:C(e),resultName:t,nextLoc:r},"next"===this.method&&(this.arg=l),h}},o}("object"==typeof t?t.exports:{});try{regeneratorRuntime=n}catch(e){Function("r","regeneratorRuntime = r")(n)}},{}],474:[function(e,t,r){for(var n=[],a=0;a<256;++a)n[a]=(a+256).toString(16).substr(1);t.exports=function(e,t){return t=t||0,[n[e[t++]],n[e[t++]],n[e[t++]],n[e[t++]],"-",n[e[t++]],n[e[t++]],"-",n[e[t++]],n[e[t++]],"-",n[e[t++]],n[e[t++]],"-",n[e[t++]],n[e[t++]],n[e[t++]],n[e[t++]],n[e[t++]],n[e[t++]]].join("")}},{}],475:[function(e,t,r){var n,a,s="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);s?(n=new Uint8Array(16),t.exports=function(){return s(n),n}):(a=new Array(16),t.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),a[t]=e>>>((3&t)<<3)&255;return a})},{}],476:[function(e,t,r){var o=e("./lib/rng"),i=e("./lib/bytesToUuid");t.exports=function(e,t,r){var n=t&&r||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var a=(e=e||{}).random||(e.rng||o)();if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,t)for(var s=0;s<16;++s)t[n+s]=a[s];return t||i(a)}},{"./lib/bytesToUuid":474,"./lib/rng":475}]},{},[16])(16)});
components/tooltip/Tooltip.js
showings/react-toolbox
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { themr } from 'react-css-themr'; import Portal from '../hoc/Portal'; import { getViewport } from '../utils/utils'; import { TOOLTIP } from '../identifiers'; import events from '../utils/events'; const POSITION = { BOTTOM: 'bottom', HORIZONTAL: 'horizontal', LEFT: 'left', RIGHT: 'right', TOP: 'top', VERTICAL: 'vertical', }; const defaults = { className: '', delay: 0, hideOnClick: true, passthrough: true, showOnClick: false, position: POSITION.VERTICAL, theme: {}, }; const tooltipFactory = (options = {}) => { const { className: defaultClassName, delay: defaultDelay, hideOnClick: defaultHideOnClick, showOnClick: defaultShowOnClick, passthrough: defaultPassthrough, position: defaultPosition, theme: defaultTheme, } = { ...defaults, ...options }; return (ComposedComponent) => { class TooltippedComponent extends Component { static propTypes = { children: PropTypes.node, className: PropTypes.string, onClick: PropTypes.func, onMouseEnter: PropTypes.func, onMouseLeave: PropTypes.func, theme: PropTypes.shape({ tooltip: PropTypes.string, tooltipActive: PropTypes.string, tooltipWrapper: PropTypes.string, }), tooltip: PropTypes.oneOfType([ PropTypes.string, PropTypes.node, ]), tooltipDelay: PropTypes.number, tooltipHideOnClick: PropTypes.bool, tooltipPosition: PropTypes.oneOf(Object.keys(POSITION).map(key => POSITION[key])), tooltipShowOnClick: PropTypes.bool, }; static defaultProps = { className: defaultClassName, tooltipDelay: defaultDelay, tooltipHideOnClick: defaultHideOnClick, tooltipPosition: defaultPosition, tooltipShowOnClick: defaultShowOnClick, }; state = { active: false, position: this.props.tooltipPosition, visible: false, }; componentWillUnmount() { if (this.tooltipNode) { events.removeEventListenerOnTransitionEnded(this.tooltipNode, this.onTransformEnd); } if (this.timeout) clearTimeout(this.timeout); } onTransformEnd = (e) => { if (e.propertyName === 'transform') { events.removeEventListenerOnTransitionEnded(this.tooltipNode, this.onTransformEnd); this.setState({ visible: false }); } }; getPosition(element) { const { tooltipPosition } = this.props; if (tooltipPosition === POSITION.HORIZONTAL) { const origin = element.getBoundingClientRect(); const { width: ww } = getViewport(); const toRight = origin.left < ((ww / 2) - (origin.width / 2)); return toRight ? POSITION.RIGHT : POSITION.LEFT; } else if (tooltipPosition === POSITION.VERTICAL) { const origin = element.getBoundingClientRect(); const { height: wh } = getViewport(); const toBottom = origin.top < ((wh / 2) - (origin.height / 2)); return toBottom ? POSITION.BOTTOM : POSITION.TOP; } return tooltipPosition; } activate({ top, left, position }) { if (this.timeout) clearTimeout(this.timeout); this.setState({ visible: true, position }); this.timeout = setTimeout(() => { this.setState({ active: true, top, left }); }, this.props.tooltipDelay); } deactivate() { if (this.timeout) clearTimeout(this.timeout); if (this.state.active) { events.addEventListenerOnTransitionEnded(this.tooltipNode, this.onTransformEnd); this.setState({ active: false }); } else if (this.state.visible) { this.setState({ visible: false }); } } calculatePosition(element) { const position = this.getPosition(element); const { top, left, height, width } = element.getBoundingClientRect(); const xOffset = window.scrollX || window.pageXOffset; const yOffset = window.scrollY || window.pageYOffset; if (position === POSITION.BOTTOM) { return { top: top + height + yOffset, left: left + (width / 2) + xOffset, position, }; } else if (position === POSITION.TOP) { return { top: top + yOffset, left: left + (width / 2) + xOffset, position, }; } else if (position === POSITION.LEFT) { return { top: top + (height / 2) + yOffset, left: left + xOffset, position, }; } else if (position === POSITION.RIGHT) { return { top: top + (height / 2) + yOffset, left: left + width + xOffset, position, }; } return undefined; } handleMouseEnter = (event) => { this.activate(this.calculatePosition(event.currentTarget)); if (this.props.onMouseEnter) this.props.onMouseEnter(event); }; handleMouseLeave = (event) => { this.deactivate(); if (this.props.onMouseLeave) this.props.onMouseLeave(event); }; handleClick = (event) => { if (this.props.tooltipHideOnClick && this.state.active) { this.deactivate(); } if (this.props.tooltipShowOnClick && !this.state.active) { this.activate(this.calculatePosition(event.currentTarget)); } if (this.props.onClick) this.props.onClick(event); }; render() { const { active, left, top, position, visible } = this.state; const positionClass = `tooltip${position.charAt(0).toUpperCase() + position.slice(1)}`; const { children, className, theme, onClick, // eslint-disable-line no-unused-vars onMouseEnter, // eslint-disable-line no-unused-vars onMouseLeave, // eslint-disable-line no-unused-vars tooltip, tooltipDelay, // eslint-disable-line no-unused-vars tooltipHideOnClick, // eslint-disable-line no-unused-vars tooltipPosition, // eslint-disable-line no-unused-vars tooltipShowOnClick, // eslint-disable-line no-unused-vars ...other } = this.props; const _className = classnames(theme.tooltip, { [theme.tooltipActive]: active, [theme[positionClass]]: theme[positionClass], }); const childProps = { ...other, className, onClick: this.handleClick, onMouseEnter: this.handleMouseEnter, onMouseLeave: this.handleMouseLeave, }; const shouldPass = typeof ComposedComponent !== 'string' && defaultPassthrough; const finalProps = shouldPass ? { ...childProps, theme } : childProps; return React.createElement(ComposedComponent, finalProps, children, visible && ( <Portal> <span ref={(node) => { this.tooltipNode = node; }} className={_className} data-react-toolbox="tooltip" style={{ top, left }} > <span className={theme.tooltipInner}>{tooltip}</span> </span> </Portal> ), ); } } return themr(TOOLTIP, defaultTheme)(TooltippedComponent); }; }; export default tooltipFactory;
js/components/class/index.js
mrcflorian/classbook
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { Container, Header, Title, Content, Button, Icon, Left, Right, Body, Text, ListItem, List } from 'native-base'; import { Actions } from 'react-native-router-flux'; import { actions } from 'react-native-navigation-redux-helpers'; import { openDrawer, closeDrawer } from '../../actions/drawer'; import styles from './styles'; const { pushRoute, } = actions; const datas = [ { route: 'student', text: 'Anghel Radu', }, { route: 'student', text: 'Eremia Alexandru', }, { route: 'student', text: 'Farcas Marian', }, { route: 'student', text: 'Gheorghe Andrei', }, { route: 'student', text: 'Marcu Florian', }, { route: 'student', text: 'Oprea Alexandra', }, { route: 'student', text: 'Popescu Vasile', }, { route: 'student', text: 'Sirghie Roxana', }, ]; class ClassList extends Component { // eslint-disable-line static propTypes = { openDrawer: React.PropTypes.func, pushRoute: React.PropTypes.func, navigation: React.PropTypes.shape({ key: React.PropTypes.string, }), } pushRoute(route) { this.props.pushRoute({ key: route, index: 1 }, this.props.navigation.key); } render() { return ( <Container style={styles.container}> <Header> <Left> <Button transparent onPress={this.props.openDrawer}> <Icon name="menu" /> </Button> </Left> <Body> <Title>Clasa 12A</Title> </Body> <Right /> </Header> <Content> <List dataArray={datas} renderRow={data => <ListItem button onPress={() => { Actions[data.route](); this.props.closeDrawer() }} > <Text>{data.text}</Text> <Right> <Icon name="arrow-forward" style={{ color: '#999' }} /> </Right> </ListItem> } /> </Content> </Container> ); } } function bindAction(dispatch) { return { openDrawer: () => dispatch(openDrawer()), closeDrawer: () => dispatch(closeDrawer()), pushRoute: (route, key) => dispatch(pushRoute(route, key)), }; } const mapStateToProps = state => ({ navigation: state.cardNavigation, themeState: state.drawer.themeState, }); export default connect(mapStateToProps, bindAction)(ClassList);
ajax/libs/radium/0.18.0/radium.js
jdh8/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react")); else if(typeof define === 'function' && define.amd) define(["react"], factory); else if(typeof exports === 'object') exports["Radium"] = factory(require("react")); else root["Radium"] = factory(root["React"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_3__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _enhancer = __webpack_require__(2); var _enhancer2 = _interopRequireDefault(_enhancer); var _plugins = __webpack_require__(48); var _plugins2 = _interopRequireDefault(_plugins); var _style = __webpack_require__(60); var _style2 = _interopRequireDefault(_style); var _styleRoot = __webpack_require__(61); var _styleRoot2 = _interopRequireDefault(_styleRoot); var _getState = __webpack_require__(44); var _getState2 = _interopRequireDefault(_getState); var _keyframes = __webpack_require__(63); var _keyframes2 = _interopRequireDefault(_keyframes); var _resolveStyles = __webpack_require__(5); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function Radium(ComposedComponent) { return (0, _enhancer2.default)(ComposedComponent); } Radium.Plugins = _plugins2.default; Radium.Style = _style2.default; Radium.StyleRoot = _styleRoot2.default; Radium.getState = _getState2.default; Radium.keyframes = _keyframes2.default; if (process.env.NODE_ENV !== 'production') { Radium.TestMode = { clearState: _resolveStyles.__clearStateForTests, disable: _resolveStyles.__setTestMode.bind(null, false), enable: _resolveStyles.__setTestMode.bind(null, true) }; } exports.default = Radium; module.exports = exports['default']; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1))) /***/ }, /* 1 */ /***/ function(module, exports) { 'use strict'; // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; (function () { try { cachedSetTimeout = setTimeout; } catch (e) { cachedSetTimeout = function cachedSetTimeout() { throw new Error('setTimeout is not defined'); }; } try { cachedClearTimeout = clearTimeout; } catch (e) { cachedClearTimeout = function cachedClearTimeout() { throw new Error('clearTimeout is not defined'); }; } })(); 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 = cachedSetTimeout(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; cachedClearTimeout(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) { cachedSetTimeout(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; }; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = enhanceWithRadium; var _react = __webpack_require__(3); var _styleKeeper = __webpack_require__(4); var _styleKeeper2 = _interopRequireDefault(_styleKeeper); var _resolveStyles = __webpack_require__(5); var _resolveStyles2 = _interopRequireDefault(_resolveStyles); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var KEYS_TO_IGNORE_WHEN_COPYING_PROPERTIES = ['arguments', 'callee', 'caller', 'length', 'name', 'prototype', 'type']; function copyProperties(source, target) { Object.getOwnPropertyNames(source).forEach(function (key) { if (KEYS_TO_IGNORE_WHEN_COPYING_PROPERTIES.indexOf(key) < 0 && !target.hasOwnProperty(key)) { var descriptor = Object.getOwnPropertyDescriptor(source, key); Object.defineProperty(target, key, descriptor); } }); } function isStateless(component) { return !component.render && !(component.prototype && component.prototype.render); } function enhanceWithRadium(configOrComposedComponent) { var _class, _temp; var config = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; if (typeof configOrComposedComponent !== 'function') { var _ret = function () { var newConfig = _extends({}, config, configOrComposedComponent); return { v: function v(configOrComponent) { return enhanceWithRadium(configOrComponent, newConfig); } }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v; } var component = configOrComposedComponent; var ComposedComponent = component; // Handle stateless components if (isStateless(ComposedComponent)) { ComposedComponent = function (_Component) { _inherits(ComposedComponent, _Component); function ComposedComponent() { _classCallCheck(this, ComposedComponent); return _possibleConstructorReturn(this, _Component.apply(this, arguments)); } ComposedComponent.prototype.render = function render() { return component(this.props, this.context); }; return ComposedComponent; }(_react.Component); ComposedComponent.displayName = component.displayName || component.name; } var RadiumEnhancer = (_temp = _class = function (_ComposedComponent) { _inherits(RadiumEnhancer, _ComposedComponent); function RadiumEnhancer() { _classCallCheck(this, RadiumEnhancer); var _this2 = _possibleConstructorReturn(this, _ComposedComponent.apply(this, arguments)); _this2.state = _this2.state || {}; _this2.state._radiumStyleState = {}; _this2._radiumIsMounted = true; return _this2; } RadiumEnhancer.prototype.componentWillUnmount = function componentWillUnmount() { if (_ComposedComponent.prototype.componentWillUnmount) { _ComposedComponent.prototype.componentWillUnmount.call(this); } this._radiumIsMounted = false; if (this._radiumMouseUpListener) { this._radiumMouseUpListener.remove(); } if (this._radiumMediaQueryListenersByQuery) { Object.keys(this._radiumMediaQueryListenersByQuery).forEach(function (query) { this._radiumMediaQueryListenersByQuery[query].remove(); }, this); } }; RadiumEnhancer.prototype.getChildContext = function getChildContext() { var superChildContext = _ComposedComponent.prototype.getChildContext ? _ComposedComponent.prototype.getChildContext.call(this) : {}; if (!this.props.radiumConfig) { return superChildContext; } var newContext = _extends({}, superChildContext); if (this.props.radiumConfig) { newContext._radiumConfig = this.props.radiumConfig; } return newContext; }; RadiumEnhancer.prototype.render = function render() { var renderedElement = _ComposedComponent.prototype.render.call(this); var currentConfig = this.props.radiumConfig || this.context._radiumConfig || config; if (config && currentConfig !== config) { currentConfig = _extends({}, config, currentConfig); } return (0, _resolveStyles2.default)(this, renderedElement, currentConfig); }; return RadiumEnhancer; }(ComposedComponent), _class._isRadiumEnhanced = true, _temp); // Class inheritance uses Object.create and because of __proto__ issues // with IE <10 any static properties of the superclass aren't inherited and // so need to be manually populated. // See http://babeljs.io/docs/advanced/caveats/#classes-10-and-below- copyProperties(component, RadiumEnhancer); if (process.env.NODE_ENV !== 'production') { // This also fixes React Hot Loader by exposing the original components top // level prototype methods on the Radium enhanced prototype as discussed in // https://github.com/FormidableLabs/radium/issues/219. copyProperties(ComposedComponent.prototype, RadiumEnhancer.prototype); } if (RadiumEnhancer.propTypes && RadiumEnhancer.propTypes.style) { RadiumEnhancer.propTypes = _extends({}, RadiumEnhancer.propTypes, { style: _react.PropTypes.oneOfType([_react.PropTypes.array, _react.PropTypes.object]) }); } RadiumEnhancer.displayName = component.displayName || component.name || 'Component'; RadiumEnhancer.contextTypes = _extends({}, RadiumEnhancer.contextTypes, { _radiumConfig: _react.PropTypes.object, _radiumStyleKeeper: _react.PropTypes.instanceOf(_styleKeeper2.default) }); RadiumEnhancer.childContextTypes = _extends({}, RadiumEnhancer.childContextTypes, { _radiumConfig: _react.PropTypes.object, _radiumStyleKeeper: _react.PropTypes.instanceOf(_styleKeeper2.default) }); return RadiumEnhancer; } module.exports = exports['default']; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1))) /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; /***/ }, /* 4 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var StyleKeeper = function () { function StyleKeeper(userAgent) { _classCallCheck(this, StyleKeeper); this._userAgent = userAgent; this._listeners = []; this._cssSet = {}; } StyleKeeper.prototype.subscribe = function subscribe(listener) { var _this = this; if (this._listeners.indexOf(listener) === -1) { this._listeners.push(listener); } return { // Must be fat arrow to capture `this` remove: function remove() { var listenerIndex = _this._listeners.indexOf(listener); if (listenerIndex > -1) { _this._listeners.splice(listenerIndex, 1); } } }; }; StyleKeeper.prototype.addCSS = function addCSS(css) { var _this2 = this; if (!this._cssSet[css]) { this._cssSet[css] = true; this._emitChange(); } return { // Must be fat arrow to capture `this` remove: function remove() { delete _this2._cssSet[css]; _this2._emitChange(); } }; }; StyleKeeper.prototype.getCSS = function getCSS() { return Object.keys(this._cssSet).join('\n'); }; StyleKeeper.prototype._emitChange = function _emitChange() { this._listeners.forEach(function (listener) { return listener(); }); }; return StyleKeeper; }(); exports.default = StyleKeeper; module.exports = exports['default']; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _appendImportantToEachValue = __webpack_require__(6); var _appendImportantToEachValue2 = _interopRequireDefault(_appendImportantToEachValue); var _cssRuleSetToString = __webpack_require__(9); var _cssRuleSetToString2 = _interopRequireDefault(_cssRuleSetToString); var _getState = __webpack_require__(44); var _getState2 = _interopRequireDefault(_getState); var _getStateKey = __webpack_require__(45); var _getStateKey2 = _interopRequireDefault(_getStateKey); var _hash = __webpack_require__(46); var _hash2 = _interopRequireDefault(_hash); var _mergeStyles = __webpack_require__(47); var _plugins = __webpack_require__(48); var _plugins2 = _interopRequireDefault(_plugins); var _exenv = __webpack_require__(58); var _exenv2 = _interopRequireDefault(_exenv); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var DEFAULT_CONFIG = { plugins: [_plugins2.default.mergeStyleArray, _plugins2.default.checkProps, _plugins2.default.resolveMediaQueries, _plugins2.default.resolveInteractionStyles, _plugins2.default.keyframes, _plugins2.default.visited, _plugins2.default.removeNestedStyles, _plugins2.default.prefix, _plugins2.default.checkProps] }; // Gross var globalState = {}; // Declare early for recursive helpers. var resolveStyles = null; var _shouldResolveStyles = function _shouldResolveStyles(component) { return component.type && !component.type._isRadiumEnhanced; }; var _resolveChildren = function _resolveChildren(_ref) { var children = _ref.children; var component = _ref.component; var config = _ref.config; var existingKeyMap = _ref.existingKeyMap; if (!children) { return children; } var childrenType = typeof children === 'undefined' ? 'undefined' : _typeof(children); if (childrenType === 'string' || childrenType === 'number') { // Don't do anything with a single primitive child return children; } if (childrenType === 'function') { // Wrap the function, resolving styles on the result return function () { var result = children.apply(this, arguments); if (_react2.default.isValidElement(result)) { return resolveStyles(component, result, config, existingKeyMap, true); } return result; }; } if (_react2.default.Children.count(children) === 1 && children.type) { // If a React Element is an only child, don't wrap it in an array for // React.Children.map() for React.Children.only() compatibility. var onlyChild = _react2.default.Children.only(children); return resolveStyles(component, onlyChild, config, existingKeyMap, true); } return _react2.default.Children.map(children, function (child) { if (_react2.default.isValidElement(child)) { return resolveStyles(component, child, config, existingKeyMap, true); } return child; }); }; // Recurse over props, just like children var _resolveProps = function _resolveProps(_ref2) { var component = _ref2.component; var config = _ref2.config; var existingKeyMap = _ref2.existingKeyMap; var props = _ref2.props; var newProps = props; Object.keys(props).forEach(function (prop) { // We already recurse over children above if (prop === 'children') { return; } var propValue = props[prop]; if (_react2.default.isValidElement(propValue)) { newProps = _extends({}, newProps); newProps[prop] = resolveStyles(component, propValue, config, existingKeyMap, true); } }); return newProps; }; var _buildGetKey = function _buildGetKey(_ref3) { var componentName = _ref3.componentName; var existingKeyMap = _ref3.existingKeyMap; var renderedElement = _ref3.renderedElement; // We need a unique key to correlate state changes due to user interaction // with the rendered element, so we know to apply the proper interactive // styles. var originalKey = typeof renderedElement.ref === 'string' ? renderedElement.ref : renderedElement.key; var key = (0, _getStateKey2.default)(originalKey); var alreadyGotKey = false; var getKey = function getKey() { if (alreadyGotKey) { return key; } alreadyGotKey = true; if (existingKeyMap[key]) { var elementName = void 0; if (typeof renderedElement.type === 'string') { elementName = renderedElement.type; } else if (renderedElement.type.constructor) { elementName = renderedElement.type.constructor.displayName || renderedElement.type.constructor.name; } throw new Error('Radium requires each element with interactive styles to have a unique ' + 'key, set using either the ref or key prop. ' + (originalKey ? 'Key "' + originalKey + '" is a duplicate.' : 'Multiple elements have no key specified.') + ' ' + 'Component: "' + componentName + '". ' + (elementName ? 'Element: "' + elementName + '".' : '')); } existingKeyMap[key] = true; return key; }; return getKey; }; var _setStyleState = function _setStyleState(component, key, stateKey, value) { if (!component._radiumIsMounted) { return; } var existing = component._lastRadiumState || component.state && component.state._radiumStyleState || {}; var state = { _radiumStyleState: _extends({}, existing) }; state._radiumStyleState[key] = _extends({}, state._radiumStyleState[key]); state._radiumStyleState[key][stateKey] = value; component._lastRadiumState = state._radiumStyleState; component.setState(state); }; var _runPlugins = function _runPlugins(_ref4) { var component = _ref4.component; var config = _ref4.config; var existingKeyMap = _ref4.existingKeyMap; var props = _ref4.props; var renderedElement = _ref4.renderedElement; // Don't run plugins if renderedElement is not a simple ReactDOMElement or has // no style. if (!_react2.default.isValidElement(renderedElement) || typeof renderedElement.type !== 'string' || !props.style) { return props; } var newProps = props; var plugins = config.plugins || DEFAULT_CONFIG.plugins; var componentName = component.constructor.displayName || component.constructor.name; var getKey = _buildGetKey({ renderedElement: renderedElement, existingKeyMap: existingKeyMap, componentName: componentName }); var getComponentField = function getComponentField(key) { return component[key]; }; var getGlobalState = function getGlobalState(key) { return globalState[key]; }; var componentGetState = function componentGetState(stateKey, elementKey) { return (0, _getState2.default)(component.state, elementKey || getKey(), stateKey); }; var setState = function setState(stateKey, value, elementKey) { return _setStyleState(component, elementKey || getKey(), stateKey, value); }; var addCSS = function addCSS(css) { var styleKeeper = component._radiumStyleKeeper || component.context._radiumStyleKeeper; if (!styleKeeper) { if (__isTestModeEnabled) { return { remove: function remove() {} }; } throw new Error('To use plugins requiring `addCSS` (e.g. keyframes, media queries), ' + 'please wrap your application in the StyleRoot component. Component ' + 'name: `' + componentName + '`.'); } return styleKeeper.addCSS(css); }; var newStyle = props.style; plugins.forEach(function (plugin) { var result = plugin({ ExecutionEnvironment: _exenv2.default, addCSS: addCSS, appendImportantToEachValue: _appendImportantToEachValue2.default, componentName: componentName, config: config, cssRuleSetToString: _cssRuleSetToString2.default, getComponentField: getComponentField, getGlobalState: getGlobalState, getState: componentGetState, hash: _hash2.default, mergeStyles: _mergeStyles.mergeStyles, props: newProps, setState: setState, isNestedStyle: _mergeStyles.isNestedStyle, style: newStyle }) || {}; newStyle = result.style || newStyle; newProps = result.props && Object.keys(result.props).length ? _extends({}, newProps, result.props) : newProps; var newComponentFields = result.componentFields || {}; Object.keys(newComponentFields).forEach(function (fieldName) { component[fieldName] = newComponentFields[fieldName]; }); var newGlobalState = result.globalState || {}; Object.keys(newGlobalState).forEach(function (key) { globalState[key] = newGlobalState[key]; }); }); if (newStyle !== props.style) { newProps = _extends({}, newProps, { style: newStyle }); } return newProps; }; // Wrapper around React.cloneElement. To avoid processing the same element // twice, whenever we clone an element add a special prop to make sure we don't // process this element again. var _cloneElement = function _cloneElement(renderedElement, newProps, newChildren) { // Only add flag if this is a normal DOM element if (typeof renderedElement.type === 'string') { newProps = _extends({}, newProps, { 'data-radium': true }); } return _react2.default.cloneElement(renderedElement, newProps, newChildren); }; // // The nucleus of Radium. resolveStyles is called on the rendered elements // before they are returned in render. It iterates over the elements and // children, rewriting props to add event handlers required to capture user // interactions (e.g. mouse over). It also replaces the style prop because it // adds in the various interaction styles (e.g. :hover). // resolveStyles = function resolveStyles(component, // ReactComponent, flow+eslint complaining renderedElement) { var // ReactElement config = arguments.length <= 2 || arguments[2] === undefined ? DEFAULT_CONFIG : arguments[2]; var existingKeyMap = arguments[3]; var shouldCheckBeforeResolve = arguments.length <= 4 || arguments[4] === undefined ? false : arguments[4]; // ReactElement existingKeyMap = existingKeyMap || {}; if (!renderedElement || // Bail if we've already processed this element. This ensures that only the // owner of an element processes that element, since the owner's render // function will be called first (which will always be the case, since you // can't know what else to render until you render the parent component). renderedElement.props && renderedElement.props['data-radium'] || // Bail if this element is a radium enhanced element, because if it is, // then it will take care of resolving its own styles. shouldCheckBeforeResolve && !_shouldResolveStyles(renderedElement)) { return renderedElement; } var newChildren = _resolveChildren({ children: renderedElement.props.children, component: component, config: config, existingKeyMap: existingKeyMap }); var newProps = _resolveProps({ component: component, config: config, existingKeyMap: existingKeyMap, props: renderedElement.props }); newProps = _runPlugins({ component: component, config: config, existingKeyMap: existingKeyMap, props: newProps, renderedElement: renderedElement }); // If nothing changed, don't bother cloning the element. Might be a bit // wasteful, as we add the sentinal to stop double-processing when we clone. // Assume benign double-processing is better than unneeded cloning. if (newChildren === renderedElement.props.children && newProps === renderedElement.props) { return renderedElement; } return _cloneElement(renderedElement, newProps !== renderedElement.props ? newProps : {}, newChildren); }; // Only for use by tests var __isTestModeEnabled = false; if (process.env.NODE_ENV !== 'production') { resolveStyles.__clearStateForTests = function () { globalState = {}; }; resolveStyles.__setTestMode = function (isEnabled) { __isTestModeEnabled = isEnabled; }; } exports.default = resolveStyles; module.exports = exports['default']; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1))) /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = appendImportantToEachValue; var _appendPxIfNeeded = __webpack_require__(7); var _appendPxIfNeeded2 = _interopRequireDefault(_appendPxIfNeeded); var _mapObject = __webpack_require__(8); var _mapObject2 = _interopRequireDefault(_mapObject); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function appendImportantToEachValue(style) { return (0, _mapObject2.default)(style, function (result, key) { return (0, _appendPxIfNeeded2.default)(key, style[key]) + ' !important'; }); } module.exports = exports['default']; /***/ }, /* 7 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = appendPxIfNeeded; // Copied from https://github.com/facebook/react/blob/ // 102cd291899f9942a76c40a0e78920a6fe544dc1/ // src/renderers/dom/shared/CSSProperty.js var isUnitlessNumber = { animationIterationCount: 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, stopOpacity: true, strokeDashoffset: true, strokeOpacity: true, strokeWidth: true }; function appendPxIfNeeded(propertyName, value) { var needsPxSuffix = !isUnitlessNumber[propertyName] && typeof value === 'number' && value !== 0; return needsPxSuffix ? value + 'px' : value; } module.exports = exports['default']; /***/ }, /* 8 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = mapObject; function mapObject(object, mapper) { return Object.keys(object).reduce(function (result, key) { result[key] = mapper(object[key], key); return result; }, {}); } module.exports = exports["default"]; /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = cssRuleSetToString; var _appendPxIfNeeded = __webpack_require__(7); var _appendPxIfNeeded2 = _interopRequireDefault(_appendPxIfNeeded); var _camelCasePropsToDashCase = __webpack_require__(10); var _camelCasePropsToDashCase2 = _interopRequireDefault(_camelCasePropsToDashCase); var _mapObject = __webpack_require__(8); var _mapObject2 = _interopRequireDefault(_mapObject); var _prefixer = __webpack_require__(11); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function createMarkupForStyles(style) { return Object.keys(style).map(function (property) { return property + ': ' + style[property] + ';'; }).join('\n'); } function cssRuleSetToString(selector, rules, userAgent) { if (!rules) { return ''; } var rulesWithPx = (0, _mapObject2.default)(rules, function (value, key) { return (0, _appendPxIfNeeded2.default)(key, value); }); var prefixedRules = (0, _prefixer.getPrefixedStyle)(rulesWithPx, userAgent); var cssPrefixedRules = (0, _camelCasePropsToDashCase2.default)(prefixedRules); var serializedRules = createMarkupForStyles(cssPrefixedRules); return selector + '{' + serializedRules + '}'; } module.exports = exports['default']; /***/ }, /* 10 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _camelCaseRegex = /([a-z])?([A-Z])/g; var _camelCaseReplacer = function _camelCaseReplacer(match, p1, p2) { return (p1 || '') + '-' + p2.toLowerCase(); }; var _camelCaseToDashCase = function _camelCaseToDashCase(s) { return s.replace(_camelCaseRegex, _camelCaseReplacer); }; var camelCasePropsToDashCase = function camelCasePropsToDashCase(prefixedStyle) { // Since prefix is expected to work on inline style objects, we must // translate the keys to dash case for rendering to CSS. return Object.keys(prefixedStyle).reduce(function (result, key) { var dashCaseKey = _camelCaseToDashCase(key); // Fix IE vendor prefix if (/^ms-/.test(dashCaseKey)) { dashCaseKey = '-' + dashCaseKey; } result[dashCaseKey] = prefixedStyle[key]; return result; }, {}); }; exports.default = camelCasePropsToDashCase; module.exports = exports['default']; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global, process) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; /** * Based on https://github.com/jsstyles/css-vendor, but without having to * convert between different cases all the time. * * */ exports.getPrefixedKeyframes = getPrefixedKeyframes; exports.getPrefixedStyle = getPrefixedStyle; var _inlineStylePrefixer = __webpack_require__(12); var _inlineStylePrefixer2 = _interopRequireDefault(_inlineStylePrefixer); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function transformValues(style) { return Object.keys(style).reduce(function (newStyle, key) { var value = style[key]; if (Array.isArray(value)) { value = value.join(';' + key + ':'); } else if (value && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && typeof value.toString === 'function') { value = value.toString(); } newStyle[key] = value; return newStyle; }, {}); } var _hasWarnedAboutUserAgent = false; var _lastUserAgent = void 0; var _cachedPrefixer = void 0; function getPrefixer(userAgent) { var actualUserAgent = userAgent || global && global.navigator && global.navigator.userAgent; if (process.env.NODE_ENV !== 'production') { if (!actualUserAgent && !_hasWarnedAboutUserAgent) { /* eslint-disable no-console */ console.warn('Radium: userAgent should be supplied for server-side rendering. See ' + 'https://github.com/FormidableLabs/radium/tree/master/docs/api#radium ' + 'for more information.'); /* eslint-enable no-console */ _hasWarnedAboutUserAgent = true; } } if (!_cachedPrefixer || actualUserAgent !== _lastUserAgent) { if (actualUserAgent === 'all') { _cachedPrefixer = { prefix: _inlineStylePrefixer2.default.prefixAll, prefixedKeyframes: 'keyframes' }; } else { _cachedPrefixer = new _inlineStylePrefixer2.default({ userAgent: actualUserAgent }); } _lastUserAgent = actualUserAgent; } return _cachedPrefixer; } function getPrefixedKeyframes(userAgent) { return getPrefixer(userAgent).prefixedKeyframes; } // Returns a new style object with vendor prefixes added to property names // and values. function getPrefixedStyle(style, userAgent) { var styleWithFallbacks = transformValues(style); var prefixer = getPrefixer(userAgent); var prefixedStyle = prefixer.prefix(styleWithFallbacks); return prefixedStyle; } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()), __webpack_require__(1))) /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i];descriptor.enumerable = descriptor.enumerable || false;descriptor.configurable = true;if ('value' in descriptor) descriptor.writable = true;Object.defineProperty(target, descriptor.key, descriptor); } }return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps);if (staticProps) defineProperties(Constructor, staticProps);return Constructor; }; }(); 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'); } } var _inlineStylePrefixAll = __webpack_require__(13); var _inlineStylePrefixAll2 = _interopRequireDefault(_inlineStylePrefixAll); var _utilsGetBrowserInformation = __webpack_require__(28); var _utilsGetBrowserInformation2 = _interopRequireDefault(_utilsGetBrowserInformation); var _utilsGetPrefixedKeyframes = __webpack_require__(30); var _utilsGetPrefixedKeyframes2 = _interopRequireDefault(_utilsGetPrefixedKeyframes); var _utilsCapitalizeString = __webpack_require__(31); var _utilsCapitalizeString2 = _interopRequireDefault(_utilsCapitalizeString); var _utilsAssign = __webpack_require__(32); var _utilsAssign2 = _interopRequireDefault(_utilsAssign); var _prefixProps = __webpack_require__(33); var _prefixProps2 = _interopRequireDefault(_prefixProps); var _pluginsCalc = __webpack_require__(34); var _pluginsCalc2 = _interopRequireDefault(_pluginsCalc); var _pluginsCursor = __webpack_require__(36); var _pluginsCursor2 = _interopRequireDefault(_pluginsCursor); var _pluginsFlex = __webpack_require__(37); var _pluginsFlex2 = _interopRequireDefault(_pluginsFlex); var _pluginsSizing = __webpack_require__(38); var _pluginsSizing2 = _interopRequireDefault(_pluginsSizing); var _pluginsGradient = __webpack_require__(39); var _pluginsGradient2 = _interopRequireDefault(_pluginsGradient); var _pluginsTransition = __webpack_require__(40); var _pluginsTransition2 = _interopRequireDefault(_pluginsTransition); // special flexbox specifications var _pluginsFlexboxIE = __webpack_require__(42); var _pluginsFlexboxIE2 = _interopRequireDefault(_pluginsFlexboxIE); var _pluginsFlexboxOld = __webpack_require__(43); var _pluginsFlexboxOld2 = _interopRequireDefault(_pluginsFlexboxOld); var plugins = [_pluginsCalc2['default'], _pluginsCursor2['default'], _pluginsSizing2['default'], _pluginsGradient2['default'], _pluginsTransition2['default'], _pluginsFlexboxIE2['default'], _pluginsFlexboxOld2['default'], // this must be run AFTER the flexbox specs _pluginsFlex2['default']]; var Prefixer = function () { /** * Instantiante a new prefixer * @param {string} userAgent - userAgent to gather prefix information according to caniuse.com * @param {string} keepUnprefixed - keeps unprefixed properties and values */ function Prefixer() { var _this = this; var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; _classCallCheck(this, Prefixer); var defaultUserAgent = typeof navigator !== 'undefined' ? navigator.userAgent : undefined; this._userAgent = options.userAgent || defaultUserAgent; this._keepUnprefixed = options.keepUnprefixed || false; this._browserInfo = (0, _utilsGetBrowserInformation2['default'])(this._userAgent); // Checks if the userAgent was resolved correctly if (this._browserInfo && this._browserInfo.prefix) { // set additional prefix information this.cssPrefix = this._browserInfo.prefix.css; this.jsPrefix = this._browserInfo.prefix.inline; this.prefixedKeyframes = (0, _utilsGetPrefixedKeyframes2['default'])(this._browserInfo); } else { this._usePrefixAllFallback = true; return false; } var data = this._browserInfo.browser && _prefixProps2['default'][this._browserInfo.browser]; if (data) { this._requiresPrefix = Object.keys(data).filter(function (key) { return data[key] >= _this._browserInfo.version; }).reduce(function (result, name) { result[name] = true; return result; }, {}); this._hasPropsRequiringPrefix = Object.keys(this._requiresPrefix).length > 0; } else { this._usePrefixAllFallback = true; } } /** * Returns a prefixed version of the style object * @param {Object} styles - Style object that gets prefixed properties added * @returns {Object} - Style object with prefixed properties and values */ _createClass(Prefixer, [{ key: 'prefix', value: function prefix(styles) { var _this2 = this; // use prefixAll as fallback if userAgent can not be resolved if (this._usePrefixAllFallback) { return (0, _inlineStylePrefixAll2['default'])(styles); } // only add prefixes if needed if (!this._hasPropsRequiringPrefix) { return styles; } styles = (0, _utilsAssign2['default'])({}, styles); Object.keys(styles).forEach(function (property) { var value = styles[property]; if (value instanceof Object) { // recurse through nested style objects styles[property] = _this2.prefix(value); } else { // add prefixes if needed if (_this2._requiresPrefix[property]) { styles[_this2.jsPrefix + (0, _utilsCapitalizeString2['default'])(property)] = value; if (!_this2._keepUnprefixed) { delete styles[property]; } } // resolve plugins plugins.forEach(function (plugin) { // generates a new plugin interface with current data var resolvedStyles = plugin({ property: property, value: value, styles: styles, browserInfo: _this2._browserInfo, prefix: { js: _this2.jsPrefix, css: _this2.cssPrefix, keyframes: _this2.prefixedKeyframes }, keepUnprefixed: _this2._keepUnprefixed, requiresPrefix: _this2._requiresPrefix }); (0, _utilsAssign2['default'])(styles, resolvedStyles); }); } }); return styles; } /** * Returns a prefixed version of the style object using all vendor prefixes * @param {Object} styles - Style object that gets prefixed properties added * @returns {Object} - Style object with prefixed properties and values */ }], [{ key: 'prefixAll', value: function prefixAll(styles) { return (0, _inlineStylePrefixAll2['default'])(styles); } }]); return Prefixer; }(); exports['default'] = Prefixer; module.exports = exports['default']; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = prefixAll; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _prefixProps = __webpack_require__(14); var _prefixProps2 = _interopRequireDefault(_prefixProps); var _utilsCapitalizeString = __webpack_require__(15); var _utilsCapitalizeString2 = _interopRequireDefault(_utilsCapitalizeString); var _utilsAssign = __webpack_require__(16); var _utilsAssign2 = _interopRequireDefault(_utilsAssign); var _pluginsCalc = __webpack_require__(17); var _pluginsCalc2 = _interopRequireDefault(_pluginsCalc); var _pluginsCursor = __webpack_require__(21); var _pluginsCursor2 = _interopRequireDefault(_pluginsCursor); var _pluginsFlex = __webpack_require__(22); var _pluginsFlex2 = _interopRequireDefault(_pluginsFlex); var _pluginsSizing = __webpack_require__(23); var _pluginsSizing2 = _interopRequireDefault(_pluginsSizing); var _pluginsGradient = __webpack_require__(24); var _pluginsGradient2 = _interopRequireDefault(_pluginsGradient); var _pluginsTransition = __webpack_require__(25); var _pluginsTransition2 = _interopRequireDefault(_pluginsTransition); // special flexbox specifications var _pluginsFlexboxIE = __webpack_require__(26); var _pluginsFlexboxIE2 = _interopRequireDefault(_pluginsFlexboxIE); var _pluginsFlexboxOld = __webpack_require__(27); var _pluginsFlexboxOld2 = _interopRequireDefault(_pluginsFlexboxOld); var plugins = [_pluginsCalc2['default'], _pluginsCursor2['default'], _pluginsSizing2['default'], _pluginsGradient2['default'], _pluginsTransition2['default'], _pluginsFlexboxIE2['default'], _pluginsFlexboxOld2['default'], _pluginsFlex2['default']]; /** * Returns a prefixed version of the style object using all vendor prefixes * @param {Object} styles - Style object that gets prefixed properties added * @returns {Object} - Style object with prefixed properties and values */ function prefixAll(styles) { return Object.keys(styles).reduce(function (prefixedStyles, property) { var value = styles[property]; if (value instanceof Object && !Array.isArray(value)) { // recurse through nested style objects prefixedStyles[property] = prefixAll(value); } else { Object.keys(_prefixProps2['default']).forEach(function (prefix) { var properties = _prefixProps2['default'][prefix]; // add prefixes if needed if (properties[property]) { prefixedStyles[prefix + (0, _utilsCapitalizeString2['default'])(property)] = value; } }); // resolve every special plugins plugins.forEach(function (plugin) { return (0, _utilsAssign2['default'])(prefixedStyles, plugin(property, value)); }); } return prefixedStyles; }, styles); } module.exports = exports['default']; /***/ }, /* 14 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = { "Webkit": { "transform": true, "transformOrigin": true, "transformOriginX": true, "transformOriginY": true, "backfaceVisibility": true, "perspective": true, "perspectiveOrigin": true, "transformStyle": true, "transformOriginZ": true, "animation": true, "animationDelay": true, "animationDirection": true, "animationFillMode": true, "animationDuration": true, "animationIterationCount": true, "animationName": true, "animationPlayState": true, "animationTimingFunction": true, "appearance": true, "userSelect": true, "fontKerning": true, "textEmphasisPosition": true, "textEmphasis": true, "textEmphasisStyle": true, "textEmphasisColor": true, "boxDecorationBreak": true, "clipPath": true, "maskImage": true, "maskMode": true, "maskRepeat": true, "maskPosition": true, "maskClip": true, "maskOrigin": true, "maskSize": true, "maskComposite": true, "mask": true, "maskBorderSource": true, "maskBorderMode": true, "maskBorderSlice": true, "maskBorderWidth": true, "maskBorderOutset": true, "maskBorderRepeat": true, "maskBorder": true, "maskType": true, "textDecorationStyle": true, "textDecorationSkip": true, "textDecorationLine": true, "textDecorationColor": true, "filter": true, "fontFeatureSettings": true, "breakAfter": true, "breakBefore": true, "breakInside": true, "columnCount": true, "columnFill": true, "columnGap": true, "columnRule": true, "columnRuleColor": true, "columnRuleStyle": true, "columnRuleWidth": true, "columns": true, "columnSpan": true, "columnWidth": true, "flex": true, "flexBasis": true, "flexDirection": true, "flexGrow": true, "flexFlow": true, "flexShrink": true, "flexWrap": true, "alignContent": true, "alignItems": true, "alignSelf": true, "justifyContent": true, "order": true, "transition": true, "transitionDelay": true, "transitionDuration": true, "transitionProperty": true, "transitionTimingFunction": true, "backdropFilter": true, "scrollSnapType": true, "scrollSnapPointsX": true, "scrollSnapPointsY": true, "scrollSnapDestination": true, "scrollSnapCoordinate": true, "shapeImageThreshold": true, "shapeImageMargin": true, "shapeImageOutside": true, "hyphens": true, "flowInto": true, "flowFrom": true, "regionFragment": true, "textSizeAdjust": true, "borderImage": true, "borderImageOutset": true, "borderImageRepeat": true, "borderImageSlice": true, "borderImageSource": true, "borderImageWidth": true, "tabSize": true, "objectFit": true, "objectPosition": true }, "Moz": { "appearance": true, "userSelect": true, "boxSizing": true, "textAlignLast": true, "textDecorationStyle": true, "textDecorationSkip": true, "textDecorationLine": true, "textDecorationColor": true, "tabSize": true, "hyphens": true, "fontFeatureSettings": true, "breakAfter": true, "breakBefore": true, "breakInside": true, "columnCount": true, "columnFill": true, "columnGap": true, "columnRule": true, "columnRuleColor": true, "columnRuleStyle": true, "columnRuleWidth": true, "columns": true, "columnSpan": true, "columnWidth": true }, "ms": { "flex": true, "flexBasis": false, "flexDirection": true, "flexGrow": false, "flexFlow": true, "flexShrink": false, "flexWrap": true, "alignContent": false, "alignItems": false, "alignSelf": false, "justifyContent": false, "order": false, "transform": true, "transformOrigin": true, "transformOriginX": true, "transformOriginY": true, "userSelect": true, "wrapFlow": true, "wrapThrough": true, "wrapMargin": true, "scrollSnapType": true, "scrollSnapPointsX": true, "scrollSnapPointsY": true, "scrollSnapDestination": true, "scrollSnapCoordinate": true, "touchAction": true, "hyphens": true, "flowInto": true, "flowFrom": true, "breakBefore": true, "breakAfter": true, "breakInside": true, "regionFragment": true, "gridTemplateColumns": true, "gridTemplateRows": true, "gridTemplateAreas": true, "gridTemplate": true, "gridAutoColumns": true, "gridAutoRows": true, "gridAutoFlow": true, "grid": true, "gridRowStart": true, "gridColumnStart": true, "gridRowEnd": true, "gridRow": true, "gridColumn": true, "gridColumnEnd": true, "gridColumnGap": true, "gridRowGap": true, "gridArea": true, "gridGap": true, "textSizeAdjust": true } }; module.exports = exports["default"]; /***/ }, /* 15 */ /***/ function(module, exports) { // helper to capitalize strings "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = function (str) { return str.charAt(0).toUpperCase() + str.slice(1); }; module.exports = exports["default"]; /***/ }, /* 16 */ /***/ function(module, exports) { // leight polyfill for Object.assign "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = function (base) { var extend = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; return Object.keys(extend).reduce(function (out, key) { base[key] = extend[key]; return out; }, {}); }; module.exports = exports["default"]; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = calc; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsJoinPrefixedRules = __webpack_require__(18); var _utilsJoinPrefixedRules2 = _interopRequireDefault(_utilsJoinPrefixedRules); var _utilsIsPrefixedValue = __webpack_require__(20); var _utilsIsPrefixedValue2 = _interopRequireDefault(_utilsIsPrefixedValue); function calc(property, value) { if (typeof value === 'string' && value.indexOf('calc(') > -1) { if ((0, _utilsIsPrefixedValue2['default'])(value)) return; return (0, _utilsJoinPrefixedRules2['default'])(property, value, function (prefix, value) { return value.replace(/calc\(/g, prefix + 'calc('); }); } } module.exports = exports['default']; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var _camelToDashCase = __webpack_require__(19); var _camelToDashCase2 = _interopRequireDefault(_camelToDashCase); // returns a style object with a single concated prefixed value string exports['default'] = function (property, value) { var replacer = arguments.length <= 2 || arguments[2] === undefined ? function (prefix, value) { return prefix + value; } : arguments[2]; return function () { return _defineProperty({}, property, ['-webkit-', '-moz-', ''].map(function (prefix) { return replacer(prefix, value); })); }(); }; module.exports = exports['default']; /***/ }, /* 19 */ /***/ function(module, exports) { /** * Converts a camel-case string to a dash-case string * @param {string} str - str that gets converted to dash-case */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = function (str) { return str.replace(/([a-z]|^)([A-Z])/g, function (match, p1, p2) { return p1 + '-' + p2.toLowerCase(); }).replace('ms-', '-ms-'); }; module.exports = exports['default']; /***/ }, /* 20 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = function (value) { if (Array.isArray(value)) value = value.join(','); return value.match(/-webkit-|-moz-|-ms-/) !== null; }; module.exports = exports['default']; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = cursor; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsJoinPrefixedRules = __webpack_require__(18); var _utilsJoinPrefixedRules2 = _interopRequireDefault(_utilsJoinPrefixedRules); var values = { 'zoom-in': true, 'zoom-out': true, 'grab': true, 'grabbing': true }; function cursor(property, value) { if (property === 'cursor' && values[value]) { return (0, _utilsJoinPrefixedRules2['default'])(property, value); } } module.exports = exports['default']; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = flex; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsCamelToDashCase = __webpack_require__(19); var _utilsCamelToDashCase2 = _interopRequireDefault(_utilsCamelToDashCase); var values = { flex: true, 'inline-flex': true }; function flex(property, value) { if (property === 'display' && values[value]) { return { display: ['-webkit-box', '-moz-box', '-ms-' + value + 'box', '-webkit-' + value, value] }; } } module.exports = exports['default']; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = sizing; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsJoinPrefixedRules = __webpack_require__(18); var _utilsJoinPrefixedRules2 = _interopRequireDefault(_utilsJoinPrefixedRules); var properties = { maxHeight: true, maxWidth: true, width: true, height: true, columnWidth: true, minWidth: true, minHeight: true }; var values = { 'min-content': true, 'max-content': true, 'fill-available': true, 'fit-content': true, 'contain-floats': true }; function sizing(property, value) { if (properties[property] && values[value]) { return (0, _utilsJoinPrefixedRules2['default'])(property, value); } } module.exports = exports['default']; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = gradient; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsJoinPrefixedRules = __webpack_require__(18); var _utilsJoinPrefixedRules2 = _interopRequireDefault(_utilsJoinPrefixedRules); var _utilsIsPrefixedValue = __webpack_require__(20); var _utilsIsPrefixedValue2 = _interopRequireDefault(_utilsIsPrefixedValue); var values = /linear-gradient|radial-gradient|repeating-linear-gradient|repeating-radial-gradient/; function gradient(property, value) { if (typeof value === 'string' && value.match(values) !== null) { if ((0, _utilsIsPrefixedValue2['default'])(value)) return; return (0, _utilsJoinPrefixedRules2['default'])(property, value); } } module.exports = exports['default']; /***/ }, /* 25 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = transition; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var _utilsCamelToDashCase = __webpack_require__(19); var _utilsCamelToDashCase2 = _interopRequireDefault(_utilsCamelToDashCase); var _utilsCapitalizeString = __webpack_require__(15); var _utilsCapitalizeString2 = _interopRequireDefault(_utilsCapitalizeString); var _utilsIsPrefixedValue = __webpack_require__(20); var _utilsIsPrefixedValue2 = _interopRequireDefault(_utilsIsPrefixedValue); var _prefixProps = __webpack_require__(14); var _prefixProps2 = _interopRequireDefault(_prefixProps); var properties = { transition: true, transitionProperty: true, WebkitTransition: true, WebkitTransitionProperty: true }; function transition(property, value) { // also check for already prefixed transitions if (typeof value === 'string' && properties[property]) { var _ref2; var outputValue = prefixValue(value); var webkitOutput = outputValue.split(',').filter(function (value) { return value.match(/-moz-|-ms-/) === null; }).join(','); // if the property is already prefixed if (property.indexOf('Webkit') > -1) { return _defineProperty({}, property, webkitOutput); } return _ref2 = {}, _defineProperty(_ref2, 'Webkit' + (0, _utilsCapitalizeString2['default'])(property), webkitOutput), _defineProperty(_ref2, property, outputValue), _ref2; } } function prefixValue(value) { if ((0, _utilsIsPrefixedValue2['default'])(value)) { return value; } // only split multi values, not cubic beziers var multipleValues = value.split(/,(?![^()]*(?:\([^()]*\))?\))/g); // iterate each single value and check for transitioned properties // that need to be prefixed as well multipleValues.forEach(function (val, index) { multipleValues[index] = Object.keys(_prefixProps2['default']).reduce(function (out, prefix) { var dashCasePrefix = '-' + prefix.toLowerCase() + '-'; Object.keys(_prefixProps2['default'][prefix]).forEach(function (prop) { var dashCaseProperty = (0, _utilsCamelToDashCase2['default'])(prop); if (val.indexOf(dashCaseProperty) > -1) { // join all prefixes and create a new value out = val.replace(dashCaseProperty, dashCasePrefix + dashCaseProperty) + ',' + out; } }); return out; }, val); }); return multipleValues.join(','); } module.exports = exports['default']; /***/ }, /* 26 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = flexboxIE; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var alternativeValues = { 'space-around': 'distribute', 'space-between': 'justify', 'flex-start': 'start', 'flex-end': 'end' }; var alternativeProps = { alignContent: 'msFlexLinePack', alignSelf: 'msFlexItemAlign', alignItems: 'msFlexAlign', justifyContent: 'msFlexPack', order: 'msFlexOrder', flexGrow: 'msFlexPositive', flexShrink: 'msFlexNegative', flexBasis: 'msPreferredSize' }; function flexboxIE(property, value) { if (alternativeProps[property]) { return _defineProperty({}, alternativeProps[property], alternativeValues[value] || value); } } module.exports = exports['default']; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = flexboxOld; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var _utilsCamelToDashCase = __webpack_require__(19); var _utilsCamelToDashCase2 = _interopRequireDefault(_utilsCamelToDashCase); var alternativeValues = { 'space-around': 'justify', 'space-between': 'justify', 'flex-start': 'start', 'flex-end': 'end', 'wrap-reverse': 'multiple', wrap: 'multiple' }; var alternativeProps = { alignItems: 'WebkitBoxAlign', justifyContent: 'WebkitBoxPack', flexWrap: 'WebkitBoxLines' }; function flexboxOld(property, value) { if (property === 'flexDirection') { return { WebkitBoxOrient: value.indexOf('column') > -1 ? 'vertical' : 'horizontal', WebkitBoxDirection: value.indexOf('reverse') > -1 ? 'reverse' : 'normal' }; } if (alternativeProps[property]) { return _defineProperty({}, alternativeProps[property], alternativeValues[value] || value); } } module.exports = exports['default']; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _bowser = __webpack_require__(29); var _bowser2 = _interopRequireDefault(_bowser); var vendorPrefixes = { Webkit: ['chrome', 'safari', 'ios', 'android', 'phantom', 'opera', 'webos', 'blackberry', 'bada', 'tizen'], Moz: ['firefox', 'seamonkey', 'sailfish'], ms: ['msie', 'msedge'] }; var browsers = { chrome: [['chrome']], safari: [['safari']], firefox: [['firefox']], ie: [['msie']], edge: [['msedge']], opera: [['opera']], ios_saf: [['ios', 'mobile'], ['ios', 'tablet']], ie_mob: [['windowsphone', 'mobile', 'msie'], ['windowsphone', 'tablet', 'msie'], ['windowsphone', 'mobile', 'msedge'], ['windowsphone', 'tablet', 'msedge']], op_mini: [['opera', 'mobile'], ['opera', 'tablet']], and_uc: [['android', 'mobile'], ['android', 'tablet']], android: [['android', 'mobile'], ['android', 'tablet']] }; /** * Uses bowser to get default browser information such as version and name * Evaluates bowser info and adds vendorPrefix information * @param {string} userAgent - userAgent that gets evaluated */ exports['default'] = function (userAgent) { if (!userAgent) { return false; } var info = _bowser2['default']._detect(userAgent); Object.keys(vendorPrefixes).forEach(function (prefix) { vendorPrefixes[prefix].forEach(function (browser) { if (info[browser]) { info.prefix = { inline: prefix, css: '-' + prefix.toLowerCase() + '-' }; } }); }); var name = ''; Object.keys(browsers).forEach(function (browser) { browsers[browser].forEach(function (condition) { var match = 0; condition.forEach(function (single) { if (info[single]) { match += 1; } }); if (condition.length === match) { name = browser; } }); }); info.browser = name; // For cordova IOS 8 the version is missing, set truncated osversion to prevent NaN info.version = info.version ? parseFloat(info.version) : parseInt(parseFloat(info.osversion), 10); // seperate native android chrome // https://github.com/rofrischmann/inline-style-prefixer/issues/45 if (info.browser === 'android' && info.chrome && info.version > 37) { info.browser = 'and_chr'; } info.version = parseFloat(info.version); info.osversion = parseFloat(info.osversion); // For android < 4.4 we want to check the osversion // not the chrome version, see issue #26 // https://github.com/rofrischmann/inline-style-prefixer/issues/26 if (info.browser === 'android' && info.osversion < 5) { info.version = info.osversion; } return info; }; module.exports = exports['default']; /***/ }, /* 29 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; /*! * Bowser - a browser detector * https://github.com/ded/bowser * MIT License | (c) Dustin Diaz 2015 */ !function (name, definition) { if (typeof module != 'undefined' && module.exports) module.exports = definition();else if (true) !(__WEBPACK_AMD_DEFINE_FACTORY__ = (definition), __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? (__WEBPACK_AMD_DEFINE_FACTORY__.call(exports, __webpack_require__, exports, module)) : __WEBPACK_AMD_DEFINE_FACTORY__), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));else this[name] = definition(); }('bowser', function () { /** * See useragents.js for examples of navigator.userAgent */ var t = true; function detect(ua) { function getFirstMatch(regex) { var match = ua.match(regex); return match && match.length > 1 && match[1] || ''; } function getSecondMatch(regex) { var match = ua.match(regex); return match && match.length > 1 && match[2] || ''; } var iosdevice = getFirstMatch(/(ipod|iphone|ipad)/i).toLowerCase(), likeAndroid = /like android/i.test(ua), android = !likeAndroid && /android/i.test(ua), nexusMobile = /nexus\s*[0-6]\s*/i.test(ua), nexusTablet = !nexusMobile && /nexus\s*[0-9]+/i.test(ua), chromeos = /CrOS/.test(ua), silk = /silk/i.test(ua), sailfish = /sailfish/i.test(ua), tizen = /tizen/i.test(ua), webos = /(web|hpw)os/i.test(ua), windowsphone = /windows phone/i.test(ua), windows = !windowsphone && /windows/i.test(ua), mac = !iosdevice && !silk && /macintosh/i.test(ua), linux = !android && !sailfish && !tizen && !webos && /linux/i.test(ua), edgeVersion = getFirstMatch(/edge\/(\d+(\.\d+)?)/i), versionIdentifier = getFirstMatch(/version\/(\d+(\.\d+)?)/i), tablet = /tablet/i.test(ua), mobile = !tablet && /[^-]mobi/i.test(ua), xbox = /xbox/i.test(ua), result; if (/opera|opr|opios/i.test(ua)) { result = { name: 'Opera', opera: t, version: versionIdentifier || getFirstMatch(/(?:opera|opr|opios)[\s\/](\d+(\.\d+)?)/i) }; } else if (/coast/i.test(ua)) { result = { name: 'Opera Coast', coast: t, version: versionIdentifier || getFirstMatch(/(?:coast)[\s\/](\d+(\.\d+)?)/i) }; } else if (/yabrowser/i.test(ua)) { result = { name: 'Yandex Browser', yandexbrowser: t, version: versionIdentifier || getFirstMatch(/(?:yabrowser)[\s\/](\d+(\.\d+)?)/i) }; } else if (/ucbrowser/i.test(ua)) { result = { name: 'UC Browser', ucbrowser: t, version: getFirstMatch(/(?:ucbrowser)[\s\/](\d+(?:\.\d+)+)/i) }; } else if (/mxios/i.test(ua)) { result = { name: 'Maxthon', maxthon: t, version: getFirstMatch(/(?:mxios)[\s\/](\d+(?:\.\d+)+)/i) }; } else if (/epiphany/i.test(ua)) { result = { name: 'Epiphany', epiphany: t, version: getFirstMatch(/(?:epiphany)[\s\/](\d+(?:\.\d+)+)/i) }; } else if (/puffin/i.test(ua)) { result = { name: 'Puffin', puffin: t, version: getFirstMatch(/(?:puffin)[\s\/](\d+(?:\.\d+)?)/i) }; } else if (/sleipnir/i.test(ua)) { result = { name: 'Sleipnir', sleipnir: t, version: getFirstMatch(/(?:sleipnir)[\s\/](\d+(?:\.\d+)+)/i) }; } else if (/k-meleon/i.test(ua)) { result = { name: 'K-Meleon', kMeleon: t, version: getFirstMatch(/(?:k-meleon)[\s\/](\d+(?:\.\d+)+)/i) }; } else if (windowsphone) { result = { name: 'Windows Phone', windowsphone: t }; if (edgeVersion) { result.msedge = t; result.version = edgeVersion; } else { result.msie = t; result.version = getFirstMatch(/iemobile\/(\d+(\.\d+)?)/i); } } else if (/msie|trident/i.test(ua)) { result = { name: 'Internet Explorer', msie: t, version: getFirstMatch(/(?:msie |rv:)(\d+(\.\d+)?)/i) }; } else if (chromeos) { result = { name: 'Chrome', chromeos: t, chromeBook: t, chrome: t, version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i) }; } else if (/chrome.+? edge/i.test(ua)) { result = { name: 'Microsoft Edge', msedge: t, version: edgeVersion }; } else if (/vivaldi/i.test(ua)) { result = { name: 'Vivaldi', vivaldi: t, version: getFirstMatch(/vivaldi\/(\d+(\.\d+)?)/i) || versionIdentifier }; } else if (sailfish) { result = { name: 'Sailfish', sailfish: t, version: getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i) }; } else if (/seamonkey\//i.test(ua)) { result = { name: 'SeaMonkey', seamonkey: t, version: getFirstMatch(/seamonkey\/(\d+(\.\d+)?)/i) }; } else if (/firefox|iceweasel|fxios/i.test(ua)) { result = { name: 'Firefox', firefox: t, version: getFirstMatch(/(?:firefox|iceweasel|fxios)[ \/](\d+(\.\d+)?)/i) }; if (/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(ua)) { result.firefoxos = t; } } else if (silk) { result = { name: 'Amazon Silk', silk: t, version: getFirstMatch(/silk\/(\d+(\.\d+)?)/i) }; } else if (/phantom/i.test(ua)) { result = { name: 'PhantomJS', phantom: t, version: getFirstMatch(/phantomjs\/(\d+(\.\d+)?)/i) }; } else if (/slimerjs/i.test(ua)) { result = { name: 'SlimerJS', slimer: t, version: getFirstMatch(/slimerjs\/(\d+(\.\d+)?)/i) }; } else if (/blackberry|\bbb\d+/i.test(ua) || /rim\stablet/i.test(ua)) { result = { name: 'BlackBerry', blackberry: t, version: versionIdentifier || getFirstMatch(/blackberry[\d]+\/(\d+(\.\d+)?)/i) }; } else if (webos) { result = { name: 'WebOS', webos: t, version: versionIdentifier || getFirstMatch(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i) }; /touchpad\//i.test(ua) && (result.touchpad = t); } else if (/bada/i.test(ua)) { result = { name: 'Bada', bada: t, version: getFirstMatch(/dolfin\/(\d+(\.\d+)?)/i) }; } else if (tizen) { result = { name: 'Tizen', tizen: t, version: getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i) || versionIdentifier }; } else if (/qupzilla/i.test(ua)) { result = { name: 'QupZilla', qupzilla: t, version: getFirstMatch(/(?:qupzilla)[\s\/](\d+(?:\.\d+)+)/i) || versionIdentifier }; } else if (/chromium/i.test(ua)) { result = { name: 'Chromium', chromium: t, version: getFirstMatch(/(?:chromium)[\s\/](\d+(?:\.\d+)?)/i) || versionIdentifier }; } else if (/chrome|crios|crmo/i.test(ua)) { result = { name: 'Chrome', chrome: t, version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i) }; } else if (android) { result = { name: 'Android', version: versionIdentifier }; } else if (/safari|applewebkit/i.test(ua)) { result = { name: 'Safari', safari: t }; if (versionIdentifier) { result.version = versionIdentifier; } } else if (iosdevice) { result = { name: iosdevice == 'iphone' ? 'iPhone' : iosdevice == 'ipad' ? 'iPad' : 'iPod' }; // WTF: version is not part of user agent in web apps if (versionIdentifier) { result.version = versionIdentifier; } } else if (/googlebot/i.test(ua)) { result = { name: 'Googlebot', googlebot: t, version: getFirstMatch(/googlebot\/(\d+(\.\d+))/i) || versionIdentifier }; } else { result = { name: getFirstMatch(/^(.*)\/(.*) /), version: getSecondMatch(/^(.*)\/(.*) /) }; } // set webkit or gecko flag for browsers based on these engines if (!result.msedge && /(apple)?webkit/i.test(ua)) { if (/(apple)?webkit\/537\.36/i.test(ua)) { result.name = result.name || "Blink"; result.blink = t; } else { result.name = result.name || "Webkit"; result.webkit = t; } if (!result.version && versionIdentifier) { result.version = versionIdentifier; } } else if (!result.opera && /gecko\//i.test(ua)) { result.name = result.name || "Gecko"; result.gecko = t; result.version = result.version || getFirstMatch(/gecko\/(\d+(\.\d+)?)/i); } // set OS flags for platforms that have multiple browsers if (!result.msedge && (android || result.silk)) { result.android = t; } else if (iosdevice) { result[iosdevice] = t; result.ios = t; } else if (mac) { result.mac = t; } else if (xbox) { result.xbox = t; } else if (windows) { result.windows = t; } else if (linux) { result.linux = t; } // OS version extraction var osVersion = ''; if (result.windowsphone) { osVersion = getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i); } else if (iosdevice) { osVersion = getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i); osVersion = osVersion.replace(/[_\s]/g, '.'); } else if (android) { osVersion = getFirstMatch(/android[ \/-](\d+(\.\d+)*)/i); } else if (result.webos) { osVersion = getFirstMatch(/(?:web|hpw)os\/(\d+(\.\d+)*)/i); } else if (result.blackberry) { osVersion = getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i); } else if (result.bada) { osVersion = getFirstMatch(/bada\/(\d+(\.\d+)*)/i); } else if (result.tizen) { osVersion = getFirstMatch(/tizen[\/\s](\d+(\.\d+)*)/i); } if (osVersion) { result.osversion = osVersion; } // device type extraction var osMajorVersion = osVersion.split('.')[0]; if (tablet || nexusTablet || iosdevice == 'ipad' || android && (osMajorVersion == 3 || osMajorVersion >= 4 && !mobile) || result.silk) { result.tablet = t; } else if (mobile || iosdevice == 'iphone' || iosdevice == 'ipod' || android || nexusMobile || result.blackberry || result.webos || result.bada) { result.mobile = t; } // Graded Browser Support // http://developer.yahoo.com/yui/articles/gbs if (result.msedge || result.msie && result.version >= 10 || result.yandexbrowser && result.version >= 15 || result.vivaldi && result.version >= 1.0 || result.chrome && result.version >= 20 || result.firefox && result.version >= 20.0 || result.safari && result.version >= 6 || result.opera && result.version >= 10.0 || result.ios && result.osversion && result.osversion.split(".")[0] >= 6 || result.blackberry && result.version >= 10.1 || result.chromium && result.version >= 20) { result.a = t; } else if (result.msie && result.version < 10 || result.chrome && result.version < 20 || result.firefox && result.version < 20.0 || result.safari && result.version < 6 || result.opera && result.version < 10.0 || result.ios && result.osversion && result.osversion.split(".")[0] < 6 || result.chromium && result.version < 20) { result.c = t; } else result.x = t; return result; } var bowser = detect(typeof navigator !== 'undefined' ? navigator.userAgent : ''); bowser.test = function (browserList) { for (var i = 0; i < browserList.length; ++i) { var browserItem = browserList[i]; if (typeof browserItem === 'string') { if (browserItem in bowser) { return true; } } } return false; }; /** * Get version precisions count * * @example * getVersionPrecision("1.10.3") // 3 * * @param {string} version * @return {number} */ function getVersionPrecision(version) { return version.split(".").length; } /** * Array::map polyfill * * @param {Array} arr * @param {Function} iterator * @return {Array} */ function map(arr, iterator) { var result = [], i; if (Array.prototype.map) { return Array.prototype.map.call(arr, iterator); } for (i = 0; i < arr.length; i++) { result = iterator(arr[i]); } return result; } /** * Calculate browser version weight * * @example * compareVersions(['1.10.2.1', '1.8.2.1.90']) // 1 * compareVersions(['1.010.2.1', '1.09.2.1.90']); // 1 * compareVersions(['1.10.2.1', '1.10.2.1']); // 0 * compareVersions(['1.10.2.1', '1.0800.2']); // -1 * * @param {Array<String>} versions versions to compare * @return {Number} comparison result */ function compareVersions(versions) { // 1) get common precision for both versions, for example for "10.0" and "9" it should be 2 var precision = Math.max(getVersionPrecision(versions[0]), getVersionPrecision(versions[1])); var chunks = map(versions, function (version) { var delta = precision - getVersionPrecision(version); // 2) "9" -> "9.0" (for precision = 2) version = version + new Array(delta + 1).join(".0"); // 3) "9.0" -> ["000000000"", "000000009"] return map(version.split("."), function (chunk) { return new Array(20 - chunk.length).join("0") + chunk; }).reverse(); }); // iterate in reverse order by reversed chunks array while (--precision >= 0) { // 4) compare: "000000009" > "000000010" = false (but "9" > "10" = true) if (chunks[0][precision] > chunks[1][precision]) { return 1; } else if (chunks[0][precision] === chunks[1][precision]) { if (precision === 0) { // all version chunks are same return 0; } } else { return -1; } } } /** * Check if browser is unsupported * * @example * bowser.isUnsupportedBrowser({ * msie: "10", * firefox: "23", * chrome: "29", * safari: "5.1", * opera: "16", * phantom: "534" * }); * * @param {Object} minVersions map of minimal version to browser * @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map * @param {String} [ua] user agent string * @return {Boolean} */ function isUnsupportedBrowser(minVersions, strictMode, ua) { var _bowser = bowser; // make strictMode param optional with ua param usage if (typeof strictMode === 'string') { ua = strictMode; strictMode = void 0; } if (strictMode === void 0) { strictMode = false; } if (ua) { _bowser = detect(ua); } var version = "" + _bowser.version; for (var browser in minVersions) { if (minVersions.hasOwnProperty(browser)) { if (_bowser[browser]) { // browser version and min supported version. if (compareVersions([version, minVersions[browser]]) < 0) { return true; // unsupported } } } } return strictMode; // not found } /** * Check if browser is supported * * @param {Object} minVersions map of minimal version to browser * @param {Boolean} [strictMode = false] flag to return false if browser wasn't found in map * @return {Boolean} */ function check(minVersions, strictMode) { return !isUnsupportedBrowser(minVersions, strictMode); } bowser.isUnsupportedBrowser = isUnsupportedBrowser; bowser.compareVersions = compareVersions; bowser.check = check; /* * Set our detect method to the main bowser object so we can * reuse it to test other user agents. * This is needed to implement future tests. */ bowser._detect = detect; return bowser; }); /***/ }, /* 30 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = function (_ref) { var browser = _ref.browser; var version = _ref.version; var prefix = _ref.prefix; var prefixedKeyframes = 'keyframes'; if (browser === 'chrome' && version < 43 || (browser === 'safari' || browser === 'ios_saf') && version < 9 || browser === 'opera' && version < 30 || browser === 'android' && version <= 4.4 || browser === 'and_uc') { prefixedKeyframes = prefix.css + prefixedKeyframes; } return prefixedKeyframes; }; module.exports = exports['default']; /***/ }, /* 31 */ /***/ function(module, exports) { // helper to capitalize strings "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = function (str) { return str.charAt(0).toUpperCase() + str.slice(1); }; module.exports = exports["default"]; /***/ }, /* 32 */ /***/ function(module, exports) { // leight polyfill for Object.assign "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = function (base) { var extend = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; Object.keys(extend).forEach(function (key) { return base[key] = extend[key]; }); return base; }; module.exports = exports["default"]; /***/ }, /* 33 */ /***/ function(module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = { "chrome": { "transform": 35, "transformOrigin": 35, "transformOriginX": 35, "transformOriginY": 35, "backfaceVisibility": 35, "perspective": 35, "perspectiveOrigin": 35, "transformStyle": 35, "transformOriginZ": 35, "animation": 42, "animationDelay": 42, "animationDirection": 42, "animationFillMode": 42, "animationDuration": 42, "animationIterationCount": 42, "animationName": 42, "animationPlayState": 42, "animationTimingFunction": 42, "appearance": 52, "userSelect": 52, "fontKerning": 32, "textEmphasisPosition": 52, "textEmphasis": 52, "textEmphasisStyle": 52, "textEmphasisColor": 52, "boxDecorationBreak": 52, "clipPath": 52, "maskImage": 52, "maskMode": 52, "maskRepeat": 52, "maskPosition": 52, "maskClip": 52, "maskOrigin": 52, "maskSize": 52, "maskComposite": 52, "mask": 52, "maskBorderSource": 52, "maskBorderMode": 52, "maskBorderSlice": 52, "maskBorderWidth": 52, "maskBorderOutset": 52, "maskBorderRepeat": 52, "maskBorder": 52, "maskType": 52, "textDecorationStyle": 52, "textDecorationSkip": 52, "textDecorationLine": 52, "textDecorationColor": 52, "filter": 52, "fontFeatureSettings": 47, "breakAfter": 52, "breakBefore": 52, "breakInside": 52, "columnCount": 52, "columnFill": 52, "columnGap": 52, "columnRule": 52, "columnRuleColor": 52, "columnRuleStyle": 52, "columnRuleWidth": 52, "columns": 52, "columnSpan": 52, "columnWidth": 52 }, "safari": { "flex": 8, "flexBasis": 8, "flexDirection": 8, "flexGrow": 8, "flexFlow": 8, "flexShrink": 8, "flexWrap": 8, "alignContent": 8, "alignItems": 8, "alignSelf": 8, "justifyContent": 8, "order": 8, "transition": 6, "transitionDelay": 6, "transitionDuration": 6, "transitionProperty": 6, "transitionTimingFunction": 6, "transform": 8, "transformOrigin": 8, "transformOriginX": 8, "transformOriginY": 8, "backfaceVisibility": 8, "perspective": 8, "perspectiveOrigin": 8, "transformStyle": 8, "transformOriginZ": 8, "animation": 8, "animationDelay": 8, "animationDirection": 8, "animationFillMode": 8, "animationDuration": 8, "animationIterationCount": 8, "animationName": 8, "animationPlayState": 8, "animationTimingFunction": 8, "appearance": 9.1, "userSelect": 9.1, "backdropFilter": 9.1, "fontKerning": 9.1, "scrollSnapType": 9.1, "scrollSnapPointsX": 9.1, "scrollSnapPointsY": 9.1, "scrollSnapDestination": 9.1, "scrollSnapCoordinate": 9.1, "textEmphasisPosition": 7, "textEmphasis": 7, "textEmphasisStyle": 7, "textEmphasisColor": 7, "boxDecorationBreak": 9.1, "clipPath": 9.1, "maskImage": 9.1, "maskMode": 9.1, "maskRepeat": 9.1, "maskPosition": 9.1, "maskClip": 9.1, "maskOrigin": 9.1, "maskSize": 9.1, "maskComposite": 9.1, "mask": 9.1, "maskBorderSource": 9.1, "maskBorderMode": 9.1, "maskBorderSlice": 9.1, "maskBorderWidth": 9.1, "maskBorderOutset": 9.1, "maskBorderRepeat": 9.1, "maskBorder": 9.1, "maskType": 9.1, "textDecorationStyle": 9.1, "textDecorationSkip": 9.1, "textDecorationLine": 9.1, "textDecorationColor": 9.1, "shapeImageThreshold": 9.1, "shapeImageMargin": 9.1, "shapeImageOutside": 9.1, "filter": 9, "hyphens": 9.1, "flowInto": 9.1, "flowFrom": 9.1, "breakBefore": 8, "breakAfter": 8, "breakInside": 8, "regionFragment": 9.1, "columnCount": 8, "columnFill": 8, "columnGap": 8, "columnRule": 8, "columnRuleColor": 8, "columnRuleStyle": 8, "columnRuleWidth": 8, "columns": 8, "columnSpan": 8, "columnWidth": 8 }, "firefox": { "appearance": 47, "userSelect": 47, "boxSizing": 28, "textAlignLast": 47, "textDecorationStyle": 35, "textDecorationSkip": 35, "textDecorationLine": 35, "textDecorationColor": 35, "tabSize": 47, "hyphens": 42, "fontFeatureSettings": 33, "breakAfter": 47, "breakBefore": 47, "breakInside": 47, "columnCount": 47, "columnFill": 47, "columnGap": 47, "columnRule": 47, "columnRuleColor": 47, "columnRuleStyle": 47, "columnRuleWidth": 47, "columns": 47, "columnSpan": 47, "columnWidth": 47 }, "opera": { "flex": 16, "flexBasis": 16, "flexDirection": 16, "flexGrow": 16, "flexFlow": 16, "flexShrink": 16, "flexWrap": 16, "alignContent": 16, "alignItems": 16, "alignSelf": 16, "justifyContent": 16, "order": 16, "transform": 22, "transformOrigin": 22, "transformOriginX": 22, "transformOriginY": 22, "backfaceVisibility": 22, "perspective": 22, "perspectiveOrigin": 22, "transformStyle": 22, "transformOriginZ": 22, "animation": 29, "animationDelay": 29, "animationDirection": 29, "animationFillMode": 29, "animationDuration": 29, "animationIterationCount": 29, "animationName": 29, "animationPlayState": 29, "animationTimingFunction": 29, "appearance": 37, "userSelect": 37, "fontKerning": 19, "textEmphasisPosition": 37, "textEmphasis": 37, "textEmphasisStyle": 37, "textEmphasisColor": 37, "boxDecorationBreak": 37, "clipPath": 37, "maskImage": 37, "maskMode": 37, "maskRepeat": 37, "maskPosition": 37, "maskClip": 37, "maskOrigin": 37, "maskSize": 37, "maskComposite": 37, "mask": 37, "maskBorderSource": 37, "maskBorderMode": 37, "maskBorderSlice": 37, "maskBorderWidth": 37, "maskBorderOutset": 37, "maskBorderRepeat": 37, "maskBorder": 37, "maskType": 37, "filter": 37, "fontFeatureSettings": 37, "breakAfter": 37, "breakBefore": 37, "breakInside": 37, "columnCount": 37, "columnFill": 37, "columnGap": 37, "columnRule": 37, "columnRuleColor": 37, "columnRuleStyle": 37, "columnRuleWidth": 37, "columns": 37, "columnSpan": 37, "columnWidth": 37 }, "ie": { "gridTemplateRows": 11, "breakInside": 11, "transformOriginY": 9, "gridRowStart": 11, "gridColumn": 11, "regionFragment": 11, "breakBefore": 11, "userSelect": 11, "gridColumnEnd": 11, "gridRowEnd": 11, "gridTemplateColumns": 11, "gridColumnStart": 11, "gridArea": 11, "flexDirection": 10, "gridRowGap": 11, "gridTemplateAreas": 11, "gridAutoRows": 11, "gridRow": 11, "scrollSnapDestination": 11, "scrollSnapPointsY": 11, "touchAction": 10, "gridGap": 11, "gridColumnGap": 11, "wrapFlow": 11, "scrollSnapPointsX": 11, "flowFrom": 11, "transform": 9, "breakAfter": 11, "wrapMargin": 11, "scrollSnapCoordinate": 11, "flexWrap": 10, "scrollSnapType": 11, "flex": 10, "wrapThrough": 11, "gridAutoColumns": 11, "flexFlow": 10, "gridTemplate": 11, "hyphens": 11, "grid": 11, "transformOriginX": 9, "flowInto": 11, "transformOrigin": 9, "gridAutoFlow": 11, "textSizeAdjust": 11 }, "edge": { "userSelect": 14, "wrapFlow": 14, "wrapThrough": 14, "wrapMargin": 14, "scrollSnapType": 14, "scrollSnapPointsX": 14, "scrollSnapPointsY": 14, "scrollSnapDestination": 14, "scrollSnapCoordinate": 14, "hyphens": 14, "flowInto": 14, "flowFrom": 14, "breakBefore": 14, "breakAfter": 14, "breakInside": 14, "regionFragment": 14, "gridTemplateColumns": 14, "gridTemplateRows": 14, "gridTemplateAreas": 14, "gridTemplate": 14, "gridAutoColumns": 14, "gridAutoRows": 14, "gridAutoFlow": 14, "grid": 14, "gridRowStart": 14, "gridColumnStart": 14, "gridRowEnd": 14, "gridRow": 14, "gridColumn": 14, "gridColumnEnd": 14, "gridColumnGap": 14, "gridRowGap": 14, "gridArea": 14, "gridGap": 14 }, "ios_saf": { "flex": 8.1, "flexBasis": 8.1, "flexDirection": 8.1, "flexGrow": 8.1, "flexFlow": 8.1, "flexShrink": 8.1, "flexWrap": 8.1, "alignContent": 8.1, "alignItems": 8.1, "alignSelf": 8.1, "justifyContent": 8.1, "order": 8.1, "transition": 6, "transitionDelay": 6, "transitionDuration": 6, "transitionProperty": 6, "transitionTimingFunction": 6, "transform": 8.1, "transformOrigin": 8.1, "transformOriginX": 8.1, "transformOriginY": 8.1, "backfaceVisibility": 8.1, "perspective": 8.1, "perspectiveOrigin": 8.1, "transformStyle": 8.1, "transformOriginZ": 8.1, "animation": 8.1, "animationDelay": 8.1, "animationDirection": 8.1, "animationFillMode": 8.1, "animationDuration": 8.1, "animationIterationCount": 8.1, "animationName": 8.1, "animationPlayState": 8.1, "animationTimingFunction": 8.1, "appearance": 9.3, "userSelect": 9.3, "backdropFilter": 9.3, "fontKerning": 9.3, "scrollSnapType": 9.3, "scrollSnapPointsX": 9.3, "scrollSnapPointsY": 9.3, "scrollSnapDestination": 9.3, "scrollSnapCoordinate": 9.3, "boxDecorationBreak": 9.3, "clipPath": 9.3, "maskImage": 9.3, "maskMode": 9.3, "maskRepeat": 9.3, "maskPosition": 9.3, "maskClip": 9.3, "maskOrigin": 9.3, "maskSize": 9.3, "maskComposite": 9.3, "mask": 9.3, "maskBorderSource": 9.3, "maskBorderMode": 9.3, "maskBorderSlice": 9.3, "maskBorderWidth": 9.3, "maskBorderOutset": 9.3, "maskBorderRepeat": 9.3, "maskBorder": 9.3, "maskType": 9.3, "textSizeAdjust": 9.3, "textDecorationStyle": 9.3, "textDecorationSkip": 9.3, "textDecorationLine": 9.3, "textDecorationColor": 9.3, "shapeImageThreshold": 9.3, "shapeImageMargin": 9.3, "shapeImageOutside": 9.3, "filter": 9, "hyphens": 9.3, "flowInto": 9.3, "flowFrom": 9.3, "breakBefore": 8.1, "breakAfter": 8.1, "breakInside": 8.1, "regionFragment": 9.3, "columnCount": 8.1, "columnFill": 8.1, "columnGap": 8.1, "columnRule": 8.1, "columnRuleColor": 8.1, "columnRuleStyle": 8.1, "columnRuleWidth": 8.1, "columns": 8.1, "columnSpan": 8.1, "columnWidth": 8.1 }, "android": { "borderImage": 4.2, "borderImageOutset": 4.2, "borderImageRepeat": 4.2, "borderImageSlice": 4.2, "borderImageSource": 4.2, "borderImageWidth": 4.2, "flex": 4.2, "flexBasis": 4.2, "flexDirection": 4.2, "flexGrow": 4.2, "flexFlow": 4.2, "flexShrink": 4.2, "flexWrap": 4.2, "alignContent": 4.2, "alignItems": 4.2, "alignSelf": 4.2, "justifyContent": 4.2, "order": 4.2, "transition": 4.2, "transitionDelay": 4.2, "transitionDuration": 4.2, "transitionProperty": 4.2, "transitionTimingFunction": 4.2, "transform": 4.4, "transformOrigin": 4.4, "transformOriginX": 4.4, "transformOriginY": 4.4, "backfaceVisibility": 4.4, "perspective": 4.4, "perspectiveOrigin": 4.4, "transformStyle": 4.4, "transformOriginZ": 4.4, "animation": 4.4, "animationDelay": 4.4, "animationDirection": 4.4, "animationFillMode": 4.4, "animationDuration": 4.4, "animationIterationCount": 4.4, "animationName": 4.4, "animationPlayState": 4.4, "animationTimingFunction": 4.4, "appearance": 47, "userSelect": 47, "fontKerning": 4.4, "textEmphasisPosition": 47, "textEmphasis": 47, "textEmphasisStyle": 47, "textEmphasisColor": 47, "boxDecorationBreak": 47, "clipPath": 47, "maskImage": 47, "maskMode": 47, "maskRepeat": 47, "maskPosition": 47, "maskClip": 47, "maskOrigin": 47, "maskSize": 47, "maskComposite": 47, "mask": 47, "maskBorderSource": 47, "maskBorderMode": 47, "maskBorderSlice": 47, "maskBorderWidth": 47, "maskBorderOutset": 47, "maskBorderRepeat": 47, "maskBorder": 47, "maskType": 47, "filter": 47, "fontFeatureSettings": 47, "breakAfter": 47, "breakBefore": 47, "breakInside": 47, "columnCount": 47, "columnFill": 47, "columnGap": 47, "columnRule": 47, "columnRuleColor": 47, "columnRuleStyle": 47, "columnRuleWidth": 47, "columns": 47, "columnSpan": 47, "columnWidth": 47 }, "and_chr": { "appearance": 47, "userSelect": 47, "textEmphasisPosition": 47, "textEmphasis": 47, "textEmphasisStyle": 47, "textEmphasisColor": 47, "boxDecorationBreak": 47, "clipPath": 47, "maskImage": 47, "maskMode": 47, "maskRepeat": 47, "maskPosition": 47, "maskClip": 47, "maskOrigin": 47, "maskSize": 47, "maskComposite": 47, "mask": 47, "maskBorderSource": 47, "maskBorderMode": 47, "maskBorderSlice": 47, "maskBorderWidth": 47, "maskBorderOutset": 47, "maskBorderRepeat": 47, "maskBorder": 47, "maskType": 47, "textDecorationStyle": 47, "textDecorationSkip": 47, "textDecorationLine": 47, "textDecorationColor": 47, "filter": 47, "fontFeatureSettings": 47, "breakAfter": 47, "breakBefore": 47, "breakInside": 47, "columnCount": 47, "columnFill": 47, "columnGap": 47, "columnRule": 47, "columnRuleColor": 47, "columnRuleStyle": 47, "columnRuleWidth": 47, "columns": 47, "columnSpan": 47, "columnWidth": 47 }, "and_uc": { "flex": 9.9, "flexBasis": 9.9, "flexDirection": 9.9, "flexGrow": 9.9, "flexFlow": 9.9, "flexShrink": 9.9, "flexWrap": 9.9, "alignContent": 9.9, "alignItems": 9.9, "alignSelf": 9.9, "justifyContent": 9.9, "order": 9.9, "transition": 9.9, "transitionDelay": 9.9, "transitionDuration": 9.9, "transitionProperty": 9.9, "transitionTimingFunction": 9.9, "transform": 9.9, "transformOrigin": 9.9, "transformOriginX": 9.9, "transformOriginY": 9.9, "backfaceVisibility": 9.9, "perspective": 9.9, "perspectiveOrigin": 9.9, "transformStyle": 9.9, "transformOriginZ": 9.9, "animation": 9.9, "animationDelay": 9.9, "animationDirection": 9.9, "animationFillMode": 9.9, "animationDuration": 9.9, "animationIterationCount": 9.9, "animationName": 9.9, "animationPlayState": 9.9, "animationTimingFunction": 9.9, "appearance": 9.9, "userSelect": 9.9, "fontKerning": 9.9, "textEmphasisPosition": 9.9, "textEmphasis": 9.9, "textEmphasisStyle": 9.9, "textEmphasisColor": 9.9, "maskImage": 9.9, "maskMode": 9.9, "maskRepeat": 9.9, "maskPosition": 9.9, "maskClip": 9.9, "maskOrigin": 9.9, "maskSize": 9.9, "maskComposite": 9.9, "mask": 9.9, "maskBorderSource": 9.9, "maskBorderMode": 9.9, "maskBorderSlice": 9.9, "maskBorderWidth": 9.9, "maskBorderOutset": 9.9, "maskBorderRepeat": 9.9, "maskBorder": 9.9, "maskType": 9.9, "textSizeAdjust": 9.9, "filter": 9.9, "hyphens": 9.9, "flowInto": 9.9, "flowFrom": 9.9, "breakBefore": 9.9, "breakAfter": 9.9, "breakInside": 9.9, "regionFragment": 9.9, "fontFeatureSettings": 9.9, "columnCount": 9.9, "columnFill": 9.9, "columnGap": 9.9, "columnRule": 9.9, "columnRuleColor": 9.9, "columnRuleStyle": 9.9, "columnRuleWidth": 9.9, "columns": 9.9, "columnSpan": 9.9, "columnWidth": 9.9 }, "op_mini": { "borderImage": 5, "borderImageOutset": 5, "borderImageRepeat": 5, "borderImageSlice": 5, "borderImageSource": 5, "borderImageWidth": 5, "tabSize": 5, "objectFit": 5, "objectPosition": 5 } }; module.exports = exports["default"]; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = calc; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var _utilsCamelToDashCase = __webpack_require__(35); var _utilsCamelToDashCase2 = _interopRequireDefault(_utilsCamelToDashCase); function calc(_ref2) { var property = _ref2.property; var value = _ref2.value; var _ref2$browserInfo = _ref2.browserInfo; var browser = _ref2$browserInfo.browser; var version = _ref2$browserInfo.version; var css = _ref2.prefix.css; var keepUnprefixed = _ref2.keepUnprefixed; if (typeof value === 'string' && value.indexOf('calc(') > -1 && (browser === 'firefox' && version < 15 || browser === 'chrome' && version < 25 || browser === 'safari' && version < 6.1 || browser === 'ios_saf' && version < 7)) { return _defineProperty({}, property, value.replace(/calc\(/g, css + 'calc(') + (keepUnprefixed ? ';' + (0, _utilsCamelToDashCase2['default'])(property) + ':' + value : '')); } } module.exports = exports['default']; /***/ }, /* 35 */ /***/ function(module, exports) { /** * Converts a camel-case string to a dash-case string * @param {string} str - str that gets converted to dash-case */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = function (str) { return str.replace(/([a-z]|^)([A-Z])/g, function (match, p1, p2) { return p1 + '-' + p2.toLowerCase(); }).replace('ms-', '-ms-'); }; module.exports = exports['default']; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = cursor; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsCamelToDashCase = __webpack_require__(35); var _utilsCamelToDashCase2 = _interopRequireDefault(_utilsCamelToDashCase); var values = { 'zoom-in': true, 'zoom-out': true, 'grab': true, 'grabbing': true }; function cursor(_ref) { var property = _ref.property; var value = _ref.value; var _ref$browserInfo = _ref.browserInfo; var browser = _ref$browserInfo.browser; var version = _ref$browserInfo.version; var css = _ref.prefix.css; var keepUnprefixed = _ref.keepUnprefixed; if (property === 'cursor' && values[value] && (browser === 'firefox' && version < 24 || browser === 'chrome' && version < 37 || browser === 'safari' && version < 9 || browser === 'opera' && version < 24)) { return { cursor: css + value + (keepUnprefixed ? ';' + (0, _utilsCamelToDashCase2['default'])(property) + ':' + value : '') }; } } module.exports = exports['default']; /***/ }, /* 37 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = flex; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsCamelToDashCase = __webpack_require__(35); var _utilsCamelToDashCase2 = _interopRequireDefault(_utilsCamelToDashCase); var values = { 'flex': true, 'inline-flex': true }; function flex(_ref) { var property = _ref.property; var value = _ref.value; var _ref$browserInfo = _ref.browserInfo; var browser = _ref$browserInfo.browser; var version = _ref$browserInfo.version; var css = _ref.prefix.css; var keepUnprefixed = _ref.keepUnprefixed; if (property === 'display' && values[value] && (browser === 'chrome' && version < 29 && version > 20 || (browser === 'safari' || browser === 'ios_saf') && version < 9 && version > 6 || browser === 'opera' && (version == 15 || version == 16))) { return { display: css + value + (keepUnprefixed ? ';' + (0, _utilsCamelToDashCase2['default'])(property) + ':' + value : '') }; } } module.exports = exports['default']; /***/ }, /* 38 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = sizing; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var _utilsCamelToDashCase = __webpack_require__(35); var _utilsCamelToDashCase2 = _interopRequireDefault(_utilsCamelToDashCase); var properties = { maxHeight: true, maxWidth: true, width: true, height: true, columnWidth: true, minWidth: true, minHeight: true }; var values = { 'min-content': true, 'max-content': true, 'fill-available': true, 'fit-content': true, 'contain-floats': true }; function sizing(_ref2) { var property = _ref2.property; var value = _ref2.value; var css = _ref2.prefix.css; var keepUnprefixed = _ref2.keepUnprefixed; // This might change in the future // Keep an eye on it if (properties[property] && values[value]) { return _defineProperty({}, property, css + value + (keepUnprefixed ? ';' + (0, _utilsCamelToDashCase2['default'])(property) + ':' + value : '')); } } module.exports = exports['default']; /***/ }, /* 39 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = gradient; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var _utilsCamelToDashCase = __webpack_require__(35); var _utilsCamelToDashCase2 = _interopRequireDefault(_utilsCamelToDashCase); var values = /linear-gradient|radial-gradient|repeating-linear-gradient|repeating-radial-gradient/; function gradient(_ref2) { var property = _ref2.property; var value = _ref2.value; var _ref2$browserInfo = _ref2.browserInfo; var browser = _ref2$browserInfo.browser; var version = _ref2$browserInfo.version; var css = _ref2.prefix.css; var keepUnprefixed = _ref2.keepUnprefixed; if (typeof value === 'string' && value.match(values) !== null && (browser === 'firefox' && version < 16 || browser === 'chrome' && version < 26 || (browser === 'safari' || browser === 'ios_saf') && version < 7 || (browser === 'opera' || browser === 'op_mini') && version < 12.1 || browser === 'android' && version < 4.4 || browser === 'and_uc')) { return _defineProperty({}, property, css + value + (keepUnprefixed ? ';' + (0, _utilsCamelToDashCase2['default'])(property) + ':' + value : '')); } } module.exports = exports['default']; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = transition; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var _utilsCamelToDashCase = __webpack_require__(35); var _utilsCamelToDashCase2 = _interopRequireDefault(_utilsCamelToDashCase); var _utilsCapitalizeString = __webpack_require__(31); var _utilsCapitalizeString2 = _interopRequireDefault(_utilsCapitalizeString); var _utilsUnprefixProperty = __webpack_require__(41); var _utilsUnprefixProperty2 = _interopRequireDefault(_utilsUnprefixProperty); var properties = { transition: true, transitionProperty: true }; function transition(_ref2) { var property = _ref2.property; var value = _ref2.value; var css = _ref2.prefix.css; var requiresPrefix = _ref2.requiresPrefix; var keepUnprefixed = _ref2.keepUnprefixed; // also check for already prefixed transitions var unprefixedProperty = (0, _utilsUnprefixProperty2['default'])(property); if (typeof value === 'string' && properties[unprefixedProperty]) { var _ret = function () { var requiresPrefixDashCased = Object.keys(requiresPrefix).map(function (prop) { return (0, _utilsCamelToDashCase2['default'])(prop); }); // only split multi values, not cubic beziers var multipleValues = value.split(/,(?![^()]*(?:\([^()]*\))?\))/g); requiresPrefixDashCased.forEach(function (property) { multipleValues.forEach(function (val, index) { if (val.indexOf(property) > -1) { multipleValues[index] = val.replace(property, css + property) + (keepUnprefixed ? ',' + val : ''); } }); }); return { v: _defineProperty({}, property, multipleValues.join(',')) }; }(); if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === 'object') return _ret.v; } } module.exports = exports['default']; /***/ }, /* 41 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = function (property) { var unprefixed = property.replace(/^(ms|Webkit|Moz|O)/, ''); return unprefixed.charAt(0).toLowerCase() + unprefixed.slice(1); }; module.exports = exports['default']; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = flexboxIE; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var _utilsCamelToDashCase = __webpack_require__(35); var _utilsCamelToDashCase2 = _interopRequireDefault(_utilsCamelToDashCase); var alternativeValues = { 'space-around': 'distribute', 'space-between': 'justify', 'flex-start': 'start', 'flex-end': 'end', flex: 'flexbox', 'inline-flex': 'inline-flexbox' }; var alternativeProps = { alignContent: 'msFlexLinePack', alignSelf: 'msFlexItemAlign', alignItems: 'msFlexAlign', justifyContent: 'msFlexPack', order: 'msFlexOrder', flexGrow: 'msFlexPositive', flexShrink: 'msFlexNegative', flexBasis: 'msPreferredSize' }; var properties = Object.keys(alternativeProps).reduce(function (result, prop) { result[prop] = true; return result; }, {}); function flexboxIE(_ref2) { var property = _ref2.property; var value = _ref2.value; var styles = _ref2.styles; var _ref2$browserInfo = _ref2.browserInfo; var browser = _ref2$browserInfo.browser; var version = _ref2$browserInfo.version; var css = _ref2.prefix.css; var keepUnprefixed = _ref2.keepUnprefixed; if ((properties[property] || property === 'display' && typeof value === 'string' && value.indexOf('flex') > -1) && (browser === 'ie_mob' || browser === 'ie') && version == 10) { if (!keepUnprefixed) { delete styles[property]; } if (property === 'display' && alternativeValues[value]) { return { display: css + alternativeValues[value] + (keepUnprefixed ? ';' + (0, _utilsCamelToDashCase2['default'])(property) + ':' + value : '') }; } if (alternativeProps[property]) { return _defineProperty({}, alternativeProps[property], alternativeValues[value] || value); } } } module.exports = exports['default']; /***/ }, /* 43 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = flexboxOld; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var _utilsCamelToDashCase = __webpack_require__(35); var _utilsCamelToDashCase2 = _interopRequireDefault(_utilsCamelToDashCase); var alternativeValues = { 'space-around': 'justify', 'space-between': 'justify', 'flex-start': 'start', 'flex-end': 'end', 'wrap-reverse': 'multiple', wrap: 'multiple', flex: 'box', 'inline-flex': 'inline-box' }; var alternativeProps = { alignItems: 'WebkitBoxAlign', justifyContent: 'WebkitBoxPack', flexWrap: 'WebkitBoxLines' }; var otherProps = ['alignContent', 'alignSelf', 'order', 'flexGrow', 'flexShrink', 'flexBasis', 'flexDirection']; var properties = Object.keys(alternativeProps).concat(otherProps).reduce(function (result, prop) { result[prop] = true; return result; }, {}); function flexboxOld(_ref2) { var property = _ref2.property; var value = _ref2.value; var styles = _ref2.styles; var _ref2$browserInfo = _ref2.browserInfo; var browser = _ref2$browserInfo.browser; var version = _ref2$browserInfo.version; var css = _ref2.prefix.css; var keepUnprefixed = _ref2.keepUnprefixed; if ((properties[property] || property === 'display' && typeof value === 'string' && value.indexOf('flex') > -1) && (browser === 'firefox' && version < 22 || browser === 'chrome' && version < 21 || (browser === 'safari' || browser === 'ios_saf') && version <= 6.1 || browser === 'android' && version < 4.4 || browser === 'and_uc')) { if (!keepUnprefixed) { delete styles[property]; } if (property === 'flexDirection') { return { WebkitBoxOrient: value.indexOf('column') > -1 ? 'vertical' : 'horizontal', WebkitBoxDirection: value.indexOf('reverse') > -1 ? 'reverse' : 'normal' }; } if (property === 'display' && alternativeValues[value]) { return { display: css + alternativeValues[value] + (keepUnprefixed ? ';' + (0, _utilsCamelToDashCase2['default'])(property) + ':' + value : '') }; } if (alternativeProps[property]) { return _defineProperty({}, alternativeProps[property], alternativeValues[value] || value); } } } module.exports = exports['default']; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _getStateKey = __webpack_require__(45); var _getStateKey2 = _interopRequireDefault(_getStateKey); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var getState = function getState(state, elementKey, value) { var key = (0, _getStateKey2.default)(elementKey); return !!state && !!state._radiumStyleState && !!state._radiumStyleState[key] && state._radiumStyleState[key][value]; }; exports.default = getState; module.exports = exports['default']; /***/ }, /* 45 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var getStateKey = function getStateKey(elementKey) { return elementKey === null || elementKey === undefined ? 'main' : elementKey.toString(); }; exports.default = getStateKey; module.exports = exports['default']; /***/ }, /* 46 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = hash; // a simple djb2 hash based on hash-string: // https://github.com/MatthewBarker/hash-string/blob/master/source/hash-string.js // returns a hex-encoded hash function hash(text) { if (!text) { return ''; } var hashValue = 5381; var index = text.length - 1; while (index) { hashValue = hashValue * 33 ^ text.charCodeAt(index); index -= 1; } return (hashValue >>> 0).toString(16); } module.exports = exports['default']; /***/ }, /* 47 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; exports.isNestedStyle = isNestedStyle; exports.mergeStyles = mergeStyles; function isNestedStyle(value) { // Don't merge objects overriding toString, since they should be converted // to string values. return value && value.constructor === Object && value.toString === Object.prototype.toString; } // Merge style objects. Deep merge plain object values. function mergeStyles(styles) { var result = {}; styles.forEach(function (style) { if (!style || (typeof style === 'undefined' ? 'undefined' : _typeof(style)) !== 'object') { return; } if (Array.isArray(style)) { style = mergeStyles(style); } Object.keys(style).forEach(function (key) { // Simple case, nothing nested if (!isNestedStyle(style[key]) || !isNestedStyle(result[key])) { result[key] = style[key]; return; } // If nested media, don't merge the nested styles, append a space to the // end (benign when converted to CSS). This way we don't end up merging // media queries that appear later in the chain with those that appear // earlier. if (key.indexOf('@media') === 0) { var newKey = key; while (true) { // eslint-disable-line no-constant-condition newKey += ' '; if (!result[newKey]) { result[newKey] = style[key]; return; } } } // Merge all other nested styles recursively result[key] = mergeStyles([result[key], style[key]]); }); }); return result; } /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _checkPropsPlugin = __webpack_require__(49); var _checkPropsPlugin2 = _interopRequireDefault(_checkPropsPlugin); var _keyframesPlugin = __webpack_require__(50); var _keyframesPlugin2 = _interopRequireDefault(_keyframesPlugin); var _mergeStyleArrayPlugin = __webpack_require__(51); var _mergeStyleArrayPlugin2 = _interopRequireDefault(_mergeStyleArrayPlugin); var _prefixPlugin = __webpack_require__(52); var _prefixPlugin2 = _interopRequireDefault(_prefixPlugin); var _removeNestedStylesPlugin = __webpack_require__(53); var _removeNestedStylesPlugin2 = _interopRequireDefault(_removeNestedStylesPlugin); var _resolveInteractionStylesPlugin = __webpack_require__(54); var _resolveInteractionStylesPlugin2 = _interopRequireDefault(_resolveInteractionStylesPlugin); var _resolveMediaQueriesPlugin = __webpack_require__(56); var _resolveMediaQueriesPlugin2 = _interopRequireDefault(_resolveMediaQueriesPlugin); var _visitedPlugin = __webpack_require__(57); var _visitedPlugin2 = _interopRequireDefault(_visitedPlugin); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { checkProps: _checkPropsPlugin2.default, keyframes: _keyframesPlugin2.default, mergeStyleArray: _mergeStyleArrayPlugin2.default, prefix: _prefixPlugin2.default, removeNestedStyles: _removeNestedStylesPlugin2.default, resolveInteractionStyles: _resolveInteractionStylesPlugin2.default, resolveMediaQueries: _resolveMediaQueriesPlugin2.default, visited: _visitedPlugin2.default }; /* eslint-disable block-scoped-const */ module.exports = exports['default']; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process) {'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _checkProps = function checkProps() {}; if (process.env.NODE_ENV !== 'production') { (function () { // Warn if you use longhand and shorthand properties in the same style // object. // https://developer.mozilla.org/en-US/docs/Web/CSS/Shorthand_properties var shorthandPropertyExpansions = { 'background': ['backgroundAttachment', 'backgroundBlendMode', 'backgroundClip', 'backgroundColor', 'backgroundImage', 'backgroundOrigin', 'backgroundPosition', 'backgroundPositionX', 'backgroundPositionY', 'backgroundRepeat', 'backgroundRepeatX', 'backgroundRepeatY', 'backgroundSize'], 'border': ['borderBottom', 'borderBottomColor', 'borderBottomStyle', 'borderBottomWidth', 'borderColor', 'borderLeft', 'borderLeftColor', 'borderLeftStyle', 'borderLeftWidth', 'borderRight', 'borderRightColor', 'borderRightStyle', 'borderRightWidth', 'borderStyle', 'borderTop', 'borderTopColor', 'borderTopStyle', 'borderTopWidth', 'borderWidth'], 'borderImage': ['borderImageOutset', 'borderImageRepeat', 'borderImageSlice', 'borderImageSource', 'borderImageWidth'], 'borderRadius': ['borderBottomLeftRadius', 'borderBottomRightRadius', 'borderTopLeftRadius', 'borderTopRightRadius'], 'font': ['fontFamily', 'fontKerning', 'fontSize', 'fontStretch', 'fontStyle', 'fontVariant', 'fontVariantLigatures', 'fontWeight', 'lineHeight'], 'listStyle': ['listStyleImage', 'listStylePosition', 'listStyleType'], 'margin': ['marginBottom', 'marginLeft', 'marginRight', 'marginTop'], 'padding': ['paddingBottom', 'paddingLeft', 'paddingRight', 'paddingTop'], 'transition': ['transitionDelay', 'transitionDuration', 'transitionProperty', 'transitionTimingFunction'] }; _checkProps = function checkProps(config) { var componentName = config.componentName; var style = config.style; if ((typeof style === 'undefined' ? 'undefined' : _typeof(style)) !== 'object' || !style) { return; } var styleKeys = Object.keys(style); styleKeys.forEach(function (styleKey) { if (Array.isArray(shorthandPropertyExpansions[styleKey]) && shorthandPropertyExpansions[styleKey].some(function (sp) { return styleKeys.indexOf(sp) !== -1; })) { if (process.env.NODE_ENV !== 'production') { /* eslint-disable no-console */ console.warn('Radium: property "' + styleKey + '" in style object', style, ': do not mix longhand and ' + 'shorthand properties in the same style object. Check the render ' + 'method of ' + componentName + '.', 'See https://github.com/FormidableLabs/radium/issues/95 for more ' + 'information.'); /* eslint-enable no-console */ } } }); styleKeys.forEach(function (k) { return _checkProps(_extends({}, config, { style: style[k] })); }); return; }; })(); } exports.default = _checkProps; module.exports = exports['default']; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(1))) /***/ }, /* 50 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = keyframesPlugin; function keyframesPlugin(_ref // eslint-disable-line no-shadow ) { var addCSS = _ref.addCSS; var config = _ref.config; var style = _ref.style; var newStyle = Object.keys(style).reduce(function (newStyleInProgress, key) { var value = style[key]; if (key === 'animationName' && value && value.__radiumKeyframes) { var keyframesValue = value; var _keyframesValue$__pro = keyframesValue.__process(config.userAgent); var animationName = _keyframesValue$__pro.animationName; var css = _keyframesValue$__pro.css; addCSS(css); value = animationName; } newStyleInProgress[key] = value; return newStyleInProgress; }, {}); return { style: newStyle }; } module.exports = exports['default']; /***/ }, /* 51 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); // Convenient syntax for multiple styles: `style={[style1, style2, etc]}` // Ignores non-objects, so you can do `this.state.isCool && styles.cool`. var mergeStyleArrayPlugin = function mergeStyleArrayPlugin(_ref) { var style = _ref.style; var mergeStyles = _ref.mergeStyles; // eslint-disable-line no-shadow var newStyle = Array.isArray(style) ? mergeStyles(style) : style; return { style: newStyle }; }; exports.default = mergeStyleArrayPlugin; module.exports = exports['default']; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = prefixPlugin; var _prefixer = __webpack_require__(11); function prefixPlugin(_ref // eslint-disable-line no-shadow ) { var config = _ref.config; var style = _ref.style; var newStyle = (0, _prefixer.getPrefixedStyle)(style, config.userAgent); return { style: newStyle }; } module.exports = exports['default']; /***/ }, /* 53 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = removeNestedStyles; function removeNestedStyles(_ref) { var isNestedStyle = _ref.isNestedStyle; var style = _ref.style; // eslint-disable-line no-shadow var newStyle = Object.keys(style).reduce(function (newStyleInProgress, key) { var value = style[key]; if (!isNestedStyle(value)) { newStyleInProgress[key] = value; } return newStyleInProgress; }, {}); return { style: newStyle }; } module.exports = exports['default']; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _mouseUpListener = __webpack_require__(55); var _mouseUpListener2 = _interopRequireDefault(_mouseUpListener); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var _isInteractiveStyleField = function _isInteractiveStyleField(styleFieldName) { return styleFieldName === ':hover' || styleFieldName === ':active' || styleFieldName === ':focus'; }; var resolveInteractionStyles = function resolveInteractionStyles(config) { var ExecutionEnvironment = config.ExecutionEnvironment; var getComponentField = config.getComponentField; var getState = config.getState; var mergeStyles = config.mergeStyles; var props = config.props; var setState = config.setState; var style = config.style; var newComponentFields = {}; var newProps = {}; // Only add handlers if necessary if (style[':hover']) { (function () { // Always call the existing handler if one is already defined. // This code, and the very similar ones below, could be abstracted a bit // more, but it hurts readability IMO. var existingOnMouseEnter = props.onMouseEnter; newProps.onMouseEnter = function (e) { existingOnMouseEnter && existingOnMouseEnter(e); setState(':hover', true); }; var existingOnMouseLeave = props.onMouseLeave; newProps.onMouseLeave = function (e) { existingOnMouseLeave && existingOnMouseLeave(e); setState(':hover', false); }; })(); } if (style[':active']) { (function () { var existingOnMouseDown = props.onMouseDown; newProps.onMouseDown = function (e) { existingOnMouseDown && existingOnMouseDown(e); newComponentFields._lastMouseDown = Date.now(); setState(':active', 'viamousedown'); }; var existingOnKeyDown = props.onKeyDown; newProps.onKeyDown = function (e) { existingOnKeyDown && existingOnKeyDown(e); if (e.key === ' ' || e.key === 'Enter') { setState(':active', 'viakeydown'); } }; var existingOnKeyUp = props.onKeyUp; newProps.onKeyUp = function (e) { existingOnKeyUp && existingOnKeyUp(e); if (e.key === ' ' || e.key === 'Enter') { setState(':active', false); } }; })(); } if (style[':focus']) { (function () { var existingOnFocus = props.onFocus; newProps.onFocus = function (e) { existingOnFocus && existingOnFocus(e); setState(':focus', true); }; var existingOnBlur = props.onBlur; newProps.onBlur = function (e) { existingOnBlur && existingOnBlur(e); setState(':focus', false); }; })(); } if (style[':active'] && !getComponentField('_radiumMouseUpListener') && ExecutionEnvironment.canUseEventListeners) { newComponentFields._radiumMouseUpListener = _mouseUpListener2.default.subscribe(function () { Object.keys(getComponentField('state')._radiumStyleState).forEach(function (key) { if (getState(':active', key) === 'viamousedown') { setState(':active', false, key); } }); }); } // Merge the styles in the order they were defined var interactionStyles = props.disabled ? [style[':disabled']] : Object.keys(style).filter(function (name) { return _isInteractiveStyleField(name) && getState(name); }).map(function (name) { return style[name]; }); var newStyle = mergeStyles([style].concat(interactionStyles)); // Remove interactive styles newStyle = Object.keys(newStyle).reduce(function (styleWithoutInteractions, name) { if (!_isInteractiveStyleField(name) && name !== ':disabled') { styleWithoutInteractions[name] = newStyle[name]; } return styleWithoutInteractions; }, {}); return { componentFields: newComponentFields, props: newProps, style: newStyle }; }; exports.default = resolveInteractionStyles; module.exports = exports['default']; /***/ }, /* 55 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _callbacks = []; var _mouseUpListenerIsActive = false; function _handleMouseUp() { _callbacks.forEach(function (callback) { callback(); }); } var subscribe = function subscribe(callback) { if (_callbacks.indexOf(callback) === -1) { _callbacks.push(callback); } if (!_mouseUpListenerIsActive) { window.addEventListener('mouseup', _handleMouseUp); _mouseUpListenerIsActive = true; } return { remove: function remove() { var index = _callbacks.indexOf(callback); _callbacks.splice(index, 1); if (_callbacks.length === 0 && _mouseUpListenerIsActive) { window.removeEventListener('mouseup', _handleMouseUp); _mouseUpListenerIsActive = false; } } }; }; exports.default = { subscribe: subscribe, __triggerForTests: _handleMouseUp }; module.exports = exports['default']; /***/ }, /* 56 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; exports.default = resolveMediaQueries; var _windowMatchMedia = void 0; function _getWindowMatchMedia(ExecutionEnvironment) { if (_windowMatchMedia === undefined) { _windowMatchMedia = !!ExecutionEnvironment.canUseDOM && !!window && !!window.matchMedia && function (mediaQueryString) { return window.matchMedia(mediaQueryString); } || null; } return _windowMatchMedia; } function _filterObject(obj, predicate) { return Object.keys(obj).filter(function (key) { return predicate(obj[key], key); }).reduce(function (result, key) { result[key] = obj[key]; return result; }, {}); } function _removeMediaQueries(style) { return Object.keys(style).reduce(function (styleWithoutMedia, key) { if (key.indexOf('@media') !== 0) { styleWithoutMedia[key] = style[key]; } return styleWithoutMedia; }, {}); } function _topLevelRulesToCSS(_ref) { var addCSS = _ref.addCSS; var appendImportantToEachValue = _ref.appendImportantToEachValue; var cssRuleSetToString = _ref.cssRuleSetToString; var hash = _ref.hash; var isNestedStyle = _ref.isNestedStyle; var style = _ref.style; var userAgent = _ref.userAgent; var className = ''; Object.keys(style).filter(function (name) { return name.indexOf('@media') === 0; }).map(function (query) { var topLevelRules = appendImportantToEachValue(_filterObject(style[query], function (value) { return !isNestedStyle(value); })); if (!Object.keys(topLevelRules).length) { return; } var ruleCSS = cssRuleSetToString('', topLevelRules, userAgent); // CSS classes cannot start with a number var mediaQueryClassName = 'rmq-' + hash(query + ruleCSS); var css = query + '{ .' + mediaQueryClassName + ruleCSS + '}'; addCSS(css); className += (className ? ' ' : '') + mediaQueryClassName; }); return className; } function _subscribeToMediaQuery(_ref2) { var listener = _ref2.listener; var listenersByQuery = _ref2.listenersByQuery; var matchMedia = _ref2.matchMedia; var mediaQueryListsByQuery = _ref2.mediaQueryListsByQuery; var query = _ref2.query; query = query.replace('@media ', ''); var mql = mediaQueryListsByQuery[query]; if (!mql && matchMedia) { mediaQueryListsByQuery[query] = mql = matchMedia(query); } if (!listenersByQuery || !listenersByQuery[query]) { mql.addListener(listener); listenersByQuery[query] = { remove: function remove() { mql.removeListener(listener); } }; } return mql; } function resolveMediaQueries(_ref3) { var ExecutionEnvironment = _ref3.ExecutionEnvironment; var addCSS = _ref3.addCSS; var appendImportantToEachValue = _ref3.appendImportantToEachValue; var config = _ref3.config; var cssRuleSetToString = _ref3.cssRuleSetToString; var getComponentField = _ref3.getComponentField; var getGlobalState = _ref3.getGlobalState; var hash = _ref3.hash; var isNestedStyle = _ref3.isNestedStyle; var mergeStyles = _ref3.mergeStyles; var props = _ref3.props; var setState = _ref3.setState; var style = _ref3.style; // eslint-disable-line no-shadow var newStyle = _removeMediaQueries(style); var mediaQueryClassNames = _topLevelRulesToCSS({ addCSS: addCSS, appendImportantToEachValue: appendImportantToEachValue, cssRuleSetToString: cssRuleSetToString, hash: hash, isNestedStyle: isNestedStyle, style: style, userAgent: config.userAgent }); var newProps = mediaQueryClassNames ? { className: mediaQueryClassNames + (props.className ? ' ' + props.className : '') } : null; var matchMedia = config.matchMedia || _getWindowMatchMedia(ExecutionEnvironment); if (!matchMedia) { return { props: newProps, style: newStyle }; } var listenersByQuery = _extends({}, getComponentField('_radiumMediaQueryListenersByQuery')); var mediaQueryListsByQuery = getGlobalState('mediaQueryListsByQuery') || {}; Object.keys(style).filter(function (name) { return name.indexOf('@media') === 0; }).map(function (query) { var nestedRules = _filterObject(style[query], isNestedStyle); if (!Object.keys(nestedRules).length) { return; } var mql = _subscribeToMediaQuery({ listener: function listener() { return setState(query, mql.matches, '_all'); }, listenersByQuery: listenersByQuery, matchMedia: matchMedia, mediaQueryListsByQuery: mediaQueryListsByQuery, query: query }); // Apply media query states if (mql.matches) { newStyle = mergeStyles([newStyle, nestedRules]); } }); return { componentFields: { _radiumMediaQueryListenersByQuery: listenersByQuery }, globalState: { mediaQueryListsByQuery: mediaQueryListsByQuery }, props: newProps, style: newStyle }; } module.exports = exports['default']; /***/ }, /* 57 */ /***/ function(module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = visited; function visited(_ref) { var addCSS = _ref.addCSS; var appendImportantToEachValue = _ref.appendImportantToEachValue; var config = _ref.config; var cssRuleSetToString = _ref.cssRuleSetToString; var hash = _ref.hash; var props = _ref.props; var style = _ref.style; // eslint-disable-line no-shadow var className = props.className; var newStyle = Object.keys(style).reduce(function (newStyleInProgress, key) { var value = style[key]; if (key === ':visited') { value = appendImportantToEachValue(value); var ruleCSS = cssRuleSetToString('', value, config.userAgent); var visitedClassName = 'rad-' + hash(ruleCSS); var css = '.' + visitedClassName + ':visited' + ruleCSS; addCSS(css); className = (className ? className + ' ' : '') + visitedClassName; } else { newStyleInProgress[key] = value; } return newStyleInProgress; }, {}); return { props: className === props.className ? null : { className: className }, style: newStyle }; } module.exports = exports['default']; /***/ }, /* 58 */ /***/ function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; /*! Copyright (c) 2015 Jed Watson. Based on code that is Copyright 2013-2015, Facebook, Inc. All rights reserved. */ /* global define */ (function () { 'use strict'; var canUseDOM = !!(typeof window !== 'undefined' && window.document && window.document.createElement); var ExecutionEnvironment = { canUseDOM: canUseDOM, canUseWorkers: typeof Worker !== 'undefined', canUseEventListeners: canUseDOM && !!(window.addEventListener || window.attachEvent), canUseViewport: canUseDOM && !!window.screen }; if ("function" === 'function' && _typeof(__webpack_require__(59)) === 'object' && __webpack_require__(59)) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function () { return ExecutionEnvironment; }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module !== 'undefined' && module.exports) { module.exports = ExecutionEnvironment; } else { window.ExecutionEnvironment = ExecutionEnvironment; } })(); /***/ }, /* 59 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {module.exports = __webpack_amd_options__; /* WEBPACK VAR INJECTION */}.call(exports, {})) /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _cssRuleSetToString = __webpack_require__(9); var _cssRuleSetToString2 = _interopRequireDefault(_cssRuleSetToString); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Style = _react2.default.createClass({ displayName: 'Style', propTypes: { radiumConfig: _react.PropTypes.object, rules: _react.PropTypes.object, scopeSelector: _react.PropTypes.string }, contextTypes: { _radiumConfig: _react.PropTypes.object }, getDefaultProps: function getDefaultProps() { return { scopeSelector: '' }; }, _buildStyles: function _buildStyles(styles) { var _this = this; var userAgent = this.props.radiumConfig && this.props.radiumConfig.userAgent || this.context && this.context._radiumConfig && this.context._radiumConfig.userAgent; var scopeSelector = this.props.scopeSelector; var rootRules = Object.keys(styles).reduce(function (accumulator, selector) { if (_typeof(styles[selector]) !== 'object') { accumulator[selector] = styles[selector]; } return accumulator; }, {}); var rootStyles = Object.keys(rootRules).length ? (0, _cssRuleSetToString2.default)(scopeSelector || '', rootRules, userAgent) : ''; return rootStyles + Object.keys(styles).reduce(function (accumulator, selector) { var rules = styles[selector]; if (selector === 'mediaQueries') { accumulator += _this._buildMediaQueryString(rules); } else if (_typeof(styles[selector]) === 'object') { var completeSelector = scopeSelector ? selector.split(',').map(function (part) { return scopeSelector + ' ' + part.trim(); }).join(',') : selector; accumulator += (0, _cssRuleSetToString2.default)(completeSelector, rules, userAgent); } return accumulator; }, ''); }, _buildMediaQueryString: function _buildMediaQueryString(stylesByMediaQuery) { var _this2 = this; var mediaQueryString = ''; Object.keys(stylesByMediaQuery).forEach(function (query) { mediaQueryString += '@media ' + query + '{' + _this2._buildStyles(stylesByMediaQuery[query]) + '}'; }); return mediaQueryString; }, render: function render() { if (!this.props.rules) { return null; } var styles = this._buildStyles(this.props.rules); return _react2.default.createElement('style', { dangerouslySetInnerHTML: { __html: styles } }); } }); exports.default = Style; module.exports = exports['default']; /***/ }, /* 61 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _enhancer = __webpack_require__(2); var _enhancer2 = _interopRequireDefault(_enhancer); var _styleKeeper = __webpack_require__(4); var _styleKeeper2 = _interopRequireDefault(_styleKeeper); var _styleSheet = __webpack_require__(62); var _styleSheet2 = _interopRequireDefault(_styleSheet); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _getStyleKeeper(instance) { if (!instance._radiumStyleKeeper) { var userAgent = instance.props.radiumConfig && instance.props.radiumConfig.userAgent || instance.context._radiumConfig && instance.context._radiumConfig.userAgent; instance._radiumStyleKeeper = new _styleKeeper2.default(userAgent); } return instance._radiumStyleKeeper; } var StyleRoot = function (_Component) { _inherits(StyleRoot, _Component); function StyleRoot() { _classCallCheck(this, StyleRoot); var _this = _possibleConstructorReturn(this, _Component.apply(this, arguments)); _getStyleKeeper(_this); return _this; } StyleRoot.prototype.getChildContext = function getChildContext() { return { _radiumStyleKeeper: _getStyleKeeper(this) }; }; StyleRoot.prototype.render = function render() { return _react2.default.createElement( 'div', this.props, this.props.children, _react2.default.createElement(_styleSheet2.default, null) ); }; return StyleRoot; }(_react.Component); StyleRoot.contextTypes = { _radiumConfig: _react.PropTypes.object, _radiumStyleKeeper: _react.PropTypes.instanceOf(_styleKeeper2.default) }; StyleRoot.childContextTypes = { _radiumStyleKeeper: _react.PropTypes.instanceOf(_styleKeeper2.default) }; StyleRoot = (0, _enhancer2.default)(StyleRoot); exports.default = StyleRoot; module.exports = exports['default']; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = undefined; var _class, _temp; var _react = __webpack_require__(3); var _react2 = _interopRequireDefault(_react); var _styleKeeper = __webpack_require__(4); var _styleKeeper2 = _interopRequireDefault(_styleKeeper); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var StyleSheet = (_temp = _class = function (_Component) { _inherits(StyleSheet, _Component); function StyleSheet() { _classCallCheck(this, StyleSheet); var _this = _possibleConstructorReturn(this, _Component.apply(this, arguments)); _this.state = _this._getCSSState(); _this._onChange = _this._onChange.bind(_this); return _this; } StyleSheet.prototype.componentDidMount = function componentDidMount() { this._isMounted = true; this._subscription = this.context._radiumStyleKeeper.subscribe(this._onChange); this._onChange(); }; StyleSheet.prototype.componentWillUnmount = function componentWillUnmount() { this._isMounted = false; if (this._subscription) { this._subscription.remove(); } }; StyleSheet.prototype._getCSSState = function _getCSSState() { return { css: this.context._radiumStyleKeeper.getCSS() }; }; StyleSheet.prototype._onChange = function _onChange() { var _this2 = this; setTimeout(function () { _this2._isMounted && _this2.setState(_this2._getCSSState()); }, 0); }; StyleSheet.prototype.render = function render() { return _react2.default.createElement('style', { dangerouslySetInnerHTML: { __html: this.state.css } }); }; return StyleSheet; }(_react.Component), _class.contextTypes = { _radiumStyleKeeper: _react2.default.PropTypes.instanceOf(_styleKeeper2.default) }, _temp); exports.default = StyleSheet; module.exports = exports['default']; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = keyframes; var _cssRuleSetToString = __webpack_require__(9); var _cssRuleSetToString2 = _interopRequireDefault(_cssRuleSetToString); var _hash = __webpack_require__(46); var _hash2 = _interopRequireDefault(_hash); var _prefixer = __webpack_require__(11); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function keyframes(keyframeRules, name) { return { __radiumKeyframes: true, __process: function __process(userAgent) { var keyframesPrefixed = (0, _prefixer.getPrefixedKeyframes)(userAgent); var rules = Object.keys(keyframeRules).map(function (percentage) { return (0, _cssRuleSetToString2.default)(percentage, keyframeRules[percentage], userAgent); }).join('\n'); var animationName = (name ? name + '-' : '') + 'radium-animation-' + (0, _hash2.default)(rules); var css = '@' + keyframesPrefixed + ' ' + animationName + ' {\n' + rules + '\n}\n'; return { css: css, animationName: animationName }; } }; } module.exports = exports['default']; /***/ } /******/ ]) }); ;
src/modules/xman/components/FlightList/Cop.js
devteamreims/4me.react
import React from 'react'; import moment from 'moment'; import ToneDowner from './ToneDowner'; const Cop = ({name, targetTime, overrideText}) => { const tto = moment.utc(targetTime); const estimates = tto.format('HH:mm'); return ( <div style={{flexDirection: 'column'}}> <ToneDowner path="cop" value={name} > <span>{name}</span> </ToneDowner> <div>{overrideText || estimates}</div> </div> ); }; Cop.propTypes = { name: React.PropTypes.string.isRequired, targetTime: React.PropTypes.string.isRequired, estimatedTime: React.PropTypes.string.isRequired, overrideText: React.PropTypes.string, }; export default Cop;
docs/src/app/components/pages/discover-more/Community.js
barakmitz/material-ui
import React from 'react'; import Title from 'react-title-component'; import MarkdownElement from '../../MarkdownElement'; import communityText from './community.md'; const Community = () => ( <div> <Title render={(previousTitle) => `Community - ${previousTitle}`} /> <MarkdownElement text={communityText} /> </div> ); export default Community;
client/js/morpheus/casts/factory.js
CaptEmulation/webgl-pano
import React from 'react'; import { head, once, tail, reverse, wrap, } from 'lodash'; import { createSelector } from 'reselect'; import { selectors as sceneSelectors, getSceneType, } from 'morpheus/scene'; import { decorate as faderDecorator } from './components/Fader'; import Special from './components/Special'; import Pano from './components/Pano'; import Sound from './components/Sound'; function createSceneMapper(map) { return sceneData => map[getSceneType(sceneData)]; } export const createLiveSceneSelector = createSceneMapper({ panorama: Pano, special: Special, }); export const createEnteringSceneSelector = createSceneMapper({ panorama: Pano, }); export const createExitingSceneSelector = createSceneMapper({ panorama: Pano, special: Special, }); // wrap...once creates a lazy init selector to break a circular dependency export default wrap(once(() => createSelector( sceneSelectors.currentScenesData, sceneSelectors.isEntering, sceneSelectors.isLive, sceneSelectors.isExiting, sceneSelectors.dissolve, (_currentScenes, _isEntering, _isLive, _isExiting, dissolve) => { const currentScenes = _currentScenes.toJS(); let scenes = []; const current = head(currentScenes); const previouses = reverse(tail(currentScenes)); const CurrentScene = createLiveSceneSelector(current); const EnteringScene = createEnteringSceneSelector(current); const CurrentExitingScene = createExitingSceneSelector(current); const PreviousScenes = previouses.map(createExitingSceneSelector); let previousScene; if (PreviousScenes.length) { previousScene = PreviousScenes.map((PreviousScene, index) => ( <PreviousScene key={`scene${previouses[index].sceneId}`} scene={previouses[index]} /> )); scenes = scenes.concat(previousScene); } if (_isLive && CurrentScene) { if (previousScene && dissolve) { const Fader = faderDecorator(<CurrentScene scene={current} />); scenes.push(<Fader key={`scene${current.sceneId}`} />); } else { scenes.push(<CurrentScene key={`scene${current.sceneId}`} scene={current} />); } } if (_isEntering && EnteringScene) { scenes.push(<EnteringScene key={`scene${current.sceneId}`} scene={current} />); } if (_isExiting && CurrentExitingScene) { scenes.push(<CurrentExitingScene key={`scene${current.sceneId}`} scene={current} />); } scenes.push(<Sound key="sound" scene={current} />); return scenes; }, )), (selectorFactory, state) => selectorFactory()(state));
__tests__/components/Timer.spec.js
kawikadkekahuna/Hue-Pomodoro
import React from 'react'; import { shallow } from 'enzyme'; import toJson from 'enzyme-to-json'; import Timer from '../../app/components/Timer'; describe('Timer Component', () => { test('has correct default state', () => { const tree = shallow(<Timer />); expect(toJson(tree)).toMatchSnapshot(); }); test('correctly returns seconds text', () => { const tree = shallow(<Timer />); expect(tree.instance().getSeconds(60)).toEqual('00'); expect(tree.instance().getSeconds(59)).toEqual(59); }); });
files/rxjs/2.2.17/rx.lite.js
perosb/jsdelivr
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: {} }; // Defaults function noop() { } function identity(x) { return x; } var defaultNow = Date.now; function defaultComparer(x, y) { return isEqual(x, y); } function defaultSubComparer(x, y) { return x - y; } function defaultKeySerializer(x) { return x.toString(); } function defaultError(err) { throw err; } function isPromise(p) { return typeof p.then === 'function' && p.then !== Rx.Observable.prototype.then; } // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'object' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = { done: true, value: undefined }; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } function isFunction(value) { return typeof value == 'function'; } // 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; } if (old) { old.dispose(); } if (shouldDispose && value) { value.dispose(); } }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } if (old) { old.dispose(); } }; return BooleanDisposable; }()); /** * Represents a disposable resource which only allows a single assignment of its underlying disposable resource. * If an underlying disposable resource has already been set, future attempts to set the underlying disposable resource will throw an Error. */ var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function (super_) { inherits(SingleAssignmentDisposable, super_); function SingleAssignmentDisposable() { super_.call(this, true); } return SingleAssignmentDisposable; }(BooleanDisposable)); /** * Represents a disposable resource whose underlying disposable resource can be replaced by another disposable resource, causing automatic disposal of the previous underlying disposable resource. */ var SerialDisposable = Rx.SerialDisposable = (function (super_) { inherits(SerialDisposable, super_); function SerialDisposable() { super_.call(this, false); } return SerialDisposable; }(BooleanDisposable)); /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); 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 a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, function () { action(); }); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ schedulerProto.schedulePeriodicWithState = function (state, period, action) { var s = state, id = setInterval(function () { s = action(s); }, period); return disposableCreate(function () { clearInterval(id); }); }; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, function (s, p) { return invokeRecImmediate(s, p); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, function (_action, self) { _action(function (dt) { self(_action, dt); }); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { if (timeSpan < 0) { timeSpan = 0; } return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt), t; if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return queue === null; }; currentScheduler.ensureTrampoline = function (action) { if (queue === null) { return this.schedule(action); } else { return action(); } }; return currentScheduler; }()); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; (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); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } var NotificationPrototype = Notification.prototype; /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ NotificationPrototype.accept = function (observerOrOnNext, onError, onCompleted) { if (arguments.length === 1 && typeof observerOrOnNext === 'object') { return this._acceptObservable(observerOrOnNext); } return this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notification * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ NotificationPrototype.toObservable = function (scheduler) { var notification = this; scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); if (notification.kind === 'N') { observer.onCompleted(); } }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (exception) { var notification = new Notification('E'); notification.exception = exception; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentItem.value.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; } var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentItem.value.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)); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * * @static * @memberOf Observer * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler) { return new AnonymousObserver(function (x) { return handler(notificationCreateOnNext(x)); }, function (exception) { return handler(notificationCreateOnError(exception)); }, function () { return handler(notificationCreateOnCompleted()); }); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (_super) { inherits(AbstractObserver, _super); /** * Creates a new observer in a non-stopped state. * * @constructor */ function AbstractObserver() { this.isStopped = false; _super.call(this); } /** * Notifies the observer of a new element in the sequence. * * @memberOf AbstractObserver * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * * @memberOf AbstractObserver * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (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 observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { /** * @constructor * @private */ function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; observableProto.finalValue = function () { var source = this; return new AnonymousObservable(function (observer) { var hasValue = false, value; return source.subscribe(function (x) { hasValue = true; value = x; }, observer.onError.bind(observer), function () { if (!hasValue) { observer.onError(new Error(sequenceContainsNoElements)); } else { observer.onNext(value); observer.onCompleted(); } }); }); }; /** * Subscribes an observer to the observable sequence. * * @example * 1 - source.subscribe(); * 2 - source.subscribe(observer); * 3 - source.subscribe(function (x) { console.log(x); }); * 4 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }); * 5 - source.subscribe(function (x) { console.log(x); }, function (err) { console.log(err); }, function () { console.log('done'); }); * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { var subscriber; if (typeof observerOrOnNext === 'object') { subscriber = observerOrOnNext; } else { subscriber = observerCreate(observerOrOnNext, onError, onCompleted); } return this._subscribe(subscriber); }; /** * Creates a list from an observable sequence. * * @memberOf Observable * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { function accumulator(list, i) { var newList = list.slice(0); newList.push(i); return newList; } return this.scan([], accumulator).startWith([]).finalValue(); }; return Observable; })(); 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)); /** * 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. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0; return scheduler.scheduleRecursive(function (self) { if (count < array.length) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an iterable into an Observable sequence * * @example * var res = Rx.Observable.fromIterable(new Map()); * var res = Rx.Observable.fromIterable(new Set(), Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given generator sequence. */ Observable.fromIterable = function (iterable, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var iterator; try { iterator = iterable[$iterator$](); } catch (e) { observer.onError(e); return; } return scheduler.scheduleRecursive(function (self) { var next; try { next = iterator.next(); } catch (err) { observer.onError(err); return; } if (next.done) { observer.onCompleted(); } else { observer.onNext(next.value); self(); } }); }); }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var first = true, state = initialState; return scheduler.scheduleRecursive(function (self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); } } catch (exception) { observer.onError(exception); return; } if (hasResult) { observer.onNext(result); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { scheduler || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { scheduler || (scheduler = currentThreadScheduler); if (repeatCount == null) { repeatCount = -1; } return observableReturn(value, scheduler).repeat(repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = function (value, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwException' for browsers <IE9. * * @example * var res = Rx.Observable.throwException(new Error('Error')); * var res = Rx.Observable.throwException(new Error('Error'), Rx.Scheduler.timeout); * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = function (exception, scheduler) { scheduler || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @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) { if (typeof handlerOrSecond === 'function') { return observableCatchHandler(this, handlerOrSecond); } return observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.catchException(xs, ys, zs); * 2 - res = Rx.Observable.catchException([xs, ys, zs]); * @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 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 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) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(args[i].subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @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; }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable} other The observable sequence that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { if (isOpen) { observer.onNext(left); } }, observer.onError.bind(observer), function () { if (isOpen) { observer.onCompleted(); } })); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @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} other Observable sequence that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); var next = function (i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @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); }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * * @example * var res = observable.doAction(observer); * var res = observable.doAction(onNext); * var res = observable.doAction(onNext, onError); * var res = observable.doAction(onNext, onError, onCompleted); * @param {Mixed} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (exception) { if (!onError) { observer.onError(exception); } else { try { onError(exception); } catch (e) { observer.onError(e); } observer.onError(exception); } }, function () { if (!onCompleted) { observer.onCompleted(); } else { try { onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); } }); }); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription = source.subscribe(observer); return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(42); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { try { if (!hasValue) { hasValue = true; } if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { if (!hasValue && hasSeed) { observer.onNext(seed); } observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { observer.onNext(q.shift()); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * * @memberOf Observable# * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && 'now' in Object(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableFor([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence, using an optional scheduler to drain the queue. * * @example * var res = source.takeLast(5); * var res = source.takeLast(5, Rx.Scheduler.timeout); * * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @param {Scheduler} [scheduler] Scheduler used to drain the queue upon completion of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count, scheduler) { return this.takeLastBuffer(count).selectMany(function (xs) { return observableFromArray(xs, scheduler); }); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); if (q.length > count) { q.shift(); } }, observer.onError.bind(observer), function () { observer.onNext(q); observer.onCompleted(); }); }); }; /** * Projects each element of an observable sequence into 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)); }); }; function selectMany(selector) { return this.select(function (x, i) { var result = selector(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. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector) { if (resultSelector) { return this.selectMany(function (x, i) { var selectorResult = selector(x, i), result = isPromise(selectorResult) ? observableFromPromise(selectorResult) : selectorResult; return result.select(function (y) { return resultSelector(x, y, i); }); }); } if (typeof selector === 'function') { return selectMany.call(this, selector); } return selectMany.call(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } if (running) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new Error(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining > 0) { remaining--; observer.onNext(x); if (remaining === 0) { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * * @example * var res = source.takeWhile(function (value) { return value < 10; }); * var res = source.takeWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (exception) { observer.onError(exception); return; } if (shouldRun) { observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = immediateScheduler); return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } } else { if (results.length === 1) { results = results[0]; } } observer.onNext(results); observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, scheduler, context, selector) { scheduler || (scheduler = immediateScheduler); return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } } else { if (results.length === 1) { results = results[0]; } } observer.onNext(results); observer.onCompleted(); } args.push(handler); func.apply(context, args); }); }); }; }; function createListener (element, name, handler) { // Node.js specific if (element.addListener) { element.addListener(name, handler); return disposableCreate(function () { element.removeListener(name, handler); }); } else if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (el && el.length) { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el[i], eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * 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) { 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 */ Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return new AnonymousObservable(function (observer) { promise.then( function (value) { observer.onNext(value); observer.onCompleted(); }, function (reason) { observer.onError(reason); }); }); }; /* * 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); } }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : 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 ConnectableObservable = Rx.ConnectableObservable = (function (_super) { inherits(ConnectableObservable, _super); /** * @constructor * @private */ function ConnectableObservable(source, subject) { var state = { subject: subject, source: source.asObservable(), hasSubscription: false, subscription: null }; this.connect = function () { if (!state.hasSubscription) { state.hasSubscription = true; state.subscription = new CompositeDisposable(state.source.subscribe(state.subject), disposableCreate(function () { state.hasSubscription = false; })); } return state.subscription; }; function subscribe(observer) { return state.subject.subscribe(observer); } _super.call(this, subscribe); } /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.connect = function () { return this.connect(); }; /** * @private * @memberOf ConnectableObservable */ ConnectableObservable.prototype.refCount = function () { var connectableSubscription = null, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect, subscription; count++; shouldConnect = count === 1; subscription = source.subscribe(observer); if (shouldConnect) { connectableSubscription = source.connect(); } return disposableCreate(function () { subscription.dispose(); count--; if (count === 0) { connectableSubscription.dispose(); } }); }); }; return ConnectableObservable; }(Observable)); function observableTimerTimeSpan(dueTime, scheduler) { var d = normalizeTime(dueTime); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(d, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { if (dueTime === period) { return new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }); } return observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { scheduler || (scheduler = timeoutScheduler); return observableTimerTimeSpanAndPeriod(period, period, scheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * * @example * var res = Rx.Observable.timer(5000); * var res = Rx.Observable.timer(5000, 1000); * var res = Rx.Observable.timer(5000, Rx.Scheduler.timeout); * var res = Rx.Observable.timer(5000, 1000, Rx.Scheduler.timeout); * * @param {Number} dueTime Relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; scheduler || (scheduler = timeoutScheduler); if (typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (typeof periodOrScheduler === 'object' && 'now' in periodOrScheduler) { scheduler = periodOrScheduler; } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * var res = Rx.Observable.delay(5000); * var res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return this.throttleWithSelector(function () { return observableTimer(dueTime, scheduler); }) }; /** * Records the time interval between consecutive values in an observable sequence. * * @example * 1 - res = source.timeInterval(); * 2 - res = source.timeInterval(Rx.Scheduler.timeout); * * @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with time interval information on values. */ observableProto.timeInterval = function (scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return observableDefer(function () { var last = scheduler.now(); return source.select(function (x) { var now = scheduler.now(), span = now - last; last = now; return { value: x, interval: span }; }); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { scheduler || (scheduler = timeoutScheduler); return this.select(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } if (atEnd) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { scheduler || (scheduler = timeoutScheduler); if (typeof intervalOrSampler === 'number') { return sampleObservable(this, observableinterval(intervalOrSampler, scheduler)); } return sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * * @example * 1 - res = source.timeout(new Date()); // As a date * 2 - res = source.timeout(5000); // 5 seconds * 3 - res = source.timeout(new Date(), Rx.Observable.returnValue(42)); // As a date and timeout observable * 4 - res = source.timeout(5000, Rx.Observable.returnValue(42)); // 5 seconds and timeout observable * 5 - res = source.timeout(new Date(), Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // As a date and timeout observable * 6 - res = source.timeout(5000, Rx.Observable.returnValue(42), Rx.Scheduler.timeout); // 5 seconds and timeout observable * * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { var schedulerMethod, source = this; other || (other = observableThrow(new Error('Timeout'))); scheduler || (scheduler = timeoutScheduler); if (dueTime instanceof Date) { schedulerMethod = function (dt, action) { scheduler.scheduleWithAbsolute(dt, action); }; } else { schedulerMethod = function (dt, action) { scheduler.scheduleWithRelative(dt, action); }; } return new AnonymousObservable(function (observer) { var createTimer, id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); createTimer = function () { var myId = id; timer.setDisposable(schedulerMethod(dueTime, function () { switched = id === myId; var timerWins = switched; if (timerWins) { subscription.setDisposable(other.subscribe(observer)); } })); }; createTimer(); original.setDisposable(source.subscribe(function (x) { var onNextWins = !switched; if (onNextWins) { id++; observer.onNext(x); createTimer(); } }, function (e) { var onErrorWins = !switched; if (onErrorWins) { id++; observer.onError(e); } }, function () { var onCompletedWins = !switched; if (onCompletedWins) { 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.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.generateWithTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) { scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var first = true, hasResult = false, result, state = initialState, time; return scheduler.scheduleRecursiveWithRelative(0, function (self) { if (hasResult) { observer.onNext(result); } try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); if (hasResult) { result = resultSelector(state); time = timeSelector(state); } } catch (e) { observer.onError(e); return; } if (hasResult) { self(time); } else { observer.onCompleted(); } }); }); }; /** * Time shifts the observable sequence by delaying the subscription. * * @example * 1 - res = source.delaySubscription(5000); // 5s * 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Number} dueTime Absolute or relative time to perform the subscription at. * @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delaySubscription = function (dueTime, scheduler) { scheduler || (scheduler = timeoutScheduler); return this.delayWithSelector(observableTimer(dueTime, scheduler), function () { return observableEmpty(); }); }; /** * Time shifts the observable sequence based on a subscription delay and a delay selector function for each element. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only * 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector * * @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source. * @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element. * @returns {Observable} Time-shifted sequence. */ observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) { var source = this, subDelay, selector; if (typeof subscriptionDelay === 'function') { selector = subscriptionDelay; } else { subDelay = subscriptionDelay; selector = delayDurationSelector; } return new AnonymousObservable(function (observer) { var delays = new CompositeDisposable(), atEnd = false, done = function () { if (atEnd && delays.length === 0) { observer.onCompleted(); } }, subscription = new SerialDisposable(), start = function () { subscription.setDisposable(source.subscribe(function (x) { var delay; try { delay = selector(x); } catch (error) { observer.onError(error); return; } var d = new SingleAssignmentDisposable(); delays.add(d); d.setDisposable(delay.subscribe(function () { observer.onNext(x); delays.remove(d); done(); }, observer.onError.bind(observer), function () { observer.onNext(x); delays.remove(d); done(); })); }, observer.onError.bind(observer), function () { atEnd = true; subscription.dispose(); done(); })); }; if (!subDelay) { start(); } else { subscription.setDisposable(subDelay.subscribe(function () { start(); }, observer.onError.bind(observer), function () { start(); })); } return new CompositeDisposable(subscription, delays); }); }; /** * Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled. * * @example * 1 - res = source.timeoutWithSelector(Rx.Observable.timer(500)); * 2 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }); * 3 - res = source.timeoutWithSelector(Rx.Observable.timer(500), function (x) { return Rx.Observable.timer(200); }, Rx.Observable.returnValue(42)); * * @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never(). * @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element. * @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException(). * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) { if (arguments.length === 1) { timeoutdurationSelector = firstTimeout; var firstTimeout = observableNever(); } other || (other = observableThrow(new Error('Timeout'))); var source = this; return new AnonymousObservable(function (observer) { var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable(); subscription.setDisposable(original); var id = 0, switched = false, setTimer = function (timeout) { var myId = id, timerWins = function () { return id === myId; }; var d = new SingleAssignmentDisposable(); timer.setDisposable(d); d.setDisposable(timeout.subscribe(function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } d.dispose(); }, function (e) { if (timerWins()) { observer.onError(e); } }, function () { if (timerWins()) { subscription.setDisposable(other.subscribe(observer)); } })); }; setTimer(firstTimeout); var observerWins = function () { var res = !switched; if (res) { id++; } return res; }; original.setDisposable(source.subscribe(function (x) { if (observerWins()) { observer.onNext(x); var timeout; try { timeout = timeoutdurationSelector(x); } catch (e) { observer.onError(e); return; } setTimer(timeout); } }, function (e) { if (observerWins()) { observer.onError(e); } }, function () { if (observerWins()) { observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; /** * Ignores values from an observable sequence which are followed by another value within a computed throttle duration. * * @example * 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(x + x); }); * * @param {Function} throttleDurationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element. * @returns {Observable} The throttled sequence. */ observableProto.throttleWithSelector = function (throttleDurationSelector) { var source = this; return new AnonymousObservable(function (observer) { var value, hasValue = false, cancelable = new SerialDisposable(), id = 0, subscription = source.subscribe(function (x) { var throttle; try { throttle = throttleDurationSelector(x); } catch (e) { observer.onError(e); return; } hasValue = true; value = x; id++; var currentid = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(throttle.subscribe(function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); }, observer.onError.bind(observer), function () { if (hasValue && id === currentid) { observer.onNext(value); } hasValue = false; d.dispose(); })); }, function (e) { cancelable.dispose(); observer.onError(e); hasValue = false; id++; }, function () { cancelable.dispose(); if (hasValue) { observer.onNext(value); } observer.onCompleted(); hasValue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * 1 - res = source.skipLastWithTime(5000); * 2 - res = source.skipLastWithTime(5000, scheduler); * * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for skipping elements from the end of the sequence. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence. */ observableProto.skipLastWithTime = function (duration, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } }, observer.onError.bind(observer), function () { var now = scheduler.now(); while (q.length > 0 && now - q[0].interval >= duration) { observer.onNext(q.shift().value); } observer.onCompleted(); }); }); }; /** * Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements. * * @example * 1 - res = source.takeLastWithTime(5000, [optional timer scheduler], [optional loop scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} [timerScheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @param {Scheduler} [loopScheduler] Scheduler to drain the collected elements. If not specified, defaults to Rx.Scheduler.immediate. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastWithTime = function (duration, timerScheduler, loopScheduler) { return this.takeLastBufferWithTime(duration, timerScheduler).selectMany(function (xs) { return observableFromArray(xs, loopScheduler); }); }; /** * Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeLastBufferWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the end of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence. */ observableProto.takeLastBufferWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { var now = scheduler.now(); q.push({ interval: now, value: x }); while (q.length > 0 && now - q[0].interval >= duration) { q.shift(); } }, observer.onError.bind(observer), function () { var now = scheduler.now(), res = []; while (q.length > 0) { var next = q.shift(); if (now - next.interval <= duration) { res.push(next.value); } } observer.onNext(res); observer.onCompleted(); }); }); }; /** * Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.takeWithTime(5000, [optional scheduler]); * @description * This operator accumulates a queue with a length enough to store elements received during the initial duration window. * As more elements are received, elements older than the specified duration are taken from the queue and produced on the * result sequence. This causes elements to be delayed with duration. * @param {Number} duration Duration for taking elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence. */ observableProto.takeWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var t = scheduler.scheduleWithRelative(duration, function () { observer.onCompleted(); }); return new CompositeDisposable(t, source.subscribe(observer)); }); }; /** * Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers. * * @example * 1 - res = source.skipWithTime(5000, [optional scheduler]); * * @description * Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence. * This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded * may not execute immediately, despite the zero due time. * * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration. * @param {Number} duration Duration for skipping elements from the start of the sequence. * @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence. */ observableProto.skipWithTime = function (duration, scheduler) { var source = this; scheduler || (scheduler = timeoutScheduler); return new AnonymousObservable(function (observer) { var open = false, t = scheduler.scheduleWithRelative(duration, function () { open = true; }), d = source.subscribe(function (x) { if (open) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); return new CompositeDisposable(t, d); }); }; /** * Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers. * Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time>. * * @examples * 1 - res = source.skipUntilWithTime(new Date(), [optional scheduler]); * @param startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped. * @param scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout. * @returns {Observable} An observable sequence with the elements skipped until the specified start time. */ observableProto.skipUntilWithTime = function (startTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var open = false, t = scheduler.scheduleWithAbsolute(startTime, function () { open = true; }), d = source.subscribe(function (x) { if (open) { observer.onNext(x); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); return new CompositeDisposable(t, d); }); }; /** * 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]); * @param {Number} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately. * @param {Scheduler} scheduler Scheduler to run the timer on. * @returns {Observable} An observable sequence with the elements taken until the specified end time. */ observableProto.takeUntilWithTime = function (endTime, scheduler) { scheduler || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { return new CompositeDisposable(scheduler.scheduleWithAbsolute(endTime, function () { observer.onCompleted(); }), source.subscribe(observer)); }); }; /** * 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) { var self = this; return new AnonymousObservable(function (observer) { var conn = self.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); }); }; 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)) ); }); } /** * 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) { var source = this; return new AnonymousObservable(function (observer) { var q = [], previous = true; var subscription = combineLatestSource( source, subject.distinctUntilChanged(), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (results.shouldFire && previous) { observer.onNext(results.data); } if (results.shouldFire && !previous) { while (q.length > 0) { observer.onNext(q.shift()); } previous = true; } else if (!results.shouldFire && !previous) { q.push(results.data); } else if (!results.shouldFire && previous) { previous = false; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer) ); subject.onNext(false); return subscription; }); }; /** * 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)); var AnonymousObservable = Rx.AnonymousObservable = (function (_super) { inherits(AnonymousObservable, _super); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (typeof subscriber === 'undefined') { subscriber = disposableEmpty; } else if (typeof subscriber === 'function') { subscriber = disposableCreate(subscriber); } return subscriber; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }); } else { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } } return autoDetachObserver; } _super.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, _super); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { _super.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { this.value = value; this.hasValue = true; } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); /** @private */ var AnonymousSubject = (function (_super) { inherits(AnonymousSubject, _super); function subscribe(observer) { return this.observable.subscribe(observer); } /** * @private * @constructor */ function AnonymousSubject(observer, observable) { _super.call(this, subscribe); this.observer = observer; this.observable = observable; } addProperties(AnonymousSubject.prototype, Observer, { /** * @private * @memberOf AnonymousSubject# */ onCompleted: function () { this.observer.onCompleted(); }, /** * @private * @memberOf AnonymousSubject# */ onError: function (exception) { this.observer.onError(exception); }, /** * @private * @memberOf AnonymousSubject# */ onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * 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)); 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));
example/client/src/app.js
samsarahq/thunder
import React from 'react'; import { connectGraphQL, mutate } from 'thunder-react'; import { GraphiQLWithFetcher } from './graphiql'; const Editor = React.createClass({ getInitialState() { return {text: ''}; }, onSubmit(e) { mutate({ query: '{ addMessage(text: $text) }', variables: { text: this.state.text }, }).then(() => { this.setState({text: ''}); }); }, render() { return ( <div> <input type="text" value={this.state.text} onChange={e => this.setState({text: e.target.value})} /> <button onClick={this.onSubmit}>Submit</button> </div> ); }, }); function deleteMessage(id) { mutate({ query: '{ deleteMessage(id: $id) }', variables: { id }, }); } function addReaction(messageId, reaction) { mutate({ query: '{ addReaction(messageId: $messageId, reaction: $reaction) }', variables: { messageId, reaction }, }); } let Messages = function(props) { return ( <div> {props.data.value.messages.map(({id, text, reactions}) => <p key={id}>{text} <button onClick={() => deleteMessage(id)}>X</button> {reactions.map(({reaction, count}) => <button onClick={() => addReaction(id, reaction)}>{reaction} x{count}</button> )} </p> )} <Editor /> </div> ); } Messages = connectGraphQL(Messages, () => ({ query: ` { messages { id, text reactions { reaction count } } }`, variables: {}, onlyValidData: true, })); function App() { if (window.location.pathname === "/graphiql") { return <GraphiQLWithFetcher />; } else { return <Messages />; } } export default App;
ajax/libs/yui/3.7.0/datatable-body/datatable-body.js
dmsanchez86/cdnjs
YUI.add('datatable-body', function (Y, NAME) { /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. @module datatable @submodule datatable-body @since 3.5.0 **/ var Lang = Y.Lang, isArray = Lang.isArray, isNumber = Lang.isNumber, isString = Lang.isString, fromTemplate = Lang.sub, htmlEscape = Y.Escape.html, toArray = Y.Array, bind = Y.bind, YObject = Y.Object; /** View class responsible for rendering the `<tbody>` section of a table. Used as the default `bodyView` for `Y.DataTable.Base` and `Y.DataTable` classes. Translates the provided `modelList` into a rendered `<tbody>` based on the data in the constituent Models, altered or ammended by any special column configurations. The `columns` configuration, passed to the constructor, determines which columns will be rendered. The rendering process involves constructing an HTML template for a complete row of data, built by concatenating a customized copy of the instance's `CELL_TEMPLATE` into the `ROW_TEMPLATE` once for each column. This template is then populated with values from each Model in the `modelList`, aggregating a complete HTML string of all row and column data. A `<tbody>` Node is then created from the markup and any column `nodeFormatter`s are applied. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @class BodyView @namespace DataTable @extends View @since 3.5.0 **/ Y.namespace('DataTable').BodyView = Y.Base.create('tableBody', Y.View, [], { // -- Instance properties ------------------------------------------------- /** HTML template used to create table cells. @property CELL_TEMPLATE @type {HTML} @default '<td {headers} class="{className}">{content}</td>' @since 3.5.0 **/ CELL_TEMPLATE: '<td {headers} class="{className}">{content}</td>', /** CSS class applied to even rows. This is assigned at instantiation. For DataTable, this will be `yui3-datatable-even`. @property CLASS_EVEN @type {String} @default 'yui3-table-even' @since 3.5.0 **/ //CLASS_EVEN: null /** CSS class applied to odd rows. This is assigned at instantiation. When used by DataTable instances, this will be `yui3-datatable-odd`. @property CLASS_ODD @type {String} @default 'yui3-table-odd' @since 3.5.0 **/ //CLASS_ODD: null /** HTML template used to create table rows. @property ROW_TEMPLATE @type {HTML} @default '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>' @since 3.5.0 **/ ROW_TEMPLATE : '<tr id="{rowId}" data-yui3-record="{clientId}" class="{rowClass}">{content}</tr>', /** The object that serves as the source of truth for column and row data. This property is assigned at instantiation from the `host` property of the configuration object passed to the constructor. @property host @type {Object} @default (initially unset) @since 3.5.0 **/ //TODO: should this be protected? //host: null, /** HTML templates used to create the `<tbody>` containing the table rows. @property TBODY_TEMPLATE @type {HTML} @default '<tbody class="{className}">{content}</tbody>' @since 3.6.0 **/ TBODY_TEMPLATE: '<tbody class="{className}"></tbody>', // -- Public methods ------------------------------------------------------ /** Returns the `<td>` Node from the given row and column index. Alternately, the `seed` can be a Node. If so, the nearest ancestor cell is returned. If the `seed` is a cell, it is returned. If there is no cell at the given coordinates, `null` is returned. Optionally, include an offset array or string to return a cell near the cell identified by the `seed`. The offset can be an array containing the number of rows to shift followed by the number of columns to shift, or one of "above", "below", "next", or "previous". <pre><code>// Previous cell in the previous row var cell = table.getCell(e.target, [-1, -1]); // Next cell var cell = table.getCell(e.target, 'next'); var cell = table.getCell(e.taregt, [0, 1];</pre></code> @method getCell @param {Number[]|Node} seed Array of row and column indexes, or a Node that is either the cell itself or a descendant of one. @param {Number[]|String} [shift] Offset by which to identify the returned cell Node @return {Node} @since 3.5.0 **/ getCell: function (seed, shift) { var tbody = this.tbodyNode, row, cell, index, rowIndexOffset; if (seed && tbody) { if (isArray(seed)) { row = tbody.get('children').item(seed[0]); cell = row && row.get('children').item(seed[1]); } else if (Y.instanceOf(seed, Y.Node)) { cell = seed.ancestor('.' + this.getClassName('cell'), true); } if (cell && shift) { rowIndexOffset = tbody.get('firstChild.rowIndex'); if (isString(shift)) { // TODO this should be a static object map switch (shift) { case 'above' : shift = [-1, 0]; break; case 'below' : shift = [1, 0]; break; case 'next' : shift = [0, 1]; break; case 'previous': shift = [0, -1]; break; } } if (isArray(shift)) { index = cell.get('parentNode.rowIndex') + shift[0] - rowIndexOffset; row = tbody.get('children').item(index); index = cell.get('cellIndex') + shift[1]; cell = row && row.get('children').item(index); } } } return cell || null; }, /** Returns the generated CSS classname based on the input. If the `host` attribute is configured, it will attempt to relay to its `getClassName` or use its static `NAME` property as a string base. If `host` is absent or has neither method nor `NAME`, a CSS classname will be generated using this class's `NAME`. @method getClassName @param {String} token* Any number of token strings to assemble the classname from. @return {String} @protected @since 3.5.0 **/ getClassName: function () { var host = this.host, args; if (host && host.getClassName) { return host.getClassName.apply(host, arguments); } else { args = toArray(arguments); args.unshift(this.constructor.NAME); return Y.ClassNameManager.getClassName .apply(Y.ClassNameManager, args); } }, /** Returns the Model associated to the row Node or id provided. Passing the Node or id for a descendant of the row also works. If no Model can be found, `null` is returned. @method getRecord @param {String|Node} seed Row Node or `id`, or one for a descendant of a row @return {Model} @since 3.5.0 **/ getRecord: function (seed) { var modelList = this.get('modelList'), tbody = this.tbodyNode, row = null, record; if (tbody) { if (isString(seed)) { seed = tbody.one('#' + seed); } if (Y.instanceOf(seed, Y.Node)) { row = seed.ancestor(function (node) { return node.get('parentNode').compareTo(tbody); }, true); record = row && modelList.getByClientId(row.getData('yui3-record')); } } return record || null; }, /** Returns the `<tr>` Node from the given row index, Model, or Model's `clientId`. If the rows haven't been rendered yet, or if the row can't be found by the input, `null` is returned. @method getRow @param {Number|String|Model} id Row index, Model instance, or clientId @return {Node} @since 3.5.0 **/ getRow: function (id) { var tbody = this.tbodyNode, row = null; if (tbody) { if (id) { id = this._idMap[id.get ? id.get('clientId') : id] || id; } row = isNumber(id) ? tbody.get('children').item(id) : tbody.one('#' + id); } return row; }, /** Creates the table's `<tbody>` content by assembling markup generated by populating the `ROW\_TEMPLATE`, and `CELL\_TEMPLATE` templates with content from the `columns` and `modelList` attributes. The rendering process happens in three stages: 1. A row template is assembled from the `columns` attribute (see `_createRowTemplate`) 2. An HTML string is built up by concatening the application of the data in each Model in the `modelList` to the row template. For cells with `formatter`s, the function is called to generate cell content. Cells with `nodeFormatter`s are ignored. For all other cells, the data value from the Model attribute for the given column key is used. The accumulated row markup is then inserted into the container. 3. If any column is configured with a `nodeFormatter`, the `modelList` is iterated again to apply the `nodeFormatter`s. Supported properties of the column objects include: * `key` - Used to link a column to an attribute in a Model. * `name` - Used for columns that don't relate to an attribute in the Model (`formatter` or `nodeFormatter` only) if the implementer wants a predictable name to refer to in their CSS. * `cellTemplate` - Overrides the instance's `CELL_TEMPLATE` for cells in this column only. * `formatter` - Used to customize or override the content value from the Model. These do not have access to the cell or row Nodes and should return string (HTML) content. * `nodeFormatter` - Used to provide content for a cell as well as perform any custom modifications on the cell or row Node that could not be performed by `formatter`s. Should be used sparingly for better performance. * `emptyCellValue` - String (HTML) value to use if the Model data for a column, or the content generated by a `formatter`, is the empty string, `null`, or `undefined`. * `allowHTML` - Set to `true` if a column value, `formatter`, or `emptyCellValue` can contain HTML. This defaults to `false` to protect against XSS. * `className` - Space delimited CSS classes to add to all `<td>`s in a column. Column `formatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `className` - Initially empty string to allow `formatter`s to add CSS classes to the cell's `<td>`. * `rowIndex` - The zero-based row number. * `rowClass` - Initially empty string to allow `formatter`s to add CSS classes to the cell's containing row `<tr>`. They may return a value or update `o.value` to assign specific HTML content. A returned value has higher precedence. Column `nodeFormatter`s are passed an object (`o`) with the following properties: * `value` - The current value of the column's associated attribute, if any. * `td` - The `<td>` Node instance. * `cell` - The `<div>` liner Node instance if present, otherwise, the `<td>`. When adding content to the cell, prefer appending into this property. * `data` - An object map of Model keys to their current values. * `record` - The Model instance. * `column` - The column configuration object for the current column. * `rowIndex` - The zero-based row number. They are expected to inject content into the cell's Node directly, including any "empty" cell content. Each `nodeFormatter` will have access through the Node API to all cells and rows in the `<tbody>`, but not to the `<table>`, as it will not be attached yet. If a `nodeFormatter` returns `false`, the `o.td` and `o.cell` Nodes will be `destroy()`ed to remove them from the Node cache and free up memory. The DOM elements will remain as will any content added to them. _It is highly advisable to always return `false` from your `nodeFormatter`s_. @method render @return {BodyView} The instance @chainable @since 3.5.0 **/ render: function () { var table = this.get('container'), data = this.get('modelList'), columns = this.get('columns'), tbody = this.tbodyNode || (this.tbodyNode = this._createTBodyNode()); // Needed for mutation this._createRowTemplate(columns); if (data) { tbody.setHTML(this._createDataHTML(columns)); this._applyNodeFormatters(tbody, columns); } if (tbody.get('parentNode') !== table) { table.appendChild(tbody); } this.bindUI(); return this; }, // -- Protected and private methods --------------------------------------- /** Handles changes in the source's columns attribute. Redraws the table data. @method _afterColumnsChange @param {EventFacade} e The `columnsChange` event object @protected @since 3.5.0 **/ // TODO: Preserve existing DOM // This will involve parsing and comparing the old and new column configs // and reacting to four types of changes: // 1. formatter, nodeFormatter, emptyCellValue changes // 2. column deletions // 3. column additions // 4. column moves (preserve cells) _afterColumnsChange: function (e) { this.render(); }, /** Handles modelList changes, including additions, deletions, and updates. Modifies the existing table DOM accordingly. @method _afterDataChange @param {EventFacade} e The `change` event from the ModelList @protected @since 3.5.0 **/ _afterDataChange: function (e) { //var type = e.type.slice(e.type.lastIndexOf(':') + 1); // TODO: Isolate changes this.render(); }, /** Handles replacement of the modelList. Rerenders the `<tbody>` contents. @method _afterModelListChange @param {EventFacade} e The `modelListChange` event @protected @since 3.6.0 **/ _afterModelListChange: function (e) { var handles = this._eventHandles; if (handles.dataChange) { handles.dataChange.detach(); delete handles.dataChange; this.bindUI(); } if (this.tbodyNode) { this.render(); } }, /** Iterates the `modelList`, and calls any `nodeFormatter`s found in the `columns` param on the appropriate cell Nodes in the `tbody`. @method _applyNodeFormatters @param {Node} tbody The `<tbody>` Node whose columns to update @param {Object[]} columns The column configurations @protected @since 3.5.0 **/ _applyNodeFormatters: function (tbody, columns) { var host = this.host, data = this.get('modelList'), formatters = [], linerQuery = '.' + this.getClassName('liner'), rows, i, len; // Only iterate the ModelList again if there are nodeFormatters for (i = 0, len = columns.length; i < len; ++i) { if (columns[i].nodeFormatter) { formatters.push(i); } } if (data && formatters.length) { rows = tbody.get('childNodes'); data.each(function (record, index) { var formatterData = { data : record.toJSON(), record : record, rowIndex : index }, row = rows.item(index), i, len, col, key, cells, cell, keep; if (row) { cells = row.get('childNodes'); for (i = 0, len = formatters.length; i < len; ++i) { cell = cells.item(formatters[i]); if (cell) { col = formatterData.column = columns[formatters[i]]; key = col.key || col.id; formatterData.value = record.get(key); formatterData.td = cell; formatterData.cell = cell.one(linerQuery) || cell; keep = col.nodeFormatter.call(host,formatterData); if (keep === false) { // Remove from the Node cache to reduce // memory footprint. This also purges events, // which you shouldn't be scoping to a cell // anyway. You've been warned. Incidentally, // you should always return false. Just sayin. cell.destroy(true); } } } } }); } }, /** Binds event subscriptions from the UI and the host (if assigned). @method bindUI @protected @since 3.5.0 **/ bindUI: function () { var handles = this._eventHandles, modelList = this.get('modelList'), changeEvent = modelList.model.NAME + ':change'; if (!handles.columnsChange) { handles.columnsChange = this.after('columnsChange', bind('_afterColumnsChange', this)); } if (modelList && !handles.dataChange) { handles.dataChange = modelList.after( ['add', 'remove', 'reset', changeEvent], bind('_afterDataChange', this)); } }, /** Iterates the `modelList` and applies each Model to the `_rowTemplate`, allowing any column `formatter` or `emptyCellValue` to override cell content for the appropriate column. The aggregated HTML string is returned. @method _createDataHTML @param {Object[]} columns The column configurations to customize the generated cell content or class names @return {HTML} The markup for all Models in the `modelList`, each applied to the `_rowTemplate` @protected @since 3.5.0 **/ _createDataHTML: function (columns) { var data = this.get('modelList'), html = ''; if (data) { data.each(function (model, index) { html += this._createRowHTML(model, index, columns); }, this); } return html; }, /** Applies the data of a given Model, modified by any column formatters and supplemented by other template values to the instance's `_rowTemplate` (see `_createRowTemplate`). The generated string is then returned. The data from Model's attributes is fetched by `toJSON` and this data object is appended with other properties to supply values to {placeholders} in the template. For a template generated from a Model with 'foo' and 'bar' attributes, the data object would end up with the following properties before being used to populate the `_rowTemplate`: * `clientID` - From Model, used the assign the `<tr>`'s 'id' attribute. * `foo` - The value to populate the 'foo' column cell content. This value will be the value stored in the Model's `foo` attribute, or the result of the column's `formatter` if assigned. If the value is '', `null`, or `undefined`, and the column's `emptyCellValue` is assigned, that value will be used. * `bar` - Same for the 'bar' column cell content. * `foo-className` - String of CSS classes to apply to the `<td>`. * `bar-className` - Same. * `rowClass` - String of CSS classes to apply to the `<tr>`. This will be the odd/even class per the specified index plus any additional classes assigned by column formatters (via `o.rowClass`). Because this object is available to formatters, any additional properties can be added to fill in custom {placeholders} in the `_rowTemplate`. @method _createRowHTML @param {Model} model The Model instance to apply to the row template @param {Number} index The index the row will be appearing @param {Object[]} columns The column configurations @return {HTML} The markup for the provided Model, less any `nodeFormatter`s @protected @since 3.5.0 **/ _createRowHTML: function (model, index, columns) { var data = model.toJSON(), clientId = model.get('clientId'), values = { rowId : this._getRowId(clientId), clientId: clientId, rowClass: (index % 2) ? this.CLASS_ODD : this.CLASS_EVEN }, host = this.host || this, i, len, col, token, value, formatterData; for (i = 0, len = columns.length; i < len; ++i) { col = columns[i]; value = data[col.key]; token = col._id || col.key; values[token + '-className'] = ''; if (col.formatter) { formatterData = { value : value, data : data, column : col, record : model, className: '', rowClass : '', rowIndex : index }; if (typeof col.formatter === 'string') { if (value !== undefined) { // TODO: look for known formatters by string name value = fromTemplate(col.formatter, formatterData); } } else { // Formatters can either return a value value = col.formatter.call(host, formatterData); // or update the value property of the data obj passed if (value === undefined) { value = formatterData.value; } values[token + '-className'] = formatterData.className; values.rowClass += ' ' + formatterData.rowClass; } } if (value === undefined || value === null || value === '') { value = col.emptyCellValue || ''; } values[token] = col.allowHTML ? value : htmlEscape(value); values.rowClass = values.rowClass.replace(/\s+/g, ' '); } return fromTemplate(this._rowTemplate, values); }, /** Creates a custom HTML template string for use in generating the markup for individual table rows with {placeholder}s to capture data from the Models in the `modelList` attribute or from column `formatter`s. Assigns the `_rowTemplate` property. @method _createRowTemplate @param {Object[]} columns Array of column configuration objects @protected @since 3.5.0 **/ _createRowTemplate: function (columns) { var html = '', cellTemplate = this.CELL_TEMPLATE, i, len, col, key, token, headers, tokenValues; for (i = 0, len = columns.length; i < len; ++i) { col = columns[i]; key = col.key; token = col._id || key; // Only include headers if there are more than one headers = (col._headers || []).length > 1 ? 'headers="' + col._headers.join(' ') + '"' : ''; tokenValues = { content : '{' + token + '}', headers : headers, className: this.getClassName('col', token) + ' ' + (col.className || '') + ' ' + this.getClassName('cell') + ' {' + token + '-className}' }; if (col.nodeFormatter) { // Defer all node decoration to the formatter tokenValues.content = ''; } html += fromTemplate(col.cellTemplate || cellTemplate, tokenValues); } this._rowTemplate = fromTemplate(this.ROW_TEMPLATE, { content: html }); }, /** Creates the `<tbody>` node that will store the data rows. @method _createTBodyNode @return {Node} @protected @since 3.6.0 **/ _createTBodyNode: function () { return Y.Node.create(fromTemplate(this.TBODY_TEMPLATE, { className: this.getClassName('data') })); }, /** Destroys the instance. @method destructor @protected @since 3.5.0 **/ destructor: function () { (new Y.EventHandle(YObject.values(this._eventHandles))).detach(); }, /** Holds the event subscriptions needing to be detached when the instance is `destroy()`ed. @property _eventHandles @type {Object} @default undefined (initially unset) @protected @since 3.5.0 **/ //_eventHandles: null, /** Returns the row ID associated with a Model's clientId. @method _getRowId @param {String} clientId The Model clientId @return {String} @protected **/ _getRowId: function (clientId) { return this._idMap[clientId] || (this._idMap[clientId] = Y.guid()); }, /** Map of Model clientIds to row ids. @property _idMap @type {Object} @protected **/ //_idMap, /** Initializes the instance. Reads the following configuration properties in addition to the instance attributes: * `columns` - (REQUIRED) The initial column information * `host` - The object to serve as source of truth for column info and for generating class names @method initializer @param {Object} config Configuration data @protected @since 3.5.0 **/ initializer: function (config) { this.host = config.host; this._eventHandles = { modelListChange: this.after('modelListChange', bind('_afterModelListChange', this)) }; this._idMap = {}; this.CLASS_ODD = this.getClassName('odd'); this.CLASS_EVEN = this.getClassName('even'); } /** The HTML template used to create a full row of markup for a single Model in the `modelList` plus any customizations defined in the column configurations. @property _rowTemplate @type {HTML} @default (initially unset) @protected @since 3.5.0 **/ //_rowTemplate: null }); }, '@VERSION@', {"requires": ["datatable-core", "view", "classnamemanager"]});
src/App.js
davyengone/meetup.demo
import React, { Component } from 'react'; export default class App extends Component { render() { return ( <h1>Hello, world Davy Engone.</h1> ); } }
src/js/components/ui/CardContent/CardContent.js
nekuno/client
import PropTypes from 'prop-types'; import React, { Component } from 'react'; import styles from './CardContent.scss'; import CardIcons from '../CardIcons'; import Image from '../Image'; import LinkImageService from '../../../services/LinkImageService'; import NetworkLine from "../NetworkLine/NetworkLine"; import ContentTypeIcon from "../ContentTypeIcon/ContentTypeIcon"; import translate from "../../../i18n/Translate"; @translate('CardContent') export default class CardContent extends Component { static propTypes = { title : PropTypes.string, description: PropTypes.string, types : PropTypes.array.isRequired, // network : PropTypes.string.isRequired, url : PropTypes.string.isRequired, embed_id : PropTypes.string, embed_type : PropTypes.string, thumbnail : PropTypes.string, }; constructor(props) { super(props); this.handleClick = this.handleClick.bind(this); this.state = { embedHtml: null } } componentDidMount() { if (!window.cordova && this.state.embedHtml && this.props.embed_type === 'facebook') { FB.XFBML.parse(); } } componentDidUpdate() { if (!window.cordova && this.state.embedHtml && this.props.embed_type === 'facebook') { FB.XFBML.parse(); } } handleClick() { const {url, types, embed_type, embed_id} = this.props; const isVideo = types.indexOf('Video') > -1; if (isVideo && !window.cordova && window.screen.width > 320) { this.preVisualizeVideo(embed_type, embed_id, url); } else { window.cordova ? document.location = url : window.open(url); } } preVisualizeVideo = function(embed_type, embed_id, url) { let html = null; switch (embed_type) { case 'youtube': html = <iframe className="discover-video" src={'https://www.youtube.com/embed/' + embed_id + '?autoplay=1'} frameBorder="0" allowFullScreen></iframe>; break; case 'facebook': html = <div className="fb-video" data-href={url} data-show-text="false" data-autoplay="true"></div>; break; case 'tumblr': html = <div dangerouslySetInnerHTML={{__html: embed_id.replace('<video', '<video controls style="width: 100%"')}}></div>; break; default: break; } this.setState({ embedHtml: html }); }; preventDefault(e) { e.preventDefault(); } getType(types) { return types.find((type) => { return type !== 'Link' }); } render() { const {title, description, types, thumbnail, url, strings} = this.props; const cardTitle = title ? title.length > 20 ? title.substr(0, 20) + '...' : title : strings.emptyTitle; const subTitle = description ? <div>{description.substr(0, 20)}{description.length > 20 ? '...' : ''}</div> : ''; const type = this.getType(types); const isImage = type === 'Image'; const footerClassName = isImage ? styles.footerImage : styles.footer; const defaultSrc = 'img/default-content-image.jpg'; let imgSrc = defaultSrc; if (thumbnail) { imgSrc = thumbnail; } else if (isImage) { imgSrc = url; } imgSrc = LinkImageService.getThumbnail(imgSrc, 'medium'); return ( <div className={styles.cardContent}> {isImage ? <div className={styles.contentImageFullWrapper}> <img src={imgSrc} alt=''/> {/*<NetworkLine network={network}/>*/} </div> : <div> <div className={styles.contentImageWrapper}> <img src={imgSrc} alt=''/> </div> {/*<NetworkLine network={network}/>*/} <div className={styles.cardTitle} onClick={this.handleClick}> <a href={url} onClick={this.preventDefault}> {cardTitle} </a> </div> <div className={styles.cardSubtitle} onClick={this.handleClick}> {subTitle} </div> </div> } <div className={footerClassName}> <ContentTypeIcon type={type}/> </div> </div> ); } }
assets/node_modules/karma/node_modules/core-js/library/modules/es6.promise.js
rochellecanale/tutorials
'use strict'; var $ = require('./$') , ctx = require('./$.ctx') , cof = require('./$.cof') , $def = require('./$.def') , assert = require('./$.assert') , forOf = require('./$.for-of') , setProto = require('./$.set-proto').set , same = require('./$.same') , species = require('./$.species') , SPECIES = require('./$.wks')('species') , RECORD = require('./$.uid').safe('record') , PROMISE = 'Promise' , global = $.g , process = global.process , isNode = cof(process) == 'process' , asap = process && process.nextTick || require('./$.task').set , P = global[PROMISE] , isFunction = $.isFunction , isObject = $.isObject , assertFunction = assert.fn , assertObject = assert.obj , Wrapper; function testResolve(sub){ var test = new P(function(){}); if(sub)test.constructor = Object; return P.resolve(test) === test; } var useNative = function(){ var works = false; function P2(x){ var self = new P(x); setProto(self, P2.prototype); return self; } try { works = isFunction(P) && isFunction(P.resolve) && testResolve(); setProto(P2, P); P2.prototype = $.create(P.prototype, {constructor: {value: P2}}); // actual Firefox has broken subclass support, test that if(!(P2.resolve(5).then(function(){}) instanceof P2)){ works = false; } // actual V8 bug, https://code.google.com/p/v8/issues/detail?id=4162 if(works && $.DESC){ var thenableThenGotten = false; P.resolve($.setDesc({}, 'then', { get: function(){ thenableThenGotten = true; } })); works = thenableThenGotten; } } catch(e){ works = false; } return works; }(); // helpers function isPromise(it){ return isObject(it) && (useNative ? cof.classof(it) == 'Promise' : RECORD in it); } function sameConstructor(a, b){ // library wrapper special case if(!$.FW && a === P && b === Wrapper)return true; return same(a, b); } function getConstructor(C){ var S = assertObject(C)[SPECIES]; return S != undefined ? S : C; } function isThenable(it){ var then; if(isObject(it))then = it.then; return isFunction(then) ? then : false; } function notify(record){ var chain = record.c; // strange IE + webpack dev server bug - use .call(global) if(chain.length)asap.call(global, function(){ var value = record.v , ok = record.s == 1 , i = 0; function run(react){ var cb = ok ? react.ok : react.fail , ret, then; try { if(cb){ if(!ok)record.h = true; ret = cb === true ? value : cb(value); if(ret === react.P){ react.rej(TypeError('Promise-chain cycle')); } else if(then = isThenable(ret)){ then.call(ret, react.res, react.rej); } else react.res(ret); } else react.rej(value); } catch(err){ react.rej(err); } } while(chain.length > i)run(chain[i++]); // variable length - can't use forEach chain.length = 0; }); } function isUnhandled(promise){ var record = promise[RECORD] , chain = record.a || record.c , i = 0 , react; if(record.h)return false; while(chain.length > i){ react = chain[i++]; if(react.fail || !isUnhandled(react.P))return false; } return true; } function $reject(value){ var record = this , promise; if(record.d)return; record.d = true; record = record.r || record; // unwrap record.v = value; record.s = 2; record.a = record.c.slice(); setTimeout(function(){ // strange IE + webpack dev server bug - use .call(global) asap.call(global, function(){ if(isUnhandled(promise = record.p)){ if(isNode){ process.emit('unhandledRejection', value, promise); } else if(global.console && console.error){ console.error('Unhandled promise rejection', value); } } record.a = undefined; }); }, 1); notify(record); } function $resolve(value){ var record = this , then; if(record.d)return; record.d = true; record = record.r || record; // unwrap try { if(then = isThenable(value)){ // strange IE + webpack dev server bug - use .call(global) asap.call(global, function(){ var wrapper = {r: record, d: false}; // wrap try { then.call(value, ctx($resolve, wrapper, 1), ctx($reject, wrapper, 1)); } catch(e){ $reject.call(wrapper, e); } }); } else { record.v = value; record.s = 1; notify(record); } } catch(e){ $reject.call({r: record, d: false}, e); // wrap } } // constructor polyfill if(!useNative){ // 25.4.3.1 Promise(executor) P = function Promise(executor){ assertFunction(executor); var record = { p: assert.inst(this, P, PROMISE), // <- promise c: [], // <- awaiting reactions a: undefined, // <- checked in isUnhandled reactions s: 0, // <- state d: false, // <- done v: undefined, // <- value h: false // <- handled rejection }; $.hide(this, RECORD, record); try { executor(ctx($resolve, record, 1), ctx($reject, record, 1)); } catch(err){ $reject.call(record, err); } }; require('./$.mix')(P.prototype, { // 25.4.5.3 Promise.prototype.then(onFulfilled, onRejected) then: function then(onFulfilled, onRejected){ var S = assertObject(assertObject(this).constructor)[SPECIES]; var react = { ok: isFunction(onFulfilled) ? onFulfilled : true, fail: isFunction(onRejected) ? onRejected : false }; var promise = react.P = new (S != undefined ? S : P)(function(res, rej){ react.res = assertFunction(res); react.rej = assertFunction(rej); }); var record = this[RECORD]; record.c.push(react); if(record.a)record.a.push(react); if(record.s)notify(record); return promise; }, // 25.4.5.1 Promise.prototype.catch(onRejected) 'catch': function(onRejected){ return this.then(undefined, onRejected); } }); } // export $def($def.G + $def.W + $def.F * !useNative, {Promise: P}); cof.set(P, PROMISE); species(P); species(Wrapper = $.core[PROMISE]); // statics $def($def.S + $def.F * !useNative, PROMISE, { // 25.4.4.5 Promise.reject(r) reject: function reject(r){ return new (getConstructor(this))(function(res, rej){ rej(r); }); } }); $def($def.S + $def.F * (!useNative || testResolve(true)), PROMISE, { // 25.4.4.6 Promise.resolve(x) resolve: function resolve(x){ return isPromise(x) && sameConstructor(x.constructor, this) ? x : new this(function(res){ res(x); }); } }); $def($def.S + $def.F * !(useNative && require('./$.iter-detect')(function(iter){ P.all(iter)['catch'](function(){}); })), PROMISE, { // 25.4.4.1 Promise.all(iterable) all: function all(iterable){ var C = getConstructor(this) , values = []; return new C(function(res, rej){ forOf(iterable, false, values.push, values); var remaining = values.length , results = Array(remaining); if(remaining)$.each.call(values, function(promise, index){ C.resolve(promise).then(function(value){ results[index] = value; --remaining || res(results); }, rej); }); else res(results); }); }, // 25.4.4.4 Promise.race(iterable) race: function race(iterable){ var C = getConstructor(this); return new C(function(res, rej){ forOf(iterable, false, function(promise){ C.resolve(promise).then(res, rej); }); }); } });
src/components/Privacy/Privacy.react.js
DeveloperAlfa/chat.susi.ai
import '../Terms/Terms.css'; import $ from 'jquery'; import Footer from '../Footer/Footer.react'; import PropTypes from 'prop-types'; import StaticAppBar from '../StaticAppBar/StaticAppBar.react'; import React, { Component } from 'react'; class Privacy extends Component { constructor(props) { super(props); this.state = { open: false, showOptions: false, anchorEl: null, login: false, signup: false, video: false, openDrawer: false, }; } componentDidMount() { // Adding title tag to page document.title = 'Privacy Policy - SUSI.AI, Open Source Artificial Intelligence for Personal Assistants, Robots, Help Desks and Chatbots'; // Scrolling to top of page when component loads $('html, body').animate({ scrollTop: 0 }, 'fast'); } showOptions = (event) => { event.preventDefault(); this.setState({ showOptions: true, anchorEl: event.currentTarget }) } _onReady(event) { // access to player in all event handlers via event.target event.target.pauseVideo(); } render() { document.body.style.setProperty('background-image', 'none'); return ( <div> <StaticAppBar {...this.props} location={this.props.location} /> <div className='head_section'> <div className='container'> <div className="heading"> <h1>Privacy</h1> <p>Privacy Policy for SUSI</p> </div> </div> </div> <div className='section'> <div className="section-container" > <div className="terms-list"> <br /><br /> <h2>Welcome to SUSI!</h2> <p>Thanks for using our products and services (“Services”). The Services are provided by SUSI Inc. (“SUSI”), located at 93 Mau Than, Can Tho City, Viet Nam. By using our Services, you are agreeing to these terms. Please read them carefully. </p> <h2>Using our Services</h2> <p>You must follow any policies made available to you within the Services. <br /><br /> Don’t misuse our Services. For example, don’t interfere with our Services or try to access them using a method other than the interface and the instructions that we provide. You may use our Services only as permitted by law, including applicable export and re-export control laws and regulations. We may suspend or stop providing our Services to you if you do not comply with our terms or policies or if we are investigating suspected misconduct. <br /><br /> Using our Services does not give you ownership of any intellectual property rights in our Services or the content you access. You may not use content from our Services unless you obtain permission from its owner or are otherwise permitted by law. These terms do not grant you the right to use any branding or logos used in our Services. Don’t remove, obscure, or alter any legal notices displayed in or along with our Services. <br /><br /> Our Services display some content that is not SUSI’s. This content is the sole responsibility of the entity that makes it available. We may review content to determine whether it is illegal or violates our policies, and we may remove or refuse to display content that we reasonably believe violates our policies or the law. But that does not necessarily mean that we review content, so please don’t assume that we do. <br /><br /> In connection with your use of the Services, we may send you service announcements, administrative messages, and other information. You may opt out of some of those communications. <br /><br /> Some of our Services are available on mobile devices. Do not use such Services in a way that distracts you and prevents you from obeying traffic or safety laws. <br /><br /> </p> <h2>Your SUSI Account</h2> <p> You may need a SUSI Account in order to use some of our Services. You may create your own SUSI Account, or your SUSI Account may be assigned to you by an administrator, such as your employer or educational institution. If you are using a SUSI Account assigned to you by an administrator, different or additional terms may apply and your administrator may be able to access or disable your account. <br /><br /> To protect your SUSI Account, keep your password confidential. You are responsible for the activity that happens on or through your SUSI Account. Try not to reuse your SUSI Account password on third-party applications. If you learn of any unauthorized use of your password or SUSI Account, change your password and take measures to secure your account. <br /><br /> </p> <h2>Privacy and Copyright Protection</h2> <p>SUSI’s privacy policies ensures that your personal data is safe and protected. By using our Services, you agree that SUSI can use such data in accordance with our privacy policies. <br /><br /> We respond to notices of alleged copyright infringement and terminate accounts of repeat infringers. If you think somebody is violating your copyrights and want to notify us, you can find information about submitting notices and SUSI’s policy about responding to notices on our website. <br /><br /> </p> <h2>Your Content in our Services</h2> <p>Some of our Services allow you to upload, submit, store, send or receive content. You retain ownership of any intellectual property rights that you hold in that content. In short, what belongs to you stays yours. <br /><br /> When you upload, submit, store, send or receive content to or through our Services, you give SUSI (and those we work with) a worldwide license to use, host, store, reproduce, modify, create derivative works (such as those resulting from translations, adaptations or other changes we make so that your content works better with our Services), communicate, publish, publicly perform, publicly display and distribute such content. The rights you grant in this license are for the limited purpose of operating, promoting, and improving our Services, and to develop new ones. This license continues even if you stop using our Services (for example, for a business listing you have added to SUSI Maps). Some Services may offer you ways to access and remove content that has been provided to that Service. Also, in some of our Services, there are terms or settings that narrow the scope of our use of the content submitted in those Services. Make sure you have the necessary rights to grant this license for any content that you submit to our Services. <br /><br /> If you have a SUSI Account, we may display your Profile name, Profile photo, and actions you take on SUSI or on third-party applications connected to your SUSI Account in our Services, including displaying in ads and other commercial contexts. We will respect the choices you make to limit sharing or visibility settings in your SUSI Account. <br /><br /> </p> <h2>About Software in our Services</h2> <p>When a Service requires or includes downloadable software, this software may update automatically on your device once a new version or feature is available. Some Services may let you adjust your automatic update settings. <br /><br /> SUSI gives you a personal, worldwide, royalty-free, non-assignable and non-exclusive license to use the software provided to you by SUSI as part of the Services. This license is for the sole purpose of enabling you to use and enjoy the benefit of the Services as provided by SUSI, in the manner permitted by these terms. <br /><br /> Most of our services are offered through Free Software and/or Open Source Software. You may copy, modify, distribute, sell, or lease these applications and share the source code of that software as stated in the License agreement provided with the Software. <br /><br /> </p> <h2>Modifying and Terminating our Services</h2> <p>We are constantly changing and improving our Services. We may add or remove functionalities or features, and we may suspend or stop a Service altogether. <br /><br /> You can stop using our Services at any time. SUSI may also stop providing Services to you, or add or create new limits to our Services at any time. <br /><br /> We believe that you own your data and preserving your access to such data is important. If we discontinue a Service, where reasonably possible, we will give you reasonable advance notice and a chance to get information out of that Service. <br /><br /> </p> <h2>Our Warranties and Disclaimers</h2> <p>We provide our Services using a reasonable level of skill and care and we hope that you will enjoy using them. But there are certain things that we don’t promise about our Services. <br /><br /> Other than as expressly set out in these terms or additional terms, neither SUSI nor its suppliers or distributors make any specific promises about the Services. For example, we don’t make any commitments about the content within the Services, the specific functions of the Services, or their reliability, availability, or ability to meet your needs. We provide the Services “as is”. <br /><br /> Some jurisdictions provide for certain warranties, like the implied warranty of merchantability, fitness for a particular purpose and non-infringement. To the extent permitted by law, we exclude all warranties. <br /><br /> </p> <h2>Liability for our Services</h2> <p>When permitted by law, SUSI, and SUSI’s suppliers and distributors, will not be responsible for lost profits, revenues, or data, financial losses or indirect, special, consequential, exemplary, or punitive damages. <br /><br /> To the extent permitted by law, the total liability of SUSI, and its suppliers and distributors, for any claims under these terms, including for any implied warranties, is limited to the amount you paid us to use the Services (or, if we choose, to supplying you the Services again). <br /><br /> In all cases, SUSI, and its suppliers and distributors, will not be liable for any loss or damage that is not reasonably foreseeable. <br /><br /> We recognize that in some countries, you might have legal rights as a consumer. If you are using the Services for a personal purpose, then nothing in these terms or any additional terms limits any consumer legal rights which may not be waived by contract. <br /><br /> </p> <h2>Business uses of our Services</h2> <p>If you are using our Services on behalf of a business, that business accepts these terms. It will hold harmless and indemnify SUSI and its affiliates, officers, agents, and employees from any claim, suit or action arising from or related to the use of the Services or violation of these terms, including any liability or expense arising from claims, losses , damages, suits, judgments, litigation costs and attorneys’ fees. <br /><br /></p> <h2>About these Terms</h2> <p>We may modify these terms or any additional terms that apply to a Service to, for example, reflect changes to the law or changes to our Services. You should look at the terms regularly. We’ll post notice of modifications to these terms on this page. We’ll post notice of modified additional terms in the applicable Service. Changes will not apply retroactively and will become effective no sooner than fourteen days after they are posted. However,changes addressing new functions for a Service or changes made for legal reasons will be effective immediately. If you do not agree to the modified terms for a Service, you should discontinue your use of that Service. <br /><br /> If there is a conflict between these terms and the additional terms, the additional terms will control for that conflict. <br /> These terms control the relationship between SUSI and you. They do not create any third party beneficiary rights. <br /><br /> If you do not comply with these terms, and we don’t take action right away, this doesn’t mean that we are giving up any rights that we may have (such as taking action in the future). <br /><br /> If it turns out that a particular term is not enforceable, this will not affect any other terms.<br /><br /> You agree that the laws of Can Tho, Viet Nam will apply to any disputes arising out of or relating to these terms or the Services. All claims arising out of or relating to these terms or the services will be litigated exclusively in the courts of Can Tho City, Viet Nam, and you and SUSI consent to personal jurisdiction in those courts. <br /><br /> For information about how to contact SUSI, please visit our contact page. <br /><br /> </p> </div> </div> </div> <Footer /> </div> ); }; } Privacy.propTypes = { history: PropTypes.object, location: PropTypes.object } export default Privacy;
client/src/components/HomePage.js
yegor-sytnyk/contoso-express
import React from 'react'; class HomePage extends React.Component { render() { return ( <div className="container"> <div className="jumbotron"> <h1>Contoso University</h1> </div> <div className="row"> <div className="col-md-4"> <h2>Welcome to Contoso Express</h2> <p> Contoso Express is a sample application that demonstrates best practices of modern JavaScript full-stack development. </p> </div> <div className="col-md-4"> <h2>Original Contoso</h2> <p>That is remake of famous in .NET world Contoso Express project.</p> <p>Generally data base schema and functionality stays the same; UI is a bit updated as project demonstrates SPA techniques for client side.</p> <p> <a className="btn btn-default" href="http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/">See original tutorial here &raquo;</a> </p> </div> <div className="col-md-4"> <h2>Source</h2> <p>See the latest source code on GitHub.</p> <p> <a className="btn btn-default" href="https://github.com/yegor-sytnyk/contoso-express">Check out source code on github &raquo;</a> </p> </div> </div> </div> ); } } export default HomePage;
actor-apps/app-web/src/app/components/modals/Contacts.react.js
supertanglang/actor-platform
// // Deprecated // import _ from 'lodash'; import React from 'react'; import { PureRenderMixin } from 'react/addons'; import ContactActionCreators from 'actions/ContactActionCreators'; import DialogActionCreators from 'actions/DialogActionCreators'; import ContactStore from 'stores/ContactStore'; import Modal from 'react-modal'; import AvatarItem from 'components/common/AvatarItem.react'; let appElement = document.getElementById('actor-web-app'); Modal.setAppElement(appElement); let getStateFromStores = () => { return { contacts: ContactStore.getContacts(), isShown: ContactStore.isContactsOpen() }; }; class Contacts extends React.Component { componentWillMount() { ContactStore.addChangeListener(this._onChange); } componentWillUnmount() { ContactStore.removeChangeListener(this._onChange); } constructor() { super(); this._onClose = this._onClose.bind(this); this._onChange = this._onChange.bind(this); this.state = getStateFromStores(); } _onChange() { this.setState(getStateFromStores()); } _onClose() { ContactActionCreators.hideContactList(); } render() { let contacts = this.state.contacts; let isShown = this.state.isShown; let contactList = _.map(contacts, (contact, i) => { return ( <Contacts.ContactItem contact={contact} key={i}/> ); }); if (contacts !== null) { return ( <Modal className="modal contacts" closeTimeoutMS={150} isOpen={isShown}> <header className="modal__header"> <a className="modal__header__close material-icons" onClick={this._onClose}>clear</a> <h3>Contact list</h3> </header> <div className="modal__body"> <ul className="contacts__list"> {contactList} </ul> </div> </Modal> ); } else { return (null); } } } Contacts.ContactItem = React.createClass({ propTypes: { contact: React.PropTypes.object }, mixins: [PureRenderMixin], _openNewPrivateCoversation() { DialogActionCreators.selectDialogPeerUser(this.props.contact.uid); ContactActionCreators.hideContactList(); }, render() { let contact = this.props.contact; return ( <li className="contacts__list__item row"> <AvatarItem image={contact.avatar} placeholder={contact.placeholder} size="small" title={contact.name}/> <div className="col-xs"> <span className="title"> {contact.name} </span> </div> <div className="controls"> <a className="material-icons" onClick={this._openNewPrivateCoversation}>message</a> </div> </li> ); } }); export default Contacts;
ajax/libs/webshim/1.14.4/dev/shims/moxie/js/moxie.js
xymostech/cdnjs
/** * mOxie - multi-runtime File API & XMLHttpRequest L2 Polyfill * v1.2.1 * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing * * Date: 2014-05-14 */ /** * Compiled inline version. (Library mode) */ /*jshint smarttabs:true, undef:true, latedef:true, curly:true, bitwise:true, camelcase:true */ /*globals $code */ (function(exports, undefined) { "use strict"; var modules = {}; function require(ids, callback) { var module, defs = []; for (var i = 0; i < ids.length; ++i) { module = modules[ids[i]] || resolve(ids[i]); if (!module) { throw 'module definition dependecy not found: ' + ids[i]; } defs.push(module); } callback.apply(null, defs); } function define(id, dependencies, definition) { if (typeof id !== 'string') { throw 'invalid module definition, module id must be defined and be a string'; } if (dependencies === undefined) { throw 'invalid module definition, dependencies must be specified'; } if (definition === undefined) { throw 'invalid module definition, definition function must be specified'; } require(dependencies, function() { modules[id] = definition.apply(null, arguments); }); } function defined(id) { return !!modules[id]; } function resolve(id) { var target = exports; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length; ++fi) { if (!target[fragments[fi]]) { return; } target = target[fragments[fi]]; } return target; } function expose(ids) { for (var i = 0; i < ids.length; i++) { var target = exports; var id = ids[i]; var fragments = id.split(/[.\/]/); for (var fi = 0; fi < fragments.length - 1; ++fi) { if (target[fragments[fi]] === undefined) { target[fragments[fi]] = {}; } target = target[fragments[fi]]; } target[fragments[fragments.length - 1]] = modules[id]; } } // Included from: src/javascript/core/utils/Basic.js /** * Basic.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Basic', [], function() { /** Gets the true type of the built-in object (better version of typeof). @author Angus Croll (http://javascriptweblog.wordpress.com/) @method typeOf @for Utils @static @param {Object} o Object to check. @return {String} Object [[Class]] */ var typeOf = function(o) { var undef; if (o === undef) { return 'undefined'; } else if (o === null) { return 'null'; } else if (o.nodeType) { return 'node'; } // the snippet below is awesome, however it fails to detect null, undefined and arguments types in IE lte 8 return ({}).toString.call(o).match(/\s([a-z|A-Z]+)/)[1].toLowerCase(); }; /** Extends the specified object with another object. @method extend @static @param {Object} target Object to extend. @param {Object} [obj]* Multiple objects to extend with. @return {Object} Same as target, the extended object. */ var extend = function(target) { var undef; each(arguments, function(arg, i) { if (i > 0) { each(arg, function(value, key) { if (value !== undef) { if (typeOf(target[key]) === typeOf(value) && !!~inArray(typeOf(value), ['array', 'object'])) { extend(target[key], value); } else { target[key] = value; } } }); } }); return target; }; /** Executes the callback function for each item in array/object. If you return false in the callback it will break the loop. @method each @static @param {Object} obj Object to iterate. @param {function} callback Callback function to execute for each item. */ var each = function(obj, callback) { var length, key, i, undef; if (obj) { try { length = obj.length; } catch(ex) { length = undef; } if (length === undef) { // Loop object items for (key in obj) { if (obj.hasOwnProperty(key)) { if (callback(obj[key], key) === false) { return; } } } } else { // Loop array items for (i = 0; i < length; i++) { if (callback(obj[i], i) === false) { return; } } } } }; /** Checks if object is empty. @method isEmptyObj @static @param {Object} o Object to check. @return {Boolean} */ var isEmptyObj = function(obj) { var prop; if (!obj || typeOf(obj) !== 'object') { return true; } for (prop in obj) { return false; } return true; }; /** Recieve an array of functions (usually async) to call in sequence, each function receives a callback as first argument that it should call, when it completes. Finally, after everything is complete, main callback is called. Passing truthy value to the callback as a first argument will interrupt the sequence and invoke main callback immediately. @method inSeries @static @param {Array} queue Array of functions to call in sequence @param {Function} cb Main callback that is called in the end, or in case of error */ var inSeries = function(queue, cb) { var i = 0, length = queue.length; if (typeOf(cb) !== 'function') { cb = function() {}; } if (!queue || !queue.length) { cb(); } function callNext(i) { if (typeOf(queue[i]) === 'function') { queue[i](function(error) { /*jshint expr:true */ ++i < length && !error ? callNext(i) : cb(error); }); } } callNext(i); }; /** Recieve an array of functions (usually async) to call in parallel, each function receives a callback as first argument that it should call, when it completes. After everything is complete, main callback is called. Passing truthy value to the callback as a first argument will interrupt the process and invoke main callback immediately. @method inParallel @static @param {Array} queue Array of functions to call in sequence @param {Function} cb Main callback that is called in the end, or in case of erro */ var inParallel = function(queue, cb) { var count = 0, num = queue.length, cbArgs = new Array(num); each(queue, function(fn, i) { fn(function(error) { if (error) { return cb(error); } var args = [].slice.call(arguments); args.shift(); // strip error - undefined or not cbArgs[i] = args; count++; if (count === num) { cbArgs.unshift(null); cb.apply(this, cbArgs); } }); }); }; /** Find an element in array and return it's index if present, otherwise return -1. @method inArray @static @param {Mixed} needle Element to find @param {Array} array @return {Int} Index of the element, or -1 if not found */ var inArray = function(needle, array) { if (array) { if (Array.prototype.indexOf) { return Array.prototype.indexOf.call(array, needle); } for (var i = 0, length = array.length; i < length; i++) { if (array[i] === needle) { return i; } } } return -1; }; /** Returns elements of first array if they are not present in second. And false - otherwise. @private @method arrayDiff @param {Array} needles @param {Array} array @return {Array|Boolean} */ var arrayDiff = function(needles, array) { var diff = []; if (typeOf(needles) !== 'array') { needles = [needles]; } if (typeOf(array) !== 'array') { array = [array]; } for (var i in needles) { if (inArray(needles[i], array) === -1) { diff.push(needles[i]); } } return diff.length ? diff : false; }; /** Find intersection of two arrays. @private @method arrayIntersect @param {Array} array1 @param {Array} array2 @return {Array} Intersection of two arrays or null if there is none */ var arrayIntersect = function(array1, array2) { var result = []; each(array1, function(item) { if (inArray(item, array2) !== -1) { result.push(item); } }); return result.length ? result : null; }; /** Forces anything into an array. @method toArray @static @param {Object} obj Object with length field. @return {Array} Array object containing all items. */ var toArray = function(obj) { var i, arr = []; for (i = 0; i < obj.length; i++) { arr[i] = obj[i]; } return arr; }; /** Generates an unique ID. This is 99.99% unique since it takes the current time and 5 random numbers. The only way a user would be able to get the same ID is if the two persons at the same exact milisecond manages to get 5 the same random numbers between 0-65535 it also uses a counter so each call will be guaranteed to be page unique. It's more probable for the earth to be hit with an ansteriod. Y @method guid @static @param {String} prefix to prepend (by default 'o' will be prepended). @method guid @return {String} Virtually unique id. */ var guid = (function() { var counter = 0; return function(prefix) { var guid = new Date().getTime().toString(32), i; for (i = 0; i < 5; i++) { guid += Math.floor(Math.random() * 65535).toString(32); } return (prefix || 'o_') + guid + (counter++).toString(32); }; }()); /** Trims white spaces around the string @method trim @static @param {String} str @return {String} */ var trim = function(str) { if (!str) { return str; } return String.prototype.trim ? String.prototype.trim.call(str) : str.toString().replace(/^\s*/, '').replace(/\s*$/, ''); }; /** Parses the specified size string into a byte value. For example 10kb becomes 10240. @method parseSizeStr @static @param {String/Number} size String to parse or number to just pass through. @return {Number} Size in bytes. */ var parseSizeStr = function(size) { if (typeof(size) !== 'string') { return size; } var muls = { t: 1099511627776, g: 1073741824, m: 1048576, k: 1024 }, mul; size = /^([0-9]+)([mgk]?)$/.exec(size.toLowerCase().replace(/[^0-9mkg]/g, '')); mul = size[2]; size = +size[1]; if (muls.hasOwnProperty(mul)) { size *= muls[mul]; } return size; }; return { guid: guid, typeOf: typeOf, extend: extend, each: each, isEmptyObj: isEmptyObj, inSeries: inSeries, inParallel: inParallel, inArray: inArray, arrayDiff: arrayDiff, arrayIntersect: arrayIntersect, toArray: toArray, trim: trim, parseSizeStr: parseSizeStr }; }); // Included from: src/javascript/core/I18n.js /** * I18n.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/I18n", [ "moxie/core/utils/Basic" ], function(Basic) { var i18n = {}; return { /** * Extends the language pack object with new items. * * @param {Object} pack Language pack items to add. * @return {Object} Extended language pack object. */ addI18n: function(pack) { return Basic.extend(i18n, pack); }, /** * Translates the specified string by checking for the english string in the language pack lookup. * * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ translate: function(str) { return i18n[str] || str; }, /** * Shortcut for translate function * * @param {String} str String to look for. * @return {String} Translated string or the input string if it wasn't found. */ _: function(str) { return this.translate(str); }, /** * Pseudo sprintf implementation - simple way to replace tokens with specified values. * * @param {String} str String with tokens * @return {String} String with replaced tokens */ sprintf: function(str) { var args = [].slice.call(arguments, 1); return str.replace(/%[a-z]/g, function() { var value = args.shift(); return Basic.typeOf(value) !== 'undefined' ? value : ''; }); } }; }); // Included from: src/javascript/core/utils/Mime.js /** * Mime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/utils/Mime", [ "moxie/core/utils/Basic", "moxie/core/I18n" ], function(Basic, I18n) { var mimeData = "" + "application/msword,doc dot," + "application/pdf,pdf," + "application/pgp-signature,pgp," + "application/postscript,ps ai eps," + "application/rtf,rtf," + "application/vnd.ms-excel,xls xlb," + "application/vnd.ms-powerpoint,ppt pps pot," + "application/zip,zip," + "application/x-shockwave-flash,swf swfl," + "application/vnd.openxmlformats-officedocument.wordprocessingml.document,docx," + "application/vnd.openxmlformats-officedocument.wordprocessingml.template,dotx," + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,xlsx," + "application/vnd.openxmlformats-officedocument.presentationml.presentation,pptx," + "application/vnd.openxmlformats-officedocument.presentationml.template,potx," + "application/vnd.openxmlformats-officedocument.presentationml.slideshow,ppsx," + "application/x-javascript,js," + "application/json,json," + "audio/mpeg,mp3 mpga mpega mp2," + "audio/x-wav,wav," + "audio/x-m4a,m4a," + "audio/ogg,oga ogg," + "audio/aiff,aiff aif," + "audio/flac,flac," + "audio/aac,aac," + "audio/ac3,ac3," + "audio/x-ms-wma,wma," + "image/bmp,bmp," + "image/gif,gif," + "image/jpeg,jpg jpeg jpe," + "image/photoshop,psd," + "image/png,png," + "image/svg+xml,svg svgz," + "image/tiff,tiff tif," + "text/plain,asc txt text diff log," + "text/html,htm html xhtml," + "text/css,css," + "text/csv,csv," + "text/rtf,rtf," + "video/mpeg,mpeg mpg mpe m2v," + "video/quicktime,qt mov," + "video/mp4,mp4," + "video/x-m4v,m4v," + "video/x-flv,flv," + "video/x-ms-wmv,wmv," + "video/avi,avi," + "video/webm,webm," + "video/3gpp,3gpp 3gp," + "video/3gpp2,3g2," + "video/vnd.rn-realvideo,rv," + "video/ogg,ogv," + "video/x-matroska,mkv," + "application/vnd.oasis.opendocument.formula-template,otf," + "application/octet-stream,exe"; var Mime = { mimes: {}, extensions: {}, // Parses the default mime types string into a mimes and extensions lookup maps addMimeType: function (mimeData) { var items = mimeData.split(/,/), i, ii, ext; for (i = 0; i < items.length; i += 2) { ext = items[i + 1].split(/ /); // extension to mime lookup for (ii = 0; ii < ext.length; ii++) { this.mimes[ext[ii]] = items[i]; } // mime to extension lookup this.extensions[items[i]] = ext; } }, extList2mimes: function (filters, addMissingExtensions) { var self = this, ext, i, ii, type, mimes = []; // convert extensions to mime types list for (i = 0; i < filters.length; i++) { ext = filters[i].extensions.split(/\s*,\s*/); for (ii = 0; ii < ext.length; ii++) { // if there's an asterisk in the list, then accept attribute is not required if (ext[ii] === '*') { return []; } type = self.mimes[ext[ii]]; if (!type) { if (addMissingExtensions && /^\w+$/.test(ext[ii])) { mimes.push('.' + ext[ii]); } else { return []; // accept all } } else if (Basic.inArray(type, mimes) === -1) { mimes.push(type); } } } return mimes; }, mimes2exts: function(mimes) { var self = this, exts = []; Basic.each(mimes, function(mime) { if (mime === '*') { exts = []; return false; } // check if this thing looks like mime type var m = mime.match(/^(\w+)\/(\*|\w+)$/); if (m) { if (m[2] === '*') { // wildcard mime type detected Basic.each(self.extensions, function(arr, mime) { if ((new RegExp('^' + m[1] + '/')).test(mime)) { [].push.apply(exts, self.extensions[mime]); } }); } else if (self.extensions[mime]) { [].push.apply(exts, self.extensions[mime]); } } }); return exts; }, mimes2extList: function(mimes) { var accept = [], exts = []; if (Basic.typeOf(mimes) === 'string') { mimes = Basic.trim(mimes).split(/\s*,\s*/); } exts = this.mimes2exts(mimes); accept.push({ title: I18n.translate('Files'), extensions: exts.length ? exts.join(',') : '*' }); // save original mimes string accept.mimes = mimes; return accept; }, getFileExtension: function(fileName) { var matches = fileName && fileName.match(/\.([^.]+)$/); if (matches) { return matches[1].toLowerCase(); } return ''; }, getFileMime: function(fileName) { return this.mimes[this.getFileExtension(fileName)] || ''; } }; Mime.addMimeType(mimeData); return Mime; }); // Included from: src/javascript/core/utils/Env.js /** * Env.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/core/utils/Env", [ "moxie/core/utils/Basic" ], function(Basic) { // UAParser.js v0.6.2 // Lightweight JavaScript-based User-Agent string parser // https://github.com/faisalman/ua-parser-js // // Copyright © 2012-2013 Faisalman <[email protected]> // Dual licensed under GPLv2 & MIT var UAParser = (function (undefined) { ////////////// // Constants ///////////// var EMPTY = '', UNKNOWN = '?', FUNC_TYPE = 'function', UNDEF_TYPE = 'undefined', OBJ_TYPE = 'object', MAJOR = 'major', MODEL = 'model', NAME = 'name', TYPE = 'type', VENDOR = 'vendor', VERSION = 'version', ARCHITECTURE= 'architecture', CONSOLE = 'console', MOBILE = 'mobile', TABLET = 'tablet'; /////////// // Helper ////////// var util = { has : function (str1, str2) { return str2.toLowerCase().indexOf(str1.toLowerCase()) !== -1; }, lowerize : function (str) { return str.toLowerCase(); } }; /////////////// // Map helper ////////////// var mapper = { rgx : function () { // loop through all regexes maps for (var result, i = 0, j, k, p, q, matches, match, args = arguments; i < args.length; i += 2) { var regex = args[i], // even sequence (0,2,4,..) props = args[i + 1]; // odd sequence (1,3,5,..) // construct object barebones if (typeof(result) === UNDEF_TYPE) { result = {}; for (p in props) { q = props[p]; if (typeof(q) === OBJ_TYPE) { result[q[0]] = undefined; } else { result[q] = undefined; } } } // try matching uastring with regexes for (j = k = 0; j < regex.length; j++) { matches = regex[j].exec(this.getUA()); if (!!matches) { for (p = 0; p < props.length; p++) { match = matches[++k]; q = props[p]; // check if given property is actually array if (typeof(q) === OBJ_TYPE && q.length > 0) { if (q.length == 2) { if (typeof(q[1]) == FUNC_TYPE) { // assign modified match result[q[0]] = q[1].call(this, match); } else { // assign given value, ignore regex match result[q[0]] = q[1]; } } else if (q.length == 3) { // check whether function or regex if (typeof(q[1]) === FUNC_TYPE && !(q[1].exec && q[1].test)) { // call function (usually string mapper) result[q[0]] = match ? q[1].call(this, match, q[2]) : undefined; } else { // sanitize match using given regex result[q[0]] = match ? match.replace(q[1], q[2]) : undefined; } } else if (q.length == 4) { result[q[0]] = match ? q[3].call(this, match.replace(q[1], q[2])) : undefined; } } else { result[q] = match ? match : undefined; } } break; } } if(!!matches) break; // break the loop immediately if match found } return result; }, str : function (str, map) { for (var i in map) { // check if array if (typeof(map[i]) === OBJ_TYPE && map[i].length > 0) { for (var j = 0; j < map[i].length; j++) { if (util.has(map[i][j], str)) { return (i === UNKNOWN) ? undefined : i; } } } else if (util.has(map[i], str)) { return (i === UNKNOWN) ? undefined : i; } } return str; } }; /////////////// // String map ////////////// var maps = { browser : { oldsafari : { major : { '1' : ['/8', '/1', '/3'], '2' : '/4', '?' : '/' }, version : { '1.0' : '/8', '1.2' : '/1', '1.3' : '/3', '2.0' : '/412', '2.0.2' : '/416', '2.0.3' : '/417', '2.0.4' : '/419', '?' : '/' } } }, device : { sprint : { model : { 'Evo Shift 4G' : '7373KT' }, vendor : { 'HTC' : 'APA', 'Sprint' : 'Sprint' } } }, os : { windows : { version : { 'ME' : '4.90', 'NT 3.11' : 'NT3.51', 'NT 4.0' : 'NT4.0', '2000' : 'NT 5.0', 'XP' : ['NT 5.1', 'NT 5.2'], 'Vista' : 'NT 6.0', '7' : 'NT 6.1', '8' : 'NT 6.2', '8.1' : 'NT 6.3', 'RT' : 'ARM' } } } }; ////////////// // Regex map ///////////// var regexes = { browser : [[ // Presto based /(opera\smini)\/((\d+)?[\w\.-]+)/i, // Opera Mini /(opera\s[mobiletab]+).+version\/((\d+)?[\w\.-]+)/i, // Opera Mobi/Tablet /(opera).+version\/((\d+)?[\w\.]+)/i, // Opera > 9.80 /(opera)[\/\s]+((\d+)?[\w\.]+)/i // Opera < 9.80 ], [NAME, VERSION, MAJOR], [ /\s(opr)\/((\d+)?[\w\.]+)/i // Opera Webkit ], [[NAME, 'Opera'], VERSION, MAJOR], [ // Mixed /(kindle)\/((\d+)?[\w\.]+)/i, // Kindle /(lunascape|maxthon|netfront|jasmine|blazer)[\/\s]?((\d+)?[\w\.]+)*/i, // Lunascape/Maxthon/Netfront/Jasmine/Blazer // Trident based /(avant\s|iemobile|slim|baidu)(?:browser)?[\/\s]?((\d+)?[\w\.]*)/i, // Avant/IEMobile/SlimBrowser/Baidu /(?:ms|\()(ie)\s((\d+)?[\w\.]+)/i, // Internet Explorer // Webkit/KHTML based /(rekonq)((?:\/)[\w\.]+)*/i, // Rekonq /(chromium|flock|rockmelt|midori|epiphany|silk|skyfire|ovibrowser|bolt|iron)\/((\d+)?[\w\.-]+)/i // Chromium/Flock/RockMelt/Midori/Epiphany/Silk/Skyfire/Bolt/Iron ], [NAME, VERSION, MAJOR], [ /(trident).+rv[:\s]((\d+)?[\w\.]+).+like\sgecko/i // IE11 ], [[NAME, 'IE'], VERSION, MAJOR], [ /(yabrowser)\/((\d+)?[\w\.]+)/i // Yandex ], [[NAME, 'Yandex'], VERSION, MAJOR], [ /(comodo_dragon)\/((\d+)?[\w\.]+)/i // Comodo Dragon ], [[NAME, /_/g, ' '], VERSION, MAJOR], [ /(chrome|omniweb|arora|[tizenoka]{5}\s?browser)\/v?((\d+)?[\w\.]+)/i // Chrome/OmniWeb/Arora/Tizen/Nokia ], [NAME, VERSION, MAJOR], [ /(dolfin)\/((\d+)?[\w\.]+)/i // Dolphin ], [[NAME, 'Dolphin'], VERSION, MAJOR], [ /((?:android.+)crmo|crios)\/((\d+)?[\w\.]+)/i // Chrome for Android/iOS ], [[NAME, 'Chrome'], VERSION, MAJOR], [ /((?:android.+))version\/((\d+)?[\w\.]+)\smobile\ssafari/i // Android Browser ], [[NAME, 'Android Browser'], VERSION, MAJOR], [ /version\/((\d+)?[\w\.]+).+?mobile\/\w+\s(safari)/i // Mobile Safari ], [VERSION, MAJOR, [NAME, 'Mobile Safari']], [ /version\/((\d+)?[\w\.]+).+?(mobile\s?safari|safari)/i // Safari & Safari Mobile ], [VERSION, MAJOR, NAME], [ /webkit.+?(mobile\s?safari|safari)((\/[\w\.]+))/i // Safari < 3.0 ], [NAME, [MAJOR, mapper.str, maps.browser.oldsafari.major], [VERSION, mapper.str, maps.browser.oldsafari.version]], [ /(konqueror)\/((\d+)?[\w\.]+)/i, // Konqueror /(webkit|khtml)\/((\d+)?[\w\.]+)/i ], [NAME, VERSION, MAJOR], [ // Gecko based /(navigator|netscape)\/((\d+)?[\w\.-]+)/i // Netscape ], [[NAME, 'Netscape'], VERSION, MAJOR], [ /(swiftfox)/i, // Swiftfox /(icedragon|iceweasel|camino|chimera|fennec|maemo\sbrowser|minimo|conkeror)[\/\s]?((\d+)?[\w\.\+]+)/i, // IceDragon/Iceweasel/Camino/Chimera/Fennec/Maemo/Minimo/Conkeror /(firefox|seamonkey|k-meleon|icecat|iceape|firebird|phoenix)\/((\d+)?[\w\.-]+)/i, // Firefox/SeaMonkey/K-Meleon/IceCat/IceApe/Firebird/Phoenix /(mozilla)\/((\d+)?[\w\.]+).+rv\:.+gecko\/\d+/i, // Mozilla // Other /(uc\s?browser|polaris|lynx|dillo|icab|doris|amaya|w3m|netsurf|qqbrowser)[\/\s]?((\d+)?[\w\.]+)/i, // UCBrowser/Polaris/Lynx/Dillo/iCab/Doris/Amaya/w3m/NetSurf/QQBrowser /(links)\s\(((\d+)?[\w\.]+)/i, // Links /(gobrowser)\/?((\d+)?[\w\.]+)*/i, // GoBrowser /(ice\s?browser)\/v?((\d+)?[\w\._]+)/i, // ICE Browser /(mosaic)[\/\s]((\d+)?[\w\.]+)/i // Mosaic ], [NAME, VERSION, MAJOR] ], engine : [[ /(presto)\/([\w\.]+)/i, // Presto /(webkit|trident|netfront|netsurf|amaya|lynx|w3m)\/([\w\.]+)/i, // WebKit/Trident/NetFront/NetSurf/Amaya/Lynx/w3m /(khtml|tasman|links)[\/\s]\(?([\w\.]+)/i, // KHTML/Tasman/Links /(icab)[\/\s]([23]\.[\d\.]+)/i // iCab ], [NAME, VERSION], [ /rv\:([\w\.]+).*(gecko)/i // Gecko ], [VERSION, NAME] ], os : [[ // Windows based /(windows)\snt\s6\.2;\s(arm)/i, // Windows RT /(windows\sphone(?:\sos)*|windows\smobile|windows)[\s\/]?([ntce\d\.\s]+\w)/i ], [NAME, [VERSION, mapper.str, maps.os.windows.version]], [ /(win(?=3|9|n)|win\s9x\s)([nt\d\.]+)/i ], [[NAME, 'Windows'], [VERSION, mapper.str, maps.os.windows.version]], [ // Mobile/Embedded OS /\((bb)(10);/i // BlackBerry 10 ], [[NAME, 'BlackBerry'], VERSION], [ /(blackberry)\w*\/?([\w\.]+)*/i, // Blackberry /(tizen)\/([\w\.]+)/i, // Tizen /(android|webos|palm\os|qnx|bada|rim\stablet\sos|meego)[\/\s-]?([\w\.]+)*/i // Android/WebOS/Palm/QNX/Bada/RIM/MeeGo ], [NAME, VERSION], [ /(symbian\s?os|symbos|s60(?=;))[\/\s-]?([\w\.]+)*/i // Symbian ], [[NAME, 'Symbian'], VERSION],[ /mozilla.+\(mobile;.+gecko.+firefox/i // Firefox OS ], [[NAME, 'Firefox OS'], VERSION], [ // Console /(nintendo|playstation)\s([wids3portablevu]+)/i, // Nintendo/Playstation // GNU/Linux based /(mint)[\/\s\(]?(\w+)*/i, // Mint /(joli|[kxln]?ubuntu|debian|[open]*suse|gentoo|arch|slackware|fedora|mandriva|centos|pclinuxos|redhat|zenwalk)[\/\s-]?([\w\.-]+)*/i, // Joli/Ubuntu/Debian/SUSE/Gentoo/Arch/Slackware // Fedora/Mandriva/CentOS/PCLinuxOS/RedHat/Zenwalk /(hurd|linux)\s?([\w\.]+)*/i, // Hurd/Linux /(gnu)\s?([\w\.]+)*/i // GNU ], [NAME, VERSION], [ /(cros)\s[\w]+\s([\w\.]+\w)/i // Chromium OS ], [[NAME, 'Chromium OS'], VERSION],[ // Solaris /(sunos)\s?([\w\.]+\d)*/i // Solaris ], [[NAME, 'Solaris'], VERSION], [ // BSD based /\s([frentopc-]{0,4}bsd|dragonfly)\s?([\w\.]+)*/i // FreeBSD/NetBSD/OpenBSD/PC-BSD/DragonFly ], [NAME, VERSION],[ /(ip[honead]+)(?:.*os\s*([\w]+)*\slike\smac|;\sopera)/i // iOS ], [[NAME, 'iOS'], [VERSION, /_/g, '.']], [ /(mac\sos\sx)\s?([\w\s\.]+\w)*/i // Mac OS ], [NAME, [VERSION, /_/g, '.']], [ // Other /(haiku)\s(\w+)/i, // Haiku /(aix)\s((\d)(?=\.|\)|\s)[\w\.]*)*/i, // AIX /(macintosh|mac(?=_powerpc)|plan\s9|minix|beos|os\/2|amigaos|morphos|risc\sos)/i, // Plan9/Minix/BeOS/OS2/AmigaOS/MorphOS/RISCOS /(unix)\s?([\w\.]+)*/i // UNIX ], [NAME, VERSION] ] }; ///////////////// // Constructor //////////////// var UAParser = function (uastring) { var ua = uastring || ((window && window.navigator && window.navigator.userAgent) ? window.navigator.userAgent : EMPTY); this.getBrowser = function () { return mapper.rgx.apply(this, regexes.browser); }; this.getEngine = function () { return mapper.rgx.apply(this, regexes.engine); }; this.getOS = function () { return mapper.rgx.apply(this, regexes.os); }; this.getResult = function() { return { ua : this.getUA(), browser : this.getBrowser(), engine : this.getEngine(), os : this.getOS() }; }; this.getUA = function () { return ua; }; this.setUA = function (uastring) { ua = uastring; return this; }; this.setUA(ua); }; return new UAParser().getResult(); })(); function version_compare(v1, v2, operator) { // From: http://phpjs.org/functions // + original by: Philippe Jausions (http://pear.php.net/user/jausions) // + original by: Aidan Lister (http://aidanlister.com/) // + reimplemented by: Kankrelune (http://www.webfaktory.info/) // + improved by: Brett Zamir (http://brett-zamir.me) // + improved by: Scott Baker // + improved by: Theriault // * example 1: version_compare('8.2.5rc', '8.2.5a'); // * returns 1: 1 // * example 2: version_compare('8.2.50', '8.2.52', '<'); // * returns 2: true // * example 3: version_compare('5.3.0-dev', '5.3.0'); // * returns 3: -1 // * example 4: version_compare('4.1.0.52','4.01.0.51'); // * returns 4: 1 // Important: compare must be initialized at 0. var i = 0, x = 0, compare = 0, // vm maps textual PHP versions to negatives so they're less than 0. // PHP currently defines these as CASE-SENSITIVE. It is important to // leave these as negatives so that they can come before numerical versions // and as if no letters were there to begin with. // (1alpha is < 1 and < 1.1 but > 1dev1) // If a non-numerical value can't be mapped to this table, it receives // -7 as its value. vm = { 'dev': -6, 'alpha': -5, 'a': -5, 'beta': -4, 'b': -4, 'RC': -3, 'rc': -3, '#': -2, 'p': 1, 'pl': 1 }, // This function will be called to prepare each version argument. // It replaces every _, -, and + with a dot. // It surrounds any nonsequence of numbers/dots with dots. // It replaces sequences of dots with a single dot. // version_compare('4..0', '4.0') == 0 // Important: A string of 0 length needs to be converted into a value // even less than an unexisting value in vm (-7), hence [-8]. // It's also important to not strip spaces because of this. // version_compare('', ' ') == 1 prepVersion = function (v) { v = ('' + v).replace(/[_\-+]/g, '.'); v = v.replace(/([^.\d]+)/g, '.$1.').replace(/\.{2,}/g, '.'); return (!v.length ? [-8] : v.split('.')); }, // This converts a version component to a number. // Empty component becomes 0. // Non-numerical component becomes a negative number. // Numerical component becomes itself as an integer. numVersion = function (v) { return !v ? 0 : (isNaN(v) ? vm[v] || -7 : parseInt(v, 10)); }; v1 = prepVersion(v1); v2 = prepVersion(v2); x = Math.max(v1.length, v2.length); for (i = 0; i < x; i++) { if (v1[i] == v2[i]) { continue; } v1[i] = numVersion(v1[i]); v2[i] = numVersion(v2[i]); if (v1[i] < v2[i]) { compare = -1; break; } else if (v1[i] > v2[i]) { compare = 1; break; } } if (!operator) { return compare; } // Important: operator is CASE-SENSITIVE. // "No operator" seems to be treated as "<." // Any other values seem to make the function return null. switch (operator) { case '>': case 'gt': return (compare > 0); case '>=': case 'ge': return (compare >= 0); case '<=': case 'le': return (compare <= 0); case '==': case '=': case 'eq': return (compare === 0); case '<>': case '!=': case 'ne': return (compare !== 0); case '': case '<': case 'lt': return (compare < 0); default: return null; } } var can = (function() { var caps = { define_property: (function() { /* // currently too much extra code required, not exactly worth it try { // as of IE8, getters/setters are supported only on DOM elements var obj = {}; if (Object.defineProperty) { Object.defineProperty(obj, 'prop', { enumerable: true, configurable: true }); return true; } } catch(ex) {} if (Object.prototype.__defineGetter__ && Object.prototype.__defineSetter__) { return true; }*/ return false; }()), create_canvas: (function() { // On the S60 and BB Storm, getContext exists, but always returns undefined // so we actually have to call getContext() to verify // github.com/Modernizr/Modernizr/issues/issue/97/ var el = document.createElement('canvas'); return !!(el.getContext && el.getContext('2d')); }()), return_response_type: function(responseType) { try { if (Basic.inArray(responseType, ['', 'text', 'document']) !== -1) { return true; } else if (window.XMLHttpRequest) { var xhr = new XMLHttpRequest(); xhr.open('get', '/'); // otherwise Gecko throws an exception if ('responseType' in xhr) { xhr.responseType = responseType; // as of 23.0.1271.64, Chrome switched from throwing exception to merely logging it to the console (why? o why?) if (xhr.responseType !== responseType) { return false; } return true; } } } catch (ex) {} return false; }, // ideas for this heavily come from Modernizr (http://modernizr.com/) use_data_uri: (function() { var du = new Image(); du.onload = function() { caps.use_data_uri = (du.width === 1 && du.height === 1); }; setTimeout(function() { du.src = "data:image/gif;base64,R0lGODlhAQABAIAAAP8AAAAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=="; }, 1); return false; }()), use_data_uri_over32kb: function() { // IE8 return caps.use_data_uri && (Env.browser !== 'IE' || Env.version >= 9); }, use_data_uri_of: function(bytes) { return (caps.use_data_uri && bytes < 33000 || caps.use_data_uri_over32kb()); }, use_fileinput: function() { var el = document.createElement('input'); el.setAttribute('type', 'file'); return !el.disabled; } }; return function(cap) { var args = [].slice.call(arguments); args.shift(); // shift of cap return Basic.typeOf(caps[cap]) === 'function' ? caps[cap].apply(this, args) : !!caps[cap]; }; }()); var Env = { can: can, browser: UAParser.browser.name, version: parseFloat(UAParser.browser.major), os: UAParser.os.name, // everybody intuitively types it in a lowercase for some reason osVersion: UAParser.os.version, verComp: version_compare, swf_url: "../flash/Moxie.swf", xap_url: "../silverlight/Moxie.xap", global_event_dispatcher: "moxie.core.EventTarget.instance.dispatchEvent" }; // for backward compatibility // @deprecated Use `Env.os` instead Env.OS = Env.os; return Env; }); // Included from: src/javascript/core/utils/Dom.js /** * Dom.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Dom', ['moxie/core/utils/Env'], function(Env) { /** Get DOM Element by it's id. @method get @for Utils @param {String} id Identifier of the DOM Element @return {DOMElement} */ var get = function(id) { if (typeof id !== 'string') { return id; } return document.getElementById(id); }; /** Checks if specified DOM element has specified class. @method hasClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var hasClass = function(obj, name) { if (!obj.className) { return false; } var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)"); return regExp.test(obj.className); }; /** Adds specified className to specified DOM element. @method addClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var addClass = function(obj, name) { if (!hasClass(obj, name)) { obj.className = !obj.className ? name : obj.className.replace(/\s+$/, '') + ' ' + name; } }; /** Removes specified className from specified DOM element. @method removeClass @static @param {Object} obj DOM element like object to add handler to. @param {String} name Class name */ var removeClass = function(obj, name) { if (obj.className) { var regExp = new RegExp("(^|\\s+)"+name+"(\\s+|$)"); obj.className = obj.className.replace(regExp, function($0, $1, $2) { return $1 === ' ' && $2 === ' ' ? ' ' : ''; }); } }; /** Returns a given computed style of a DOM element. @method getStyle @static @param {Object} obj DOM element like object. @param {String} name Style you want to get from the DOM element */ var getStyle = function(obj, name) { if (obj.currentStyle) { return obj.currentStyle[name]; } else if (window.getComputedStyle) { return window.getComputedStyle(obj, null)[name]; } }; /** Returns the absolute x, y position of an Element. The position will be returned in a object with x, y fields. @method getPos @static @param {Element} node HTML element or element id to get x, y position from. @param {Element} root Optional root element to stop calculations at. @return {object} Absolute position of the specified element object with x, y fields. */ var getPos = function(node, root) { var x = 0, y = 0, parent, doc = document, nodeRect, rootRect; node = node; root = root || doc.body; // Returns the x, y cordinate for an element on IE 6 and IE 7 function getIEPos(node) { var bodyElm, rect, x = 0, y = 0; if (node) { rect = node.getBoundingClientRect(); bodyElm = doc.compatMode === "CSS1Compat" ? doc.documentElement : doc.body; x = rect.left + bodyElm.scrollLeft; y = rect.top + bodyElm.scrollTop; } return { x : x, y : y }; } // Use getBoundingClientRect on IE 6 and IE 7 but not on IE 8 in standards mode if (node && node.getBoundingClientRect && Env.browser === 'IE' && (!doc.documentMode || doc.documentMode < 8)) { nodeRect = getIEPos(node); rootRect = getIEPos(root); return { x : nodeRect.x - rootRect.x, y : nodeRect.y - rootRect.y }; } parent = node; while (parent && parent != root && parent.nodeType) { x += parent.offsetLeft || 0; y += parent.offsetTop || 0; parent = parent.offsetParent; } parent = node.parentNode; while (parent && parent != root && parent.nodeType) { x -= parent.scrollLeft || 0; y -= parent.scrollTop || 0; parent = parent.parentNode; } return { x : x, y : y }; }; /** Returns the size of the specified node in pixels. @method getSize @static @param {Node} node Node to get the size of. @return {Object} Object with a w and h property. */ var getSize = function(node) { return { w : node.offsetWidth || node.clientWidth, h : node.offsetHeight || node.clientHeight }; }; return { get: get, hasClass: hasClass, addClass: addClass, removeClass: removeClass, getStyle: getStyle, getPos: getPos, getSize: getSize }; }); // Included from: src/javascript/core/Exceptions.js /** * Exceptions.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/Exceptions', [ 'moxie/core/utils/Basic' ], function(Basic) { function _findKey(obj, value) { var key; for (key in obj) { if (obj[key] === value) { return key; } } return null; } return { RuntimeError: (function() { var namecodes = { NOT_INIT_ERR: 1, NOT_SUPPORTED_ERR: 9, JS_ERR: 4 }; function RuntimeError(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": RuntimeError " + this.code; } Basic.extend(RuntimeError, namecodes); RuntimeError.prototype = Error.prototype; return RuntimeError; }()), OperationNotAllowedException: (function() { function OperationNotAllowedException(code) { this.code = code; this.name = 'OperationNotAllowedException'; } Basic.extend(OperationNotAllowedException, { NOT_ALLOWED_ERR: 1 }); OperationNotAllowedException.prototype = Error.prototype; return OperationNotAllowedException; }()), ImageError: (function() { var namecodes = { WRONG_FORMAT: 1, MAX_RESOLUTION_ERR: 2 }; function ImageError(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": ImageError " + this.code; } Basic.extend(ImageError, namecodes); ImageError.prototype = Error.prototype; return ImageError; }()), FileException: (function() { var namecodes = { NOT_FOUND_ERR: 1, SECURITY_ERR: 2, ABORT_ERR: 3, NOT_READABLE_ERR: 4, ENCODING_ERR: 5, NO_MODIFICATION_ALLOWED_ERR: 6, INVALID_STATE_ERR: 7, SYNTAX_ERR: 8 }; function FileException(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": FileException " + this.code; } Basic.extend(FileException, namecodes); FileException.prototype = Error.prototype; return FileException; }()), DOMException: (function() { var namecodes = { INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2, HIERARCHY_REQUEST_ERR: 3, WRONG_DOCUMENT_ERR: 4, INVALID_CHARACTER_ERR: 5, NO_DATA_ALLOWED_ERR: 6, NO_MODIFICATION_ALLOWED_ERR: 7, NOT_FOUND_ERR: 8, NOT_SUPPORTED_ERR: 9, INUSE_ATTRIBUTE_ERR: 10, INVALID_STATE_ERR: 11, SYNTAX_ERR: 12, INVALID_MODIFICATION_ERR: 13, NAMESPACE_ERR: 14, INVALID_ACCESS_ERR: 15, VALIDATION_ERR: 16, TYPE_MISMATCH_ERR: 17, SECURITY_ERR: 18, NETWORK_ERR: 19, ABORT_ERR: 20, URL_MISMATCH_ERR: 21, QUOTA_EXCEEDED_ERR: 22, TIMEOUT_ERR: 23, INVALID_NODE_TYPE_ERR: 24, DATA_CLONE_ERR: 25 }; function DOMException(code) { this.code = code; this.name = _findKey(namecodes, code); this.message = this.name + ": DOMException " + this.code; } Basic.extend(DOMException, namecodes); DOMException.prototype = Error.prototype; return DOMException; }()), EventException: (function() { function EventException(code) { this.code = code; this.name = 'EventException'; } Basic.extend(EventException, { UNSPECIFIED_EVENT_TYPE_ERR: 0 }); EventException.prototype = Error.prototype; return EventException; }()) }; }); // Included from: src/javascript/core/EventTarget.js /** * EventTarget.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/EventTarget', [ 'moxie/core/Exceptions', 'moxie/core/utils/Basic' ], function(x, Basic) { /** Parent object for all event dispatching components and objects @class EventTarget @constructor EventTarget */ function EventTarget() { // hash of event listeners by object uid var eventpool = {}; Basic.extend(this, { /** Unique id of the event dispatcher, usually overriden by children @property uid @type String */ uid: null, /** Can be called from within a child in order to acquire uniqie id in automated manner @method init */ init: function() { if (!this.uid) { this.uid = Basic.guid('uid_'); } }, /** Register a handler to a specific event dispatched by the object @method addEventListener @param {String} type Type or basically a name of the event to subscribe to @param {Function} fn Callback function that will be called when event happens @param {Number} [priority=0] Priority of the event handler - handlers with higher priorities will be called first @param {Object} [scope=this] A scope to invoke event handler in */ addEventListener: function(type, fn, priority, scope) { var self = this, list; type = Basic.trim(type); if (/\s/.test(type)) { // multiple event types were passed for one handler Basic.each(type.split(/\s+/), function(type) { self.addEventListener(type, fn, priority, scope); }); return; } type = type.toLowerCase(); priority = parseInt(priority, 10) || 0; list = eventpool[this.uid] && eventpool[this.uid][type] || []; list.push({fn : fn, priority : priority, scope : scope || this}); if (!eventpool[this.uid]) { eventpool[this.uid] = {}; } eventpool[this.uid][type] = list; }, /** Check if any handlers were registered to the specified event @method hasEventListener @param {String} type Type or basically a name of the event to check @return {Mixed} Returns a handler if it was found and false, if - not */ hasEventListener: function(type) { return type ? !!(eventpool[this.uid] && eventpool[this.uid][type]) : !!eventpool[this.uid]; }, /** Unregister the handler from the event, or if former was not specified - unregister all handlers @method removeEventListener @param {String} type Type or basically a name of the event @param {Function} [fn] Handler to unregister */ removeEventListener: function(type, fn) { type = type.toLowerCase(); var list = eventpool[this.uid] && eventpool[this.uid][type], i; if (list) { if (fn) { for (i = list.length - 1; i >= 0; i--) { if (list[i].fn === fn) { list.splice(i, 1); break; } } } else { list = []; } // delete event list if it has become empty if (!list.length) { delete eventpool[this.uid][type]; // and object specific entry in a hash if it has no more listeners attached if (Basic.isEmptyObj(eventpool[this.uid])) { delete eventpool[this.uid]; } } } }, /** Remove all event handlers from the object @method removeAllEventListeners */ removeAllEventListeners: function() { if (eventpool[this.uid]) { delete eventpool[this.uid]; } }, /** Dispatch the event @method dispatchEvent @param {String/Object} Type of event or event object to dispatch @param {Mixed} [...] Variable number of arguments to be passed to a handlers @return {Boolean} true by default and false if any handler returned false */ dispatchEvent: function(type) { var uid, list, args, tmpEvt, evt = {}, result = true, undef; if (Basic.typeOf(type) !== 'string') { // we can't use original object directly (because of Silverlight) tmpEvt = type; if (Basic.typeOf(tmpEvt.type) === 'string') { type = tmpEvt.type; if (tmpEvt.total !== undef && tmpEvt.loaded !== undef) { // progress event evt.total = tmpEvt.total; evt.loaded = tmpEvt.loaded; } evt.async = tmpEvt.async || false; } else { throw new x.EventException(x.EventException.UNSPECIFIED_EVENT_TYPE_ERR); } } // check if event is meant to be dispatched on an object having specific uid if (type.indexOf('::') !== -1) { (function(arr) { uid = arr[0]; type = arr[1]; }(type.split('::'))); } else { uid = this.uid; } type = type.toLowerCase(); list = eventpool[uid] && eventpool[uid][type]; if (list) { // sort event list by prority list.sort(function(a, b) { return b.priority - a.priority; }); args = [].slice.call(arguments); // first argument will be pseudo-event object args.shift(); evt.type = type; args.unshift(evt); // Dispatch event to all listeners var queue = []; Basic.each(list, function(handler) { // explicitly set the target, otherwise events fired from shims do not get it args[0].target = handler.scope; // if event is marked as async, detach the handler if (evt.async) { queue.push(function(cb) { setTimeout(function() { cb(handler.fn.apply(handler.scope, args) === false); }, 1); }); } else { queue.push(function(cb) { cb(handler.fn.apply(handler.scope, args) === false); // if handler returns false stop propagation }); } }); if (queue.length) { Basic.inSeries(queue, function(err) { result = !err; }); } } return result; }, /** Alias for addEventListener @method bind @protected */ bind: function() { this.addEventListener.apply(this, arguments); }, /** Alias for removeEventListener @method unbind @protected */ unbind: function() { this.removeEventListener.apply(this, arguments); }, /** Alias for removeAllEventListeners @method unbindAll @protected */ unbindAll: function() { this.removeAllEventListeners.apply(this, arguments); }, /** Alias for dispatchEvent @method trigger @protected */ trigger: function() { return this.dispatchEvent.apply(this, arguments); }, /** Converts properties of on[event] type to corresponding event handlers, is used to avoid extra hassle around the process of calling them back @method convertEventPropsToHandlers @private */ convertEventPropsToHandlers: function(handlers) { var h; if (Basic.typeOf(handlers) !== 'array') { handlers = [handlers]; } for (var i = 0; i < handlers.length; i++) { h = 'on' + handlers[i]; if (Basic.typeOf(this[h]) === 'function') { this.addEventListener(handlers[i], this[h]); } else if (Basic.typeOf(this[h]) === 'undefined') { this[h] = null; // object must have defined event properties, even if it doesn't make use of them } } } }); } EventTarget.instance = new EventTarget(); return EventTarget; }); // Included from: src/javascript/core/utils/Encode.js /** * Encode.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Encode', [], function() { /** Encode string with UTF-8 @method utf8_encode @for Utils @static @param {String} str String to encode @return {String} UTF-8 encoded string */ var utf8_encode = function(str) { return unescape(encodeURIComponent(str)); }; /** Decode UTF-8 encoded string @method utf8_decode @static @param {String} str String to decode @return {String} Decoded string */ var utf8_decode = function(str_data) { return decodeURIComponent(escape(str_data)); }; /** Decode Base64 encoded string (uses browser's default method if available), from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_decode.js @method atob @static @param {String} data String to decode @return {String} Decoded string */ var atob = function(data, utf8) { if (typeof(window.atob) === 'function') { return utf8 ? utf8_decode(window.atob(data)) : window.atob(data); } // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Thunder.m // + input by: Aman Gupta // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Onno Marsman // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA=='); // * returns 1: 'Kevin van Zonneveld' // mozilla has this native // - but breaks in 2.0.0.12! //if (typeof this.window.atob == 'function') { // return atob(data); //} var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = []; if (!data) { return data; } data += ''; do { // unpack four hexets into three octets using index points in b64 h1 = b64.indexOf(data.charAt(i++)); h2 = b64.indexOf(data.charAt(i++)); h3 = b64.indexOf(data.charAt(i++)); h4 = b64.indexOf(data.charAt(i++)); bits = h1 << 18 | h2 << 12 | h3 << 6 | h4; o1 = bits >> 16 & 0xff; o2 = bits >> 8 & 0xff; o3 = bits & 0xff; if (h3 == 64) { tmp_arr[ac++] = String.fromCharCode(o1); } else if (h4 == 64) { tmp_arr[ac++] = String.fromCharCode(o1, o2); } else { tmp_arr[ac++] = String.fromCharCode(o1, o2, o3); } } while (i < data.length); dec = tmp_arr.join(''); return utf8 ? utf8_decode(dec) : dec; }; /** Base64 encode string (uses browser's default method if available), from: https://raw.github.com/kvz/phpjs/master/functions/url/base64_encode.js @method btoa @static @param {String} data String to encode @return {String} Base64 encoded string */ var btoa = function(data, utf8) { if (utf8) { utf8_encode(data); } if (typeof(window.btoa) === 'function') { return window.btoa(data); } // http://kevin.vanzonneveld.net // + original by: Tyler Akins (http://rumkin.com) // + improved by: Bayron Guevara // + improved by: Thunder.m // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + bugfixed by: Pellentesque Malesuada // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Rafał Kukawski (http://kukawski.pl) // * example 1: base64_encode('Kevin van Zonneveld'); // * returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA==' // mozilla has this native // - but breaks in 2.0.0.12! var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="; var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc = "", tmp_arr = []; if (!data) { return data; } do { // pack three octets into four hexets o1 = data.charCodeAt(i++); o2 = data.charCodeAt(i++); o3 = data.charCodeAt(i++); bits = o1 << 16 | o2 << 8 | o3; h1 = bits >> 18 & 0x3f; h2 = bits >> 12 & 0x3f; h3 = bits >> 6 & 0x3f; h4 = bits & 0x3f; // use hexets to index into b64, and append result to encoded string tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4); } while (i < data.length); enc = tmp_arr.join(''); var r = data.length % 3; return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3); }; return { utf8_encode: utf8_encode, utf8_decode: utf8_decode, atob: atob, btoa: btoa }; }); // Included from: src/javascript/runtime/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/Runtime', [ "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/EventTarget" ], function(Basic, Dom, EventTarget) { var runtimeConstructors = {}, runtimes = {}; /** Common set of methods and properties for every runtime instance @class Runtime @param {Object} options @param {String} type Sanitized name of the runtime @param {Object} [caps] Set of capabilities that differentiate specified runtime @param {Object} [modeCaps] Set of capabilities that do require specific operational mode @param {String} [preferredMode='browser'] Preferred operational mode to choose if no required capabilities were requested */ function Runtime(options, type, caps, modeCaps, preferredMode) { /** Dispatched when runtime is initialized and ready. Results in RuntimeInit on a connected component. @event Init */ /** Dispatched when runtime fails to initialize. Results in RuntimeError on a connected component. @event Error */ var self = this , _shim , _uid = Basic.guid(type + '_') , defaultMode = preferredMode || 'browser' ; options = options || {}; // register runtime in private hash runtimes[_uid] = this; /** Default set of capabilities, which can be redifined later by specific runtime @private @property caps @type Object */ caps = Basic.extend({ // Runtime can: // provide access to raw binary data of the file access_binary: false, // provide access to raw binary data of the image (image extension is optional) access_image_binary: false, // display binary data as thumbs for example display_media: false, // make cross-domain requests do_cors: false, // accept files dragged and dropped from the desktop drag_and_drop: false, // filter files in selection dialog by their extensions filter_by_extension: true, // resize image (and manipulate it raw data of any file in general) resize_image: false, // periodically report how many bytes of total in the file were uploaded (loaded) report_upload_progress: false, // provide access to the headers of http response return_response_headers: false, // support response of specific type, which should be passed as an argument // e.g. runtime.can('return_response_type', 'blob') return_response_type: false, // return http status code of the response return_status_code: true, // send custom http header with the request send_custom_headers: false, // pick up the files from a dialog select_file: false, // select whole folder in file browse dialog select_folder: false, // select multiple files at once in file browse dialog select_multiple: true, // send raw binary data, that is generated after image resizing or manipulation of other kind send_binary_string: false, // send cookies with http request and therefore retain session send_browser_cookies: true, // send data formatted as multipart/form-data send_multipart: true, // slice the file or blob to smaller parts slice_blob: false, // upload file without preloading it to memory, stream it out directly from disk stream_upload: false, // programmatically trigger file browse dialog summon_file_dialog: false, // upload file of specific size, size should be passed as argument // e.g. runtime.can('upload_filesize', '500mb') upload_filesize: true, // initiate http request with specific http method, method should be passed as argument // e.g. runtime.can('use_http_method', 'put') use_http_method: true }, caps); // default to the mode that is compatible with preferred caps if (options.preferred_caps) { defaultMode = Runtime.getMode(modeCaps, options.preferred_caps, defaultMode); } // small extension factory here (is meant to be extended with actual extensions constructors) _shim = (function() { var objpool = {}; return { exec: function(uid, comp, fn, args) { if (_shim[comp]) { if (!objpool[uid]) { objpool[uid] = { context: this, instance: new _shim[comp]() }; } if (objpool[uid].instance[fn]) { return objpool[uid].instance[fn].apply(this, args); } } }, removeInstance: function(uid) { delete objpool[uid]; }, removeAllInstances: function() { var self = this; Basic.each(objpool, function(obj, uid) { if (Basic.typeOf(obj.instance.destroy) === 'function') { obj.instance.destroy.call(obj.context); } self.removeInstance(uid); }); } }; }()); // public methods Basic.extend(this, { /** Specifies whether runtime instance was initialized or not @property initialized @type {Boolean} @default false */ initialized: false, // shims require this flag to stop initialization retries /** Unique ID of the runtime @property uid @type {String} */ uid: _uid, /** Runtime type (e.g. flash, html5, etc) @property type @type {String} */ type: type, /** Runtime (not native one) may operate in browser or client mode. @property mode @private @type {String|Boolean} current mode or false, if none possible */ mode: Runtime.getMode(modeCaps, (options.required_caps), defaultMode), /** id of the DOM container for the runtime (if available) @property shimid @type {String} */ shimid: _uid + '_container', /** Number of connected clients. If equal to zero, runtime can be destroyed @property clients @type {Number} */ clients: 0, /** Runtime initialization options @property options @type {Object} */ options: options, /** Checks if the runtime has specific capability @method can @param {String} cap Name of capability to check @param {Mixed} [value] If passed, capability should somehow correlate to the value @param {Object} [refCaps] Set of capabilities to check the specified cap against (defaults to internal set) @return {Boolean} true if runtime has such capability and false, if - not */ can: function(cap, value) { var refCaps = arguments[2] || caps; // if cap var is a comma-separated list of caps, convert it to object (key/value) if (Basic.typeOf(cap) === 'string' && Basic.typeOf(value) === 'undefined') { cap = Runtime.parseCaps(cap); } if (Basic.typeOf(cap) === 'object') { for (var key in cap) { if (!this.can(key, cap[key], refCaps)) { return false; } } return true; } // check the individual cap if (Basic.typeOf(refCaps[cap]) === 'function') { return refCaps[cap].call(this, value); } else { return (value === refCaps[cap]); } }, /** Returns container for the runtime as DOM element @method getShimContainer @return {DOMElement} */ getShimContainer: function() { var container, shimContainer = Dom.get(this.shimid); // if no container for shim, create one if (!shimContainer) { container = this.options.container ? Dom.get(this.options.container) : document.body; // create shim container and insert it at an absolute position into the outer container shimContainer = document.createElement('div'); shimContainer.id = this.shimid; shimContainer.className = 'moxie-shim moxie-shim-' + this.type; Basic.extend(shimContainer.style, { position: 'absolute', top: '0px', left: '0px', width: '1px', height: '1px', overflow: 'hidden' }); container.appendChild(shimContainer); container = null; } return shimContainer; }, /** Returns runtime as DOM element (if appropriate) @method getShim @return {DOMElement} */ getShim: function() { return _shim; }, /** Invokes a method within the runtime itself (might differ across the runtimes) @method shimExec @param {Mixed} [] @protected @return {Mixed} Depends on the action and component */ shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return self.getShim().exec.call(this, this.uid, component, action, args); }, /** Operaional interface that is used by components to invoke specific actions on the runtime (is invoked in the scope of component) @method exec @param {Mixed} []* @protected @return {Mixed} Depends on the action and component */ exec: function(component, action) { // this is called in the context of component, not runtime var args = [].slice.call(arguments, 2); if (self[component] && self[component][action]) { return self[component][action].apply(this, args); } return self.shimExec.apply(this, arguments); }, /** Destroys the runtime (removes all events and deletes DOM structures) @method destroy */ destroy: function() { if (!self) { return; // obviously already destroyed } var shimContainer = Dom.get(this.shimid); if (shimContainer) { shimContainer.parentNode.removeChild(shimContainer); } if (_shim) { _shim.removeAllInstances(); } this.unbindAll(); delete runtimes[this.uid]; this.uid = null; // mark this runtime as destroyed _uid = self = _shim = shimContainer = null; } }); // once we got the mode, test against all caps if (this.mode && options.required_caps && !this.can(options.required_caps)) { this.mode = false; } } /** Default order to try different runtime types @property order @type String @static */ Runtime.order = 'html5,flash,silverlight,html4'; /** Retrieves runtime from private hash by it's uid @method getRuntime @private @static @param {String} uid Unique identifier of the runtime @return {Runtime|Boolean} Returns runtime, if it exists and false, if - not */ Runtime.getRuntime = function(uid) { return runtimes[uid] ? runtimes[uid] : false; }; /** Register constructor for the Runtime of new (or perhaps modified) type @method addConstructor @static @param {String} type Runtime type (e.g. flash, html5, etc) @param {Function} construct Constructor for the Runtime type */ Runtime.addConstructor = function(type, constructor) { constructor.prototype = EventTarget.instance; runtimeConstructors[type] = constructor; }; /** Get the constructor for the specified type. method getConstructor @static @param {String} type Runtime type (e.g. flash, html5, etc) @return {Function} Constructor for the Runtime type */ Runtime.getConstructor = function(type) { return runtimeConstructors[type] || null; }; /** Get info about the runtime (uid, type, capabilities) @method getInfo @static @param {String} uid Unique identifier of the runtime @return {Mixed} Info object or null if runtime doesn't exist */ Runtime.getInfo = function(uid) { var runtime = Runtime.getRuntime(uid); if (runtime) { return { uid: runtime.uid, type: runtime.type, mode: runtime.mode, can: function() { return runtime.can.apply(runtime, arguments); } }; } return null; }; /** Convert caps represented by a comma-separated string to the object representation. @method parseCaps @static @param {String} capStr Comma-separated list of capabilities @return {Object} */ Runtime.parseCaps = function(capStr) { var capObj = {}; if (Basic.typeOf(capStr) !== 'string') { return capStr || {}; } Basic.each(capStr.split(','), function(key) { capObj[key] = true; // we assume it to be - true }); return capObj; }; /** Test the specified runtime for specific capabilities. @method can @static @param {String} type Runtime type (e.g. flash, html5, etc) @param {String|Object} caps Set of capabilities to check @return {Boolean} Result of the test */ Runtime.can = function(type, caps) { var runtime , constructor = Runtime.getConstructor(type) , mode ; if (constructor) { runtime = new constructor({ required_caps: caps }); mode = runtime.mode; runtime.destroy(); return !!mode; } return false; }; /** Figure out a runtime that supports specified capabilities. @method thatCan @static @param {String|Object} caps Set of capabilities to check @param {String} [runtimeOrder] Comma-separated list of runtimes to check against @return {String} Usable runtime identifier or null */ Runtime.thatCan = function(caps, runtimeOrder) { var types = (runtimeOrder || Runtime.order).split(/\s*,\s*/); for (var i in types) { if (Runtime.can(types[i], caps)) { return types[i]; } } return null; }; /** Figure out an operational mode for the specified set of capabilities. @method getMode @static @param {Object} modeCaps Set of capabilities that depend on particular runtime mode @param {Object} [requiredCaps] Supplied set of capabilities to find operational mode for @param {String|Boolean} [defaultMode='browser'] Default mode to use @return {String|Boolean} Compatible operational mode */ Runtime.getMode = function(modeCaps, requiredCaps, defaultMode) { var mode = null; if (Basic.typeOf(defaultMode) === 'undefined') { // only if not specified defaultMode = 'browser'; } if (requiredCaps && !Basic.isEmptyObj(modeCaps)) { // loop over required caps and check if they do require the same mode Basic.each(requiredCaps, function(value, cap) { if (modeCaps.hasOwnProperty(cap)) { var capMode = modeCaps[cap](value); // make sure we always have an array if (typeof(capMode) === 'string') { capMode = [capMode]; } if (!mode) { mode = capMode; } else if (!(mode = Basic.arrayIntersect(mode, capMode))) { // if cap requires conflicting mode - runtime cannot fulfill required caps return (mode = false); } } }); if (mode) { return Basic.inArray(defaultMode, mode) !== -1 ? defaultMode : mode[0]; } else if (mode === false) { return false; } } return defaultMode; }; /** Capability check that always returns true @private @static @return {True} */ Runtime.capTrue = function() { return true; }; /** Capability check that always returns false @private @static @return {False} */ Runtime.capFalse = function() { return false; }; /** Evaluate the expression to boolean value and create a function that always returns it. @private @static @param {Mixed} expr Expression to evaluate @return {Function} Function returning the result of evaluation */ Runtime.capTest = function(expr) { return function() { return !!expr; }; }; return Runtime; }); // Included from: src/javascript/runtime/RuntimeClient.js /** * RuntimeClient.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/RuntimeClient', [ 'moxie/core/Exceptions', 'moxie/core/utils/Basic', 'moxie/runtime/Runtime' ], function(x, Basic, Runtime) { /** Set of methods and properties, required by a component to acquire ability to connect to a runtime @class RuntimeClient */ return function RuntimeClient() { var runtime; Basic.extend(this, { /** Connects to the runtime specified by the options. Will either connect to existing runtime or create a new one. Increments number of clients connected to the specified runtime. @method connectRuntime @param {Mixed} options Can be a runtme uid or a set of key-value pairs defining requirements and pre-requisites */ connectRuntime: function(options) { var comp = this, ruid; function initialize(items) { var type, constructor; // if we ran out of runtimes if (!items.length) { comp.trigger('RuntimeError', new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); runtime = null; return; } type = items.shift(); constructor = Runtime.getConstructor(type); if (!constructor) { initialize(items); return; } // try initializing the runtime runtime = new constructor(options); runtime.bind('Init', function() { // mark runtime as initialized runtime.initialized = true; // jailbreak ... setTimeout(function() { runtime.clients++; // this will be triggered on component comp.trigger('RuntimeInit', runtime); }, 1); }); runtime.bind('Error', function() { runtime.destroy(); // runtime cannot destroy itself from inside at a right moment, thus we do it here initialize(items); }); /*runtime.bind('Exception', function() { });*/ // check if runtime managed to pick-up operational mode if (!runtime.mode) { runtime.trigger('Error'); return; } runtime.init(); } // check if a particular runtime was requested if (Basic.typeOf(options) === 'string') { ruid = options; } else if (Basic.typeOf(options.ruid) === 'string') { ruid = options.ruid; } if (ruid) { runtime = Runtime.getRuntime(ruid); if (runtime) { runtime.clients++; return runtime; } else { // there should be a runtime and there's none - weird case throw new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR); } } // initialize a fresh one, that fits runtime list and required features best initialize((options.runtime_order || Runtime.order).split(/\s*,\s*/)); }, /** Returns the runtime to which the client is currently connected. @method getRuntime @return {Runtime} Runtime or null if client is not connected */ getRuntime: function() { if (runtime && runtime.uid) { return runtime; } runtime = null; // make sure we do not leave zombies rambling around return null; }, /** Disconnects from the runtime. Decrements number of clients connected to the specified runtime. @method disconnectRuntime */ disconnectRuntime: function() { if (runtime && --runtime.clients <= 0) { runtime.destroy(); runtime = null; } } }); }; }); // Included from: src/javascript/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/Blob', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Encode', 'moxie/runtime/RuntimeClient' ], function(Basic, Encode, RuntimeClient) { var blobpool = {}; /** @class Blob @constructor @param {String} ruid Unique id of the runtime, to which this blob belongs to @param {Object} blob Object "Native" blob object, as it is represented in the runtime */ function Blob(ruid, blob) { function _sliceDetached(start, end, type) { var blob, data = blobpool[this.uid]; if (Basic.typeOf(data) !== 'string' || !data.length) { return null; // or throw exception } blob = new Blob(null, { type: type, size: end - start }); blob.detach(data.substr(start, blob.size)); return blob; } RuntimeClient.call(this); if (ruid) { this.connectRuntime(ruid); } if (!blob) { blob = {}; } else if (Basic.typeOf(blob) === 'string') { // dataUrl or binary string blob = { data: blob }; } Basic.extend(this, { /** Unique id of the component @property uid @type {String} */ uid: blob.uid || Basic.guid('uid_'), /** Unique id of the connected runtime, if falsy, then runtime will have to be initialized before this Blob can be used, modified or sent @property ruid @type {String} */ ruid: ruid, /** Size of blob @property size @type {Number} @default 0 */ size: blob.size || 0, /** Mime type of blob @property type @type {String} @default '' */ type: blob.type || '', /** @method slice @param {Number} [start=0] */ slice: function(start, end, type) { if (this.isDetached()) { return _sliceDetached.apply(this, arguments); } return this.getRuntime().exec.call(this, 'Blob', 'slice', this.getSource(), start, end, type); }, /** Returns "native" blob object (as it is represented in connected runtime) or null if not found @method getSource @return {Blob} Returns "native" blob object or null if not found */ getSource: function() { if (!blobpool[this.uid]) { return null; } return blobpool[this.uid]; }, /** Detaches blob from any runtime that it depends on and initialize with standalone value @method detach @protected @param {DOMString} [data=''] Standalone value */ detach: function(data) { if (this.ruid) { this.getRuntime().exec.call(this, 'Blob', 'destroy'); this.disconnectRuntime(); this.ruid = null; } data = data || ''; // if dataUrl, convert to binary string var matches = data.match(/^data:([^;]*);base64,/); if (matches) { this.type = matches[1]; data = Encode.atob(data.substring(data.indexOf('base64,') + 7)); } this.size = data.length; blobpool[this.uid] = data; }, /** Checks if blob is standalone (detached of any runtime) @method isDetached @protected @return {Boolean} */ isDetached: function() { return !this.ruid && Basic.typeOf(blobpool[this.uid]) === 'string'; }, /** Destroy Blob and free any resources it was using @method destroy */ destroy: function() { this.detach(); delete blobpool[this.uid]; } }); if (blob.data) { this.detach(blob.data); // auto-detach if payload has been passed } else { blobpool[this.uid] = blob; } } return Blob; }); // Included from: src/javascript/file/File.js /** * File.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/File', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Mime', 'moxie/file/Blob' ], function(Basic, Mime, Blob) { /** @class File @extends Blob @constructor @param {String} ruid Unique id of the runtime, to which this blob belongs to @param {Object} file Object "Native" file object, as it is represented in the runtime */ function File(ruid, file) { var name, type; if (!file) { // avoid extra errors in case we overlooked something file = {}; } // figure out the type if (file.type && file.type !== '') { type = file.type; } else { type = Mime.getFileMime(file.name); } // sanitize file name or generate new one if (file.name) { name = file.name.replace(/\\/g, '/'); name = name.substr(name.lastIndexOf('/') + 1); } else { var prefix = type.split('/')[0]; name = Basic.guid((prefix !== '' ? prefix : 'file') + '_'); if (Mime.extensions[type]) { name += '.' + Mime.extensions[type][0]; // append proper extension if possible } } Blob.apply(this, arguments); Basic.extend(this, { /** File mime type @property type @type {String} @default '' */ type: type || '', /** File name @property name @type {String} @default UID */ name: name || Basic.guid('file_'), /** Relative path to the file inside a directory @property relativePath @type {String} @default '' */ relativePath: '', /** Date of last modification @property lastModifiedDate @type {String} @default now */ lastModifiedDate: file.lastModifiedDate || (new Date()).toLocaleString() // Thu Aug 23 2012 19:40:00 GMT+0400 (GET) }); } File.prototype = Blob.prototype; return File; }); // Included from: src/javascript/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileInput', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Mime', 'moxie/core/utils/Dom', 'moxie/core/Exceptions', 'moxie/core/EventTarget', 'moxie/core/I18n', 'moxie/file/File', 'moxie/runtime/Runtime', 'moxie/runtime/RuntimeClient' ], function(Basic, Mime, Dom, x, EventTarget, I18n, File, Runtime, RuntimeClient) { /** Provides a convenient way to create cross-browser file-picker. Generates file selection dialog on click, converts selected files to _File_ objects, to be used in conjunction with _Image_, preloaded in memory with _FileReader_ or uploaded to a server through _XMLHttpRequest_. @class FileInput @constructor @extends EventTarget @uses RuntimeClient @param {Object|String|DOMElement} options If options is string or node, argument is considered as _browse\_button_. @param {String|DOMElement} options.browse_button DOM Element to turn into file picker. @param {Array} [options.accept] Array of mime types to accept. By default accepts all. @param {String} [options.file='file'] Name of the file field (not the filename). @param {Boolean} [options.multiple=false] Enable selection of multiple files. @param {Boolean} [options.directory=false] Turn file input into the folder input (cannot be both at the same time). @param {String|DOMElement} [options.container] DOM Element to use as a container for file-picker. Defaults to parentNode for _browse\_button_. @param {Object|String} [options.required_caps] Set of required capabilities, that chosen runtime must support. @example <div id="container"> <a id="file-picker" href="javascript:;">Browse...</a> </div> <script> var fileInput = new mOxie.FileInput({ browse_button: 'file-picker', // or document.getElementById('file-picker') container: 'container', accept: [ {title: "Image files", extensions: "jpg,gif,png"} // accept only images ], multiple: true // allow multiple file selection }); fileInput.onchange = function(e) { // do something to files array console.info(e.target.files); // or this.files or fileInput.files }; fileInput.init(); // initialize </script> */ var dispatches = [ /** Dispatched when runtime is connected and file-picker is ready to be used. @event ready @param {Object} event */ 'ready', /** Dispatched right after [ready](#event_ready) event, and whenever [refresh()](#method_refresh) is invoked. Check [corresponding documentation entry](#method_refresh) for more info. @event refresh @param {Object} event */ /** Dispatched when selection of files in the dialog is complete. @event change @param {Object} event */ 'change', 'cancel', // TODO: might be useful /** Dispatched when mouse cursor enters file-picker area. Can be used to style element accordingly. @event mouseenter @param {Object} event */ 'mouseenter', /** Dispatched when mouse cursor leaves file-picker area. Can be used to style element accordingly. @event mouseleave @param {Object} event */ 'mouseleave', /** Dispatched when functional mouse button is pressed on top of file-picker area. @event mousedown @param {Object} event */ 'mousedown', /** Dispatched when functional mouse button is released on top of file-picker area. @event mouseup @param {Object} event */ 'mouseup' ]; function FileInput(options) { var self = this, container, browseButton, defaults; // if flat argument passed it should be browse_button id if (Basic.inArray(Basic.typeOf(options), ['string', 'node']) !== -1) { options = { browse_button : options }; } // this will help us to find proper default container browseButton = Dom.get(options.browse_button); if (!browseButton) { // browse button is required throw new x.DOMException(x.DOMException.NOT_FOUND_ERR); } // figure out the options defaults = { accept: [{ title: I18n.translate('All Files'), extensions: '*' }], name: 'file', multiple: false, required_caps: false, container: browseButton.parentNode || document.body }; options = Basic.extend({}, defaults, options); // convert to object representation if (typeof(options.required_caps) === 'string') { options.required_caps = Runtime.parseCaps(options.required_caps); } // normalize accept option (could be list of mime types or array of title/extensions pairs) if (typeof(options.accept) === 'string') { options.accept = Mime.mimes2extList(options.accept); } container = Dom.get(options.container); // make sure we have container if (!container) { container = document.body; } // make container relative, if it's not if (Dom.getStyle(container, 'position') === 'static') { container.style.position = 'relative'; } container = browseButton = null; // IE RuntimeClient.call(self); Basic.extend(self, { /** Unique id of the component @property uid @protected @readOnly @type {String} @default UID */ uid: Basic.guid('uid_'), /** Unique id of the connected runtime, if any. @property ruid @protected @type {String} */ ruid: null, /** Unique id of the runtime container. Useful to get hold of it for various manipulations. @property shimid @protected @type {String} */ shimid: null, /** Array of selected mOxie.File objects @property files @type {Array} @default null */ files: null, /** Initializes the file-picker, connects it to runtime and dispatches event ready when done. @method init */ init: function() { self.convertEventPropsToHandlers(dispatches); self.bind('RuntimeInit', function(e, runtime) { self.ruid = runtime.uid; self.shimid = runtime.shimid; self.bind("Ready", function() { self.trigger("Refresh"); }, 999); self.bind("Change", function() { var files = runtime.exec.call(self, 'FileInput', 'getFiles'); self.files = []; Basic.each(files, function(file) { // ignore empty files (IE10 for example hangs if you try to send them via XHR) if (file.size === 0) { return true; } self.files.push(new File(self.ruid, file)); }); }, 999); // re-position and resize shim container self.bind('Refresh', function() { var pos, size, browseButton, shimContainer; browseButton = Dom.get(options.browse_button); shimContainer = Dom.get(runtime.shimid); // do not use runtime.getShimContainer(), since it will create container if it doesn't exist if (browseButton) { pos = Dom.getPos(browseButton, Dom.get(options.container)); size = Dom.getSize(browseButton); if (shimContainer) { Basic.extend(shimContainer.style, { top : pos.y + 'px', left : pos.x + 'px', width : size.w + 'px', height : size.h + 'px' }); } } shimContainer = browseButton = null; }); runtime.exec.call(self, 'FileInput', 'init', options); }); // runtime needs: options.required_features, options.runtime_order and options.container self.connectRuntime(Basic.extend({}, options, { required_caps: { select_file: true } })); }, /** Disables file-picker element, so that it doesn't react to mouse clicks. @method disable @param {Boolean} [state=true] Disable component if - true, enable if - false */ disable: function(state) { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'disable', Basic.typeOf(state) === 'undefined' ? true : state); } }, /** Reposition and resize dialog trigger to match the position and size of browse_button element. @method refresh */ refresh: function() { self.trigger("Refresh"); }, /** Destroy component. @method destroy */ destroy: function() { var runtime = this.getRuntime(); if (runtime) { runtime.exec.call(this, 'FileInput', 'destroy'); this.disconnectRuntime(); } if (Basic.typeOf(this.files) === 'array') { // no sense in leaving associated files behind Basic.each(this.files, function(file) { file.destroy(); }); } this.files = null; } }); } FileInput.prototype = EventTarget.instance; return FileInput; }); // Included from: src/javascript/runtime/RuntimeTarget.js /** * RuntimeTarget.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/runtime/RuntimeTarget', [ 'moxie/core/utils/Basic', 'moxie/runtime/RuntimeClient', "moxie/core/EventTarget" ], function(Basic, RuntimeClient, EventTarget) { /** Instance of this class can be used as a target for the events dispatched by shims, when allowing them onto components is for either reason inappropriate @class RuntimeTarget @constructor @protected @extends EventTarget */ function RuntimeTarget() { this.uid = Basic.guid('uid_'); RuntimeClient.call(this); this.destroy = function() { this.disconnectRuntime(); this.unbindAll(); }; } RuntimeTarget.prototype = EventTarget.instance; return RuntimeTarget; }); // Included from: src/javascript/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileReader', [ 'moxie/core/utils/Basic', 'moxie/core/utils/Encode', 'moxie/core/Exceptions', 'moxie/core/EventTarget', 'moxie/file/Blob', 'moxie/file/File', 'moxie/runtime/RuntimeTarget' ], function(Basic, Encode, x, EventTarget, Blob, File, RuntimeTarget) { /** Utility for preloading o.Blob/o.File objects in memory. By design closely follows [W3C FileReader](http://www.w3.org/TR/FileAPI/#dfn-filereader) interface. Where possible uses native FileReader, where - not falls back to shims. @class FileReader @constructor FileReader @extends EventTarget @uses RuntimeClient */ var dispatches = [ /** Dispatched when the read starts. @event loadstart @param {Object} event */ 'loadstart', /** Dispatched while reading (and decoding) blob, and reporting partial Blob data (progess.loaded/progress.total). @event progress @param {Object} event */ 'progress', /** Dispatched when the read has successfully completed. @event load @param {Object} event */ 'load', /** Dispatched when the read has been aborted. For instance, by invoking the abort() method. @event abort @param {Object} event */ 'abort', /** Dispatched when the read has failed. @event error @param {Object} event */ 'error', /** Dispatched when the request has completed (either in success or failure). @event loadend @param {Object} event */ 'loadend' ]; function FileReader() { var self = this, _fr; Basic.extend(this, { /** UID of the component instance. @property uid @type {String} */ uid: Basic.guid('uid_'), /** Contains current state of FileReader object. Can take values of FileReader.EMPTY, FileReader.LOADING and FileReader.DONE. @property readyState @type {Number} @default FileReader.EMPTY */ readyState: FileReader.EMPTY, /** Result of the successful read operation. @property result @type {String} */ result: null, /** Stores the error of failed asynchronous read operation. @property error @type {DOMError} */ error: null, /** Initiates reading of File/Blob object contents to binary string. @method readAsBinaryString @param {Blob|File} blob Object to preload */ readAsBinaryString: function(blob) { _read.call(this, 'readAsBinaryString', blob); }, /** Initiates reading of File/Blob object contents to dataURL string. @method readAsDataURL @param {Blob|File} blob Object to preload */ readAsDataURL: function(blob) { _read.call(this, 'readAsDataURL', blob); }, /** Initiates reading of File/Blob object contents to string. @method readAsText @param {Blob|File} blob Object to preload */ readAsText: function(blob) { _read.call(this, 'readAsText', blob); }, /** Aborts preloading process. @method abort */ abort: function() { this.result = null; if (Basic.inArray(this.readyState, [FileReader.EMPTY, FileReader.DONE]) !== -1) { return; } else if (this.readyState === FileReader.LOADING) { this.readyState = FileReader.DONE; } if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'abort'); } this.trigger('abort'); this.trigger('loadend'); }, /** Destroy component and release resources. @method destroy */ destroy: function() { this.abort(); if (_fr) { _fr.getRuntime().exec.call(this, 'FileReader', 'destroy'); _fr.disconnectRuntime(); } self = _fr = null; } }); function _read(op, blob) { _fr = new RuntimeTarget(); function error(err) { self.readyState = FileReader.DONE; self.error = err; self.trigger('error'); loadEnd(); } function loadEnd() { _fr.destroy(); _fr = null; self.trigger('loadend'); } function exec(runtime) { _fr.bind('Error', function(e, err) { error(err); }); _fr.bind('Progress', function(e) { self.result = runtime.exec.call(_fr, 'FileReader', 'getResult'); self.trigger(e); }); _fr.bind('Load', function(e) { self.readyState = FileReader.DONE; self.result = runtime.exec.call(_fr, 'FileReader', 'getResult'); self.trigger(e); loadEnd(); }); runtime.exec.call(_fr, 'FileReader', 'read', op, blob); } this.convertEventPropsToHandlers(dispatches); if (this.readyState === FileReader.LOADING) { return error(new x.DOMException(x.DOMException.INVALID_STATE_ERR)); } this.readyState = FileReader.LOADING; this.trigger('loadstart'); // if source is o.Blob/o.File if (blob instanceof Blob) { if (blob.isDetached()) { var src = blob.getSource(); switch (op) { case 'readAsText': case 'readAsBinaryString': this.result = src; break; case 'readAsDataURL': this.result = 'data:' + blob.type + ';base64,' + Encode.btoa(src); break; } this.readyState = FileReader.DONE; this.trigger('load'); loadEnd(); } else { exec(_fr.connectRuntime(blob.ruid)); } } else { error(new x.DOMException(x.DOMException.NOT_FOUND_ERR)); } } } /** Initial FileReader state @property EMPTY @type {Number} @final @static @default 0 */ FileReader.EMPTY = 0; /** FileReader switches to this state when it is preloading the source @property LOADING @type {Number} @final @static @default 1 */ FileReader.LOADING = 1; /** Preloading is complete, this is a final state @property DONE @type {Number} @final @static @default 2 */ FileReader.DONE = 2; FileReader.prototype = EventTarget.instance; return FileReader; }); // Included from: src/javascript/core/utils/Url.js /** * Url.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Url', [], function() { /** Parse url into separate components and fill in absent parts with parts from current url, based on https://raw.github.com/kvz/phpjs/master/functions/url/parse_url.js @method parseUrl @for Utils @static @param {String} url Url to parse (defaults to empty string if undefined) @return {Object} Hash containing extracted uri components */ var parseUrl = function(url, currentUrl) { var key = ['source', 'scheme', 'authority', 'userInfo', 'user', 'pass', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'fragment'] , i = key.length , ports = { http: 80, https: 443 } , uri = {} , regex = /^(?:([^:\/?#]+):)?(?:\/\/()(?:(?:()(?:([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?()(?:(()(?:(?:[^?#\/]*\/)*)()(?:[^?#]*))(?:\\?([^#]*))?(?:#(.*))?)/ , m = regex.exec(url || '') ; while (i--) { if (m[i]) { uri[key[i]] = m[i]; } } // when url is relative, we set the origin and the path ourselves if (!uri.scheme) { // come up with defaults if (!currentUrl || typeof(currentUrl) === 'string') { currentUrl = parseUrl(currentUrl || document.location.href); } uri.scheme = currentUrl.scheme; uri.host = currentUrl.host; uri.port = currentUrl.port; var path = ''; // for urls without trailing slash we need to figure out the path if (/^[^\/]/.test(uri.path)) { path = currentUrl.path; // if path ends with a filename, strip it if (!/(\/|\/[^\.]+)$/.test(path)) { path = path.replace(/\/[^\/]+$/, '/'); } else { path += '/'; } } uri.path = path + (uri.path || ''); // site may reside at domain.com or domain.com/subdir } if (!uri.port) { uri.port = ports[uri.scheme] || 80; } uri.port = parseInt(uri.port, 10); if (!uri.path) { uri.path = "/"; } delete uri.source; return uri; }; /** Resolve url - among other things will turn relative url to absolute @method resolveUrl @static @param {String} url Either absolute or relative @return {String} Resolved, absolute url */ var resolveUrl = function(url) { var ports = { // we ignore default ports http: 80, https: 443 } , urlp = parseUrl(url) ; return urlp.scheme + '://' + urlp.host + (urlp.port !== ports[urlp.scheme] ? ':' + urlp.port : '') + urlp.path + (urlp.query ? urlp.query : ''); }; /** Check if specified url has the same origin as the current document @method hasSameOrigin @param {String|Object} url @return {Boolean} */ var hasSameOrigin = function(url) { function origin(url) { return [url.scheme, url.host, url.port].join('/'); } if (typeof url === 'string') { url = parseUrl(url); } return origin(parseUrl()) === origin(url); }; return { parseUrl: parseUrl, resolveUrl: resolveUrl, hasSameOrigin: hasSameOrigin }; }); // Included from: src/javascript/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/file/FileReaderSync', [ 'moxie/core/utils/Basic', 'moxie/runtime/RuntimeClient', 'moxie/core/utils/Encode' ], function(Basic, RuntimeClient, Encode) { /** Synchronous FileReader implementation. Something like this is available in WebWorkers environment, here it can be used to read only preloaded blobs/files and only below certain size (not yet sure what that'd be, but probably < 1mb). Not meant to be used directly by user. @class FileReaderSync @private @constructor */ return function() { RuntimeClient.call(this); Basic.extend(this, { uid: Basic.guid('uid_'), readAsBinaryString: function(blob) { return _read.call(this, 'readAsBinaryString', blob); }, readAsDataURL: function(blob) { return _read.call(this, 'readAsDataURL', blob); }, /*readAsArrayBuffer: function(blob) { return _read.call(this, 'readAsArrayBuffer', blob); },*/ readAsText: function(blob) { return _read.call(this, 'readAsText', blob); } }); function _read(op, blob) { if (blob.isDetached()) { var src = blob.getSource(); switch (op) { case 'readAsBinaryString': return src; case 'readAsDataURL': return 'data:' + blob.type + ';base64,' + Encode.btoa(src); case 'readAsText': var txt = ''; for (var i = 0, length = src.length; i < length; i++) { txt += String.fromCharCode(src[i]); } return txt; } } else { var result = this.connectRuntime(blob.ruid).exec.call(this, 'FileReaderSync', 'read', op, blob); this.disconnectRuntime(); return result; } } }; }); // Included from: src/javascript/xhr/FormData.js /** * FormData.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/xhr/FormData", [ "moxie/core/Exceptions", "moxie/core/utils/Basic", "moxie/file/Blob" ], function(x, Basic, Blob) { /** FormData @class FormData @constructor */ function FormData() { var _blob, _fields = []; Basic.extend(this, { /** Append another key-value pair to the FormData object @method append @param {String} name Name for the new field @param {String|Blob|Array|Object} value Value for the field */ append: function(name, value) { var self = this, valueType = Basic.typeOf(value); // according to specs value might be either Blob or String if (value instanceof Blob) { _blob = { name: name, value: value // unfortunately we can only send single Blob in one FormData }; } else if ('array' === valueType) { name += '[]'; Basic.each(value, function(value) { self.append(name, value); }); } else if ('object' === valueType) { Basic.each(value, function(value, key) { self.append(name + '[' + key + ']', value); }); } else if ('null' === valueType || 'undefined' === valueType || 'number' === valueType && isNaN(value)) { self.append(name, "false"); } else { _fields.push({ name: name, value: value.toString() }); } }, /** Checks if FormData contains Blob. @method hasBlob @return {Boolean} */ hasBlob: function() { return !!this.getBlob(); }, /** Retrieves blob. @method getBlob @return {Object} Either Blob if found or null */ getBlob: function() { return _blob && _blob.value || null; }, /** Retrieves blob field name. @method getBlobName @return {String} Either Blob field name or null */ getBlobName: function() { return _blob && _blob.name || null; }, /** Loop over the fields in FormData and invoke the callback for each of them. @method each @param {Function} cb Callback to call for each field */ each: function(cb) { Basic.each(_fields, function(field) { cb(field.value, field.name); }); if (_blob) { cb(_blob.value, _blob.name); } }, destroy: function() { _blob = null; _fields = []; } }); } return FormData; }); // Included from: src/javascript/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/xhr/XMLHttpRequest", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/core/EventTarget", "moxie/core/utils/Encode", "moxie/core/utils/Url", "moxie/runtime/Runtime", "moxie/runtime/RuntimeTarget", "moxie/file/Blob", "moxie/file/FileReaderSync", "moxie/xhr/FormData", "moxie/core/utils/Env", "moxie/core/utils/Mime" ], function(Basic, x, EventTarget, Encode, Url, Runtime, RuntimeTarget, Blob, FileReaderSync, FormData, Env, Mime) { var httpCode = { 100: 'Continue', 101: 'Switching Protocols', 102: 'Processing', 200: 'OK', 201: 'Created', 202: 'Accepted', 203: 'Non-Authoritative Information', 204: 'No Content', 205: 'Reset Content', 206: 'Partial Content', 207: 'Multi-Status', 226: 'IM Used', 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Found', 303: 'See Other', 304: 'Not Modified', 305: 'Use Proxy', 306: 'Reserved', 307: 'Temporary Redirect', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 409: 'Conflict', 410: 'Gone', 411: 'Length Required', 412: 'Precondition Failed', 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 416: 'Requested Range Not Satisfiable', 417: 'Expectation Failed', 422: 'Unprocessable Entity', 423: 'Locked', 424: 'Failed Dependency', 426: 'Upgrade Required', 500: 'Internal Server Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Gateway Timeout', 505: 'HTTP Version Not Supported', 506: 'Variant Also Negotiates', 507: 'Insufficient Storage', 510: 'Not Extended' }; function XMLHttpRequestUpload() { this.uid = Basic.guid('uid_'); } XMLHttpRequestUpload.prototype = EventTarget.instance; /** Implementation of XMLHttpRequest @class XMLHttpRequest @constructor @uses RuntimeClient @extends EventTarget */ var dispatches = ['loadstart', 'progress', 'abort', 'error', 'load', 'timeout', 'loadend']; // & readystatechange (for historical reasons) var NATIVE = 1, RUNTIME = 2; function XMLHttpRequest() { var self = this, // this (together with _p() @see below) is here to gracefully upgrade to setter/getter syntax where possible props = { /** The amount of milliseconds a request can take before being terminated. Initially zero. Zero means there is no timeout. @property timeout @type Number @default 0 */ timeout: 0, /** Current state, can take following values: UNSENT (numeric value 0) The object has been constructed. OPENED (numeric value 1) The open() method has been successfully invoked. During this state request headers can be set using setRequestHeader() and the request can be made using the send() method. HEADERS_RECEIVED (numeric value 2) All redirects (if any) have been followed and all HTTP headers of the final response have been received. Several response members of the object are now available. LOADING (numeric value 3) The response entity body is being received. DONE (numeric value 4) @property readyState @type Number @default 0 (UNSENT) */ readyState: XMLHttpRequest.UNSENT, /** True when user credentials are to be included in a cross-origin request. False when they are to be excluded in a cross-origin request and when cookies are to be ignored in its response. Initially false. @property withCredentials @type Boolean @default false */ withCredentials: false, /** Returns the HTTP status code. @property status @type Number @default 0 */ status: 0, /** Returns the HTTP status text. @property statusText @type String */ statusText: "", /** Returns the response type. Can be set to change the response type. Values are: the empty string (default), "arraybuffer", "blob", "document", "json", and "text". @property responseType @type String */ responseType: "", /** Returns the document response entity body. Throws an "InvalidStateError" exception if responseType is not the empty string or "document". @property responseXML @type Document */ responseXML: null, /** Returns the text response entity body. Throws an "InvalidStateError" exception if responseType is not the empty string or "text". @property responseText @type String */ responseText: null, /** Returns the response entity body (http://www.w3.org/TR/XMLHttpRequest/#response-entity-body). Can become: ArrayBuffer, Blob, Document, JSON, Text @property response @type Mixed */ response: null }, _async = true, _url, _method, _headers = {}, _user, _password, _encoding = null, _mimeType = null, // flags _sync_flag = false, _send_flag = false, _upload_events_flag = false, _upload_complete_flag = false, _error_flag = false, _same_origin_flag = false, // times _start_time, _timeoutset_time, _finalMime = null, _finalCharset = null, _options = {}, _xhr, _responseHeaders = '', _responseHeadersBag ; Basic.extend(this, props, { /** Unique id of the component @property uid @type String */ uid: Basic.guid('uid_'), /** Target for Upload events @property upload @type XMLHttpRequestUpload */ upload: new XMLHttpRequestUpload(), /** Sets the request method, request URL, synchronous flag, request username, and request password. Throws a "SyntaxError" exception if one of the following is true: method is not a valid HTTP method. url cannot be resolved. url contains the "user:password" format in the userinfo production. Throws a "SecurityError" exception if method is a case-insensitive match for CONNECT, TRACE or TRACK. Throws an "InvalidAccessError" exception if one of the following is true: Either user or password is passed as argument and the origin of url does not match the XMLHttpRequest origin. There is an associated XMLHttpRequest document and either the timeout attribute is not zero, the withCredentials attribute is true, or the responseType attribute is not the empty string. @method open @param {String} method HTTP method to use on request @param {String} url URL to request @param {Boolean} [async=true] If false request will be done in synchronous manner. Asynchronous by default. @param {String} [user] Username to use in HTTP authentication process on server-side @param {String} [password] Password to use in HTTP authentication process on server-side */ open: function(method, url, async, user, password) { var urlp; // first two arguments are required if (!method || !url) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 2 - check if any code point in method is higher than U+00FF or after deflating method it does not match the method if (/[\u0100-\uffff]/.test(method) || Encode.utf8_encode(method) !== method) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 3 if (!!~Basic.inArray(method.toUpperCase(), ['CONNECT', 'DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT', 'TRACE', 'TRACK'])) { _method = method.toUpperCase(); } // 4 - allowing these methods poses a security risk if (!!~Basic.inArray(_method, ['CONNECT', 'TRACE', 'TRACK'])) { throw new x.DOMException(x.DOMException.SECURITY_ERR); } // 5 url = Encode.utf8_encode(url); // 6 - Resolve url relative to the XMLHttpRequest base URL. If the algorithm returns an error, throw a "SyntaxError". urlp = Url.parseUrl(url); _same_origin_flag = Url.hasSameOrigin(urlp); // 7 - manually build up absolute url _url = Url.resolveUrl(url); // 9-10, 12-13 if ((user || password) && !_same_origin_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } _user = user || urlp.user; _password = password || urlp.pass; // 11 _async = async || true; if (_async === false && (_p('timeout') || _p('withCredentials') || _p('responseType') !== "")) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 14 - terminate abort() // 15 - terminate send() // 18 _sync_flag = !_async; _send_flag = false; _headers = {}; _reset.call(this); // 19 _p('readyState', XMLHttpRequest.OPENED); // 20 this.convertEventPropsToHandlers(['readystatechange']); // unify event handlers this.dispatchEvent('readystatechange'); }, /** Appends an header to the list of author request headers, or if header is already in the list of author request headers, combines its value with value. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set. Throws a "SyntaxError" exception if header is not a valid HTTP header field name or if value is not a valid HTTP header field value. @method setRequestHeader @param {String} header @param {String|Number} value */ setRequestHeader: function(header, value) { var uaHeaders = [ // these headers are controlled by the user agent "accept-charset", "accept-encoding", "access-control-request-headers", "access-control-request-method", "connection", "content-length", "cookie", "cookie2", "content-transfer-encoding", "date", "expect", "host", "keep-alive", "origin", "referer", "te", "trailer", "transfer-encoding", "upgrade", "user-agent", "via" ]; // 1-2 if (_p('readyState') !== XMLHttpRequest.OPENED || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3 if (/[\u0100-\uffff]/.test(header) || Encode.utf8_encode(header) !== header) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 4 /* this step is seemingly bypassed in browsers, probably to allow various unicode characters in header values if (/[\u0100-\uffff]/.test(value) || Encode.utf8_encode(value) !== value) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); }*/ header = Basic.trim(header).toLowerCase(); // setting of proxy-* and sec-* headers is prohibited by spec if (!!~Basic.inArray(header, uaHeaders) || /^(proxy\-|sec\-)/.test(header)) { return false; } // camelize // browsers lowercase header names (at least for custom ones) // header = header.replace(/\b\w/g, function($1) { return $1.toUpperCase(); }); if (!_headers[header]) { _headers[header] = value; } else { // http://tools.ietf.org/html/rfc2616#section-4.2 (last paragraph) _headers[header] += ', ' + value; } return true; }, /** Returns all headers from the response, with the exception of those whose field name is Set-Cookie or Set-Cookie2. @method getAllResponseHeaders @return {String} reponse headers or empty string */ getAllResponseHeaders: function() { return _responseHeaders || ''; }, /** Returns the header field value from the response of which the field name matches header, unless the field name is Set-Cookie or Set-Cookie2. @method getResponseHeader @param {String} header @return {String} value(s) for the specified header or null */ getResponseHeader: function(header) { header = header.toLowerCase(); if (_error_flag || !!~Basic.inArray(header, ['set-cookie', 'set-cookie2'])) { return null; } if (_responseHeaders && _responseHeaders !== '') { // if we didn't parse response headers until now, do it and keep for later if (!_responseHeadersBag) { _responseHeadersBag = {}; Basic.each(_responseHeaders.split(/\r\n/), function(line) { var pair = line.split(/:\s+/); if (pair.length === 2) { // last line might be empty, omit pair[0] = Basic.trim(pair[0]); // just in case _responseHeadersBag[pair[0].toLowerCase()] = { // simply to retain header name in original form header: pair[0], value: Basic.trim(pair[1]) }; } }); } if (_responseHeadersBag.hasOwnProperty(header)) { return _responseHeadersBag[header].header + ': ' + _responseHeadersBag[header].value; } } return null; }, /** Sets the Content-Type header for the response to mime. Throws an "InvalidStateError" exception if the state is LOADING or DONE. Throws a "SyntaxError" exception if mime is not a valid media type. @method overrideMimeType @param String mime Mime type to set */ overrideMimeType: function(mime) { var matches, charset; // 1 if (!!~Basic.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2 mime = Basic.trim(mime.toLowerCase()); if (/;/.test(mime) && (matches = mime.match(/^([^;]+)(?:;\scharset\=)?(.*)$/))) { mime = matches[1]; if (matches[2]) { charset = matches[2]; } } if (!Mime.mimes[mime]) { throw new x.DOMException(x.DOMException.SYNTAX_ERR); } // 3-4 _finalMime = mime; _finalCharset = charset; }, /** Initiates the request. The optional argument provides the request entity body. The argument is ignored if request method is GET or HEAD. Throws an "InvalidStateError" exception if the state is not OPENED or if the send() flag is set. @method send @param {Blob|Document|String|FormData} [data] Request entity body @param {Object} [options] Set of requirements and pre-requisities for runtime initialization */ send: function(data, options) { if (Basic.typeOf(options) === 'string') { _options = { ruid: options }; } else if (!options) { _options = {}; } else { _options = options; } this.convertEventPropsToHandlers(dispatches); this.upload.convertEventPropsToHandlers(dispatches); // 1-2 if (this.readyState !== XMLHttpRequest.OPENED || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3 // sending Blob if (data instanceof Blob) { _options.ruid = data.ruid; _mimeType = data.type || 'application/octet-stream'; } // FormData else if (data instanceof FormData) { if (data.hasBlob()) { var blob = data.getBlob(); _options.ruid = blob.ruid; _mimeType = blob.type || 'application/octet-stream'; } } // DOMString else if (typeof data === 'string') { _encoding = 'UTF-8'; _mimeType = 'text/plain;charset=UTF-8'; // data should be converted to Unicode and encoded as UTF-8 data = Encode.utf8_encode(data); } // if withCredentials not set, but requested, set it automatically if (!this.withCredentials) { this.withCredentials = (_options.required_caps && _options.required_caps.send_browser_cookies) && !_same_origin_flag; } // 4 - storage mutex // 5 _upload_events_flag = (!_sync_flag && this.upload.hasEventListener()); // DSAP // 6 _error_flag = false; // 7 _upload_complete_flag = !data; // 8 - Asynchronous steps if (!_sync_flag) { // 8.1 _send_flag = true; // 8.2 // this.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr // 8.3 //if (!_upload_complete_flag) { // this.upload.dispatchEvent('loadstart'); // will be dispatched either by native or runtime xhr //} } // 8.5 - Return the send() method call, but continue running the steps in this algorithm. _doXHR.call(this, data); }, /** Cancels any network activity. @method abort */ abort: function() { _error_flag = true; _sync_flag = false; if (!~Basic.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED, XMLHttpRequest.DONE])) { _p('readyState', XMLHttpRequest.DONE); _send_flag = false; if (_xhr) { _xhr.getRuntime().exec.call(_xhr, 'XMLHttpRequest', 'abort', _upload_complete_flag); } else { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } _upload_complete_flag = true; } else { _p('readyState', XMLHttpRequest.UNSENT); } }, destroy: function() { if (_xhr) { if (Basic.typeOf(_xhr.destroy) === 'function') { _xhr.destroy(); } _xhr = null; } this.unbindAll(); if (this.upload) { this.upload.unbindAll(); this.upload = null; } } }); /* this is nice, but maybe too lengthy // if supported by JS version, set getters/setters for specific properties o.defineProperty(this, 'readyState', { configurable: false, get: function() { return _p('readyState'); } }); o.defineProperty(this, 'timeout', { configurable: false, get: function() { return _p('timeout'); }, set: function(value) { if (_sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // timeout still should be measured relative to the start time of request _timeoutset_time = (new Date).getTime(); _p('timeout', value); } }); // the withCredentials attribute has no effect when fetching same-origin resources o.defineProperty(this, 'withCredentials', { configurable: false, get: function() { return _p('withCredentials'); }, set: function(value) { // 1-2 if (!~o.inArray(_p('readyState'), [XMLHttpRequest.UNSENT, XMLHttpRequest.OPENED]) || _send_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 3-4 if (_anonymous_flag || _sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 5 _p('withCredentials', value); } }); o.defineProperty(this, 'status', { configurable: false, get: function() { return _p('status'); } }); o.defineProperty(this, 'statusText', { configurable: false, get: function() { return _p('statusText'); } }); o.defineProperty(this, 'responseType', { configurable: false, get: function() { return _p('responseType'); }, set: function(value) { // 1 if (!!~o.inArray(_p('readyState'), [XMLHttpRequest.LOADING, XMLHttpRequest.DONE])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2 if (_sync_flag) { throw new x.DOMException(x.DOMException.INVALID_ACCESS_ERR); } // 3 _p('responseType', value.toLowerCase()); } }); o.defineProperty(this, 'responseText', { configurable: false, get: function() { // 1 if (!~o.inArray(_p('responseType'), ['', 'text'])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2-3 if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return _p('responseText'); } }); o.defineProperty(this, 'responseXML', { configurable: false, get: function() { // 1 if (!~o.inArray(_p('responseType'), ['', 'document'])) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } // 2-3 if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) { throw new x.DOMException(x.DOMException.INVALID_STATE_ERR); } return _p('responseXML'); } }); o.defineProperty(this, 'response', { configurable: false, get: function() { if (!!~o.inArray(_p('responseType'), ['', 'text'])) { if (_p('readyState') !== XMLHttpRequest.DONE && _p('readyState') !== XMLHttpRequest.LOADING || _error_flag) { return ''; } } if (_p('readyState') !== XMLHttpRequest.DONE || _error_flag) { return null; } return _p('response'); } }); */ function _p(prop, value) { if (!props.hasOwnProperty(prop)) { return; } if (arguments.length === 1) { // get return Env.can('define_property') ? props[prop] : self[prop]; } else { // set if (Env.can('define_property')) { props[prop] = value; } else { self[prop] = value; } } } /* function _toASCII(str, AllowUnassigned, UseSTD3ASCIIRules) { // TODO: http://tools.ietf.org/html/rfc3490#section-4.1 return str.toLowerCase(); } */ function _doXHR(data) { var self = this; _start_time = new Date().getTime(); _xhr = new RuntimeTarget(); function loadEnd() { if (_xhr) { // it could have been destroyed by now _xhr.destroy(); _xhr = null; } self.dispatchEvent('loadend'); self = null; } function exec(runtime) { _xhr.bind('LoadStart', function(e) { _p('readyState', XMLHttpRequest.LOADING); self.dispatchEvent('readystatechange'); self.dispatchEvent(e); if (_upload_events_flag) { self.upload.dispatchEvent(e); } }); _xhr.bind('Progress', function(e) { if (_p('readyState') !== XMLHttpRequest.LOADING) { _p('readyState', XMLHttpRequest.LOADING); // LoadStart unreliable (in Flash for example) self.dispatchEvent('readystatechange'); } self.dispatchEvent(e); }); _xhr.bind('UploadProgress', function(e) { if (_upload_events_flag) { self.upload.dispatchEvent({ type: 'progress', lengthComputable: false, total: e.total, loaded: e.loaded }); } }); _xhr.bind('Load', function(e) { _p('readyState', XMLHttpRequest.DONE); _p('status', Number(runtime.exec.call(_xhr, 'XMLHttpRequest', 'getStatus') || 0)); _p('statusText', httpCode[_p('status')] || ""); _p('response', runtime.exec.call(_xhr, 'XMLHttpRequest', 'getResponse', _p('responseType'))); if (!!~Basic.inArray(_p('responseType'), ['text', ''])) { _p('responseText', _p('response')); } else if (_p('responseType') === 'document') { _p('responseXML', _p('response')); } _responseHeaders = runtime.exec.call(_xhr, 'XMLHttpRequest', 'getAllResponseHeaders'); self.dispatchEvent('readystatechange'); if (_p('status') > 0) { // status 0 usually means that server is unreachable if (_upload_events_flag) { self.upload.dispatchEvent(e); } self.dispatchEvent(e); } else { _error_flag = true; self.dispatchEvent('error'); } loadEnd(); }); _xhr.bind('Abort', function(e) { self.dispatchEvent(e); loadEnd(); }); _xhr.bind('Error', function(e) { _error_flag = true; _p('readyState', XMLHttpRequest.DONE); self.dispatchEvent('readystatechange'); _upload_complete_flag = true; self.dispatchEvent(e); loadEnd(); }); runtime.exec.call(_xhr, 'XMLHttpRequest', 'send', { url: _url, method: _method, async: _async, user: _user, password: _password, headers: _headers, mimeType: _mimeType, encoding: _encoding, responseType: self.responseType, withCredentials: self.withCredentials, options: _options }, data); } // clarify our requirements if (typeof(_options.required_caps) === 'string') { _options.required_caps = Runtime.parseCaps(_options.required_caps); } _options.required_caps = Basic.extend({}, _options.required_caps, { return_response_type: self.responseType }); if (data instanceof FormData) { _options.required_caps.send_multipart = true; } if (!_same_origin_flag) { _options.required_caps.do_cors = true; } if (_options.ruid) { // we do not need to wait if we can connect directly exec(_xhr.connectRuntime(_options)); } else { _xhr.bind('RuntimeInit', function(e, runtime) { exec(runtime); }); _xhr.bind('RuntimeError', function(e, err) { self.dispatchEvent('RuntimeError', err); }); _xhr.connectRuntime(_options); } } function _reset() { _p('responseText', ""); _p('responseXML', null); _p('response', null); _p('status', 0); _p('statusText', ""); _start_time = _timeoutset_time = null; } } XMLHttpRequest.UNSENT = 0; XMLHttpRequest.OPENED = 1; XMLHttpRequest.HEADERS_RECEIVED = 2; XMLHttpRequest.LOADING = 3; XMLHttpRequest.DONE = 4; XMLHttpRequest.prototype = EventTarget.instance; return XMLHttpRequest; }); // Included from: src/javascript/runtime/flash/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global ActiveXObject:true */ /** Defines constructor for Flash runtime. @class moxie/runtime/flash/Runtime @private */ define("moxie/runtime/flash/Runtime", [ "moxie/core/utils/Basic", "moxie/core/utils/Env", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/runtime/Runtime" ], function(Basic, Env, Dom, x, Runtime) { var type = 'flash', extensions = {}; /** Get the version of the Flash Player @method getShimVersion @private @return {Number} Flash Player version */ function getShimVersion() { var version; try { version = navigator.plugins['Shockwave Flash']; version = version.description; } catch (e1) { try { version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version'); } catch (e2) { version = '0.0'; } } version = version.match(/\d+/g); return parseFloat(version[0] + '.' + version[1]); } /** Constructor for the Flash Runtime @class FlashRuntime @extends Runtime */ function FlashRuntime(options) { var I = this, initTimer; options = Basic.extend({ swf_url: Env.swf_url }, options); Runtime.call(this, options, type, { access_binary: function(value) { return value && I.mode === 'browser'; }, access_image_binary: function(value) { return value && I.mode === 'browser'; }, display_media: Runtime.capTrue, do_cors: Runtime.capTrue, drag_and_drop: false, report_upload_progress: function() { return I.mode === 'client'; }, resize_image: Runtime.capTrue, return_response_headers: false, return_response_type: function(responseType) { if (responseType === 'json' && !!window.JSON) { return true; } return !Basic.arrayDiff(responseType, ['', 'text', 'document']) || I.mode === 'browser'; }, return_status_code: function(code) { return I.mode === 'browser' || !Basic.arrayDiff(code, [200, 404]); }, select_file: Runtime.capTrue, select_multiple: Runtime.capTrue, send_binary_string: function(value) { return value && I.mode === 'browser'; }, send_browser_cookies: function(value) { return value && I.mode === 'browser'; }, send_custom_headers: function(value) { return value && I.mode === 'browser'; }, send_multipart: Runtime.capTrue, slice_blob: function(value) { return value && I.mode === 'browser'; }, stream_upload: function(value) { return value && I.mode === 'browser'; }, summon_file_dialog: false, upload_filesize: function(size) { return Basic.parseSizeStr(size) <= 2097152 || I.mode === 'client'; }, use_http_method: function(methods) { return !Basic.arrayDiff(methods, ['GET', 'POST']); } }, { // capabilities that require specific mode access_binary: function(value) { return value ? 'browser' : 'client'; }, access_image_binary: function(value) { return value ? 'browser' : 'client'; }, report_upload_progress: function(value) { return value ? 'browser' : 'client'; }, return_response_type: function(responseType) { return Basic.arrayDiff(responseType, ['', 'text', 'json', 'document']) ? 'browser' : ['client', 'browser']; }, return_status_code: function(code) { return Basic.arrayDiff(code, [200, 404]) ? 'browser' : ['client', 'browser']; }, send_binary_string: function(value) { return value ? 'browser' : 'client'; }, send_browser_cookies: function(value) { return value ? 'browser' : 'client'; }, send_custom_headers: function(value) { return value ? 'browser' : 'client'; }, stream_upload: function(value) { return value ? 'client' : 'browser'; }, upload_filesize: function(size) { return Basic.parseSizeStr(size) >= 2097152 ? 'client' : 'browser'; } }, 'client'); // minimal requirement for Flash Player version if (getShimVersion() < 10) { this.mode = false; // with falsy mode, runtime won't operable, no matter what the mode was before } Basic.extend(this, { getShim: function() { return Dom.get(this.uid); }, shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return I.getShim().exec(this.uid, component, action, args); }, init: function() { var html, el, container; container = this.getShimContainer(); // if not the minimal height, shims are not initialized in older browsers (e.g FF3.6, IE6,7,8, Safari 4.0,5.0, etc) Basic.extend(container.style, { position: 'absolute', top: '-8px', left: '-8px', width: '9px', height: '9px', overflow: 'hidden' }); // insert flash object html = '<object id="' + this.uid + '" type="application/x-shockwave-flash" data="' + options.swf_url + '" '; if (Env.browser === 'IE') { html += 'classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" '; } html += 'width="100%" height="100%" style="outline:0">' + '<param name="movie" value="' + options.swf_url + '" />' + '<param name="flashvars" value="uid=' + escape(this.uid) + '&target=' + Env.global_event_dispatcher + '" />' + '<param name="wmode" value="transparent" />' + '<param name="allowscriptaccess" value="always" />' + '</object>'; if (Env.browser === 'IE') { el = document.createElement('div'); container.appendChild(el); el.outerHTML = html; el = container = null; // just in case } else { container.innerHTML = html; } // Init is dispatched by the shim initTimer = setTimeout(function() { if (I && !I.initialized) { // runtime might be already destroyed by this moment I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); } }, 5000); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); clearTimeout(initTimer); // initialization check might be still onwait options = initTimer = destroy = I = null; }; }(this.destroy)) }, extensions); } Runtime.addConstructor(type, FlashRuntime); return extensions; }); // Included from: src/javascript/runtime/flash/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/Blob @private */ define("moxie/runtime/flash/file/Blob", [ "moxie/runtime/flash/Runtime", "moxie/file/Blob" ], function(extensions, Blob) { var FlashBlob = { slice: function(blob, start, end, type) { var self = this.getRuntime(); if (start < 0) { start = Math.max(blob.size + start, 0); } else if (start > 0) { start = Math.min(start, blob.size); } if (end < 0) { end = Math.max(blob.size + end, 0); } else if (end > 0) { end = Math.min(end, blob.size); } blob = self.shimExec.call(this, 'Blob', 'slice', start, end, type || ''); if (blob) { blob = new Blob(self.uid, blob); } return blob; } }; return (extensions.Blob = FlashBlob); }); // Included from: src/javascript/runtime/flash/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileInput @private */ define("moxie/runtime/flash/file/FileInput", [ "moxie/runtime/flash/Runtime" ], function(extensions) { var FileInput = { init: function(options) { this.getRuntime().shimExec.call(this, 'FileInput', 'init', { name: options.name, accept: options.accept, multiple: options.multiple }); this.trigger('ready'); } }; return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/flash/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileReader @private */ define("moxie/runtime/flash/file/FileReader", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Encode" ], function(extensions, Encode) { var _result = ''; function _formatData(data, op) { switch (op) { case 'readAsText': return Encode.atob(data, 'utf8'); case 'readAsBinaryString': return Encode.atob(data); case 'readAsDataURL': return data; } return null; } var FileReader = { read: function(op, blob) { var target = this, self = target.getRuntime(); // special prefix for DataURL read mode if (op === 'readAsDataURL') { _result = 'data:' + (blob.type || '') + ';base64,'; } target.bind('Progress', function(e, data) { if (data) { _result += _formatData(data, op); } }); return self.shimExec.call(this, 'FileReader', 'readAsBase64', blob.uid); }, getResult: function() { return _result; }, destroy: function() { _result = null; } }; return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/flash/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/file/FileReaderSync @private */ define("moxie/runtime/flash/file/FileReaderSync", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Encode" ], function(extensions, Encode) { function _formatData(data, op) { switch (op) { case 'readAsText': return Encode.atob(data, 'utf8'); case 'readAsBinaryString': return Encode.atob(data); case 'readAsDataURL': return data; } return null; } var FileReaderSync = { read: function(op, blob) { var result, self = this.getRuntime(); result = self.shimExec.call(this, 'FileReaderSync', 'readAsBase64', blob.uid); if (!result) { return null; // or throw ex } // special prefix for DataURL read mode if (op === 'readAsDataURL') { result = 'data:' + (blob.type || '') + ';base64,' + result; } return _formatData(result, op, blob.type); } }; return (extensions.FileReaderSync = FileReaderSync); }); // Included from: src/javascript/runtime/Transporter.js /** * Transporter.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define("moxie/runtime/Transporter", [ "moxie/core/utils/Basic", "moxie/core/utils/Encode", "moxie/runtime/RuntimeClient", "moxie/core/EventTarget" ], function(Basic, Encode, RuntimeClient, EventTarget) { function Transporter() { var mod, _runtime, _data, _size, _pos, _chunk_size; RuntimeClient.call(this); Basic.extend(this, { uid: Basic.guid('uid_'), state: Transporter.IDLE, result: null, transport: function(data, type, options) { var self = this; options = Basic.extend({ chunk_size: 204798 }, options); // should divide by three, base64 requires this if ((mod = options.chunk_size % 3)) { options.chunk_size += 3 - mod; } _chunk_size = options.chunk_size; _reset.call(this); _data = data; _size = data.length; if (Basic.typeOf(options) === 'string' || options.ruid) { _run.call(self, type, this.connectRuntime(options)); } else { // we require this to run only once var cb = function(e, runtime) { self.unbind("RuntimeInit", cb); _run.call(self, type, runtime); }; this.bind("RuntimeInit", cb); this.connectRuntime(options); } }, abort: function() { var self = this; self.state = Transporter.IDLE; if (_runtime) { _runtime.exec.call(self, 'Transporter', 'clear'); self.trigger("TransportingAborted"); } _reset.call(self); }, destroy: function() { this.unbindAll(); _runtime = null; this.disconnectRuntime(); _reset.call(this); } }); function _reset() { _size = _pos = 0; _data = this.result = null; } function _run(type, runtime) { var self = this; _runtime = runtime; //self.unbind("RuntimeInit"); self.bind("TransportingProgress", function(e) { _pos = e.loaded; if (_pos < _size && Basic.inArray(self.state, [Transporter.IDLE, Transporter.DONE]) === -1) { _transport.call(self); } }, 999); self.bind("TransportingComplete", function() { _pos = _size; self.state = Transporter.DONE; _data = null; // clean a bit self.result = _runtime.exec.call(self, 'Transporter', 'getAsBlob', type || ''); }, 999); self.state = Transporter.BUSY; self.trigger("TransportingStarted"); _transport.call(self); } function _transport() { var self = this, chunk, bytesLeft = _size - _pos; if (_chunk_size > bytesLeft) { _chunk_size = bytesLeft; } chunk = Encode.btoa(_data.substr(_pos, _chunk_size)); _runtime.exec.call(self, 'Transporter', 'receive', chunk, _size); } } Transporter.IDLE = 0; Transporter.BUSY = 1; Transporter.DONE = 2; Transporter.prototype = EventTarget.instance; return Transporter; }); // Included from: src/javascript/runtime/flash/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/flash/xhr/XMLHttpRequest @private */ define("moxie/runtime/flash/xhr/XMLHttpRequest", [ "moxie/runtime/flash/Runtime", "moxie/core/utils/Basic", "moxie/file/Blob", "moxie/file/File", "moxie/file/FileReaderSync", "moxie/xhr/FormData", "moxie/runtime/Transporter" ], function(extensions, Basic, Blob, File, FileReaderSync, FormData, Transporter) { var XMLHttpRequest = { send: function(meta, data) { var target = this, self = target.getRuntime(); function send() { meta.transport = self.mode; self.shimExec.call(target, 'XMLHttpRequest', 'send', meta, data); } function appendBlob(name, blob) { self.shimExec.call(target, 'XMLHttpRequest', 'appendBlob', name, blob.uid); data = null; send(); } function attachBlob(blob, cb) { var tr = new Transporter(); tr.bind("TransportingComplete", function() { cb(this.result); }); tr.transport(blob.getSource(), blob.type, { ruid: self.uid }); } // copy over the headers if any if (!Basic.isEmptyObj(meta.headers)) { Basic.each(meta.headers, function(value, header) { self.shimExec.call(target, 'XMLHttpRequest', 'setRequestHeader', header, value.toString()); // Silverlight doesn't accept integers into the arguments of type object }); } // transfer over multipart params and blob itself if (data instanceof FormData) { var blobField; data.each(function(value, name) { if (value instanceof Blob) { blobField = name; } else { self.shimExec.call(target, 'XMLHttpRequest', 'append', name, value); } }); if (!data.hasBlob()) { data = null; send(); } else { var blob = data.getBlob(); if (blob.isDetached()) { attachBlob(blob, function(attachedBlob) { blob.destroy(); appendBlob(blobField, attachedBlob); }); } else { appendBlob(blobField, blob); } } } else if (data instanceof Blob) { if (data.isDetached()) { attachBlob(data, function(attachedBlob) { data.destroy(); data = attachedBlob.uid; send(); }); } else { data = data.uid; send(); } } else { send(); } }, getResponse: function(responseType) { var frs, blob, self = this.getRuntime(); blob = self.shimExec.call(this, 'XMLHttpRequest', 'getResponseAsBlob'); if (blob) { blob = new File(self.uid, blob); if ('blob' === responseType) { return blob; } try { frs = new FileReaderSync(); if (!!~Basic.inArray(responseType, ["", "text"])) { return frs.readAsText(blob); } else if ('json' === responseType && !!window.JSON) { return JSON.parse(frs.readAsText(blob)); } } finally { blob.destroy(); } } return null; }, abort: function(upload_complete_flag) { var self = this.getRuntime(); self.shimExec.call(this, 'XMLHttpRequest', 'abort'); this.dispatchEvent('readystatechange'); // this.dispatchEvent('progress'); this.dispatchEvent('abort'); //if (!upload_complete_flag) { // this.dispatchEvent('uploadprogress'); //} } }; return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/html4/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global File:true */ /** Defines constructor for HTML4 runtime. @class moxie/runtime/html4/Runtime @private */ define("moxie/runtime/html4/Runtime", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/Runtime", "moxie/core/utils/Env" ], function(Basic, x, Runtime, Env) { var type = 'html4', extensions = {}; function Html4Runtime(options) { var I = this , Test = Runtime.capTest , True = Runtime.capTrue ; Runtime.call(this, options, type, { access_binary: Test(window.FileReader || window.File && File.getAsDataURL), access_image_binary: false, display_media: Test(extensions.Image && (Env.can('create_canvas') || Env.can('use_data_uri_over32kb'))), do_cors: false, drag_and_drop: false, filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10); }()), resize_image: function() { return extensions.Image && I.can('access_binary') && Env.can('create_canvas'); }, report_upload_progress: false, return_response_headers: false, return_response_type: function(responseType) { if (responseType === 'json' && !!window.JSON) { return true; } return !!~Basic.inArray(responseType, ['text', 'document', '']); }, return_status_code: function(code) { return !Basic.arrayDiff(code, [200, 404]); }, select_file: function() { return Env.can('use_fileinput'); }, select_multiple: false, send_binary_string: false, send_custom_headers: false, send_multipart: true, slice_blob: false, stream_upload: function() { return I.can('select_file'); }, summon_file_dialog: Test(function() { // yeah... some dirty sniffing here... return (Env.browser === 'Firefox' && Env.version >= 4) || (Env.browser === 'Opera' && Env.version >= 12) || !!~Basic.inArray(Env.browser, ['Chrome', 'Safari']); }()), upload_filesize: True, use_http_method: function(methods) { return !Basic.arrayDiff(methods, ['GET', 'POST']); } }); Basic.extend(this, { init : function() { this.trigger("Init"); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); destroy = I = null; }; }(this.destroy)) }); Basic.extend(this.getShim(), extensions); } Runtime.addConstructor(type, Html4Runtime); return extensions; }); // Included from: src/javascript/core/utils/Events.js /** * Events.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ define('moxie/core/utils/Events', [ 'moxie/core/utils/Basic' ], function(Basic) { var eventhash = {}, uid = 'moxie_' + Basic.guid(); // IE W3C like event funcs function preventDefault() { this.returnValue = false; } function stopPropagation() { this.cancelBubble = true; } /** Adds an event handler to the specified object and store reference to the handler in objects internal Plupload registry (@see removeEvent). @method addEvent @for Utils @static @param {Object} obj DOM element like object to add handler to. @param {String} name Name to add event listener to. @param {Function} callback Function to call when event occurs. @param {String} [key] that might be used to add specifity to the event record. */ var addEvent = function(obj, name, callback, key) { var func, events; name = name.toLowerCase(); // Add event listener if (obj.addEventListener) { func = callback; obj.addEventListener(name, func, false); } else if (obj.attachEvent) { func = function() { var evt = window.event; if (!evt.target) { evt.target = evt.srcElement; } evt.preventDefault = preventDefault; evt.stopPropagation = stopPropagation; callback(evt); }; obj.attachEvent('on' + name, func); } // Log event handler to objects internal mOxie registry if (!obj[uid]) { obj[uid] = Basic.guid(); } if (!eventhash.hasOwnProperty(obj[uid])) { eventhash[obj[uid]] = {}; } events = eventhash[obj[uid]]; if (!events.hasOwnProperty(name)) { events[name] = []; } events[name].push({ func: func, orig: callback, // store original callback for IE key: key }); }; /** Remove event handler from the specified object. If third argument (callback) is not specified remove all events with the specified name. @method removeEvent @static @param {Object} obj DOM element to remove event listener(s) from. @param {String} name Name of event listener to remove. @param {Function|String} [callback] might be a callback or unique key to match. */ var removeEvent = function(obj, name, callback) { var type, undef; name = name.toLowerCase(); if (obj[uid] && eventhash[obj[uid]] && eventhash[obj[uid]][name]) { type = eventhash[obj[uid]][name]; } else { return; } for (var i = type.length - 1; i >= 0; i--) { // undefined or not, key should match if (type[i].orig === callback || type[i].key === callback) { if (obj.removeEventListener) { obj.removeEventListener(name, type[i].func, false); } else if (obj.detachEvent) { obj.detachEvent('on'+name, type[i].func); } type[i].orig = null; type[i].func = null; type.splice(i, 1); // If callback was passed we are done here, otherwise proceed if (callback !== undef) { break; } } } // If event array got empty, remove it if (!type.length) { delete eventhash[obj[uid]][name]; } // If mOxie registry has become empty, remove it if (Basic.isEmptyObj(eventhash[obj[uid]])) { delete eventhash[obj[uid]]; // IE doesn't let you remove DOM object property with - delete try { delete obj[uid]; } catch(e) { obj[uid] = undef; } } }; /** Remove all kind of events from the specified object @method removeAllEvents @static @param {Object} obj DOM element to remove event listeners from. @param {String} [key] unique key to match, when removing events. */ var removeAllEvents = function(obj, key) { if (!obj || !obj[uid]) { return; } Basic.each(eventhash[obj[uid]], function(events, name) { removeEvent(obj, name, key); }); }; return { addEvent: addEvent, removeEvent: removeEvent, removeAllEvents: removeAllEvents }; }); // Included from: src/javascript/runtime/html4/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/file/FileInput @private */ define("moxie/runtime/html4/file/FileInput", [ "moxie/runtime/html4/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Events", "moxie/core/utils/Mime", "moxie/core/utils/Env" ], function(extensions, Basic, Dom, Events, Mime, Env) { function FileInput() { var _uid, _files = [], _mimes = [], _options; function addInput() { var comp = this, I = comp.getRuntime(), shimContainer, browseButton, currForm, form, input, uid; uid = Basic.guid('uid_'); shimContainer = I.getShimContainer(); // we get new ref everytime to avoid memory leaks in IE if (_uid) { // move previous form out of the view currForm = Dom.get(_uid + '_form'); if (currForm) { Basic.extend(currForm.style, { top: '100%' }); } } // build form in DOM, since innerHTML version not able to submit file for some reason form = document.createElement('form'); form.setAttribute('id', uid + '_form'); form.setAttribute('method', 'post'); form.setAttribute('enctype', 'multipart/form-data'); form.setAttribute('encoding', 'multipart/form-data'); Basic.extend(form.style, { overflow: 'hidden', position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); input = document.createElement('input'); input.setAttribute('id', uid); input.setAttribute('type', 'file'); input.setAttribute('name', _options.name || 'Filedata'); input.setAttribute('accept', _mimes.join(',')); Basic.extend(input.style, { fontSize: '999px', opacity: 0 }); form.appendChild(input); shimContainer.appendChild(form); // prepare file input to be placed underneath the browse_button element Basic.extend(input.style, { position: 'absolute', top: 0, left: 0, width: '100%', height: '100%' }); if (Env.browser === 'IE' && Env.version < 10) { Basic.extend(input.style, { filter : "progid:DXImageTransform.Microsoft.Alpha(opacity=0)" }); } input.onchange = function() { // there should be only one handler for this var file; if (!this.value) { return; } if (this.files) { file = this.files[0]; } else { file = { name: this.value }; } _files = [file]; this.onchange = function() {}; // clear event handler addInput.call(comp); // after file is initialized as o.File, we need to update form and input ids comp.bind('change', function onChange() { var input = Dom.get(uid), form = Dom.get(uid + '_form'), file; comp.unbind('change', onChange); if (comp.files.length && input && form) { file = comp.files[0]; input.setAttribute('id', file.uid); form.setAttribute('id', file.uid + '_form'); // set upload target form.setAttribute('target', file.uid + '_iframe'); } input = form = null; }, 998); input = form = null; comp.trigger('change'); }; // route click event to the input if (I.can('summon_file_dialog')) { browseButton = Dom.get(_options.browse_button); Events.removeEvent(browseButton, 'click', comp.uid); Events.addEvent(browseButton, 'click', function(e) { if (input && !input.disabled) { // for some reason FF (up to 8.0.1 so far) lets to click disabled input[type=file] input.click(); } e.preventDefault(); }, comp.uid); } _uid = uid; shimContainer = currForm = browseButton = null; } Basic.extend(this, { init: function(options) { var comp = this, I = comp.getRuntime(), shimContainer; // figure out accept string _options = options; _mimes = options.accept.mimes || Mime.extList2mimes(options.accept, I.can('filter_by_extension')); shimContainer = I.getShimContainer(); (function() { var browseButton, zIndex, top; browseButton = Dom.get(options.browse_button); // Route click event to the input[type=file] element for browsers that support such behavior if (I.can('summon_file_dialog')) { if (Dom.getStyle(browseButton, 'position') === 'static') { browseButton.style.position = 'relative'; } zIndex = parseInt(Dom.getStyle(browseButton, 'z-index'), 10) || 1; browseButton.style.zIndex = zIndex; shimContainer.style.zIndex = zIndex - 1; } /* Since we have to place input[type=file] on top of the browse_button for some browsers, browse_button loses interactivity, so we restore it here */ top = I.can('summon_file_dialog') ? browseButton : shimContainer; Events.addEvent(top, 'mouseover', function() { comp.trigger('mouseenter'); }, comp.uid); Events.addEvent(top, 'mouseout', function() { comp.trigger('mouseleave'); }, comp.uid); Events.addEvent(top, 'mousedown', function() { comp.trigger('mousedown'); }, comp.uid); Events.addEvent(Dom.get(options.container), 'mouseup', function() { comp.trigger('mouseup'); }, comp.uid); browseButton = null; }()); addInput.call(this); shimContainer = null; // trigger ready event asynchronously comp.trigger({ type: 'ready', async: true }); }, getFiles: function() { return _files; }, disable: function(state) { var input; if ((input = Dom.get(_uid))) { input.disabled = !!state; } }, destroy: function() { var I = this.getRuntime() , shim = I.getShim() , shimContainer = I.getShimContainer() ; Events.removeAllEvents(shimContainer, this.uid); Events.removeAllEvents(_options && Dom.get(_options.container), this.uid); Events.removeAllEvents(_options && Dom.get(_options.browse_button), this.uid); if (shimContainer) { shimContainer.innerHTML = ''; } shim.removeInstance(this.uid); _uid = _files = _mimes = _options = shimContainer = shim = null; } }); } return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/html5/Runtime.js /** * Runtime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global File:true */ /** Defines constructor for HTML5 runtime. @class moxie/runtime/html5/Runtime @private */ define("moxie/runtime/html5/Runtime", [ "moxie/core/utils/Basic", "moxie/core/Exceptions", "moxie/runtime/Runtime", "moxie/core/utils/Env" ], function(Basic, x, Runtime, Env) { var type = "html5", extensions = {}; function Html5Runtime(options) { var I = this , Test = Runtime.capTest , True = Runtime.capTrue ; var caps = Basic.extend({ access_binary: Test(window.FileReader || window.File && window.File.getAsDataURL), access_image_binary: function() { return I.can('access_binary') && !!extensions.Image; }, display_media: Test(Env.can('create_canvas') || Env.can('use_data_uri_over32kb')), do_cors: Test(window.XMLHttpRequest && 'withCredentials' in new XMLHttpRequest()), drag_and_drop: Test(function() { // this comes directly from Modernizr: http://www.modernizr.com/ var div = document.createElement('div'); // IE has support for drag and drop since version 5, but doesn't support dropping files from desktop return (('draggable' in div) || ('ondragstart' in div && 'ondrop' in div)) && (Env.browser !== 'IE' || Env.version > 9); }()), filter_by_extension: Test(function() { // if you know how to feature-detect this, please suggest return (Env.browser === 'Chrome' && Env.version >= 28) || (Env.browser === 'IE' && Env.version >= 10); }()), return_response_headers: True, return_response_type: function(responseType) { if (responseType === 'json' && !!window.JSON) { // we can fake this one even if it's not supported return true; } return Env.can('return_response_type', responseType); }, return_status_code: True, report_upload_progress: Test(window.XMLHttpRequest && new XMLHttpRequest().upload), resize_image: function() { return I.can('access_binary') && Env.can('create_canvas'); }, select_file: function() { return Env.can('use_fileinput') && window.File; }, select_folder: function() { return I.can('select_file') && Env.browser === 'Chrome' && Env.version >= 21; }, select_multiple: function() { // it is buggy on Safari Windows and iOS return I.can('select_file') && !(Env.browser === 'Safari' && Env.os === 'Windows') && !(Env.os === 'iOS' && Env.verComp(Env.osVersion, "7.0.4", '<')); }, send_binary_string: Test(window.XMLHttpRequest && (new XMLHttpRequest().sendAsBinary || (window.Uint8Array && window.ArrayBuffer))), send_custom_headers: Test(window.XMLHttpRequest), send_multipart: function() { return !!(window.XMLHttpRequest && new XMLHttpRequest().upload && window.FormData) || I.can('send_binary_string'); }, slice_blob: Test(window.File && (File.prototype.mozSlice || File.prototype.webkitSlice || File.prototype.slice)), stream_upload: function(){ return I.can('slice_blob') && I.can('send_multipart'); }, summon_file_dialog: Test(function() { // yeah... some dirty sniffing here... return (Env.browser === 'Firefox' && Env.version >= 4) || (Env.browser === 'Opera' && Env.version >= 12) || (Env.browser === 'IE' && Env.version >= 10) || !!~Basic.inArray(Env.browser, ['Chrome', 'Safari']); }()), upload_filesize: True }, arguments[2] ); Runtime.call(this, options, (arguments[1] || type), caps); Basic.extend(this, { init : function() { this.trigger("Init"); }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); destroy = I = null; }; }(this.destroy)) }); Basic.extend(this.getShim(), extensions); } Runtime.addConstructor(type, Html5Runtime); return extensions; }); // Included from: src/javascript/runtime/html5/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html5/file/FileReader @private */ define("moxie/runtime/html5/file/FileReader", [ "moxie/runtime/html5/Runtime", "moxie/core/utils/Encode", "moxie/core/utils/Basic" ], function(extensions, Encode, Basic) { function FileReader() { var _fr, _convertToBinary = false; Basic.extend(this, { read: function(op, blob) { var target = this; _fr = new window.FileReader(); _fr.addEventListener('progress', function(e) { target.trigger(e); }); _fr.addEventListener('load', function(e) { target.trigger(e); }); _fr.addEventListener('error', function(e) { target.trigger(e, _fr.error); }); _fr.addEventListener('loadend', function() { _fr = null; }); if (Basic.typeOf(_fr[op]) === 'function') { _convertToBinary = false; _fr[op](blob.getSource()); } else if (op === 'readAsBinaryString') { // readAsBinaryString is depricated in general and never existed in IE10+ _convertToBinary = true; _fr.readAsDataURL(blob.getSource()); } }, getResult: function() { return _fr && _fr.result ? (_convertToBinary ? _toBinary(_fr.result) : _fr.result) : null; }, abort: function() { if (_fr) { _fr.abort(); } }, destroy: function() { _fr = null; } }); function _toBinary(str) { return Encode.atob(str.substring(str.indexOf('base64,') + 7)); } } return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/html4/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/file/FileReader @private */ define("moxie/runtime/html4/file/FileReader", [ "moxie/runtime/html4/Runtime", "moxie/runtime/html5/file/FileReader" ], function(extensions, FileReader) { return (extensions.FileReader = FileReader); }); // Included from: src/javascript/runtime/html4/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/html4/xhr/XMLHttpRequest @private */ define("moxie/runtime/html4/xhr/XMLHttpRequest", [ "moxie/runtime/html4/Runtime", "moxie/core/utils/Basic", "moxie/core/utils/Dom", "moxie/core/utils/Url", "moxie/core/Exceptions", "moxie/core/utils/Events", "moxie/file/Blob", "moxie/xhr/FormData" ], function(extensions, Basic, Dom, Url, x, Events, Blob, FormData) { function XMLHttpRequest() { var _status, _response, _iframe; function cleanup(cb) { var target = this, uid, form, inputs, i, hasFile = false; if (!_iframe) { return; } uid = _iframe.id.replace(/_iframe$/, ''); form = Dom.get(uid + '_form'); if (form) { inputs = form.getElementsByTagName('input'); i = inputs.length; while (i--) { switch (inputs[i].getAttribute('type')) { case 'hidden': inputs[i].parentNode.removeChild(inputs[i]); break; case 'file': hasFile = true; // flag the case for later break; } } inputs = []; if (!hasFile) { // we need to keep the form for sake of possible retries form.parentNode.removeChild(form); } form = null; } // without timeout, request is marked as canceled (in console) setTimeout(function() { Events.removeEvent(_iframe, 'load', target.uid); if (_iframe.parentNode) { // #382 _iframe.parentNode.removeChild(_iframe); } // check if shim container has any other children, if - not, remove it as well var shimContainer = target.getRuntime().getShimContainer(); if (!shimContainer.children.length) { shimContainer.parentNode.removeChild(shimContainer); } shimContainer = _iframe = null; cb(); }, 1); } Basic.extend(this, { send: function(meta, data) { var target = this, I = target.getRuntime(), uid, form, input, blob; _status = _response = null; function createIframe() { var container = I.getShimContainer() || document.body , temp = document.createElement('div') ; // IE 6 won't be able to set the name using setAttribute or iframe.name temp.innerHTML = '<iframe id="' + uid + '_iframe" name="' + uid + '_iframe" src="javascript:&quot;&quot;" style="display:none"></iframe>'; _iframe = temp.firstChild; container.appendChild(_iframe); /* _iframe.onreadystatechange = function() { console.info(_iframe.readyState); };*/ Events.addEvent(_iframe, 'load', function() { // _iframe.onload doesn't work in IE lte 8 var el; try { el = _iframe.contentWindow.document || _iframe.contentDocument || window.frames[_iframe.id].document; // try to detect some standard error pages if (/^4(0[0-9]|1[0-7]|2[2346])\s/.test(el.title)) { // test if title starts with 4xx HTTP error _status = el.title.replace(/^(\d+).*$/, '$1'); } else { _status = 200; // get result _response = Basic.trim(el.body.innerHTML); // we need to fire these at least once target.trigger({ type: 'progress', loaded: _response.length, total: _response.length }); if (blob) { // if we were uploading a file target.trigger({ type: 'uploadprogress', loaded: blob.size || 1025, total: blob.size || 1025 }); } } } catch (ex) { if (Url.hasSameOrigin(meta.url)) { // if response is sent with error code, iframe in IE gets redirected to res://ieframe.dll/http_x.htm // which obviously results to cross domain error (wtf?) _status = 404; } else { cleanup.call(target, function() { target.trigger('error'); }); return; } } cleanup.call(target, function() { target.trigger('load'); }); }, target.uid); } // end createIframe // prepare data to be sent and convert if required if (data instanceof FormData && data.hasBlob()) { blob = data.getBlob(); uid = blob.uid; input = Dom.get(uid); form = Dom.get(uid + '_form'); if (!form) { throw new x.DOMException(x.DOMException.NOT_FOUND_ERR); } } else { uid = Basic.guid('uid_'); form = document.createElement('form'); form.setAttribute('id', uid + '_form'); form.setAttribute('method', meta.method); form.setAttribute('enctype', 'multipart/form-data'); form.setAttribute('encoding', 'multipart/form-data'); form.setAttribute('target', uid + '_iframe'); I.getShimContainer().appendChild(form); } if (data instanceof FormData) { data.each(function(value, name) { if (value instanceof Blob) { if (input) { input.setAttribute('name', name); } } else { var hidden = document.createElement('input'); Basic.extend(hidden, { type : 'hidden', name : name, value : value }); // make sure that input[type="file"], if it's there, comes last if (input) { form.insertBefore(hidden, input); } else { form.appendChild(hidden); } } }); } // set destination url form.setAttribute("action", meta.url); createIframe(); form.submit(); target.trigger('loadstart'); }, getStatus: function() { return _status; }, getResponse: function(responseType) { if ('json' === responseType) { // strip off <pre>..</pre> tags that might be enclosing the response if (Basic.typeOf(_response) === 'string' && !!window.JSON) { try { return JSON.parse(_response.replace(/^\s*<pre[^>]*>/, '').replace(/<\/pre>\s*$/, '')); } catch (ex) { return null; } } } else if ('document' === responseType) { } return _response; }, abort: function() { var target = this; if (_iframe && _iframe.contentWindow) { if (_iframe.contentWindow.stop) { // FireFox/Safari/Chrome _iframe.contentWindow.stop(); } else if (_iframe.contentWindow.document.execCommand) { // IE _iframe.contentWindow.document.execCommand('Stop'); } else { _iframe.src = "about:blank"; } } cleanup.call(this, function() { // target.dispatchEvent('readystatechange'); target.dispatchEvent('abort'); }); } }); } return (extensions.XMLHttpRequest = XMLHttpRequest); }); // Included from: src/javascript/runtime/silverlight/Runtime.js /** * RunTime.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global ActiveXObject:true */ /** Defines constructor for Silverlight runtime. @class moxie/runtime/silverlight/Runtime @private */ define("moxie/runtime/silverlight/Runtime", [ "moxie/core/utils/Basic", "moxie/core/utils/Env", "moxie/core/utils/Dom", "moxie/core/Exceptions", "moxie/runtime/Runtime" ], function(Basic, Env, Dom, x, Runtime) { var type = "silverlight", extensions = {}; function isInstalled(version) { var isVersionSupported = false, control = null, actualVer, actualVerArray, reqVerArray, requiredVersionPart, actualVersionPart, index = 0; try { try { control = new ActiveXObject('AgControl.AgControl'); if (control.IsVersionSupported(version)) { isVersionSupported = true; } control = null; } catch (e) { var plugin = navigator.plugins["Silverlight Plug-In"]; if (plugin) { actualVer = plugin.description; if (actualVer === "1.0.30226.2") { actualVer = "2.0.30226.2"; } actualVerArray = actualVer.split("."); while (actualVerArray.length > 3) { actualVerArray.pop(); } while ( actualVerArray.length < 4) { actualVerArray.push(0); } reqVerArray = version.split("."); while (reqVerArray.length > 4) { reqVerArray.pop(); } do { requiredVersionPart = parseInt(reqVerArray[index], 10); actualVersionPart = parseInt(actualVerArray[index], 10); index++; } while (index < reqVerArray.length && requiredVersionPart === actualVersionPart); if (requiredVersionPart <= actualVersionPart && !isNaN(requiredVersionPart)) { isVersionSupported = true; } } } } catch (e2) { isVersionSupported = false; } return isVersionSupported; } /** Constructor for the Silverlight Runtime @class SilverlightRuntime @extends Runtime */ function SilverlightRuntime(options) { var I = this, initTimer; options = Basic.extend({ xap_url: Env.xap_url }, options); Runtime.call(this, options, type, { access_binary: Runtime.capTrue, access_image_binary: Runtime.capTrue, display_media: Runtime.capTrue, do_cors: Runtime.capTrue, drag_and_drop: false, report_upload_progress: Runtime.capTrue, resize_image: Runtime.capTrue, return_response_headers: function(value) { return value && I.mode === 'client'; }, return_response_type: function(responseType) { if (responseType !== 'json') { return true; } else { return !!window.JSON; } }, return_status_code: function(code) { return I.mode === 'client' || !Basic.arrayDiff(code, [200, 404]); }, select_file: Runtime.capTrue, select_multiple: Runtime.capTrue, send_binary_string: Runtime.capTrue, send_browser_cookies: function(value) { return value && I.mode === 'browser'; }, send_custom_headers: function(value) { return value && I.mode === 'client'; }, send_multipart: Runtime.capTrue, slice_blob: Runtime.capTrue, stream_upload: true, summon_file_dialog: false, upload_filesize: Runtime.capTrue, use_http_method: function(methods) { return I.mode === 'client' || !Basic.arrayDiff(methods, ['GET', 'POST']); } }, { // capabilities that require specific mode return_response_headers: function(value) { return value ? 'client' : 'browser'; }, return_status_code: function(code) { return Basic.arrayDiff(code, [200, 404]) ? 'client' : ['client', 'browser']; }, send_browser_cookies: function(value) { return value ? 'browser' : 'client'; }, send_custom_headers: function(value) { return value ? 'client' : 'browser'; }, use_http_method: function(methods) { return Basic.arrayDiff(methods, ['GET', 'POST']) ? 'client' : ['client', 'browser']; } }); // minimal requirement if (!isInstalled('2.0.31005.0') || Env.browser === 'Opera') { this.mode = false; } Basic.extend(this, { getShim: function() { return Dom.get(this.uid).content.Moxie; }, shimExec: function(component, action) { var args = [].slice.call(arguments, 2); return I.getShim().exec(this.uid, component, action, args); }, init : function() { var container; container = this.getShimContainer(); container.innerHTML = '<object id="' + this.uid + '" data="data:application/x-silverlight," type="application/x-silverlight-2" width="100%" height="100%" style="outline:none;">' + '<param name="source" value="' + options.xap_url + '"/>' + '<param name="background" value="Transparent"/>' + '<param name="windowless" value="true"/>' + '<param name="enablehtmlaccess" value="true"/>' + '<param name="initParams" value="uid=' + this.uid + ',target=' + Env.global_event_dispatcher + '"/>' + '</object>'; // Init is dispatched by the shim initTimer = setTimeout(function() { if (I && !I.initialized) { // runtime might be already destroyed by this moment I.trigger("Error", new x.RuntimeError(x.RuntimeError.NOT_INIT_ERR)); } }, Env.OS !== 'Windows'? 10000 : 5000); // give it more time to initialize in non Windows OS (like Mac) }, destroy: (function(destroy) { // extend default destroy method return function() { destroy.call(I); clearTimeout(initTimer); // initialization check might be still onwait options = initTimer = destroy = I = null; }; }(this.destroy)) }, extensions); } Runtime.addConstructor(type, SilverlightRuntime); return extensions; }); // Included from: src/javascript/runtime/silverlight/file/Blob.js /** * Blob.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/Blob @private */ define("moxie/runtime/silverlight/file/Blob", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/Blob" ], function(extensions, Basic, Blob) { return (extensions.Blob = Basic.extend({}, Blob)); }); // Included from: src/javascript/runtime/silverlight/file/FileInput.js /** * FileInput.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileInput @private */ define("moxie/runtime/silverlight/file/FileInput", [ "moxie/runtime/silverlight/Runtime" ], function(extensions) { var FileInput = { init: function(options) { function toFilters(accept) { var filter = ''; for (var i = 0; i < accept.length; i++) { filter += (filter !== '' ? '|' : '') + accept[i].title + " | *." + accept[i].extensions.replace(/,/g, ';*.'); } return filter; } this.getRuntime().shimExec.call(this, 'FileInput', 'init', toFilters(options.accept), options.name, options.multiple); this.trigger('ready'); } }; return (extensions.FileInput = FileInput); }); // Included from: src/javascript/runtime/silverlight/file/FileReader.js /** * FileReader.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileReader @private */ define("moxie/runtime/silverlight/file/FileReader", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/FileReader" ], function(extensions, Basic, FileReader) { return (extensions.FileReader = Basic.extend({}, FileReader)); }); // Included from: src/javascript/runtime/silverlight/file/FileReaderSync.js /** * FileReaderSync.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/file/FileReaderSync @private */ define("moxie/runtime/silverlight/file/FileReaderSync", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/file/FileReaderSync" ], function(extensions, Basic, FileReaderSync) { return (extensions.FileReaderSync = Basic.extend({}, FileReaderSync)); }); // Included from: src/javascript/runtime/silverlight/xhr/XMLHttpRequest.js /** * XMLHttpRequest.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /** @class moxie/runtime/silverlight/xhr/XMLHttpRequest @private */ define("moxie/runtime/silverlight/xhr/XMLHttpRequest", [ "moxie/runtime/silverlight/Runtime", "moxie/core/utils/Basic", "moxie/runtime/flash/xhr/XMLHttpRequest" ], function(extensions, Basic, XMLHttpRequest) { return (extensions.XMLHttpRequest = Basic.extend({}, XMLHttpRequest)); }); expose(["moxie/core/utils/Basic","moxie/core/I18n","moxie/core/utils/Mime","moxie/core/utils/Env","moxie/core/utils/Dom","moxie/core/Exceptions","moxie/core/EventTarget","moxie/core/utils/Encode","moxie/runtime/Runtime","moxie/runtime/RuntimeClient","moxie/file/Blob","moxie/file/File","moxie/file/FileInput","moxie/runtime/RuntimeTarget","moxie/file/FileReader","moxie/core/utils/Url","moxie/file/FileReaderSync","moxie/xhr/FormData","moxie/xhr/XMLHttpRequest","moxie/runtime/Transporter","moxie/core/utils/Events"]); })(this);/** * o.js * * Copyright 2013, Moxiecode Systems AB * Released under GPL License. * * License: http://www.plupload.com/license * Contributing: http://www.plupload.com/contributing */ /*global moxie:true */ /** Globally exposed namespace with the most frequently used public classes and handy methods. @class o @static @private */ (function(exports) { "use strict"; var o = {}, inArray = exports.moxie.core.utils.Basic.inArray; // directly add some public classes // (we do it dynamically here, since for custom builds we cannot know beforehand what modules were included) (function addAlias(ns) { var name, itemType; for (name in ns) { itemType = typeof(ns[name]); if (itemType === 'object' && !~inArray(name, ['Exceptions', 'Env', 'Mime'])) { addAlias(ns[name]); } else if (itemType === 'function') { o[name] = ns[name]; } } })(exports.moxie); // add some manually o.Env = exports.moxie.core.utils.Env; o.Mime = exports.moxie.core.utils.Mime; o.Exceptions = exports.moxie.core.Exceptions; // expose globally exports.mOxie = o; if (!exports.o) { exports.o = o; } return o; })(this);
src/index.js
cgvarela/react-styleguidist
import React from 'react'; import { setComponentsNames, globalizeComponents } from './utils/utils'; import StyleGuide from 'components/StyleGuide'; import './styles.css'; global.React = React; if (module.hot) { module.hot.accept(); } // Load styleguide let { title, components } = require('styleguide!'); components = setComponentsNames(components); globalizeComponents(components); React.render(<StyleGuide title={title} components={components}/>, document.getElementById('app'));
ajax/libs/react-bootstrap/0.24.0-alpha.0/react-bootstrap.min.js
ahocevar/cdnjs
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("react")):"function"==typeof define&&define.amd?define(["react"],t):"object"==typeof exports?exports.ReactBootstrap=t(require("react")):e.ReactBootstrap=t(e.React)}(this,function(e){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(29),s=n(o),a=r(30),i=n(a),l=r(21),u=n(l),p=r(31),d=n(p),f=r(3),c=n(f),h=r(32),m=n(h),v=r(9),y=n(v),g=r(14),b=n(g),P=r(33),O=n(P),T=r(34),_=n(T),C=r(38),w=n(C),E=r(35),N=n(E),x=r(36),k=n(x),S=r(37),M=n(S),j=r(10),D=n(j),I=r(39),A=n(I),K=r(15),B=n(K),L=r(16),H=n(L),R=r(11),W=n(R),F=r(22),U=n(F),z=r(41),V=n(z),q=r(42),G=n(q),Y=r(43),Z=n(Y),Q=r(24),J=n(Q),X=r(44),$=n(X),ee=r(45),te=n(ee),re=r(46),ne=n(re),oe=r(47),se=n(oe),ae=r(48),ie=n(ae),le=r(49),ue=n(le),pe=r(25),de=n(pe),fe=r(51),ce=n(fe),he=r(26),me=n(he),ve=r(50),ye=n(ve),ge=r(52),be=n(ge),Pe=r(18),Oe=n(Pe),Te=r(53),_e=n(Te),Ce=r(56),we=n(Ce),Ee=r(27),Ne=n(Ee),xe=r(54),ke=n(xe),Se=r(55),Me=n(Se),je=r(57),De=n(je),Ie=r(58),Ae=n(Ie),Ke=r(60),Be=n(Ke),Le=r(7),He=n(Le),Re=r(61),We=n(Re),Fe=r(62),Ue=n(Fe),ze=r(64),Ve=n(ze),qe=r(65),Ge=n(qe),Ye=r(63),Ze=n(Ye),Qe=r(66),Je=n(Qe),Xe=r(67),$e=n(Xe),et=r(70),tt=n(et),rt=r(68),nt=n(rt),ot=r(12),st=n(ot);t["default"]={Accordion:s["default"],Affix:i["default"],AffixMixin:u["default"],Alert:d["default"],BootstrapMixin:c["default"],Badge:m["default"],Button:y["default"],ButtonGroup:b["default"],ButtonInput:O["default"],ButtonToolbar:_["default"],CollapsibleNav:w["default"],Carousel:N["default"],CarouselItem:k["default"],Col:M["default"],CollapsibleMixin:D["default"],DropdownButton:A["default"],DropdownMenu:B["default"],DropdownStateMixin:H["default"],FadeMixin:W["default"],FormControls:U["default"],Glyphicon:V["default"],Grid:G["default"],Input:Z["default"],Interpolate:J["default"],Jumbotron:$["default"],Label:te["default"],ListGroup:ne["default"],ListGroupItem:se["default"],MenuItem:ie["default"],Modal:ue["default"],Nav:de["default"],Navbar:ce["default"],NavItem:me["default"],ModalTrigger:ye["default"],OverlayTrigger:be["default"],OverlayMixin:Oe["default"],PageHeader:_e["default"],Panel:we["default"],PanelGroup:Ne["default"],PageItem:ke["default"],Pager:Me["default"],Popover:De["default"],ProgressBar:Ae["default"],Row:Be["default"],SafeAnchor:He["default"],SplitButton:We["default"],SubNav:Ue["default"],TabbedArea:Ve["default"],Table:Ge["default"],TabPane:Ze["default"],Thumbnail:Je["default"],Tooltip:$e["default"],utils:tt["default"],Well:nt["default"],styleMaps:st["default"]},e.exports=t["default"]},function(t,r,n){t.exports=e},function(e,t,r){var n;/*! Copyright (c) 2015 Jed Watson. Licensed under the MIT License (MIT), see http://jedwatson.github.io/classnames */ !function(){"use strict";function o(){for(var e="",t=0;t<arguments.length;t++){var r=arguments[t];if(r){var n=typeof r;if("string"===n||"number"===n)e+=" "+r;else if(Array.isArray(r))e+=" "+o.apply(null,r);else if("object"===n)for(var s in r)r.hasOwnProperty(s)&&r[s]&&(e+=" "+s)}}return e.substr(1)}n=function(){return o}.call(t,r,t,e),!(void 0!==n&&(e.exports=n))}()},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(12),s=n(o),a=r(8),i=n(a),l={propTypes:{bsClass:i["default"].keyOf(s["default"].CLASSES),bsStyle:i["default"].keyOf(s["default"].STYLES),bsSize:i["default"].keyOf(s["default"].SIZES)},getBsClassSet:function(){var e={},t=this.props.bsClass&&s["default"].CLASSES[this.props.bsClass];if(t){e[t]=!0;var r=t+"-",n=this.props.bsSize&&s["default"].SIZES[this.props.bsSize];n&&(e[r+n]=!0);var o=this.props.bsStyle&&s["default"].STYLES[this.props.bsStyle];this.props.bsStyle&&(e[r+o]=!0)}return e},prefixClass:function(e){return s["default"].CLASSES[this.props.bsClass]+"-"+e}};t["default"]=l,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){var n=0;return u["default"].Children.map(e,function(e){if(u["default"].isValidElement(e)){var o=n;return n++,t.call(r,e,o)}return e})}function s(e,t,r){var n=0;return u["default"].Children.forEach(e,function(e){u["default"].isValidElement(e)&&(t.call(r,e,n),n++)})}function a(e){var t=0;return u["default"].Children.forEach(e,function(e){u["default"].isValidElement(e)&&t++}),t}function i(e){var t=!1;return u["default"].Children.forEach(e,function(e){!t&&u["default"].isValidElement(e)&&(t=!0)}),t}Object.defineProperty(t,"__esModule",{value:!0});var l=r(1),u=n(l);t["default"]={map:o,forEach:s,numberOf:a,hasValidComponent:i},e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=p["default"].findDOMNode(e);return t&&t.ownerDocument||document}function s(e){return o(e).defaultView.getComputedStyle(e,null)}function a(e){if(window.jQuery)return window.jQuery(e).offset();var t=o(e).documentElement,r={top:0,left:0};return"undefined"!=typeof e.getBoundingClientRect&&(r=e.getBoundingClientRect()),{top:r.top+window.pageYOffset-t.clientTop,left:r.left+window.pageXOffset-t.clientLeft}}function i(e,t){if(window.jQuery)return window.jQuery(e).position();var r=void 0,n={top:0,left:0};return"fixed"===s(e).position?r=e.getBoundingClientRect():(t||(t=l(e)),r=a(e),"HTML"!==t.nodeName&&(n=a(t)),n.top+=parseInt(s(t).borderTopWidth,10),n.left+=parseInt(s(t).borderLeftWidth,10)),{top:r.top-n.top-parseInt(s(e).marginTop,10),left:r.left-n.left-parseInt(s(e).marginLeft,10)}}function l(e){for(var t=o(e).documentElement,r=e.offsetParent||t;r&&"HTML"!==r.nodeName&&"static"===s(r).position;)r=r.offsetParent;return r||t}Object.defineProperty(t,"__esModule",{value:!0});var u=r(1),p=n(u);t["default"]={ownerDocument:o,getComputedStyles:s,getOffset:a,getPosition:i,offsetParent:l},e.exports=t["default"]},function(e,t,r){"use strict";function n(e,t){var r="function"==typeof e,n="function"==typeof t;return r||n?r?n?function(){e.apply(this,arguments),t.apply(this,arguments)}:e:t:null}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=function(e,t,r){for(var n=!0;n;){var o=e,s=t,a=r;i=u=l=void 0,n=!1;var i=Object.getOwnPropertyDescriptor(o,s);if(void 0!==i){if("value"in i)return i.value;var l=i.get;return void 0===l?void 0:l.call(a)}var u=Object.getPrototypeOf(o);if(null===u)return void 0;e=u,t=s,r=a,n=!0}},u=r(1),p=n(u),d=function(e){function t(e){o(this,t),l(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),this.handleClick=this.handleClick.bind(this)}return s(t,e),i(t,[{key:"handleClick",value:function(e){void 0===this.props.href&&e.preventDefault(),this.props.onClick&&this.props.onClick(e)}},{key:"render",value:function(){return p["default"].createElement("a",a({role:this.props.href?void 0:"button"},this.props,{onClick:this.handleClick,href:this.props.href||""}))}}]),t}(p["default"].Component);t["default"]=d,d.propTypes={href:p["default"].PropTypes.string,onClick:p["default"].PropTypes.func},e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return Array.isArray(e)?e:Array.from(e)}function o(e){function t(t,r,n,o){return o=o||u,null!=r[n]?e(r,n,o):t?new Error("Required prop `"+n+"` was not specified in `"+o+"`."):void 0}var r=t.bind(null,!1);return r.isRequired=t.bind(null,!0),r}function s(){function e(e,t,r){return"object"!=typeof e[t]||"function"!=typeof e[t].render&&1!==e[t].nodeType?new Error("Invalid prop `"+t+"` supplied to `"+r+"`, expected a DOM element or an object that has a `render` method"):void 0}return o(e)}function a(e){function t(t,r,n){var o=t[r];if(!e.hasOwnProperty(o)){var s=JSON.stringify(Object.keys(e));return new Error("Invalid prop '"+r+"' of value '"+o+"' "+("supplied to '"+n+"', expected one of "+s+"."))}}return o(t)}function i(e){function t(t,r,o){var s=e.map(function(e){return t[e]}).reduce(function(e,t){return e+(void 0!==t?1:0)},0);if(s>1){var a=n(e),i=a[0],l=a.slice(1),u=""+l.join(", ")+" and "+i;return new Error("Invalid prop '"+r+"', only one of the following may be provided: "+u)}}return t}function l(e){if(void 0===e)throw new Error("No validations provided");if(!(e instanceof Array))throw new Error("Invalid argument must be an array");if(0===e.length)throw new Error("No validations provided");return function(t,r,n){for(var o=0;o<e.length;o++){var s=e[o](t,r,n);if(void 0!==s&&null!==s)return s}}}Object.defineProperty(t,"__esModule",{value:!0});var u="<<anonymous>>",p={mountable:s(),keyOf:a,singlePropFrom:i,all:l};t["default"]=p,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(3),p=n(u),d=a["default"].createClass({displayName:"Button",mixins:[p["default"]],propTypes:{active:a["default"].PropTypes.bool,disabled:a["default"].PropTypes.bool,block:a["default"].PropTypes.bool,navItem:a["default"].PropTypes.bool,navDropdown:a["default"].PropTypes.bool,componentClass:a["default"].PropTypes.node,href:a["default"].PropTypes.string,target:a["default"].PropTypes.string},getDefaultProps:function(){return{bsClass:"button",bsStyle:"default",type:"button"}},render:function(){var e=this.props.navDropdown?{}:this.getBsClassSet(),t=void 0;return e=o({active:this.props.active,"btn-block":this.props.block},e),this.props.navItem?this.renderNavItem(e):(t=this.props.href||this.props.target||this.props.navDropdown?"renderAnchor":"renderButton",this[t](e))},renderAnchor:function(e){var t=this.props.componentClass||"a",r=this.props.href||"#";return e.disabled=this.props.disabled,a["default"].createElement(t,o({},this.props,{href:r,className:l["default"](this.props.className,e),role:"button"}),this.props.children)},renderButton:function(e){var t=this.props.componentClass||"button";return a["default"].createElement(t,o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children)},renderNavItem:function(e){var t={active:this.props.active};return a["default"].createElement("li",{className:l["default"](t)},this.renderAnchor(e))}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=n(o),a=r(19),i=n(a),l={propTypes:{defaultExpanded:s["default"].PropTypes.bool,expanded:s["default"].PropTypes.bool},getInitialState:function(){var e=null!=this.props.defaultExpanded?this.props.defaultExpanded:null!=this.props.expanded?this.props.expanded:!1;return{expanded:e,collapsing:!1}},componentWillUpdate:function(e,t){var r=null!=e.expanded?e.expanded:t.expanded;if(r!==this.isExpanded()){var n=this.getCollapsibleDOMNode(),o=this.dimension(),s="0";r||(s=this.getCollapsibleDimensionValue()),n.style[o]=s+"px",this._afterWillUpdate()}},componentDidUpdate:function(e,t){this._checkToggleCollapsing(e,t),this._checkStartAnimation()},_afterWillUpdate:function(){},_checkStartAnimation:function(){if(this.state.collapsing){var e=this.getCollapsibleDOMNode(),t=this.dimension(),r=this.getCollapsibleDimensionValue(),n=void 0;n=this.isExpanded()?r+"px":"0px",e.style[t]=n}},_checkToggleCollapsing:function(e,t){var r=null!=e.expanded?e.expanded:t.expanded,n=this.isExpanded();r!==n&&(r?this._handleCollapse():this._handleExpand())},_handleExpand:function(){var e=this,t=this.getCollapsibleDOMNode(),r=this.dimension(),n=function o(){e._removeEndEventListener(t,o),t.style[r]="",e.setState({collapsing:!1})};this._addEndEventListener(t,n),this.setState({collapsing:!0})},_handleCollapse:function(){var e=this,t=this.getCollapsibleDOMNode(),r=function n(){e._removeEndEventListener(t,n),e.setState({collapsing:!1})};this._addEndEventListener(t,r),this.setState({collapsing:!0})},_addEndEventListener:function(e,t){i["default"].addEndEventListener(e,t)},_removeEndEventListener:function(e,t){i["default"].removeEndEventListener(e,t)},dimension:function(){return"function"==typeof this.getCollapsibleDimension?this.getCollapsibleDimension():"height"},isExpanded:function(){return null!=this.props.expanded?this.props.expanded:this.state.expanded},getCollapsibleClassSet:function(e){var t={};return"string"==typeof e&&e.split(" ").forEach(function(e){e&&(t[e]=!0)}),t.collapsing=this.state.collapsing,t.collapse=!this.state.collapsing,t["in"]=this.isExpanded()&&!this.state.collapsing,t}};t["default"]=l,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r=e.querySelectorAll("."+t.join("."));r=[].map.call(r,function(e){return e});for(var n=0;n<t.length;n++)if(!e.className.match(new RegExp("\\b"+t[n]+"\\b")))return r;return r.unshift(e),r}Object.defineProperty(t,"__esModule",{value:!0});var s=r(1),a=n(s),i=r(5),l=n(i);t["default"]={_fadeIn:function(){var e=void 0;this.isMounted()&&(e=o(a["default"].findDOMNode(this),["fade"]),e.length&&e.forEach(function(e){e.className+=" in"}))},_fadeOut:function(){var e=o(this._fadeOutEl,["fade","in"]);e.length&&e.forEach(function(e){e.className=e.className.replace(/\bin\b/,"")}),setTimeout(this._handleFadeOutEnd,300)},_handleFadeOutEnd:function(){this._fadeOutEl&&this._fadeOutEl.parentNode&&this._fadeOutEl.parentNode.removeChild(this._fadeOutEl)},componentDidMount:function(){document.querySelectorAll&&setTimeout(this._fadeIn,20)},componentWillUnmount:function(){var e=o(a["default"].findDOMNode(this),["fade"]),t=this.props.container&&a["default"].findDOMNode(this.props.container)||l["default"].ownerDocument(this).body;e.length&&(this._fadeOutEl=document.createElement("div"),t.appendChild(this._fadeOutEl),this._fadeOutEl.appendChild(a["default"].findDOMNode(this).cloneNode(!0)),setTimeout(this._fadeOut,20))}},e.exports=t["default"]},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={CLASSES:{alert:"alert",button:"btn","button-group":"btn-group","button-toolbar":"btn-toolbar",column:"col","input-group":"input-group",form:"form",glyphicon:"glyphicon",label:"label",thumbnail:"thumbnail","list-group-item":"list-group-item",panel:"panel","panel-group":"panel-group","progress-bar":"progress-bar",nav:"nav",navbar:"navbar",modal:"modal",row:"row",well:"well"},STYLES:{"default":"default",primary:"primary",success:"success",info:"info",warning:"warning",danger:"danger",link:"link",inline:"inline",tabs:"tabs",pills:"pills"},addStyle:function(e){n.STYLES[e]=e},SIZES:{large:"lg",medium:"md",small:"sm",xsmall:"xs"},GLYPHS:["asterisk","plus","euro","eur","minus","cloud","envelope","pencil","glass","music","search","heart","star","star-empty","user","film","th-large","th","th-list","ok","remove","zoom-in","zoom-out","off","signal","cog","trash","home","file","time","road","download-alt","download","upload","inbox","play-circle","repeat","refresh","list-alt","lock","flag","headphones","volume-off","volume-down","volume-up","qrcode","barcode","tag","tags","book","bookmark","print","camera","font","bold","italic","text-height","text-width","align-left","align-center","align-right","align-justify","list","indent-left","indent-right","facetime-video","picture","map-marker","adjust","tint","edit","share","check","move","step-backward","fast-backward","backward","play","pause","stop","forward","fast-forward","step-forward","eject","chevron-left","chevron-right","plus-sign","minus-sign","remove-sign","ok-sign","question-sign","info-sign","screenshot","remove-circle","ok-circle","ban-circle","arrow-left","arrow-right","arrow-up","arrow-down","share-alt","resize-full","resize-small","exclamation-sign","gift","leaf","fire","eye-open","eye-close","warning-sign","plane","calendar","random","comment","magnet","chevron-up","chevron-down","retweet","shopping-cart","folder-close","folder-open","resize-vertical","resize-horizontal","hdd","bullhorn","bell","certificate","thumbs-up","thumbs-down","hand-right","hand-left","hand-up","hand-down","circle-arrow-right","circle-arrow-left","circle-arrow-up","circle-arrow-down","globe","wrench","tasks","filter","briefcase","fullscreen","dashboard","paperclip","heart-empty","link","phone","pushpin","usd","gbp","sort","sort-by-alphabet","sort-by-alphabet-alt","sort-by-order","sort-by-order-alt","sort-by-attributes","sort-by-attributes-alt","unchecked","expand","collapse-down","collapse-up","log-in","flash","log-out","new-window","record","save","open","saved","import","export","send","floppy-disk","floppy-saved","floppy-remove","floppy-save","floppy-open","credit-card","transfer","cutlery","header","compressed","earphone","phone-alt","tower","stats","sd-video","hd-video","subtitles","sound-stereo","sound-dolby","sound-5-1","sound-6-1","sound-7-1","copyright-mark","registration-mark","cloud-download","cloud-upload","tree-conifer","tree-deciduous","cd","save-file","open-file","level-up","copy","paste","alert","equalizer","king","queen","pawn","bishop","knight","baby-formula","tent","blackboard","bed","apple","erase","hourglass","lamp","duplicate","piggy-bank","scissors","bitcoin","yen","ruble","scale","ice-lolly","ice-lolly-tasted","education","option-horizontal","option-vertical","menu-hamburger","modal-window","oil","grain","sunglasses","text-size","text-color","text-background","object-align-top","object-align-bottom","object-align-horizontal","object-align-left","object-align-vertical","object-align-right","triangle-right","triangle-left","triangle-bottom","triangle-top","console","superscript","subscript","menu-left","menu-right","menu-down","menu-up"]};t["default"]=n,e.exports=t["default"]},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n={listen:function(e,t,r){return e.addEventListener?(e.addEventListener(t,r,!1),{remove:function(){e.removeEventListener(t,r,!1)}}):e.attachEvent?(e.attachEvent("on"+t,r),{remove:function(){e.detachEvent("on"+t,r)}}):void 0}};t["default"]=n,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(3),p=n(u),d=r(8),f=n(d),c=a["default"].createClass({displayName:"ButtonGroup",mixins:[p["default"]],propTypes:{vertical:a["default"].PropTypes.bool,justified:a["default"].PropTypes.bool,block:f["default"].all([a["default"].PropTypes.bool,function(e,t,r){return e.block&&!e.vertical?new Error("The block property requires the vertical property to be set to have any effect"):void 0}])},getDefaultProps:function(){return{bsClass:"button-group"}},render:function(){var e=this.getBsClassSet();return e["btn-group"]=!this.props.vertical,e["btn-group-vertical"]=this.props.vertical,e["btn-group-justified"]=this.props.justified,e["btn-block"]=this.props.block,a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children)}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(6),p=n(u),d=r(4),f=n(d),c=a["default"].createClass({displayName:"DropdownMenu",propTypes:{pullRight:a["default"].PropTypes.bool,onSelect:a["default"].PropTypes.func},render:function(){var e={"dropdown-menu":!0,"dropdown-menu-right":this.props.pullRight};return a["default"].createElement("ul",o({},this.props,{className:l["default"](this.props.className,e),role:"menu"}),f["default"].map(this.props.children,this.renderMenuItem))},renderMenuItem:function(e,t){return s.cloneElement(e,{onSelect:p["default"](e.props.onSelect,this.props.onSelect),key:e.key?e.key:t})}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){for(;e;){if(e===t)return!0;e=e.parentNode}return!1}Object.defineProperty(t,"__esModule",{value:!0});var s=r(1),a=n(s),i=r(5),l=n(i),u=r(13),p=n(u),d={getInitialState:function(){return{open:!1}},setDropdownState:function(e,t){e?this.bindRootCloseHandlers():this.unbindRootCloseHandlers(),this.setState({open:e},t)},handleDocumentKeyUp:function(e){27===e.keyCode&&this.setDropdownState(!1)},handleDocumentClick:function(e){var t=e.target||e.srcElement;o(t,a["default"].findDOMNode(this))||this.setDropdownState(!1)},bindRootCloseHandlers:function(){var e=l["default"].ownerDocument(this);this._onDocumentClickListener=p["default"].listen(e,"click",this.handleDocumentClick),this._onDocumentKeyupListener=p["default"].listen(e,"keyup",this.handleDocumentKeyUp)},unbindRootCloseHandlers:function(){this._onDocumentClickListener&&this._onDocumentClickListener.remove(),this._onDocumentKeyupListener&&this._onDocumentKeyupListener.remove()},componentWillUnmount:function(){this.unbindRootCloseHandlers()}};t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(1),u=n(l),p=r(2),d=n(p),f=r(23),c=n(f),h=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return s(t,e),i(t,[{key:"getInputDOMNode",value:function(){return u["default"].findDOMNode(this.refs.input)}},{key:"getValue",value:function(){if("static"===this.props.type)return this.props.value;if(this.props.type)return"select"===this.props.type&&this.props.multiple?this.getSelectedOptions():this.getInputDOMNode().value;throw"Cannot use getValue without specifying input type."}},{key:"getChecked",value:function(){return this.getInputDOMNode().checked}},{key:"getSelectedOptions",value:function(){var e=[];return Array.prototype.forEach.call(this.getInputDOMNode().getElementsByTagName("option"),function(t){if(t.selected){var r=t.getAttribute("value")||t.innerHtml;e.push(r)}}),e}},{key:"isCheckboxOrRadio",value:function(){return"checkbox"===this.props.type||"radio"===this.props.type}},{key:"isFile",value:function(){return"file"===this.props.type}},{key:"renderInputGroup",value:function(e){var t=this.props.addonBefore?u["default"].createElement("span",{className:"input-group-addon",key:"addonBefore"},this.props.addonBefore):null,r=this.props.addonAfter?u["default"].createElement("span",{className:"input-group-addon",key:"addonAfter"},this.props.addonAfter):null,n=this.props.buttonBefore?u["default"].createElement("span",{className:"input-group-btn"},this.props.buttonBefore):null,o=this.props.buttonAfter?u["default"].createElement("span",{className:"input-group-btn"},this.props.buttonAfter):null,s=void 0;switch(this.props.bsSize){case"small":s="input-group-sm";break;case"large":s="input-group-lg"}return t||r||n||o?u["default"].createElement("div",{className:d["default"](s,"input-group"),key:"input-group"},t,n,e,r,o):e}},{key:"renderIcon",value:function(){var e={glyphicon:!0,"form-control-feedback":!0,"glyphicon-ok":"success"===this.props.bsStyle,"glyphicon-warning-sign":"warning"===this.props.bsStyle,"glyphicon-remove":"error"===this.props.bsStyle};return this.props.hasFeedback?u["default"].createElement("span",{className:d["default"](e),key:"icon"}):null}},{key:"renderHelp",value:function(){return this.props.help?u["default"].createElement("span",{className:"help-block",key:"help"},this.props.help):null}},{key:"renderCheckboxAndRadioWrapper",value:function(e){var t={checkbox:"checkbox"===this.props.type,radio:"radio"===this.props.type};return u["default"].createElement("div",{className:d["default"](t),key:"checkboxRadioWrapper"},e)}},{key:"renderWrapper",value:function(e){return this.props.wrapperClassName?u["default"].createElement("div",{className:this.props.wrapperClassName,key:"wrapper"},e):e}},{key:"renderLabel",value:function(e){var t={"control-label":!this.isCheckboxOrRadio()};return t[this.props.labelClassName]=this.props.labelClassName,this.props.label?u["default"].createElement("label",{htmlFor:this.props.id,className:d["default"](t),key:"label"},e,this.props.label):e}},{key:"renderInput",value:function(){if(!this.props.type)return this.props.children;switch(this.props.type){case"select":return u["default"].createElement("select",a({},this.props,{className:d["default"](this.props.className,"form-control"),ref:"input",key:"input"}),this.props.children);case"textarea":return u["default"].createElement("textarea",a({},this.props,{className:d["default"](this.props.className,"form-control"),ref:"input",key:"input"}));case"static":return u["default"].createElement("p",a({},this.props,{className:d["default"](this.props.className,"form-control-static"),ref:"input",key:"input"}),this.props.value)}var e=this.isCheckboxOrRadio()||this.isFile()?"":"form-control";return u["default"].createElement("input",a({},this.props,{className:d["default"](this.props.className,e),ref:"input",key:"input"}))}},{key:"renderFormGroup",value:function(e){return u["default"].createElement(c["default"],this.props,e)}},{key:"renderChildren",value:function(){return this.isCheckboxOrRadio()?this.renderWrapper([this.renderCheckboxAndRadioWrapper(this.renderLabel(this.renderInput())),this.renderHelp()]):[this.renderLabel(),this.renderWrapper([this.renderInputGroup(this.renderInput()),this.renderIcon(),this.renderHelp()])]}},{key:"render",value:function(){var e=this.renderChildren();return this.renderFormGroup(e)}}]),t}(u["default"].Component);h.propTypes={type:u["default"].PropTypes.string,label:u["default"].PropTypes.node,help:u["default"].PropTypes.node,addonBefore:u["default"].PropTypes.node,addonAfter:u["default"].PropTypes.node,buttonBefore:u["default"].PropTypes.node,buttonAfter:u["default"].PropTypes.node,bsSize:u["default"].PropTypes.oneOf(["small","medium","large"]),bsStyle:u["default"].PropTypes.oneOf(["success","warning","error"]),hasFeedback:u["default"].PropTypes.bool,id:u["default"].PropTypes.string,groupClassName:u["default"].PropTypes.string,wrapperClassName:u["default"].PropTypes.string,labelClassName:u["default"].PropTypes.string,multiple:u["default"].PropTypes.bool,disabled:u["default"].PropTypes.bool,value:u["default"].PropTypes.any},t["default"]=h,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=n(o),a=r(8),i=n(a),l=r(5),u=n(l);t["default"]={propTypes:{container:i["default"].mountable},componentWillUnmount:function(){this._unrenderOverlay(),this._overlayTarget&&(this.getContainerDOMNode().removeChild(this._overlayTarget),this._overlayTarget=null)},componentDidUpdate:function(){this._renderOverlay()},componentDidMount:function(){this._renderOverlay()},_mountOverlayTarget:function(){this._overlayTarget=document.createElement("div"),this.getContainerDOMNode().appendChild(this._overlayTarget)},_renderOverlay:function(){this._overlayTarget||this._mountOverlayTarget();var e=this.renderOverlay();null!==e?this._overlayInstance=s["default"].render(e,this._overlayTarget):this._unrenderOverlay()},_unrenderOverlay:function(){s["default"].unmountComponentAtNode(this._overlayTarget),this._overlayInstance=null},getOverlayDOMNode:function(){if(!this.isMounted())throw new Error("getOverlayDOMNode(): A component must be mounted to have a DOM node.");return this._overlayInstance?s["default"].findDOMNode(this._overlayInstance):null},getContainerDOMNode:function(){return s["default"].findDOMNode(this.props.container)||u["default"].ownerDocument(this).body}},e.exports=t["default"]},function(e,t,r){"use strict";function n(){var e=document.createElement("div"),t=e.style;"AnimationEvent"in window||delete i.animationend.animation,"TransitionEvent"in window||delete i.transitionend.transition;for(var r in i){var n=i[r];for(var o in n)if(o in t){l.push(n[o]);break}}}function o(e,t,r){e.addEventListener(t,r,!1)}function s(e,t,r){e.removeEventListener(t,r,!1)}Object.defineProperty(t,"__esModule",{value:!0});var a=!("undefined"==typeof window||!window.document||!window.document.createElement),i={transitionend:{transition:"transitionend",WebkitTransition:"webkitTransitionEnd",MozTransition:"mozTransitionEnd",OTransition:"oTransitionEnd",msTransition:"MSTransitionEnd"},animationend:{animation:"animationend",WebkitAnimation:"webkitAnimationEnd",MozAnimation:"mozAnimationEnd",OAnimation:"oAnimationEnd",msAnimation:"MSAnimationEnd"}},l=[];a&&n();var u={addEndEventListener:function(e,t){return 0===l.length?void window.setTimeout(t,0):void l.forEach(function(r){o(e,r,t)})},removeEndEventListener:function(e,t){0!==l.length&&l.forEach(function(r){s(e,r,t)})}};t["default"]=u,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){var n=i.singlePropFrom(l)(e,t,r);if(!n){var o=a["default"].PropTypes.oneOfType(u);n=o(e,t,r)}return n}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=o;var s=r(1),a=n(s),i=r(8),l=["children","value"],u=[a["default"].PropTypes.number,a["default"].PropTypes.string];e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=n(o),a=r(5),i=n(a),l=r(13),u=n(l),p={propTypes:{offset:s["default"].PropTypes.number,offsetTop:s["default"].PropTypes.number,offsetBottom:s["default"].PropTypes.number},getInitialState:function(){return{affixClass:"affix-top"}},getPinnedOffset:function(e){return this.pinnedOffset?this.pinnedOffset:(e.className=e.className.replace(/affix-top|affix-bottom|affix/,""),e.className+=e.className.length?" affix":"affix",this.pinnedOffset=i["default"].getOffset(e).top-window.pageYOffset,this.pinnedOffset)},checkPosition:function(){var e=void 0,t=void 0,r=void 0,n=void 0,o=void 0,a=void 0,l=void 0,u=void 0,p=void 0;this.isMounted()&&(e=s["default"].findDOMNode(this),t=document.documentElement.offsetHeight,r=window.pageYOffset,n=i["default"].getOffset(e),"top"===this.affixed&&(n.top+=r),o=null!=this.props.offsetTop?this.props.offsetTop:this.props.offset,a=null!=this.props.offsetBottom?this.props.offsetBottom:this.props.offset,(null!=o||null!=a)&&(null==o&&(o=0),null==a&&(a=0),l=null!=this.unpin&&r+this.unpin<=n.top?!1:null!=a&&n.top+e.offsetHeight>=t-a?"bottom":null!=o&&o>=r?"top":!1,this.affixed!==l&&(null!=this.unpin&&(e.style.top=""),u="affix"+(l?"-"+l:""),this.affixed=l,this.unpin="bottom"===l?this.getPinnedOffset(e):null,"bottom"===l&&(e.className=e.className.replace(/affix-top|affix-bottom|affix/,"affix-bottom"),p=t-a-e.offsetHeight-i["default"].getOffset(e).top),this.setState({affixClass:u,affixPositionTop:p}))))},checkPositionWithEventLoop:function(){setTimeout(this.checkPosition,0)},componentDidMount:function(){this._onWindowScrollListener=u["default"].listen(window,"scroll",this.checkPosition),this._onDocumentClickListener=u["default"].listen(i["default"].ownerDocument(this),"click",this.checkPositionWithEventLoop)},componentWillUnmount:function(){this._onWindowScrollListener&&this._onWindowScrollListener.remove(),this._onDocumentClickListener&&this._onDocumentClickListener.remove()},componentDidUpdate:function(e,t){t.affixClass===this.state.affixClass&&this.checkPositionWithEventLoop()}};t["default"]=p,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(40),s=n(o);t["default"]={Static:s["default"]},e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=r(1),l=n(i),u=r(2),p=n(u),d=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return s(t,e),a(t,[{key:"render",value:function(){var e={"form-group":!this.props.standalone,"form-group-lg":!this.props.standalone&&"large"===this.props.bsSize,"form-group-sm":!this.props.standalone&&"small"===this.props.bsSize,"has-feedback":this.props.hasFeedback,"has-success":"success"===this.props.bsStyle,"has-warning":"warning"===this.props.bsStyle,"has-error":"error"===this.props.bsStyle};return l["default"].createElement("div",{className:p["default"](e,this.props.groupClassName)},this.props.children)}}]),t}(l["default"].Component); d.defaultProps={standalone:!1},d.propTypes={standalone:l["default"].PropTypes.bool,hasFeedback:l["default"].PropTypes.bool,bsSize:function(e){return e.standalone&&void 0!==e.bsSize?new Error("bsSize will not be used when `standalone` is set."):l["default"].PropTypes.oneOf(["small","medium","large"]).apply(null,arguments)},bsStyle:l["default"].PropTypes.oneOf(["success","warning","error"]),groupClassName:l["default"].PropTypes.string},t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(4),l=n(i),u=/\%\((.+?)\)s/,p=a["default"].createClass({displayName:"Interpolate",propTypes:{format:a["default"].PropTypes.string},getDefaultProps:function(){return{component:"span"}},render:function(){var e=l["default"].hasValidComponent(this.props.children)||"string"==typeof this.props.children?this.props.children:this.props.format,t=this.props.component,r=this.props.unsafe===!0,n=o({},this.props);if(delete n.children,delete n.format,delete n.component,delete n.unsafe,r){var s=e.split(u).reduce(function(e,t,r){var o=void 0;if(r%2===0?o=t:(o=n[t],delete n[t]),a["default"].isValidElement(o))throw new Error("cannot interpolate a React component into unsafe text");return e+=o},"");return n.dangerouslySetInnerHTML={__html:s},a["default"].createElement(t,n)}var i=e.split(u).reduce(function(e,t,r){var o=void 0;if(r%2===0){if(0===t.length)return e;o=t}else o=n[t],delete n[t];return e.push(o),e},[]);return a["default"].createElement(t,n,i)}});t["default"]=p,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(3),l=n(i),u=r(10),p=n(u),d=r(2),f=n(d),c=r(5),h=n(c),m=r(4),v=n(m),y=r(6),g=n(y),b=a["default"].createClass({displayName:"Nav",mixins:[l["default"],p["default"]],propTypes:{activeHref:a["default"].PropTypes.string,activeKey:a["default"].PropTypes.any,bsStyle:a["default"].PropTypes.oneOf(["tabs","pills"]),stacked:a["default"].PropTypes.bool,justified:a["default"].PropTypes.bool,onSelect:a["default"].PropTypes.func,collapsible:a["default"].PropTypes.bool,expanded:a["default"].PropTypes.bool,navbar:a["default"].PropTypes.bool,eventKey:a["default"].PropTypes.any,pullRight:a["default"].PropTypes.bool,right:a["default"].PropTypes.bool},getDefaultProps:function(){return{bsClass:"nav"}},getCollapsibleDOMNode:function(){return a["default"].findDOMNode(this)},getCollapsibleDimensionValue:function(){var e=a["default"].findDOMNode(this.refs.ul),t=e.offsetHeight,r=h["default"].getComputedStyles(e);return t+parseInt(r.marginTop,10)+parseInt(r.marginBottom,10)},render:function(){var e=this.props.collapsible?this.getCollapsibleClassSet("navbar-collapse"):null;return this.props.navbar&&!this.props.collapsible?this.renderUl():a["default"].createElement("nav",o({},this.props,{className:f["default"](this.props.className,e)}),this.renderUl())},renderUl:function(){var e=this.getBsClassSet();return e["nav-stacked"]=this.props.stacked,e["nav-justified"]=this.props.justified,e["navbar-nav"]=this.props.navbar,e["pull-right"]=this.props.pullRight,e["navbar-right"]=this.props.right,a["default"].createElement("ul",o({},this.props,{className:f["default"](this.props.className,e),ref:"ul"}),v["default"].map(this.props.children,this.renderNavItem))},getChildActiveProp:function(e){return e.props.active?!0:null!=this.props.activeKey&&e.props.eventKey===this.props.activeKey?!0:null!=this.props.activeHref&&e.props.href===this.props.activeHref?!0:e.props.active},renderNavItem:function(e,t){return s.cloneElement(e,{active:this.getChildActiveProp(e),activeKey:this.props.activeKey,activeHref:this.props.activeHref,onSelect:g["default"](e.props.onSelect,this.props.onSelect),key:e.key?e.key:t,navItem:!0})}});t["default"]=b,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=r(1),i=n(a),l=r(2),u=n(l),p=r(3),d=n(p),f=r(7),c=n(f),h=i["default"].createClass({displayName:"NavItem",mixins:[d["default"]],propTypes:{onSelect:i["default"].PropTypes.func,active:i["default"].PropTypes.bool,disabled:i["default"].PropTypes.bool,href:i["default"].PropTypes.string,title:i["default"].PropTypes.node,eventKey:i["default"].PropTypes.any,target:i["default"].PropTypes.string},render:function(){var e=this.props,t=e.disabled,r=e.active,n=e.href,a=e.title,l=e.target,p=e.children,d=o(e,["disabled","active","href","title","target","children"]),f={active:r,disabled:t},h={href:n,title:a,target:l,onClick:this.handleClick};return"#"===n&&(h.role="button"),i["default"].createElement("li",s({},d,{className:u["default"](d.className,f)}),i["default"].createElement(c["default"],h,p))},handleClick:function(e){this.props.onSelect&&(e.preventDefault(),this.props.disabled||this.props.onSelect(this.props.eventKey,this.props.href,this.props.target))}});t["default"]=h,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(3),p=n(u),d=r(4),f=n(d),c=a["default"].createClass({displayName:"PanelGroup",mixins:[p["default"]],propTypes:{accordion:a["default"].PropTypes.bool,activeKey:a["default"].PropTypes.any,defaultActiveKey:a["default"].PropTypes.any,onSelect:a["default"].PropTypes.func},getDefaultProps:function(){return{bsClass:"panel-group"}},getInitialState:function(){var e=this.props.defaultActiveKey;return{activeKey:e}},render:function(){var e=this.getBsClassSet();return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e),onSelect:null}),f["default"].map(this.props.children,this.renderPanel))},renderPanel:function(e,t){var r=null!=this.props.activeKey?this.props.activeKey:this.state.activeKey,n={bsStyle:e.props.bsStyle||this.props.bsStyle,key:e.key?e.key:t,ref:e.ref};return this.props.accordion&&(n.collapsible=!0,n.expanded=e.props.eventKey===r,n.onSelect=this.handleSelect),s.cloneElement(e,n)},shouldComponentUpdate:function(){return!this._isChanging},handleSelect:function(e,t){e.preventDefault(),this.props.onSelect&&(this._isChanging=!0,this.props.onSelect(t),this._isChanging=!1),this.state.activeKey===t&&(t=null),this.setState({activeKey:t})}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}function i(e,t){return function(r){var n=function(e){function t(){s(this,t),null!=e&&e.apply(this,arguments)}return a(t,e),u(t,[{key:"getChildContext",value:function(){return this.props.context}},{key:"render",value:function(){var e=this.props,t=e.wrapped,r=o(e,["wrapped"]);return delete r.context,d["default"].cloneElement(t,r)}}]),t}(d["default"].Component);n.childContextTypes=r;var i=function(){function r(){s(this,r)}return u(r,[{key:"render",value:function(){var r=l({},this.props);return r[t]=this.getWrappedOverlay(),d["default"].createElement(e,r,this.props.children)}},{key:"getWrappedOverlay",value:function(){return d["default"].createElement(n,{context:this.context,wrapped:this.props[t]})}}]),r}();return i.contextTypes=r,i}}Object.defineProperty(t,"__esModule",{value:!0});var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},u=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}();t["default"]=i;var p=r(1),d=n(p);e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(27),l=n(i),u=a["default"].createClass({displayName:"Accordion",render:function(){return a["default"].createElement(l["default"],o({},this.props,{accordion:!0}),this.props.children)}});t["default"]=u,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(21),p=n(u),d=r(5),f=n(d),c=a["default"].createClass({displayName:"Affix",statics:{domUtils:f["default"]},mixins:[p["default"]],render:function(){var e={top:this.state.affixPositionTop};return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,this.state.affixClass),style:e}),this.props.children)}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(3),p=n(u),d=a["default"].createClass({displayName:"Alert",mixins:[p["default"]],propTypes:{onDismiss:a["default"].PropTypes.func,dismissAfter:a["default"].PropTypes.number},getDefaultProps:function(){return{bsClass:"alert",bsStyle:"info"}},renderDismissButton:function(){return a["default"].createElement("button",{type:"button",className:"close",onClick:this.props.onDismiss,"aria-hidden":"true"},"×")},render:function(){var e=this.getBsClassSet(),t=!!this.props.onDismiss;return e["alert-dismissable"]=t,a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),t?this.renderDismissButton():null,this.props.children)},componentDidMount:function(){this.props.dismissAfter&&this.props.onDismiss&&(this.dismissTimer=setTimeout(this.props.onDismiss,this.props.dismissAfter))},componentWillUnmount:function(){clearTimeout(this.dismissTimer)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(4),l=n(i),u=r(2),p=n(u),d=a["default"].createClass({displayName:"Badge",propTypes:{pullRight:a["default"].PropTypes.bool},hasContent:function(){return l["default"].hasValidComponent(this.props.children)||a["default"].Children.count(this.props.children)>1||"string"==typeof this.props.children||"number"==typeof this.props.children},render:function(){var e={"pull-right":this.props.pullRight,badge:this.hasContent()};return a["default"].createElement("span",o({},this.props,{className:p["default"](this.props.className,e)}),this.props.children)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},l=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),u=r(1),p=n(u),d=r(9),f=n(d),c=r(23),h=n(c),m=r(17),v=n(m),y=r(20),g=n(y),b=function(e){function t(){s(this,t),null!=e&&e.apply(this,arguments)}return a(t,e),l(t,[{key:"renderFormGroup",value:function(e){var t=this.props,r=(t.bsStyle,t.value,o(t,["bsStyle","value"]));return p["default"].createElement(h["default"],r,e)}},{key:"renderInput",value:function(){var e=this.props,t=e.children,r=e.value,n=o(e,["children","value"]),s=t?t:r;return p["default"].createElement(f["default"],i({},n,{componentClass:"input",ref:"input",key:"input",value:s}))}}]),t}(v["default"]);b.types=["button","reset","submit"],b.defaultProps={type:"button"},b.propTypes={type:p["default"].PropTypes.oneOf(b.types),bsStyle:function(e){return null},children:g["default"],value:g["default"]},t["default"]=b,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(3),p=n(u),d=a["default"].createClass({displayName:"ButtonToolbar",mixins:[p["default"]],getDefaultProps:function(){return{bsClass:"button-toolbar"}},render:function(){var e=this.getBsClassSet();return a["default"].createElement("div",o({},this.props,{role:"toolbar",className:l["default"](this.props.className,e)}),this.props.children)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(3),p=n(u),d=r(4),f=n(d),c=a["default"].createClass({displayName:"Carousel",mixins:[p["default"]],propTypes:{slide:a["default"].PropTypes.bool,indicators:a["default"].PropTypes.bool,interval:a["default"].PropTypes.number,controls:a["default"].PropTypes.bool,pauseOnHover:a["default"].PropTypes.bool,wrap:a["default"].PropTypes.bool,onSelect:a["default"].PropTypes.func,onSlideEnd:a["default"].PropTypes.func,activeIndex:a["default"].PropTypes.number,defaultActiveIndex:a["default"].PropTypes.number,direction:a["default"].PropTypes.oneOf(["prev","next"])},getDefaultProps:function(){return{slide:!0,interval:5e3,pauseOnHover:!0,wrap:!0,indicators:!0,controls:!0}},getInitialState:function(){return{activeIndex:null==this.props.defaultActiveIndex?0:this.props.defaultActiveIndex,previousActiveIndex:null,direction:null}},getDirection:function(e,t){return e===t?null:e>t?"prev":"next"},componentWillReceiveProps:function(e){var t=this.getActiveIndex();null!=e.activeIndex&&e.activeIndex!==t&&(clearTimeout(this.timeout),this.setState({previousActiveIndex:t,direction:null!=e.direction?e.direction:this.getDirection(t,e.activeIndex)}))},componentDidMount:function(){this.waitForNext()},componentWillUnmount:function(){clearTimeout(this.timeout)},next:function(e){e&&e.preventDefault();var t=this.getActiveIndex()+1,r=f["default"].numberOf(this.props.children);if(t>r-1){if(!this.props.wrap)return;t=0}this.handleSelect(t,"next")},prev:function(e){e&&e.preventDefault();var t=this.getActiveIndex()-1;if(0>t){if(!this.props.wrap)return;t=f["default"].numberOf(this.props.children)-1}this.handleSelect(t,"prev")},pause:function(){this.isPaused=!0,clearTimeout(this.timeout)},play:function(){this.isPaused=!1,this.waitForNext()},waitForNext:function(){!this.isPaused&&this.props.slide&&this.props.interval&&null==this.props.activeIndex&&(this.timeout=setTimeout(this.next,this.props.interval))},handleMouseOver:function(){this.props.pauseOnHover&&this.pause()},handleMouseOut:function(){this.isPaused&&this.play()},render:function(){var e={carousel:!0,slide:this.props.slide};return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e),onMouseOver:this.handleMouseOver,onMouseOut:this.handleMouseOut}),this.props.indicators?this.renderIndicators():null,a["default"].createElement("div",{className:"carousel-inner",ref:"inner"},f["default"].map(this.props.children,this.renderItem)),this.props.controls?this.renderControls():null)},renderPrev:function(){return a["default"].createElement("a",{className:"left carousel-control",href:"#prev",key:0,onClick:this.prev},a["default"].createElement("span",{className:"glyphicon glyphicon-chevron-left"}))},renderNext:function(){return a["default"].createElement("a",{className:"right carousel-control",href:"#next",key:1,onClick:this.next},a["default"].createElement("span",{className:"glyphicon glyphicon-chevron-right"}))},renderControls:function(){if(!this.props.wrap){var e=this.getActiveIndex(),t=f["default"].numberOf(this.props.children);return[0!==e?this.renderPrev():null,e!==t-1?this.renderNext():null]}return[this.renderPrev(),this.renderNext()]},renderIndicator:function(e,t){var r=t===this.getActiveIndex()?"active":null;return a["default"].createElement("li",{key:t,className:r,onClick:this.handleSelect.bind(this,t,null)})},renderIndicators:function(){var e=[];return f["default"].forEach(this.props.children,function(t,r){e.push(this.renderIndicator(t,r)," ")},this),a["default"].createElement("ol",{className:"carousel-indicators"},e)},getActiveIndex:function(){return null!=this.props.activeIndex?this.props.activeIndex:this.state.activeIndex},handleItemAnimateOutEnd:function(){this.setState({previousActiveIndex:null,direction:null},function(){this.waitForNext(),this.props.onSlideEnd&&this.props.onSlideEnd()})},renderItem:function(e,t){var r=this.getActiveIndex(),n=t===r,o=null!=this.state.previousActiveIndex&&this.state.previousActiveIndex===t&&this.props.slide;return s.cloneElement(e,{active:n,ref:e.ref,key:e.key?e.key:t,index:t,animateOut:o,animateIn:n&&null!=this.state.previousActiveIndex&&this.props.slide,direction:this.state.direction,onAnimateOutEnd:o?this.handleItemAnimateOutEnd:null})},handleSelect:function(e,t){clearTimeout(this.timeout);var r=this.getActiveIndex();if(t=t||this.getDirection(r,e),this.props.onSelect&&this.props.onSelect(e,t),null==this.props.activeIndex&&e!==r){if(null!=this.state.previousActiveIndex)return;this.setState({activeIndex:e,previousActiveIndex:r,direction:t})}}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(19),p=n(u),d=a["default"].createClass({displayName:"CarouselItem",propTypes:{direction:a["default"].PropTypes.oneOf(["prev","next"]),onAnimateOutEnd:a["default"].PropTypes.func,active:a["default"].PropTypes.bool,animateIn:a["default"].PropTypes.bool,animateOut:a["default"].PropTypes.bool,caption:a["default"].PropTypes.node,index:a["default"].PropTypes.number},getInitialState:function(){return{direction:null}},getDefaultProps:function(){return{animation:!0}},handleAnimateOutEnd:function(){this.props.onAnimateOutEnd&&this.isMounted()&&this.props.onAnimateOutEnd(this.props.index)},componentWillReceiveProps:function(e){this.props.active!==e.active&&this.setState({direction:null})},componentDidUpdate:function(e){!this.props.active&&e.active&&p["default"].addEndEventListener(a["default"].findDOMNode(this),this.handleAnimateOutEnd),this.props.active!==e.active&&setTimeout(this.startAnimation,20)},startAnimation:function(){this.isMounted()&&this.setState({direction:"prev"===this.props.direction?"right":"left"})},render:function(){var e={item:!0,active:this.props.active&&!this.props.animateIn||this.props.animateOut,next:this.props.active&&this.props.animateIn&&"next"===this.props.direction,prev:this.props.active&&this.props.animateIn&&"prev"===this.props.direction};return this.state.direction&&(this.props.animateIn||this.props.animateOut)&&(e[this.state.direction]=!0),a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children,this.props.caption?this.renderCaption():null)},renderCaption:function(){return a["default"].createElement("div",{className:"carousel-caption"},this.props.caption)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(12),p=n(u),d=a["default"].createClass({displayName:"Col",propTypes:{xs:a["default"].PropTypes.number,sm:a["default"].PropTypes.number,md:a["default"].PropTypes.number,lg:a["default"].PropTypes.number,xsOffset:a["default"].PropTypes.number,smOffset:a["default"].PropTypes.number,mdOffset:a["default"].PropTypes.number,lgOffset:a["default"].PropTypes.number,xsPush:a["default"].PropTypes.number,smPush:a["default"].PropTypes.number,mdPush:a["default"].PropTypes.number,lgPush:a["default"].PropTypes.number,xsPull:a["default"].PropTypes.number,smPull:a["default"].PropTypes.number,mdPull:a["default"].PropTypes.number,lgPull:a["default"].PropTypes.number,componentClass:a["default"].PropTypes.node.isRequired},getDefaultProps:function(){return{componentClass:"div"}},render:function(){var e=this.props.componentClass,t={};return Object.keys(p["default"].SIZES).forEach(function(e){var r=p["default"].SIZES[e],n=r,o=r+"-";this.props[n]&&(t["col-"+o+this.props[n]]=!0),n=r+"Offset",o=r+"-offset-",this.props[n]>=0&&(t["col-"+o+this.props[n]]=!0),n=r+"Push",o=r+"-push-",this.props[n]>=0&&(t["col-"+o+this.props[n]]=!0),n=r+"Pull",o=r+"-pull-",this.props[n]>=0&&(t["col-"+o+this.props[n]]=!0)},this),a["default"].createElement(e,o({},this.props,{className:l["default"](this.props.className,t)}),this.props.children)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=n(o),a=r(3),i=n(a),l=r(10),u=n(l),p=r(2),d=n(p),f=r(5),c=n(f),h=r(4),m=n(h),v=r(6),y=n(v),g=s["default"].createClass({displayName:"CollapsibleNav",mixins:[i["default"],u["default"]],propTypes:{onSelect:s["default"].PropTypes.func,activeHref:s["default"].PropTypes.string,activeKey:s["default"].PropTypes.any,collapsible:s["default"].PropTypes.bool,expanded:s["default"].PropTypes.bool,eventKey:s["default"].PropTypes.any},getCollapsibleDOMNode:function(){return s["default"].findDOMNode(this)},getCollapsibleDimensionValue:function(){var e=0,t=this.refs;for(var r in t)if(t.hasOwnProperty(r)){var n=s["default"].findDOMNode(t[r]),o=n.offsetHeight,a=c["default"].getComputedStyles(n);e+=o+parseInt(a.marginTop,10)+parseInt(a.marginBottom,10)}return e},render:function(){var e=this.props.collapsible?this.getCollapsibleClassSet("navbar-collapse"):null,t=this.props.collapsible?this.renderCollapsibleNavChildren:this.renderChildren;return s["default"].createElement("div",{eventKey:this.props.eventKey,className:d["default"](this.props.className,e)},m["default"].map(this.props.children,t))},getChildActiveProp:function(e){return e.props.active?!0:null!=this.props.activeKey&&e.props.eventKey===this.props.activeKey?!0:null!=this.props.activeHref&&e.props.href===this.props.activeHref?!0:e.props.active},renderChildren:function(e,t){var r=e.key?e.key:t;return o.cloneElement(e,{activeKey:this.props.activeKey,activeHref:this.props.activeHref,ref:"nocollapse_"+r,key:r,navItem:!0})},renderCollapsibleNavChildren:function(e,t){var r=e.key?e.key:t;return o.cloneElement(e,{active:this.getChildActiveProp(e),activeKey:this.props.activeKey,activeHref:this.props.activeHref,onSelect:y["default"](e.props.onSelect,this.props.onSelect),ref:"collapsible_"+r,key:r,navItem:!0})}});t["default"]=g,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(6),p=n(u),d=r(3),f=n(d),c=r(16),h=n(c),m=r(9),v=n(m),y=r(14),g=n(y),b=r(15),P=n(b),O=r(4),T=n(O),_=a["default"].createClass({displayName:"DropdownButton",mixins:[f["default"],h["default"]],propTypes:{pullRight:a["default"].PropTypes.bool,dropup:a["default"].PropTypes.bool,title:a["default"].PropTypes.node,href:a["default"].PropTypes.string,onClick:a["default"].PropTypes.func,onSelect:a["default"].PropTypes.func,navItem:a["default"].PropTypes.bool,noCaret:a["default"].PropTypes.bool,buttonClassName:a["default"].PropTypes.string},render:function(){var e=this.props.navItem?"renderNavItem":"renderButtonGroup",t=this.props.noCaret?null:a["default"].createElement("span",{className:"caret"});return this[e]([a["default"].createElement(v["default"],o({},this.props,{ref:"dropdownButton",className:l["default"]("dropdown-toggle",this.props.buttonClassName),onClick:p["default"](this.props.onClick,this.handleDropdownClick),key:0,navDropdown:this.props.navItem,navItem:null,title:null,pullRight:null,dropup:null}),this.props.title," ",t),a["default"].createElement(P["default"],{ref:"menu","aria-labelledby":this.props.id,pullRight:this.props.pullRight,key:1},T["default"].map(this.props.children,this.renderMenuItem))])},renderButtonGroup:function(e){var t={open:this.state.open,dropup:this.props.dropup};return a["default"].createElement(g["default"],{bsSize:this.props.bsSize,className:l["default"](this.props.className,t)},e)},renderNavItem:function(e){var t={dropdown:!0,open:this.state.open,dropup:this.props.dropup};return a["default"].createElement("li",{className:l["default"](this.props.className,t)},e)},renderMenuItem:function(e,t){var r=this.props.onSelect||e.props.onSelect?this.handleOptionSelect:null;return s.cloneElement(e,{onSelect:p["default"](e.props.onSelect,r),key:e.key?e.key:t})},handleDropdownClick:function(e){e.preventDefault(),this.setDropdownState(!this.state.open)},handleOptionSelect:function(e){this.props.onSelect&&this.props.onSelect(e),this.setDropdownState(!1)}});t["default"]=_,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(1),u=n(l),p=r(2),d=n(p),f=r(17),c=n(f),h=r(20),m=n(h),v=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return s(t,e),i(t,[{key:"getValue",value:function(){var e=this.props,t=e.children,r=e.value;return t?t:r}},{key:"renderInput",value:function(){return u["default"].createElement("p",a({},this.props,{className:d["default"](this.props.className,"form-control-static"),ref:"input",key:"input"}),this.getValue())}}]),t}(c["default"]);v.propTypes={value:m["default"],children:m["default"]},t["default"]=v,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(3),p=n(u),d=r(12),f=n(d),c=a["default"].createClass({displayName:"Glyphicon",mixins:[p["default"]],propTypes:{glyph:a["default"].PropTypes.oneOf(f["default"].GLYPHS).isRequired},getDefaultProps:function(){return{bsClass:"glyphicon"}},render:function(){var e=this.getBsClassSet();return e["glyphicon-"+this.props.glyph]=!0,a["default"].createElement("span",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children)}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=a["default"].createClass({displayName:"Grid",propTypes:{fluid:a["default"].PropTypes.bool,componentClass:a["default"].PropTypes.node.isRequired},getDefaultProps:function(){return{componentClass:"div"}},render:function(){var e=this.props.componentClass,t=this.props.fluid?"container-fluid":"container";return a["default"].createElement(e,o({},this.props,{className:l["default"](this.props.className,t)}),this.props.children)}});t["default"]=u,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),i=function(e,t,r){for(var n=!0;n;){var o=e,s=t,a=r;i=u=l=void 0,n=!1;var i=Object.getOwnPropertyDescriptor(o,s);if(void 0!==i){if("value"in i)return i.value;var l=i.get;return void 0===l?void 0:l.call(a)}var u=Object.getPrototypeOf(o);if(null===u)return void 0;e=u,t=s,r=a,n=!0}},l=r(1),u=n(l),p=r(17),d=n(p),f=r(22),c=n(f),h=r(69),m=n(h),v=function(e){ function t(){o(this,t),null!=e&&e.apply(this,arguments)}return s(t,e),a(t,[{key:"render",value:function(){return"static"===this.props.type?(m["default"]("Input type=static","StaticText"),u["default"].createElement(c["default"].Static,this.props)):i(Object.getPrototypeOf(t.prototype),"render",this).call(this)}}]),t}(d["default"]);t["default"]=v,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=a["default"].createClass({displayName:"Jumbotron",render:function(){return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,"jumbotron")}),this.props.children)}});t["default"]=u,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(3),p=n(u),d=a["default"].createClass({displayName:"Label",mixins:[p["default"]],getDefaultProps:function(){return{bsClass:"label",bsStyle:"default"}},render:function(){var e=this.getBsClassSet();return a["default"].createElement("span",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var a=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(1),u=n(l),p=r(2),d=n(p),f=r(4),c=n(f),h=function(e){function t(){o(this,t),null!=e&&e.apply(this,arguments)}return s(t,e),i(t,[{key:"render",value:function(){var e=this,t=c["default"].map(this.props.children,function(e,t){return l.cloneElement(e,{key:e.key?e.key:t})}),r=!1;if(!this.props.children)return this.renderDiv(t);if(1!==u["default"].Children.count(this.props.children)||Array.isArray(this.props.children))r=Array.prototype.some.call(this.props.children,function(t){return Array.isArray(t)?Array.prototype.some.call(t,function(t){return e.isAnchor(t.props)}):e.isAnchor(t.props)});else{var n=this.props.children;r=this.isAnchor(n.props)}return r?this.renderDiv(t):this.renderUL(t)}},{key:"isAnchor",value:function(e){return e.href||e.onClick}},{key:"renderUL",value:function(e){var t=c["default"].map(e,function(e,t){return l.cloneElement(e,{listItem:!0})});return u["default"].createElement("ul",a({},this.props,{className:d["default"](this.props.className,"list-group")}),t)}},{key:"renderDiv",value:function(e){return u["default"].createElement("div",a({},this.props,{className:d["default"](this.props.className,"list-group")}),e)}}]),t}(u["default"].Component);h.propTypes={className:u["default"].PropTypes.string,id:u["default"].PropTypes.string},t["default"]=h,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(3),l=n(i),u=r(2),p=n(u),d=r(7),f=n(d),c=a["default"].createClass({displayName:"ListGroupItem",mixins:[l["default"]],propTypes:{bsStyle:a["default"].PropTypes.oneOf(["danger","info","success","warning"]),className:a["default"].PropTypes.string,active:a["default"].PropTypes.any,disabled:a["default"].PropTypes.any,header:a["default"].PropTypes.node,listItem:a["default"].PropTypes.bool,onClick:a["default"].PropTypes.func,eventKey:a["default"].PropTypes.any,href:a["default"].PropTypes.string,target:a["default"].PropTypes.string},getDefaultProps:function(){return{bsClass:"list-group-item"}},render:function(){var e=this.getBsClassSet();return e.active=this.props.active,e.disabled=this.props.disabled,this.props.href||this.props.onClick?this.renderAnchor(e):this.props.listItem?this.renderLi(e):this.renderSpan(e)},renderLi:function(e){return a["default"].createElement("li",o({},this.props,{className:p["default"](this.props.className,e)}),this.props.header?this.renderStructuredContent():this.props.children)},renderAnchor:function(e){return a["default"].createElement(f["default"],o({},this.props,{className:p["default"](this.props.className,e)}),this.props.header?this.renderStructuredContent():this.props.children)},renderSpan:function(e){return a["default"].createElement("span",o({},this.props,{className:p["default"](this.props.className,e)}),this.props.header?this.renderStructuredContent():this.props.children)},renderStructuredContent:function(){var e=void 0;e=a["default"].isValidElement(this.props.header)?s.cloneElement(this.props.header,{key:"header",className:p["default"](this.props.header.props.className,"list-group-item-heading")}):a["default"].createElement("h4",{key:"header",className:"list-group-item-heading"},this.props.header);var t=a["default"].createElement("p",{key:"content",className:"list-group-item-text"},this.props.children);return[e,t]}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(7),p=n(u),d=a["default"].createClass({displayName:"MenuItem",propTypes:{header:a["default"].PropTypes.bool,divider:a["default"].PropTypes.bool,href:a["default"].PropTypes.string,title:a["default"].PropTypes.string,target:a["default"].PropTypes.string,onSelect:a["default"].PropTypes.func,eventKey:a["default"].PropTypes.any,active:a["default"].PropTypes.bool},getDefaultProps:function(){return{active:!1}},handleClick:function(e){this.props.onSelect&&(e.preventDefault(),this.props.onSelect(this.props.eventKey,this.props.href,this.props.target))},renderAnchor:function(){return a["default"].createElement(p["default"],{onClick:this.handleClick,href:this.props.href,target:this.props.target,title:this.props.title,tabIndex:"-1"},this.props.children)},render:function(){var e={"dropdown-header":this.props.header,divider:this.props.divider,active:this.props.active},t=null;return this.props.header?t=this.props.children:this.props.divider||(t=this.renderAnchor()),a["default"].createElement("li",o({},this.props,{role:"presentation",title:null,href:null,className:l["default"](this.props.className,e)}),t)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(3),p=n(u),d=r(11),f=n(d),c=r(5),h=n(c),m=r(13),v=n(m),y=a["default"].createClass({displayName:"Modal",mixins:[p["default"],f["default"]],propTypes:{title:a["default"].PropTypes.node,backdrop:a["default"].PropTypes.oneOf(["static",!0,!1]),keyboard:a["default"].PropTypes.bool,closeButton:a["default"].PropTypes.bool,animation:a["default"].PropTypes.bool,onRequestHide:a["default"].PropTypes.func.isRequired,dialogClassName:a["default"].PropTypes.string},getDefaultProps:function(){return{bsClass:"modal",backdrop:!0,keyboard:!0,animation:!0,closeButton:!0}},render:function(){var e={display:"block"},t=this.getBsClassSet();delete t.modal,t["modal-dialog"]=!0;var r={modal:!0,fade:this.props.animation,"in":!this.props.animation},n=a["default"].createElement("div",o({},this.props,{title:null,tabIndex:"-1",role:"dialog",style:e,className:l["default"](this.props.className,r),onClick:this.props.backdrop===!0?this.handleBackdropClick:null,ref:"modal"}),a["default"].createElement("div",{className:l["default"](this.props.dialogClassName,t)},a["default"].createElement("div",{className:"modal-content"},this.props.title?this.renderHeader():null,this.props.children)));return this.props.backdrop?this.renderBackdrop(n):n},renderBackdrop:function(e){var t={"modal-backdrop":!0,fade:this.props.animation,"in":!this.props.animation},r=this.props.backdrop===!0?this.handleBackdropClick:null;return a["default"].createElement("div",null,a["default"].createElement("div",{className:l["default"](t),ref:"backdrop",onClick:r}),e)},renderHeader:function(){var e=void 0;return this.props.closeButton&&(e=a["default"].createElement("button",{type:"button",className:"close","aria-hidden":"true",onClick:this.props.onRequestHide},"×")),a["default"].createElement("div",{className:"modal-header"},e,this.renderTitle())},renderTitle:function(){return a["default"].isValidElement(this.props.title)?this.props.title:a["default"].createElement("h4",{className:"modal-title"},this.props.title)},iosClickHack:function(){a["default"].findDOMNode(this.refs.modal).onclick=function(){},a["default"].findDOMNode(this.refs.backdrop).onclick=function(){}},componentDidMount:function(){this._onDocumentKeyupListener=v["default"].listen(h["default"].ownerDocument(this),"keyup",this.handleDocumentKeyUp);var e=this.props.container&&a["default"].findDOMNode(this.props.container)||h["default"].ownerDocument(this).body;e.className+=e.className.length?" modal-open":"modal-open",this.focusModalContent(),this.props.backdrop&&this.iosClickHack()},componentDidUpdate:function(e){this.props.backdrop&&this.props.backdrop!==e.backdrop&&this.iosClickHack()},componentWillUnmount:function(){this._onDocumentKeyupListener.remove();var e=this.props.container&&a["default"].findDOMNode(this.props.container)||h["default"].ownerDocument(this).body;e.className=e.className.replace(/ ?modal-open/,""),this.restoreLastFocus()},handleBackdropClick:function(e){e.target===e.currentTarget&&this.props.onRequestHide()},handleDocumentKeyUp:function(e){this.props.keyboard&&27===e.keyCode&&this.props.onRequestHide()},focusModalContent:function(){this.lastFocus=h["default"].ownerDocument(this).activeElement;var e=a["default"].findDOMNode(this.refs.modal);e.focus()},restoreLastFocus:function(){this.lastFocus&&(this.lastFocus.focus(),this.lastFocus=null)}});t["default"]=y,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(1),s=n(o),a=r(18),i=n(a),l=r(6),u=n(l),p=r(28),d=n(p),f=s["default"].createClass({displayName:"ModalTrigger",mixins:[i["default"]],propTypes:{modal:s["default"].PropTypes.node.isRequired},getInitialState:function(){return{isOverlayShown:!1}},show:function(){this.setState({isOverlayShown:!0})},hide:function(){this.setState({isOverlayShown:!1})},toggle:function(){this.setState({isOverlayShown:!this.state.isOverlayShown})},renderOverlay:function(){return this.state.isOverlayShown?o.cloneElement(this.props.modal,{onRequestHide:this.hide}):s["default"].createElement("span",null)},render:function(){var e=s["default"].Children.only(this.props.children),t={};return t.onClick=u["default"](e.props.onClick,this.toggle),t.onMouseOver=u["default"](e.props.onMouseOver,this.props.onMouseOver),t.onMouseOut=u["default"](e.props.onMouseOut,this.props.onMouseOut),t.onFocus=u["default"](e.props.onFocus,this.props.onFocus),t.onBlur=u["default"](e.props.onBlur,this.props.onBlur),o.cloneElement(e,t)}});f.withContext=d["default"](f,"modal"),t["default"]=f,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(3),l=n(i),u=r(2),p=n(u),d=r(4),f=n(d),c=r(6),h=n(c),m=a["default"].createClass({displayName:"Navbar",mixins:[l["default"]],propTypes:{fixedTop:a["default"].PropTypes.bool,fixedBottom:a["default"].PropTypes.bool,staticTop:a["default"].PropTypes.bool,inverse:a["default"].PropTypes.bool,fluid:a["default"].PropTypes.bool,role:a["default"].PropTypes.string,componentClass:a["default"].PropTypes.node.isRequired,brand:a["default"].PropTypes.node,toggleButton:a["default"].PropTypes.node,toggleNavKey:a["default"].PropTypes.oneOfType([a["default"].PropTypes.string,a["default"].PropTypes.number]),onToggle:a["default"].PropTypes.func,navExpanded:a["default"].PropTypes.bool,defaultNavExpanded:a["default"].PropTypes.bool},getDefaultProps:function(){return{bsClass:"navbar",bsStyle:"default",role:"navigation",componentClass:"nav"}},getInitialState:function(){return{navExpanded:this.props.defaultNavExpanded}},shouldComponentUpdate:function(){return!this._isChanging},handleToggle:function(){this.props.onToggle&&(this._isChanging=!0,this.props.onToggle(),this._isChanging=!1),this.setState({navExpanded:!this.state.navExpanded})},isNavExpanded:function(){return null!=this.props.navExpanded?this.props.navExpanded:this.state.navExpanded},render:function(){var e=this.getBsClassSet(),t=this.props.componentClass;return e["navbar-fixed-top"]=this.props.fixedTop,e["navbar-fixed-bottom"]=this.props.fixedBottom,e["navbar-static-top"]=this.props.staticTop,e["navbar-inverse"]=this.props.inverse,a["default"].createElement(t,o({},this.props,{className:p["default"](this.props.className,e)}),a["default"].createElement("div",{className:this.props.fluid?"container-fluid":"container"},this.props.brand||this.props.toggleButton||null!=this.props.toggleNavKey?this.renderHeader():null,f["default"].map(this.props.children,this.renderChild)))},renderChild:function(e,t){return s.cloneElement(e,{navbar:!0,collapsible:null!=this.props.toggleNavKey&&this.props.toggleNavKey===e.props.eventKey,expanded:null!=this.props.toggleNavKey&&this.props.toggleNavKey===e.props.eventKey&&this.isNavExpanded(),key:e.key?e.key:t})},renderHeader:function(){var e=void 0;return this.props.brand&&(e=a["default"].isValidElement(this.props.brand)?s.cloneElement(this.props.brand,{className:p["default"](this.props.brand.props.className,"navbar-brand")}):a["default"].createElement("span",{className:"navbar-brand"},this.props.brand)),a["default"].createElement("div",{className:"navbar-header"},e,this.props.toggleButton||null!=this.props.toggleNavKey?this.renderToggleButton():null)},renderToggleButton:function(){var e=void 0;return a["default"].isValidElement(this.props.toggleButton)?s.cloneElement(this.props.toggleButton,{className:p["default"](this.props.toggleButton.props.className,"navbar-toggle"),onClick:h["default"](this.handleToggle,this.props.toggleButton.props.onClick)}):(e=null!=this.props.toggleButton?this.props.toggleButton:[a["default"].createElement("span",{className:"sr-only",key:0},"Toggle navigation"),a["default"].createElement("span",{className:"icon-bar",key:1}),a["default"].createElement("span",{className:"icon-bar",key:2}),a["default"].createElement("span",{className:"icon-bar",key:3})],a["default"].createElement("button",{className:"navbar-toggle",type:"button",onClick:this.handleToggle},e))}});t["default"]=m,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){return Array.isArray(t)?t.indexOf(e)>=0:e===t}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=r(1),i=n(a),l=r(18),u=n(l),p=r(59),d=n(p),f=r(6),c=n(f),h=r(28),m=n(h),v=r(5),y=n(v),g=i["default"].createClass({displayName:"OverlayTrigger",mixins:[u["default"]],propTypes:{trigger:i["default"].PropTypes.oneOfType([i["default"].PropTypes.oneOf(["manual","click","hover","focus"]),i["default"].PropTypes.arrayOf(i["default"].PropTypes.oneOf(["click","hover","focus"]))]),placement:i["default"].PropTypes.oneOf(["top","right","bottom","left"]),delay:i["default"].PropTypes.number,delayShow:i["default"].PropTypes.number,delayHide:i["default"].PropTypes.number,defaultOverlayShown:i["default"].PropTypes.bool,overlay:i["default"].PropTypes.node.isRequired,containerPadding:i["default"].PropTypes.number,rootClose:i["default"].PropTypes.bool},getDefaultProps:function(){return{placement:"right",trigger:["hover","focus"],containerPadding:0}},getInitialState:function(){return{isOverlayShown:null==this.props.defaultOverlayShown?!1:this.props.defaultOverlayShown,overlayLeft:null,overlayTop:null,arrowOffsetLeft:null,arrowOffsetTop:null}},show:function(){this.setState({isOverlayShown:!0},function(){this.updateOverlayPosition()})},hide:function(){this.setState({isOverlayShown:!1})},toggle:function(){this.state.isOverlayShown?this.hide():this.show()},renderOverlay:function(){if(!this.state.isOverlayShown)return i["default"].createElement("span",null);var e=a.cloneElement(this.props.overlay,{onRequestHide:this.hide,placement:this.props.placement,positionLeft:this.state.overlayLeft,positionTop:this.state.overlayTop,arrowOffsetLeft:this.state.arrowOffsetLeft,arrowOffsetTop:this.state.arrowOffsetTop});return this.props.rootClose?i["default"].createElement(d["default"],{onRootClose:this.hide},e):e},render:function(){var e=i["default"].Children.only(this.props.children);if("manual"===this.props.trigger)return e;var t={};return t.onClick=c["default"](e.props.onClick,this.props.onClick),o("click",this.props.trigger)&&(t.onClick=c["default"](this.toggle,t.onClick)),o("hover",this.props.trigger)&&(t.onMouseOver=c["default"](this.handleDelayedShow,this.props.onMouseOver),t.onMouseOut=c["default"](this.handleDelayedHide,this.props.onMouseOut)),o("focus",this.props.trigger)&&(t.onFocus=c["default"](this.handleDelayedShow,this.props.onFocus),t.onBlur=c["default"](this.handleDelayedHide,this.props.onBlur)),a.cloneElement(e,t)},componentWillUnmount:function(){clearTimeout(this._hoverDelay)},componentDidMount:function(){this.props.defaultOverlayShown&&this.updateOverlayPosition()},handleDelayedShow:function(){if(null!=this._hoverDelay)return clearTimeout(this._hoverDelay),void(this._hoverDelay=null);var e=null!=this.props.delayShow?this.props.delayShow:this.props.delay;return e?void(this._hoverDelay=setTimeout(function(){this._hoverDelay=null,this.show()}.bind(this),e)):void this.show()},handleDelayedHide:function(){if(null!=this._hoverDelay)return clearTimeout(this._hoverDelay),void(this._hoverDelay=null);var e=null!=this.props.delayHide?this.props.delayHide:this.props.delay;return e?void(this._hoverDelay=setTimeout(function(){this._hoverDelay=null,this.hide()}.bind(this),e)):void this.hide()},updateOverlayPosition:function(){this.isMounted()&&this.setState(this.calcOverlayPosition())},calcOverlayPosition:function(){var e=this.getPosition(),t=this.getOverlayDOMNode(),r=t.offsetHeight,n=t.offsetWidth,o=this.props.placement,s=void 0,a=void 0,i=void 0,l=void 0;if("left"===o||"right"===o){a=e.top+(e.height-r)/2,s="left"===o?e.left-n:e.left+e.width;var u=this._getTopDelta(a,r);a+=u,l=50*(1-2*u/r)+"%",i=null}else{if("top"!==o&&"bottom"!==o)throw new Error('calcOverlayPosition(): No such placement of "'+this.props.placement+'" found.');s=e.left+(e.width-n)/2,a="top"===o?e.top-r:e.top+e.height;var p=this._getLeftDelta(s,n);s+=p,i=50*(1-2*p/n)+"%",l=null}return{overlayLeft:s,overlayTop:a,arrowOffsetLeft:i,arrowOffsetTop:l}},_getTopDelta:function(e,t){var r=this._getContainerDimensions(),n=r.scroll,o=r.height,s=this.props.containerPadding,a=e-s-n,i=e+s-n+t;return 0>a?-a:i>o?o-i:0},_getLeftDelta:function(e,t){var r=this._getContainerDimensions(),n=r.width,o=this.props.containerPadding,s=e-o,a=e+o+t;return 0>s?-s:a>n?n-a:0},_getContainerDimensions:function(){var e=this.getContainerDOMNode(),t=void 0,r=void 0,n=void 0;return"BODY"===e.tagName?(t=window.innerWidth,r=window.innerHeight,n=y["default"].ownerDocument(e).documentElement.scrollTop||e.scrollTop):(t=e.offsetWidth,r=e.offsetHeight,n=e.scrollTop),{width:t,height:r,scroll:n}},getPosition:function(){var e=i["default"].findDOMNode(this),t=this.getContainerDOMNode(),r="BODY"===t.tagName?y["default"].getOffset(e):y["default"].getPosition(e,t);return s({},r,{height:e.offsetHeight,width:e.offsetWidth})}});g.withContext=m["default"](g,"overlay"),t["default"]=g,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=a["default"].createClass({displayName:"PageHeader",render:function(){return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,"page-header")}),a["default"].createElement("h1",null,this.props.children))}});t["default"]=u,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(7),p=n(u),d=a["default"].createClass({displayName:"PageItem",propTypes:{href:a["default"].PropTypes.string,target:a["default"].PropTypes.string,title:a["default"].PropTypes.string,disabled:a["default"].PropTypes.bool,previous:a["default"].PropTypes.bool,next:a["default"].PropTypes.bool,onSelect:a["default"].PropTypes.func,eventKey:a["default"].PropTypes.any},render:function(){var e={disabled:this.props.disabled,previous:this.props.previous,next:this.props.next};return a["default"].createElement("li",o({},this.props,{className:l["default"](this.props.className,e)}),a["default"].createElement(p["default"],{href:this.props.href,title:this.props.title,target:this.props.target,onClick:this.handleSelect},this.props.children))},handleSelect:function(e){this.props.onSelect&&(e.preventDefault(),this.props.disabled||this.props.onSelect(this.props.eventKey,this.props.href,this.props.target))}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(4),p=n(u),d=r(6),f=n(d),c=a["default"].createClass({displayName:"Pager",propTypes:{onSelect:a["default"].PropTypes.func},render:function(){return a["default"].createElement("ul",o({},this.props,{className:l["default"](this.props.className,"pager")}),p["default"].map(this.props.children,this.renderPageItem))},renderPageItem:function(e,t){return s.cloneElement(e,{onSelect:f["default"](e.props.onSelect,this.props.onSelect),key:e.key?e.key:t})}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(3),p=n(u),d=r(10),f=n(d),c=a["default"].createClass({displayName:"Panel",mixins:[p["default"],f["default"]],propTypes:{collapsible:a["default"].PropTypes.bool,onSelect:a["default"].PropTypes.func,header:a["default"].PropTypes.node,id:a["default"].PropTypes.string,footer:a["default"].PropTypes.node,eventKey:a["default"].PropTypes.any},getDefaultProps:function(){return{bsClass:"panel",bsStyle:"default"}},handleSelect:function(e){e.selected=!0,this.props.onSelect?this.props.onSelect(e,this.props.eventKey):e.preventDefault(),e.selected&&this.handleToggle()},handleToggle:function(){this.setState({expanded:!this.state.expanded})},getCollapsibleDimensionValue:function(){return a["default"].findDOMNode(this.refs.panel).scrollHeight},getCollapsibleDOMNode:function(){return this.isMounted()&&this.refs&&this.refs.panel?a["default"].findDOMNode(this.refs.panel):null},render:function(){return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,this.getBsClassSet()),id:this.props.collapsible?null:this.props.id,onSelect:null}),this.renderHeading(),this.props.collapsible?this.renderCollapsibleBody():this.renderBody(),this.renderFooter())},renderCollapsibleBody:function(){var e=this.prefixClass("collapse");return a["default"].createElement("div",{className:l["default"](this.getCollapsibleClassSet(e)),id:this.props.id,ref:"panel","aria-expanded":this.isExpanded()?"true":"false"},this.renderBody())},renderBody:function(){function e(){return{key:l.length}}function t(t){l.push(s.cloneElement(t,e()))}function r(t){l.push(a["default"].createElement("div",o({className:p},e()),t))}function n(){0!==u.length&&(r(u),u=[])}var i=this.props.children,l=[],u=[],p=this.prefixClass("body");return Array.isArray(i)&&0!==i.length?(i.forEach(function(e){this.shouldRenderFill(e)?(n(),t(e)):u.push(e)}.bind(this)),n()):this.shouldRenderFill(i)?t(i):r(i),l},shouldRenderFill:function(e){return a["default"].isValidElement(e)&&null!=e.props.fill},renderHeading:function(){var e=this.props.header;if(!e)return null;if(!a["default"].isValidElement(e)||Array.isArray(e))e=this.props.collapsible?this.renderCollapsibleTitle(e):e;else{var t=l["default"](this.prefixClass("title"),e.props.className);e=this.props.collapsible?s.cloneElement(e,{className:t,children:this.renderAnchor(e.props.children)}):s.cloneElement(e,{className:t})}return a["default"].createElement("div",{className:this.prefixClass("heading")},e)},renderAnchor:function(e){return a["default"].createElement("a",{href:"#"+(this.props.id||""),className:this.isExpanded()?null:"collapsed","aria-expanded":this.isExpanded()?"true":"false",onClick:this.handleSelect},e)},renderCollapsibleTitle:function(e){return a["default"].createElement("h4",{className:this.prefixClass("title")},this.renderAnchor(e))},renderFooter:function(){return this.props.footer?a["default"].createElement("div",{className:this.prefixClass("footer")},this.props.footer):null}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0})}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=r(1),i=n(a),l=r(2),u=n(l),p=r(3),d=n(p),f=r(11),c=n(f),h=i["default"].createClass({displayName:"Popover",mixins:[d["default"],c["default"]],propTypes:{placement:i["default"].PropTypes.oneOf(["top","right","bottom","left"]),positionLeft:i["default"].PropTypes.number,positionTop:i["default"].PropTypes.number,arrowOffsetLeft:i["default"].PropTypes.oneOfType([i["default"].PropTypes.number,i["default"].PropTypes.string]),arrowOffsetTop:i["default"].PropTypes.oneOfType([i["default"].PropTypes.number,i["default"].PropTypes.string]),title:i["default"].PropTypes.node,animation:i["default"].PropTypes.bool},getDefaultProps:function(){return{placement:"right",animation:!0}},render:function(){var e,t=(e={popover:!0},o(e,this.props.placement,!0),o(e,"in",!this.props.animation&&(null!=this.props.positionLeft||null!=this.props.positionTop)),o(e,"fade",this.props.animation),e),r={left:this.props.positionLeft,top:this.props.positionTop,display:"block"},n={left:this.props.arrowOffsetLeft,top:this.props.arrowOffsetTop};return i["default"].createElement("div",s({},this.props,{className:u["default"](this.props.className,t),style:r,title:null}),i["default"].createElement("div",{className:"arrow",style:n}),this.props.title?this.renderTitle():null,i["default"].createElement("div",{className:"popover-content"},this.props.children))},renderTitle:function(){return i["default"].createElement("h3",{className:"popover-title"},this.props.title)}});t["default"]=h,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(24),l=n(i),u=r(3),p=n(u),d=r(2),f=n(d),c=r(4),h=n(c),m=a["default"].createClass({displayName:"ProgressBar",propTypes:{min:a["default"].PropTypes.number,now:a["default"].PropTypes.number,max:a["default"].PropTypes.number,label:a["default"].PropTypes.node,srOnly:a["default"].PropTypes.bool,striped:a["default"].PropTypes.bool,active:a["default"].PropTypes.bool},mixins:[p["default"]],getDefaultProps:function(){return{bsClass:"progress-bar",min:0,max:100}},getPercentage:function(e,t,r){var n=1e3;return Math.round((e-t)/(r-t)*100*n)/n},render:function(){var e={progress:!0};return this.props.active?(e["progress-striped"]=!0,e.active=!0):this.props.striped&&(e["progress-striped"]=!0),h["default"].hasValidComponent(this.props.children)?a["default"].createElement("div",o({},this.props,{className:f["default"](this.props.className,e)}),h["default"].map(this.props.children,this.renderChildBar)):this.props.isChild?this.renderProgressBar():a["default"].createElement("div",o({},this.props,{className:f["default"](this.props.className,e)}),this.renderProgressBar())},renderChildBar:function(e,t){return s.cloneElement(e,{isChild:!0,key:e.key?e.key:t})},renderProgressBar:function(){var e=this.getPercentage(this.props.now,this.props.min,this.props.max),t=void 0;"string"==typeof this.props.label?t=this.renderLabel(e):this.props.label&&(t=this.props.label),this.props.srOnly&&(t=this.renderScreenReaderOnlyLabel(t));var r=this.getBsClassSet();return a["default"].createElement("div",o({},this.props,{className:f["default"](this.props.className,r),role:"progressbar",style:{width:e+"%"},"aria-valuenow":this.props.now,"aria-valuemin":this.props.min,"aria-valuemax":this.props.max}),t)},renderLabel:function(e){var t=this.props.interpolateClass||l["default"];return a["default"].createElement(t,{now:this.props.now,min:this.props.min,max:this.props.max,percent:e,bsStyle:this.props.bsStyle},this.props.label)},renderScreenReaderOnlyLabel:function(e){return a["default"].createElement("span",{className:"sr-only"},e)}});t["default"]=m,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function s(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(e.__proto__=t)}function a(e,t){for(;e;){if(e===t)return!0;e=e.parentNode; }return!1}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=function(e,t,r){for(var n=!0;n;){var o=e,s=t,a=r;i=u=l=void 0,n=!1;var i=Object.getOwnPropertyDescriptor(o,s);if(void 0!==i){if("value"in i)return i.value;var l=i.get;return void 0===l?void 0:l.call(a)}var u=Object.getPrototypeOf(o);if(null===u)return void 0;e=u,t=s,r=a,n=!0}},u=r(1),p=n(u),d=r(5),f=n(d),c=r(13),h=n(c),m=function(e){function t(e){o(this,t),l(Object.getPrototypeOf(t.prototype),"constructor",this).call(this,e),this.handleDocumentClick=this.handleDocumentClick.bind(this),this.handleDocumentKeyUp=this.handleDocumentKeyUp.bind(this)}return s(t,e),i(t,[{key:"bindRootCloseHandlers",value:function(){var e=f["default"].ownerDocument(this);this._onDocumentClickListener=h["default"].listen(e,"click",this.handleDocumentClick),this._onDocumentKeyupListener=h["default"].listen(e,"keyup",this.handleDocumentKeyUp)}},{key:"handleDocumentClick",value:function(e){var t=e.target||e.srcElement;a(t,p["default"].findDOMNode(this))||this.props.onRootClose()}},{key:"handleDocumentKeyUp",value:function(e){27===e.keyCode&&this.props.onRootClose()}},{key:"unbindRootCloseHandlers",value:function(){this._onDocumentClickListener&&this._onDocumentClickListener.remove(),this._onDocumentKeyupListener&&this._onDocumentKeyupListener.remove()}},{key:"componentDidMount",value:function(){this.bindRootCloseHandlers()}},{key:"render",value:function(){return p["default"].Children.only(this.props.children)}},{key:"componentWillUnmount",value:function(){this.unbindRootCloseHandlers()}}]),t}(p["default"].Component);t["default"]=m,m.propTypes={onRootClose:p["default"].PropTypes.func.isRequired},e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=a["default"].createClass({displayName:"Row",propTypes:{componentClass:a["default"].PropTypes.node.isRequired},getDefaultProps:function(){return{componentClass:"div"}},render:function(){var e=this.props.componentClass;return a["default"].createElement(e,o({},this.props,{className:l["default"](this.props.className,"row")}),this.props.children)}});t["default"]=u,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(3),p=n(u),d=r(16),f=n(d),c=r(9),h=n(c),m=r(14),v=n(m),y=r(15),g=n(y),b=a["default"].createClass({displayName:"SplitButton",mixins:[p["default"],f["default"]],propTypes:{pullRight:a["default"].PropTypes.bool,title:a["default"].PropTypes.node,href:a["default"].PropTypes.string,id:a["default"].PropTypes.string,target:a["default"].PropTypes.string,dropdownTitle:a["default"].PropTypes.node,dropup:a["default"].PropTypes.bool,onClick:a["default"].PropTypes.func,onSelect:a["default"].PropTypes.func,disabled:a["default"].PropTypes.bool},getDefaultProps:function(){return{dropdownTitle:"Toggle dropdown"}},render:function(){var e={open:this.state.open,dropup:this.props.dropup},t=a["default"].createElement(h["default"],o({},this.props,{ref:"button",onClick:this.handleButtonClick,title:null,id:null}),this.props.title),r=a["default"].createElement(h["default"],o({},this.props,{ref:"dropdownButton",className:l["default"](this.props.className,"dropdown-toggle"),onClick:this.handleDropdownClick,title:null,href:null,target:null,id:null}),a["default"].createElement("span",{className:"sr-only"},this.props.dropdownTitle),a["default"].createElement("span",{className:"caret"}),a["default"].createElement("span",{style:{letterSpacing:"-.3em"}}," "));return a["default"].createElement(v["default"],{bsSize:this.props.bsSize,className:l["default"](e),id:this.props.id},t,r,a["default"].createElement(g["default"],{ref:"menu",onSelect:this.handleOptionSelect,"aria-labelledby":this.props.id,pullRight:this.props.pullRight},this.props.children))},handleButtonClick:function(e){this.state.open&&this.setDropdownState(!1),this.props.onClick&&this.props.onClick(e,this.props.href,this.props.target)},handleDropdownClick:function(e){e.preventDefault(),this.setDropdownState(!this.state.open)},handleOptionSelect:function(e){this.props.onSelect&&this.props.onSelect(e),this.setDropdownState(!1)}});t["default"]=b,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(4),p=n(u),d=r(6),f=n(d),c=r(3),h=n(c),m=r(7),v=n(m),y=a["default"].createClass({displayName:"SubNav",mixins:[h["default"]],propTypes:{onSelect:a["default"].PropTypes.func,active:a["default"].PropTypes.bool,activeHref:a["default"].PropTypes.string,activeKey:a["default"].PropTypes.any,disabled:a["default"].PropTypes.bool,eventKey:a["default"].PropTypes.any,href:a["default"].PropTypes.string,title:a["default"].PropTypes.string,text:a["default"].PropTypes.node,target:a["default"].PropTypes.string},getDefaultProps:function(){return{bsClass:"nav"}},handleClick:function(e){this.props.onSelect&&(e.preventDefault(),this.props.disabled||this.props.onSelect(this.props.eventKey,this.props.href,this.props.target))},isActive:function(){return this.isChildActive(this)},isChildActive:function(e){var t=this;if(e.props.active)return!0;if(null!=this.props.activeKey&&this.props.activeKey===e.props.eventKey)return!0;if(null!=this.props.activeHref&&this.props.activeHref===e.props.href)return!0;if(e.props.children){var r=function(){var r=!1;return p["default"].forEach(e.props.children,function(e){this.isChildActive(e)&&(r=!0)},t),{v:r}}();if("object"==typeof r)return r.v}return!1},getChildActiveProp:function(e){return e.props.active?!0:null!=this.props.activeKey&&e.props.eventKey===this.props.activeKey?!0:null!=this.props.activeHref&&e.props.href===this.props.activeHref?!0:e.props.active},render:function(){var e={active:this.isActive(),disabled:this.props.disabled};return a["default"].createElement("li",o({},this.props,{className:l["default"](this.props.className,e)}),a["default"].createElement(v["default"],{href:this.props.href,title:this.props.title,target:this.props.target,onClick:this.handleClick},this.props.text),a["default"].createElement("ul",{className:"nav"},p["default"].map(this.props.children,this.renderNavItem)))},renderNavItem:function(e,t){return s.cloneElement(e,{active:this.getChildActiveProp(e),onSelect:f["default"](e.props.onSelect,this.props.onSelect),key:e.key?e.key:t})}});t["default"]=y,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(19),p=n(u),d=a["default"].createClass({displayName:"TabPane",propTypes:{active:a["default"].PropTypes.bool,animation:a["default"].PropTypes.bool,onAnimateOutEnd:a["default"].PropTypes.func,disabled:a["default"].PropTypes.bool},getDefaultProps:function(){return{animation:!0}},getInitialState:function(){return{animateIn:!1,animateOut:!1}},componentWillReceiveProps:function(e){this.props.animation&&(this.state.animateIn||!e.active||this.props.active?this.state.animateOut||e.active||!this.props.active||this.setState({animateOut:!0}):this.setState({animateIn:!0}))},componentDidUpdate:function(){this.state.animateIn&&setTimeout(this.startAnimateIn,0),this.state.animateOut&&p["default"].addEndEventListener(a["default"].findDOMNode(this),this.stopAnimateOut)},startAnimateIn:function(){this.isMounted()&&this.setState({animateIn:!1})},stopAnimateOut:function(){this.isMounted()&&(this.setState({animateOut:!1}),this.props.onAnimateOutEnd&&this.props.onAnimateOutEnd())},render:function(){var e={"tab-pane":!0,fade:!0,active:this.props.active||this.state.animateOut,"in":this.props.active&&!this.state.animateIn};return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e){var t=void 0;return d["default"].forEach(e,function(e){null==t&&(t=e.props.eventKey)}),t}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=r(1),i=n(a),l=r(3),u=n(l),p=r(4),d=n(p),f=r(25),c=n(f),h=r(26),m=n(h),v=i["default"].createClass({displayName:"TabbedArea",mixins:[u["default"]],propTypes:{activeKey:i["default"].PropTypes.any,defaultActiveKey:i["default"].PropTypes.any,bsStyle:i["default"].PropTypes.oneOf(["tabs","pills"]),animation:i["default"].PropTypes.bool,id:i["default"].PropTypes.string,onSelect:i["default"].PropTypes.func},getDefaultProps:function(){return{bsStyle:"tabs",animation:!0}},getInitialState:function(){var e=null!=this.props.defaultActiveKey?this.props.defaultActiveKey:o(this.props.children);return{activeKey:e,previousActiveKey:null}},componentWillReceiveProps:function(e){null!=e.activeKey&&e.activeKey!==this.props.activeKey&&this.setState({previousActiveKey:this.props.activeKey})},handlePaneAnimateOutEnd:function(){this.setState({previousActiveKey:null})},render:function(){function e(e){return null!=e.props.tab?this.renderTab(e):null}var t=null!=this.props.activeKey?this.props.activeKey:this.state.activeKey,r=i["default"].createElement(c["default"],s({},this.props,{activeKey:t,onSelect:this.handleSelect,ref:"tabs"}),d["default"].map(this.props.children,e,this));return i["default"].createElement("div",null,r,i["default"].createElement("div",{id:this.props.id,className:"tab-content",ref:"panes"},d["default"].map(this.props.children,this.renderPane)))},getActiveKey:function(){return null!=this.props.activeKey?this.props.activeKey:this.state.activeKey},renderPane:function(e,t){var r=this.getActiveKey();return a.cloneElement(e,{active:e.props.eventKey===r&&(null==this.state.previousActiveKey||!this.props.animation),key:e.key?e.key:t,animation:this.props.animation,onAnimateOutEnd:null!=this.state.previousActiveKey&&e.props.eventKey===this.state.previousActiveKey?this.handlePaneAnimateOutEnd:null})},renderTab:function(e){var t=e.props,r=t.eventKey,n=t.className,o=t.tab,s=t.disabled;return i["default"].createElement(m["default"],{ref:"tab"+r,eventKey:r,className:n,disabled:s},o)},shouldComponentUpdate:function(){return!this._isChanging},handleSelect:function(e){this.props.onSelect?(this._isChanging=!0,this.props.onSelect(e),this._isChanging=!1):e!==this.getActiveKey()&&this.setState({activeKey:e,previousActiveKey:this.getActiveKey()})}});t["default"]=v,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=a["default"].createClass({displayName:"Table",propTypes:{striped:a["default"].PropTypes.bool,bordered:a["default"].PropTypes.bool,condensed:a["default"].PropTypes.bool,hover:a["default"].PropTypes.bool,responsive:a["default"].PropTypes.bool},render:function(){var e={table:!0,"table-striped":this.props.striped,"table-bordered":this.props.bordered,"table-condensed":this.props.condensed,"table-hover":this.props.hover},t=a["default"].createElement("table",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children);return this.props.responsive?a["default"].createElement("div",{className:"table-responsive"},t):t}});t["default"]=u,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(3),p=n(u),d=r(7),f=n(d),c=a["default"].createClass({displayName:"Thumbnail",mixins:[p["default"]],getDefaultProps:function(){return{bsClass:"thumbnail"}},render:function(){var e=this.getBsClassSet();return this.props.href?a["default"].createElement(f["default"],o({},this.props,{href:this.props.href,className:l["default"](this.props.className,e)}),a["default"].createElement("img",{src:this.props.src,alt:this.props.alt})):this.props.children?a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),a["default"].createElement("img",{src:this.props.src,alt:this.props.alt}),a["default"].createElement("div",{className:"caption"},this.props.children)):a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),a["default"].createElement("img",{src:this.props.src,alt:this.props.alt}))}});t["default"]=c,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}function o(e,t,r){return Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0})}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},a=r(1),i=n(a),l=r(2),u=n(l),p=r(3),d=n(p),f=r(11),c=n(f),h=i["default"].createClass({displayName:"Tooltip",mixins:[d["default"],c["default"]],propTypes:{placement:i["default"].PropTypes.oneOf(["top","right","bottom","left"]),positionLeft:i["default"].PropTypes.number,positionTop:i["default"].PropTypes.number,arrowOffsetLeft:i["default"].PropTypes.oneOfType([i["default"].PropTypes.number,i["default"].PropTypes.string]),arrowOffsetTop:i["default"].PropTypes.oneOfType([i["default"].PropTypes.number,i["default"].PropTypes.string]),animation:i["default"].PropTypes.bool},getDefaultProps:function(){return{placement:"right",animation:!0}},render:function(){var e,t=(e={tooltip:!0},o(e,this.props.placement,!0),o(e,"in",!this.props.animation&&(null!=this.props.positionLeft||null!=this.props.positionTop)),o(e,"fade",this.props.animation),e),r={left:this.props.positionLeft,top:this.props.positionTop},n={left:this.props.arrowOffsetLeft,top:this.props.arrowOffsetTop};return i["default"].createElement("div",s({},this.props,{className:u["default"](this.props.className,t),style:r}),i["default"].createElement("div",{className:"tooltip-arrow",style:n}),i["default"].createElement("div",{className:"tooltip-inner"},this.props.children))}});t["default"]=h,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=r(1),a=n(s),i=r(2),l=n(i),u=r(3),p=n(u),d=a["default"].createClass({displayName:"Well",mixins:[p["default"]],getDefaultProps:function(){return{bsClass:"well"}},render:function(){var e=this.getBsClassSet();return a["default"].createElement("div",o({},this.props,{className:l["default"](this.props.className,e)}),this.props.children)}});t["default"]=d,e.exports=t["default"]},function(e,t,r){"use strict";function n(e,t,r){}Object.defineProperty(t,"__esModule",{value:!0}),t["default"]=n,e.exports=t["default"]},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{"default":e}}Object.defineProperty(t,"__esModule",{value:!0});var o=r(20),s=n(o),a=r(6),i=n(a),l=r(8),u=n(l),p=r(5),d=n(p),f=r(4),c=n(f);t["default"]={childrenValueInputValidation:s["default"],createChainedFunction:i["default"],CustomPropTypes:u["default"],domUtils:d["default"],ValidComponentChildren:c["default"]},e.exports=t["default"]}])}); //# sourceMappingURL=react-bootstrap.min.js.map
draft-js-undo-plugin/src/UndoButton/__test__/index.js
koaninc/draft-js-plugins
/* eslint no-unused-expressions: 0, react/no-children-prop:0 */ import React from 'react'; import { shallow } from 'enzyme'; import sinon from 'sinon'; import chai, { expect } from 'chai'; import sinonChai from 'sinon-chai'; import { EditorState, Modifier } from 'draft-js'; import Undo from '../index'; chai.use(sinonChai); describe('UndoButton', () => { const onChange = () => sinon.spy(); let editorState; let store = { getEditorState: () => editorState, setEditorState: onChange, }; beforeEach(() => { editorState = EditorState.createEmpty(); }); it('applies the className based on the theme property `undo`', () => { const theme = { undo: 'custom-class-name' }; const result = shallow( <Undo store={store} theme={theme} children={'undo'} /> ); expect(result).to.have.prop('className', 'custom-class-name'); }); it('renders the passed in children', () => { const result = shallow( <Undo store={store} children="undo" /> ); expect(result).to.have.prop('children', 'undo'); }); it('applies a custom className as well as the theme', () => { const theme = { undo: 'custom-class-name' }; const result = shallow( <Undo store={store} theme={theme} className="undo" children="undo" /> ); expect(result).to.have.prop('className').to.contain('undo'); expect(result).to.have.prop('className').to.contain('custom-class-name'); }); it('adds disabled attribute to button if the getUndoStack is empty', () => { const result = shallow( <Undo store={store} children="redo" /> ); expect(result.find('button')).prop('disabled').to.equal(true); }); it('removes disabled attribute from button if the getUndoStack is not empty', () => { const contentState = editorState.getCurrentContent(); const SelectionState = editorState.getSelection(); const newContent = Modifier.insertText( contentState, SelectionState, 'hello' ); const newEditorState = EditorState.push(editorState, newContent, 'insert-text'); store = { getEditorState: () => newEditorState, setEditorState: onChange, }; const result = shallow( <Undo store={store} children="redo" /> ); expect(result.find('button')).prop('disabled').to.equal(false); }); it('triggers an update with undo when the button is clicked', () => { const result = shallow( <Undo store={store} children="redo" /> ); result.find('button').simulate('click'); expect(onChange).to.have.been.calledOnce; }); });
ajax/libs/jssip/0.6.31/jssip.js
Teino1978-Corp/Teino1978-Corp-cdnjs
/* * JsSIP v0.6.31 * the Javascript SIP library * Copyright: 2012-2015 José Luis Millán <[email protected]> (https://github.com/jmillan) * Homepage: http://jssip.net * License: MIT */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JsSIP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var pkg = require('../package.json'); var C = { USER_AGENT: pkg.title + ' ' + pkg.version, // SIP scheme SIP: 'sip', SIPS: 'sips', // End and Failure causes causes: { // Generic error causes CONNECTION_ERROR: 'Connection Error', REQUEST_TIMEOUT: 'Request Timeout', SIP_FAILURE_CODE: 'SIP Failure Code', INTERNAL_ERROR: 'Internal Error', // SIP error causes BUSY: 'Busy', REJECTED: 'Rejected', REDIRECTED: 'Redirected', UNAVAILABLE: 'Unavailable', NOT_FOUND: 'Not Found', ADDRESS_INCOMPLETE: 'Address Incomplete', INCOMPATIBLE_SDP: 'Incompatible SDP', MISSING_SDP: 'Missing SDP', AUTHENTICATION_ERROR: 'Authentication Error', // Session error causes BYE: 'Terminated', WEBRTC_ERROR: 'WebRTC Error', CANCELED: 'Canceled', NO_ANSWER: 'No Answer', EXPIRES: 'Expires', NO_ACK: 'No ACK', DIALOG_ERROR: 'Dialog Error', USER_DENIED_MEDIA_ACCESS: 'User Denied Media Access', BAD_MEDIA_DESCRIPTION: 'Bad Media Description', RTP_TIMEOUT: 'RTP Timeout' }, SIP_ERROR_CAUSES: { REDIRECTED: [300,301,302,305,380], BUSY: [486,600], REJECTED: [403,603], NOT_FOUND: [404,604], UNAVAILABLE: [480,410,408,430], ADDRESS_INCOMPLETE: [484], INCOMPATIBLE_SDP: [488,606], AUTHENTICATION_ERROR:[401,407] }, // SIP Methods ACK: 'ACK', BYE: 'BYE', CANCEL: 'CANCEL', INFO: 'INFO', INVITE: 'INVITE', MESSAGE: 'MESSAGE', NOTIFY: 'NOTIFY', OPTIONS: 'OPTIONS', REGISTER: 'REGISTER', UPDATE: 'UPDATE', SUBSCRIBE: 'SUBSCRIBE', /* SIP Response Reasons * DOC: http://www.iana.org/assignments/sip-parameters * Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7 */ REASON_PHRASE: { 100: 'Trying', 180: 'Ringing', 181: 'Call Is Being Forwarded', 182: 'Queued', 183: 'Session Progress', 199: 'Early Dialog Terminated', // draft-ietf-sipcore-199 200: 'OK', 202: 'Accepted', // RFC 3265 204: 'No Notification', //RFC 5839 300: 'Multiple Choices', 301: 'Moved Permanently', 302: 'Moved Temporarily', 305: 'Use Proxy', 380: 'Alternative Service', 400: 'Bad Request', 401: 'Unauthorized', 402: 'Payment Required', 403: 'Forbidden', 404: 'Not Found', 405: 'Method Not Allowed', 406: 'Not Acceptable', 407: 'Proxy Authentication Required', 408: 'Request Timeout', 410: 'Gone', 412: 'Conditional Request Failed', // RFC 3903 413: 'Request Entity Too Large', 414: 'Request-URI Too Long', 415: 'Unsupported Media Type', 416: 'Unsupported URI Scheme', 417: 'Unknown Resource-Priority', // RFC 4412 420: 'Bad Extension', 421: 'Extension Required', 422: 'Session Interval Too Small', // RFC 4028 423: 'Interval Too Brief', 428: 'Use Identity Header', // RFC 4474 429: 'Provide Referrer Identity', // RFC 3892 430: 'Flow Failed', // RFC 5626 433: 'Anonymity Disallowed', // RFC 5079 436: 'Bad Identity-Info', // RFC 4474 437: 'Unsupported Certificate', // RFC 4744 438: 'Invalid Identity Header', // RFC 4744 439: 'First Hop Lacks Outbound Support', // RFC 5626 440: 'Max-Breadth Exceeded', // RFC 5393 469: 'Bad Info Package', // draft-ietf-sipcore-info-events 470: 'Consent Needed', // RFC 5360 478: 'Unresolvable Destination', // Custom code copied from Kamailio. 480: 'Temporarily Unavailable', 481: 'Call/Transaction Does Not Exist', 482: 'Loop Detected', 483: 'Too Many Hops', 484: 'Address Incomplete', 485: 'Ambiguous', 486: 'Busy Here', 487: 'Request Terminated', 488: 'Not Acceptable Here', 489: 'Bad Event', // RFC 3265 491: 'Request Pending', 493: 'Undecipherable', 494: 'Security Agreement Required', // RFC 3329 500: 'JsSIP Internal Error', 501: 'Not Implemented', 502: 'Bad Gateway', 503: 'Service Unavailable', 504: 'Server Time-out', 505: 'Version Not Supported', 513: 'Message Too Large', 580: 'Precondition Failure', // RFC 3312 600: 'Busy Everywhere', 603: 'Decline', 604: 'Does Not Exist Anywhere', 606: 'Not Acceptable' }, ALLOWED_METHODS: 'INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS', ACCEPTED_BODY_TYPES: 'application/sdp, application/dtmf-relay', MAX_FORWARDS: 69, SESSION_EXPIRES: 90, MIN_SESSION_EXPIRES: 60 }; module.exports = C; },{"../package.json":46}],2:[function(require,module,exports){ module.exports = Dialog; var C = { // Dialog states STATUS_EARLY: 1, STATUS_CONFIRMED: 2 }; /** * Expose C object. */ Dialog.C = C; /** * Dependencies. */ var debug = require('debug')('JsSIP:Dialog'); var SIPMessage = require('./SIPMessage'); var JsSIP_C = require('./Constants'); var Transactions = require('./Transactions'); var Dialog_RequestSender = require('./Dialog/RequestSender'); // RFC 3261 12.1 function Dialog(owner, message, type, state) { var contact; this.uac_pending_reply = false; this.uas_pending_reply = false; if(!message.hasHeader('contact')) { return { error: 'unable to create a Dialog without Contact header field' }; } if(message instanceof SIPMessage.IncomingResponse) { state = (message.status_code < 200) ? C.STATUS_EARLY : C.STATUS_CONFIRMED; } else { // Create confirmed dialog if state is not defined state = state || C.STATUS_CONFIRMED; } contact = message.parseHeader('contact'); // RFC 3261 12.1.1 if(type === 'UAS') { this.id = { call_id: message.call_id, local_tag: message.to_tag, remote_tag: message.from_tag, toString: function() { return this.call_id + this.local_tag + this.remote_tag; } }; this.state = state; this.remote_seqnum = message.cseq; this.local_uri = message.parseHeader('to').uri; this.remote_uri = message.parseHeader('from').uri; this.remote_target = contact.uri; this.route_set = message.getHeaders('record-route'); } // RFC 3261 12.1.2 else if(type === 'UAC') { this.id = { call_id: message.call_id, local_tag: message.from_tag, remote_tag: message.to_tag, toString: function() { return this.call_id + this.local_tag + this.remote_tag; } }; this.state = state; this.local_seqnum = message.cseq; this.local_uri = message.parseHeader('from').uri; this.remote_uri = message.parseHeader('to').uri; this.remote_target = contact.uri; this.route_set = message.getHeaders('record-route').reverse(); } this.owner = owner; owner.ua.dialogs[this.id.toString()] = this; debug('new ' + type + ' dialog created with status ' + (this.state === C.STATUS_EARLY ? 'EARLY': 'CONFIRMED')); } Dialog.prototype = { update: function(message, type) { this.state = C.STATUS_CONFIRMED; debug('dialog '+ this.id.toString() +' changed to CONFIRMED state'); if(type === 'UAC') { // RFC 3261 13.2.2.4 this.route_set = message.getHeaders('record-route').reverse(); } }, terminate: function() { debug('dialog ' + this.id.toString() + ' deleted'); delete this.owner.ua.dialogs[this.id.toString()]; }, // RFC 3261 12.2.1.1 createRequest: function(method, extraHeaders, body) { var cseq, request; extraHeaders = extraHeaders && extraHeaders.slice() || []; if(!this.local_seqnum) { this.local_seqnum = Math.floor(Math.random() * 10000); } cseq = (method === JsSIP_C.CANCEL || method === JsSIP_C.ACK) ? this.local_seqnum : this.local_seqnum += 1; request = new SIPMessage.OutgoingRequest( method, this.remote_target, this.owner.ua, { 'cseq': cseq, 'call_id': this.id.call_id, 'from_uri': this.local_uri, 'from_tag': this.id.local_tag, 'to_uri': this.remote_uri, 'to_tag': this.id.remote_tag, 'route_set': this.route_set }, extraHeaders, body); request.dialog = this; return request; }, // RFC 3261 12.2.2 checkInDialogRequest: function(request) { var self = this; if(!this.remote_seqnum) { this.remote_seqnum = request.cseq; } else if(request.cseq < this.remote_seqnum) { //Do not try to reply to an ACK request. if (request.method !== JsSIP_C.ACK) { request.reply(500); } return false; } else if(request.cseq > this.remote_seqnum) { this.remote_seqnum = request.cseq; } // RFC3261 14.2 Modifying an Existing Session -UAS BEHAVIOR- if (request.method === JsSIP_C.INVITE || (request.method === JsSIP_C.UPDATE && request.body)) { if (this.uac_pending_reply === true) { request.reply(491); } else if (this.uas_pending_reply === true) { var retryAfter = (Math.random() * 10 | 0) + 1; request.reply(500, null, ['Retry-After:'+ retryAfter]); return false; } else { this.uas_pending_reply = true; request.server_transaction.on('stateChanged', function stateChanged(){ if (this.state === Transactions.C.STATUS_ACCEPTED || this.state === Transactions.C.STATUS_COMPLETED || this.state === Transactions.C.STATUS_TERMINATED) { request.server_transaction.removeListener('stateChanged', stateChanged); self.uas_pending_reply = false; } }); } // RFC3261 12.2.2 Replace the dialog`s remote target URI if the request is accepted if(request.hasHeader('contact')) { request.server_transaction.on('stateChanged', function(){ if (this.state === Transactions.C.STATUS_ACCEPTED) { self.remote_target = request.parseHeader('contact').uri; } }); } } else if (request.method === JsSIP_C.NOTIFY) { // RFC6665 3.2 Replace the dialog`s remote target URI if the request is accepted if(request.hasHeader('contact')) { request.server_transaction.on('stateChanged', function(){ if (this.state === Transactions.C.STATUS_COMPLETED) { self.remote_target = request.parseHeader('contact').uri; } }); } } return true; }, sendRequest: function(applicant, method, options) { options = options || {}; var extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body || null, request = this.createRequest(method, extraHeaders, body), request_sender = new Dialog_RequestSender(this, applicant, request); request_sender.send(); }, receiveRequest: function(request) { //Check in-dialog request if(!this.checkInDialogRequest(request)) { return; } this.owner.receiveRequest(request); } }; },{"./Constants":1,"./Dialog/RequestSender":3,"./SIPMessage":16,"./Transactions":18,"debug":29}],3:[function(require,module,exports){ module.exports = DialogRequestSender; /** * Dependencies. */ var JsSIP_C = require('../Constants'); var Transactions = require('../Transactions'); var RTCSession = require('../RTCSession'); var RequestSender = require('../RequestSender'); function DialogRequestSender(dialog, applicant, request) { this.dialog = dialog; this.applicant = applicant; this.request = request; // RFC3261 14.1 Modifying an Existing Session. UAC Behavior. this.reattempt = false; this.reattemptTimer = null; } DialogRequestSender.prototype = { send: function() { var self = this, request_sender = new RequestSender(this, this.dialog.owner.ua); request_sender.send(); // RFC3261 14.2 Modifying an Existing Session -UAC BEHAVIOR- if ((this.request.method === JsSIP_C.INVITE || (this.request.method === JsSIP_C.UPDATE && this.request.body)) && request_sender.clientTransaction.state !== Transactions.C.STATUS_TERMINATED) { this.dialog.uac_pending_reply = true; request_sender.clientTransaction.on('stateChanged', function stateChanged(){ if (this.state === Transactions.C.STATUS_ACCEPTED || this.state === Transactions.C.STATUS_COMPLETED || this.state === Transactions.C.STATUS_TERMINATED) { request_sender.clientTransaction.removeListener('stateChanged', stateChanged); self.dialog.uac_pending_reply = false; } }); } }, onRequestTimeout: function() { this.applicant.onRequestTimeout(); }, onTransportError: function() { this.applicant.onTransportError(); }, receiveResponse: function(response) { var self = this; // RFC3261 12.2.1.2 408 or 481 is received for a request within a dialog. if (response.status_code === 408 || response.status_code === 481) { this.applicant.onDialogError(response); } else if (response.method === JsSIP_C.INVITE && response.status_code === 491) { if (this.reattempt) { this.applicant.receiveResponse(response); } else { this.request.cseq.value = this.dialog.local_seqnum += 1; this.reattemptTimer = setTimeout(function() { if (self.applicant.owner.status !== RTCSession.C.STATUS_TERMINATED) { self.reattempt = true; self.request_sender.send(); } }, 1000); } } else { this.applicant.receiveResponse(response); } } }; },{"../Constants":1,"../RTCSession":11,"../RequestSender":15,"../Transactions":18}],4:[function(require,module,exports){ module.exports = DigestAuthentication; /** * Dependencies. */ var debug = require('debug')('JsSIP:DigestAuthentication'); var Utils = require('./Utils'); function DigestAuthentication(ua) { this.username = ua.configuration.authorization_user; this.password = ua.configuration.password; this.cnonce = null; this.nc = 0; this.ncHex = '00000000'; this.response = null; } /** * Performs Digest authentication given a SIP request and the challenge * received in a response to that request. * Returns true if credentials were successfully generated, false otherwise. */ DigestAuthentication.prototype.authenticate = function(request, challenge) { // Inspect and validate the challenge. this.algorithm = challenge.algorithm; this.realm = challenge.realm; this.nonce = challenge.nonce; this.opaque = challenge.opaque; this.stale = challenge.stale; if (this.algorithm) { if (this.algorithm !== 'MD5') { debug('challenge with Digest algorithm different than "MD5", authentication aborted'); return false; } } else { this.algorithm = 'MD5'; } if (! this.realm) { debug('challenge without Digest realm, authentication aborted'); return false; } if (! this.nonce) { debug('challenge without Digest nonce, authentication aborted'); return false; } // 'qop' can contain a list of values (Array). Let's choose just one. if (challenge.qop) { if (challenge.qop.indexOf('auth') > -1) { this.qop = 'auth'; } else if (challenge.qop.indexOf('auth-int') > -1) { this.qop = 'auth-int'; } else { // Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here. debug('challenge without Digest qop different than "auth" or "auth-int", authentication aborted'); return false; } } else { this.qop = null; } // Fill other attributes. this.method = request.method; this.uri = request.ruri; this.cnonce = Utils.createRandomToken(12); this.nc += 1; this.updateNcHex(); // nc-value = 8LHEX. Max value = 'FFFFFFFF'. if (this.nc === 4294967296) { this.nc = 1; this.ncHex = '00000001'; } // Calculate the Digest "response" value. this.calculateResponse(); return true; }; /** * Generate Digest 'response' value. */ DigestAuthentication.prototype.calculateResponse = function() { var ha1, ha2; // HA1 = MD5(A1) = MD5(username:realm:password) ha1 = Utils.calculateMD5(this.username + ':' + this.realm + ':' + this.password); if (this.qop === 'auth') { // HA2 = MD5(A2) = MD5(method:digestURI) ha2 = Utils.calculateMD5(this.method + ':' + this.uri); // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) this.response = Utils.calculateMD5(ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth:' + ha2); } else if (this.qop === 'auth-int') { // HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody)) ha2 = Utils.calculateMD5(this.method + ':' + this.uri + ':' + Utils.calculateMD5(this.body ? this.body : '')); // response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2) this.response = Utils.calculateMD5(ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth-int:' + ha2); } else if (this.qop === null) { // HA2 = MD5(A2) = MD5(method:digestURI) ha2 = Utils.calculateMD5(this.method + ':' + this.uri); // response = MD5(HA1:nonce:HA2) this.response = Utils.calculateMD5(ha1 + ':' + this.nonce + ':' + ha2); } }; /** * Return the Proxy-Authorization or WWW-Authorization header value. */ DigestAuthentication.prototype.toString = function() { var auth_params = []; if (! this.response) { throw new Error('response field does not exist, cannot generate Authorization header'); } auth_params.push('algorithm=' + this.algorithm); auth_params.push('username="' + this.username + '"'); auth_params.push('realm="' + this.realm + '"'); auth_params.push('nonce="' + this.nonce + '"'); auth_params.push('uri="' + this.uri + '"'); auth_params.push('response="' + this.response + '"'); if (this.opaque) { auth_params.push('opaque="' + this.opaque + '"'); } if (this.qop) { auth_params.push('qop=' + this.qop); auth_params.push('cnonce="' + this.cnonce + '"'); auth_params.push('nc=' + this.ncHex); } return 'Digest ' + auth_params.join(', '); }; /** * Generate the 'nc' value as required by Digest in this.ncHex by reading this.nc. */ DigestAuthentication.prototype.updateNcHex = function() { var hex = Number(this.nc).toString(16); this.ncHex = '00000000'.substr(0, 8-hex.length) + hex; }; },{"./Utils":22,"debug":29}],5:[function(require,module,exports){ /** * @namespace Exceptions * @memberOf JsSIP */ var Exceptions = { /** * Exception thrown when a valid parameter is given to the JsSIP.UA constructor. * @class ConfigurationError * @memberOf JsSIP.Exceptions */ ConfigurationError: (function(){ var exception = function(parameter, value) { this.code = 1; this.name = 'CONFIGURATION_ERROR'; this.parameter = parameter; this.value = value; this.message = (!this.value)? 'Missing parameter: '+ this.parameter : 'Invalid value '+ JSON.stringify(this.value) +' for parameter "'+ this.parameter +'"'; }; exception.prototype = new Error(); return exception; }()), InvalidStateError: (function(){ var exception = function(status) { this.code = 2; this.name = 'INVALID_STATE_ERROR'; this.status = status; this.message = 'Invalid status: '+ status; }; exception.prototype = new Error(); return exception; }()), NotSupportedError: (function(){ var exception = function(message) { this.code = 3; this.name = 'NOT_SUPPORTED_ERROR'; this.message = message; }; exception.prototype = new Error(); return exception; }()), NotReadyError: (function(){ var exception = function(message) { this.code = 4; this.name = 'NOT_READY_ERROR'; this.message = message; }; exception.prototype = new Error(); return exception; }()) }; module.exports = Exceptions; },{}],6:[function(require,module,exports){ module.exports = (function(){ /* * Generated by PEG.js 0.7.0. * * http://pegjs.majda.cz/ */ function quote(s) { /* * ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a * string literal except for the closing quote character, backslash, * carriage return, line separator, paragraph separator, and line feed. * Any character may appear in the form of an escape sequence. * * For portability, we also escape escape all control and non-ASCII * characters. Note that "\0" and "\v" escape sequences are not used * because JSHint does not like the first and IE the second. */ return '"' + s .replace(/\\/g, '\\\\') // backslash .replace(/"/g, '\\"') // closing quote character .replace(/\x08/g, '\\b') // backspace .replace(/\t/g, '\\t') // horizontal tab .replace(/\n/g, '\\n') // line feed .replace(/\f/g, '\\f') // form feed .replace(/\r/g, '\\r') // carriage return .replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape) + '"'; } var result = { /* * Parses the input with a generated parser. If the parsing is successfull, * returns a value explicitly or implicitly specified by the grammar from * which the parser was generated (see |PEG.buildParser|). If the parsing is * unsuccessful, throws |PEG.parser.SyntaxError| describing the error. */ parse: function(input, startRule) { var parseFunctions = { "CRLF": parse_CRLF, "DIGIT": parse_DIGIT, "ALPHA": parse_ALPHA, "HEXDIG": parse_HEXDIG, "WSP": parse_WSP, "OCTET": parse_OCTET, "DQUOTE": parse_DQUOTE, "SP": parse_SP, "HTAB": parse_HTAB, "alphanum": parse_alphanum, "reserved": parse_reserved, "unreserved": parse_unreserved, "mark": parse_mark, "escaped": parse_escaped, "LWS": parse_LWS, "SWS": parse_SWS, "HCOLON": parse_HCOLON, "TEXT_UTF8_TRIM": parse_TEXT_UTF8_TRIM, "TEXT_UTF8char": parse_TEXT_UTF8char, "UTF8_NONASCII": parse_UTF8_NONASCII, "UTF8_CONT": parse_UTF8_CONT, "LHEX": parse_LHEX, "token": parse_token, "token_nodot": parse_token_nodot, "separators": parse_separators, "word": parse_word, "STAR": parse_STAR, "SLASH": parse_SLASH, "EQUAL": parse_EQUAL, "LPAREN": parse_LPAREN, "RPAREN": parse_RPAREN, "RAQUOT": parse_RAQUOT, "LAQUOT": parse_LAQUOT, "COMMA": parse_COMMA, "SEMI": parse_SEMI, "COLON": parse_COLON, "LDQUOT": parse_LDQUOT, "RDQUOT": parse_RDQUOT, "comment": parse_comment, "ctext": parse_ctext, "quoted_string": parse_quoted_string, "quoted_string_clean": parse_quoted_string_clean, "qdtext": parse_qdtext, "quoted_pair": parse_quoted_pair, "SIP_URI_noparams": parse_SIP_URI_noparams, "SIP_URI": parse_SIP_URI, "uri_scheme": parse_uri_scheme, "userinfo": parse_userinfo, "user": parse_user, "user_unreserved": parse_user_unreserved, "password": parse_password, "hostport": parse_hostport, "host": parse_host, "hostname": parse_hostname, "domainlabel": parse_domainlabel, "toplabel": parse_toplabel, "IPv6reference": parse_IPv6reference, "IPv6address": parse_IPv6address, "h16": parse_h16, "ls32": parse_ls32, "IPv4address": parse_IPv4address, "dec_octet": parse_dec_octet, "port": parse_port, "uri_parameters": parse_uri_parameters, "uri_parameter": parse_uri_parameter, "transport_param": parse_transport_param, "user_param": parse_user_param, "method_param": parse_method_param, "ttl_param": parse_ttl_param, "maddr_param": parse_maddr_param, "lr_param": parse_lr_param, "other_param": parse_other_param, "pname": parse_pname, "pvalue": parse_pvalue, "paramchar": parse_paramchar, "param_unreserved": parse_param_unreserved, "headers": parse_headers, "header": parse_header, "hname": parse_hname, "hvalue": parse_hvalue, "hnv_unreserved": parse_hnv_unreserved, "Request_Response": parse_Request_Response, "Request_Line": parse_Request_Line, "Request_URI": parse_Request_URI, "absoluteURI": parse_absoluteURI, "hier_part": parse_hier_part, "net_path": parse_net_path, "abs_path": parse_abs_path, "opaque_part": parse_opaque_part, "uric": parse_uric, "uric_no_slash": parse_uric_no_slash, "path_segments": parse_path_segments, "segment": parse_segment, "param": parse_param, "pchar": parse_pchar, "scheme": parse_scheme, "authority": parse_authority, "srvr": parse_srvr, "reg_name": parse_reg_name, "query": parse_query, "SIP_Version": parse_SIP_Version, "INVITEm": parse_INVITEm, "ACKm": parse_ACKm, "OPTIONSm": parse_OPTIONSm, "BYEm": parse_BYEm, "CANCELm": parse_CANCELm, "REGISTERm": parse_REGISTERm, "SUBSCRIBEm": parse_SUBSCRIBEm, "NOTIFYm": parse_NOTIFYm, "Method": parse_Method, "Status_Line": parse_Status_Line, "Status_Code": parse_Status_Code, "extension_code": parse_extension_code, "Reason_Phrase": parse_Reason_Phrase, "Allow_Events": parse_Allow_Events, "Call_ID": parse_Call_ID, "Contact": parse_Contact, "contact_param": parse_contact_param, "name_addr": parse_name_addr, "display_name": parse_display_name, "contact_params": parse_contact_params, "c_p_q": parse_c_p_q, "c_p_expires": parse_c_p_expires, "delta_seconds": parse_delta_seconds, "qvalue": parse_qvalue, "generic_param": parse_generic_param, "gen_value": parse_gen_value, "Content_Disposition": parse_Content_Disposition, "disp_type": parse_disp_type, "disp_param": parse_disp_param, "handling_param": parse_handling_param, "Content_Encoding": parse_Content_Encoding, "Content_Length": parse_Content_Length, "Content_Type": parse_Content_Type, "media_type": parse_media_type, "m_type": parse_m_type, "discrete_type": parse_discrete_type, "composite_type": parse_composite_type, "extension_token": parse_extension_token, "x_token": parse_x_token, "m_subtype": parse_m_subtype, "m_parameter": parse_m_parameter, "m_value": parse_m_value, "CSeq": parse_CSeq, "CSeq_value": parse_CSeq_value, "Expires": parse_Expires, "Event": parse_Event, "event_type": parse_event_type, "From": parse_From, "from_param": parse_from_param, "tag_param": parse_tag_param, "Max_Forwards": parse_Max_Forwards, "Min_Expires": parse_Min_Expires, "Name_Addr_Header": parse_Name_Addr_Header, "Proxy_Authenticate": parse_Proxy_Authenticate, "challenge": parse_challenge, "other_challenge": parse_other_challenge, "auth_param": parse_auth_param, "digest_cln": parse_digest_cln, "realm": parse_realm, "realm_value": parse_realm_value, "domain": parse_domain, "URI": parse_URI, "nonce": parse_nonce, "nonce_value": parse_nonce_value, "opaque": parse_opaque, "stale": parse_stale, "algorithm": parse_algorithm, "qop_options": parse_qop_options, "qop_value": parse_qop_value, "Proxy_Require": parse_Proxy_Require, "Record_Route": parse_Record_Route, "rec_route": parse_rec_route, "Reason": parse_Reason, "reason_param": parse_reason_param, "reason_cause": parse_reason_cause, "Require": parse_Require, "Route": parse_Route, "route_param": parse_route_param, "Subscription_State": parse_Subscription_State, "substate_value": parse_substate_value, "subexp_params": parse_subexp_params, "event_reason_value": parse_event_reason_value, "Subject": parse_Subject, "Supported": parse_Supported, "To": parse_To, "to_param": parse_to_param, "Via": parse_Via, "via_param": parse_via_param, "via_params": parse_via_params, "via_ttl": parse_via_ttl, "via_maddr": parse_via_maddr, "via_received": parse_via_received, "via_branch": parse_via_branch, "response_port": parse_response_port, "sent_protocol": parse_sent_protocol, "protocol_name": parse_protocol_name, "transport": parse_transport, "sent_by": parse_sent_by, "via_host": parse_via_host, "via_port": parse_via_port, "ttl": parse_ttl, "WWW_Authenticate": parse_WWW_Authenticate, "Session_Expires": parse_Session_Expires, "s_e_expires": parse_s_e_expires, "s_e_params": parse_s_e_params, "s_e_refresher": parse_s_e_refresher, "extension_header": parse_extension_header, "header_value": parse_header_value, "message_body": parse_message_body, "uuid_URI": parse_uuid_URI, "uuid": parse_uuid, "hex4": parse_hex4, "hex8": parse_hex8, "hex12": parse_hex12 }; if (startRule !== undefined) { if (parseFunctions[startRule] === undefined) { throw new Error("Invalid rule name: " + quote(startRule) + "."); } } else { startRule = "CRLF"; } var pos = 0; var reportFailures = 0; var rightmostFailuresPos = 0; var rightmostFailuresExpected = []; function padLeft(input, padding, length) { var result = input; var padLength = length - input.length; for (var i = 0; i < padLength; i++) { result = padding + result; } return result; } function escape(ch) { var charCode = ch.charCodeAt(0); var escapeChar; var length; if (charCode <= 0xFF) { escapeChar = 'x'; length = 2; } else { escapeChar = 'u'; length = 4; } return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length); } function matchFailed(failure) { if (pos < rightmostFailuresPos) { return; } if (pos > rightmostFailuresPos) { rightmostFailuresPos = pos; rightmostFailuresExpected = []; } rightmostFailuresExpected.push(failure); } function parse_CRLF() { var result0; if (input.substr(pos, 2) === "\r\n") { result0 = "\r\n"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"\\r\\n\""); } } return result0; } function parse_DIGIT() { var result0; if (/^[0-9]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[0-9]"); } } return result0; } function parse_ALPHA() { var result0; if (/^[a-zA-Z]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z]"); } } return result0; } function parse_HEXDIG() { var result0; if (/^[0-9a-fA-F]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[0-9a-fA-F]"); } } return result0; } function parse_WSP() { var result0; result0 = parse_SP(); if (result0 === null) { result0 = parse_HTAB(); } return result0; } function parse_OCTET() { var result0; if (/^[\0-\xFF]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\0-\\xFF]"); } } return result0; } function parse_DQUOTE() { var result0; if (/^["]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\"]"); } } return result0; } function parse_SP() { var result0; if (input.charCodeAt(pos) === 32) { result0 = " "; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\" \""); } } return result0; } function parse_HTAB() { var result0; if (input.charCodeAt(pos) === 9) { result0 = "\t"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"\\t\""); } } return result0; } function parse_alphanum() { var result0; if (/^[a-zA-Z0-9]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z0-9]"); } } return result0; } function parse_reserved() { var result0; if (input.charCodeAt(pos) === 59) { result0 = ";"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 64) { result0 = "@"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } } } } return result0; } function parse_unreserved() { var result0; result0 = parse_alphanum(); if (result0 === null) { result0 = parse_mark(); } return result0; } function parse_mark() { var result0; if (input.charCodeAt(pos) === 45) { result0 = "-"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 95) { result0 = "_"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 46) { result0 = "."; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 33) { result0 = "!"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 126) { result0 = "~"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 42) { result0 = "*"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 39) { result0 = "'"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 40) { result0 = "("; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 41) { result0 = ")"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\")\""); } } } } } } } } } } return result0; } function parse_escaped() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.charCodeAt(pos) === 37) { result0 = "%"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result0 !== null) { result1 = parse_HEXDIG(); if (result1 !== null) { result2 = parse_HEXDIG(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, escaped) {return escaped.join(''); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_LWS() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; pos2 = pos; result0 = []; result1 = parse_WSP(); while (result1 !== null) { result0.push(result1); result1 = parse_WSP(); } if (result0 !== null) { result1 = parse_CRLF(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos2; } } else { result0 = null; pos = pos2; } result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result2 = parse_WSP(); if (result2 !== null) { result1 = []; while (result2 !== null) { result1.push(result2); result2 = parse_WSP(); } } else { result1 = null; } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return " "; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_SWS() { var result0; result0 = parse_LWS(); result0 = result0 !== null ? result0 : ""; return result0; } function parse_HCOLON() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = []; result1 = parse_SP(); if (result1 === null) { result1 = parse_HTAB(); } while (result1 !== null) { result0.push(result1); result1 = parse_SP(); if (result1 === null) { result1 = parse_HTAB(); } } if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ':'; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_TEXT_UTF8_TRIM() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result1 = parse_TEXT_UTF8char(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_TEXT_UTF8char(); } } else { result0 = null; } if (result0 !== null) { result1 = []; pos2 = pos; result2 = []; result3 = parse_LWS(); while (result3 !== null) { result2.push(result3); result3 = parse_LWS(); } if (result2 !== null) { result3 = parse_TEXT_UTF8char(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = []; result3 = parse_LWS(); while (result3 !== null) { result2.push(result3); result3 = parse_LWS(); } if (result2 !== null) { result3 = parse_TEXT_UTF8char(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_TEXT_UTF8char() { var result0; if (/^[!-~]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[!-~]"); } } if (result0 === null) { result0 = parse_UTF8_NONASCII(); } return result0; } function parse_UTF8_NONASCII() { var result0; if (/^[\x80-\uFFFF]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\x80-\\uFFFF]"); } } return result0; } function parse_UTF8_CONT() { var result0; if (/^[\x80-\xBF]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\x80-\\xBF]"); } } return result0; } function parse_LHEX() { var result0; result0 = parse_DIGIT(); if (result0 === null) { if (/^[a-f]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[a-f]"); } } } return result0; } function parse_token() { var result0, result1; var pos0; pos0 = pos; result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } } } } } } } } } } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } } } } } } } } } } } } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_token_nodot() { var result0, result1; var pos0; pos0 = pos; result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } } } } } } } } } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } } } } } } } } } } } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_separators() { var result0; if (input.charCodeAt(pos) === 40) { result0 = "("; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 41) { result0 = ")"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\")\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 60) { result0 = "<"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"<\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 62) { result0 = ">"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\">\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 64) { result0 = "@"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 59) { result0 = ";"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 92) { result0 = "\\"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"\\\\\""); } } if (result0 === null) { result0 = parse_DQUOTE(); if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 91) { result0 = "["; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 93) { result0 = "]"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 123) { result0 = "{"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"{\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 125) { result0 = "}"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"}\""); } } if (result0 === null) { result0 = parse_SP(); if (result0 === null) { result0 = parse_HTAB(); } } } } } } } } } } } } } } } } } } return result0; } function parse_word() { var result0, result1; var pos0; pos0 = pos; result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 40) { result1 = "("; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 41) { result1 = ")"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\")\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 60) { result1 = "<"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"<\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 62) { result1 = ">"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\">\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 92) { result1 = "\\"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"\\\\\""); } } if (result1 === null) { result1 = parse_DQUOTE(); if (result1 === null) { if (input.charCodeAt(pos) === 47) { result1 = "/"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 91) { result1 = "["; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 93) { result1 = "]"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 63) { result1 = "?"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 123) { result1 = "{"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"{\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 125) { result1 = "}"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"}\""); } } } } } } } } } } } } } } } } } } } } } } } } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_alphanum(); if (result1 === null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 33) { result1 = "!"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 37) { result1 = "%"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"%\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 95) { result1 = "_"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"_\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 96) { result1 = "`"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"`\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 39) { result1 = "'"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"'\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 126) { result1 = "~"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"~\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 40) { result1 = "("; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 41) { result1 = ")"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\")\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 60) { result1 = "<"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"<\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 62) { result1 = ">"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\">\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 92) { result1 = "\\"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"\\\\\""); } } if (result1 === null) { result1 = parse_DQUOTE(); if (result1 === null) { if (input.charCodeAt(pos) === 47) { result1 = "/"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 91) { result1 = "["; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 93) { result1 = "]"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 63) { result1 = "?"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 123) { result1 = "{"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"{\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 125) { result1 = "}"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"}\""); } } } } } } } } } } } } } } } } } } } } } } } } } } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_STAR() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 42) { result1 = "*"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"*\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "*"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_SLASH() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 47) { result1 = "/"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "/"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_EQUAL() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "="; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_LPAREN() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 40) { result1 = "("; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"(\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "("; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_RPAREN() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 41) { result1 = ")"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\")\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ")"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_RAQUOT() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.charCodeAt(pos) === 62) { result0 = ">"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\">\""); } } if (result0 !== null) { result1 = parse_SWS(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ">"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_LAQUOT() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 60) { result1 = "<"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"<\""); } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "<"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_COMMA() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ","; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_SEMI() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ";"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_COLON() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_SWS(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return ":"; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_LDQUOT() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { result1 = parse_DQUOTE(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "\""; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_RDQUOT() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_DQUOTE(); if (result0 !== null) { result1 = parse_SWS(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) {return "\""; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_comment() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_LPAREN(); if (result0 !== null) { result1 = []; result2 = parse_ctext(); if (result2 === null) { result2 = parse_quoted_pair(); if (result2 === null) { result2 = parse_comment(); } } while (result2 !== null) { result1.push(result2); result2 = parse_ctext(); if (result2 === null) { result2 = parse_quoted_pair(); if (result2 === null) { result2 = parse_comment(); } } } if (result1 !== null) { result2 = parse_RPAREN(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_ctext() { var result0; if (/^[!-']/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[!-']"); } } if (result0 === null) { if (/^[*-[]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[*-[]"); } } if (result0 === null) { if (/^[\]-~]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\]-~]"); } } if (result0 === null) { result0 = parse_UTF8_NONASCII(); if (result0 === null) { result0 = parse_LWS(); } } } } return result0; } function parse_quoted_string() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { result1 = parse_DQUOTE(); if (result1 !== null) { result2 = []; result3 = parse_qdtext(); if (result3 === null) { result3 = parse_quoted_pair(); } while (result3 !== null) { result2.push(result3); result3 = parse_qdtext(); if (result3 === null) { result3 = parse_quoted_pair(); } } if (result2 !== null) { result3 = parse_DQUOTE(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_quoted_string_clean() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_SWS(); if (result0 !== null) { result1 = parse_DQUOTE(); if (result1 !== null) { result2 = []; result3 = parse_qdtext(); if (result3 === null) { result3 = parse_quoted_pair(); } while (result3 !== null) { result2.push(result3); result3 = parse_qdtext(); if (result3 === null) { result3 = parse_quoted_pair(); } } if (result2 !== null) { result3 = parse_DQUOTE(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { return input.substring(pos-1, offset+1); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_qdtext() { var result0; result0 = parse_LWS(); if (result0 === null) { if (input.charCodeAt(pos) === 33) { result0 = "!"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"!\""); } } if (result0 === null) { if (/^[#-[]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[#-[]"); } } if (result0 === null) { if (/^[\]-~]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[\\]-~]"); } } if (result0 === null) { result0 = parse_UTF8_NONASCII(); } } } } return result0; } function parse_quoted_pair() { var result0, result1; var pos0; pos0 = pos; if (input.charCodeAt(pos) === 92) { result0 = "\\"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"\\\\\""); } } if (result0 !== null) { if (/^[\0-\t]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[\\0-\\t]"); } } if (result1 === null) { if (/^[\x0B-\f]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[\\x0B-\\f]"); } } if (result1 === null) { if (/^[\x0E-]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[\\x0E-]"); } } } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_SIP_URI_noparams() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_uri_scheme(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_userinfo(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_hostport(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { try { data.uri = new URI(data.scheme, data.user, data.host, data.port); delete data.scheme; delete data.user; delete data.host; delete data.host_type; delete data.port; } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_SIP_URI() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_uri_scheme(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_userinfo(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_hostport(); if (result3 !== null) { result4 = parse_uri_parameters(); if (result4 !== null) { result5 = parse_headers(); result5 = result5 !== null ? result5 : ""; if (result5 !== null) { result0 = [result0, result1, result2, result3, result4, result5]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var header; try { data.uri = new URI(data.scheme, data.user, data.host, data.port, data.uri_params, data.uri_headers); delete data.scheme; delete data.user; delete data.host; delete data.host_type; delete data.port; delete data.uri_params; if (startRule === 'SIP_URI') { data = data.uri;} } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_uri_scheme() { var result0; var pos0; if (input.substr(pos, 3).toLowerCase() === "sip") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"sip\""); } } if (result0 === null) { pos0 = pos; if (input.substr(pos, 4).toLowerCase() === "sips") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"sips\""); } } if (result0 !== null) { result0 = (function(offset) { data.scheme = uri_scheme.toLowerCase(); })(pos0); } if (result0 === null) { pos = pos0; } } return result0; } function parse_userinfo() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_user(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_password(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { if (input.charCodeAt(pos) === 64) { result2 = "@"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.user = decodeURIComponent(input.substring(pos-1, offset));})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_user() { var result0, result1; result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { result1 = parse_user_unreserved(); } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { result1 = parse_user_unreserved(); } } } } else { result0 = null; } return result0; } function parse_user_unreserved() { var result0; if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 59) { result0 = ";"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } } } } } } } } return result0; } function parse_password() { var result0, result1; var pos0; pos0 = pos; result0 = []; result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { if (input.charCodeAt(pos) === 38) { result1 = "&"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 36) { result1 = "$"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } while (result1 !== null) { result0.push(result1); result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { if (input.charCodeAt(pos) === 38) { result1 = "&"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 36) { result1 = "$"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } } if (result0 !== null) { result0 = (function(offset) { data.password = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_hostport() { var result0, result1, result2; var pos0, pos1; pos0 = pos; result0 = parse_host(); if (result0 !== null) { pos1 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_port(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos1; } } else { result1 = null; pos = pos1; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_host() { var result0; var pos0; pos0 = pos; result0 = parse_IPv4address(); if (result0 === null) { result0 = parse_IPv6reference(); if (result0 === null) { result0 = parse_hostname(); } } if (result0 !== null) { result0 = (function(offset) { data.host = input.substring(pos, offset).toLowerCase(); return data.host; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_hostname() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = []; pos2 = pos; result1 = parse_domainlabel(); if (result1 !== null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } while (result1 !== null) { result0.push(result1); pos2 = pos; result1 = parse_domainlabel(); if (result1 !== null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } } if (result0 !== null) { result1 = parse_toplabel(); if (result1 !== null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.host_type = 'domain'; return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_domainlabel() { var result0, result1; if (/^[a-zA-Z0-9_\-]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z0-9_\\-]"); } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); if (/^[a-zA-Z0-9_\-]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z0-9_\\-]"); } } } } else { result0 = null; } return result0; } function parse_toplabel() { var result0, result1; if (/^[a-zA-Z0-9_\-]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z0-9_\\-]"); } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); if (/^[a-zA-Z0-9_\-]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[a-zA-Z0-9_\\-]"); } } } } else { result0 = null; } return result0; } function parse_IPv6reference() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.charCodeAt(pos) === 91) { result0 = "["; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result0 !== null) { result1 = parse_IPv6address(); if (result1 !== null) { if (input.charCodeAt(pos) === 93) { result2 = "]"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.host_type = 'IPv6'; return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_IPv6address() { var result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_h16(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { if (input.charCodeAt(pos) === 58) { result7 = ":"; pos++; } else { result7 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result7 !== null) { result8 = parse_h16(); if (result8 !== null) { if (input.charCodeAt(pos) === 58) { result9 = ":"; pos++; } else { result9 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result9 !== null) { result10 = parse_h16(); if (result10 !== null) { if (input.charCodeAt(pos) === 58) { result11 = ":"; pos++; } else { result11 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result11 !== null) { result12 = parse_ls32(); if (result12 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { if (input.charCodeAt(pos) === 58) { result8 = ":"; pos++; } else { result8 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result8 !== null) { result9 = parse_h16(); if (result9 !== null) { if (input.charCodeAt(pos) === 58) { result10 = ":"; pos++; } else { result10 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result10 !== null) { result11 = parse_ls32(); if (result11 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { if (input.charCodeAt(pos) === 58) { result8 = ":"; pos++; } else { result8 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result8 !== null) { result9 = parse_ls32(); if (result9 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_ls32(); if (result7 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_ls32(); if (result5 !== null) { result0 = [result0, result1, result2, result3, result4, result5]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_ls32(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_ls32(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; if (input.substr(pos, 2) === "::") { result0 = "::"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result0 !== null) { result1 = parse_h16(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { if (input.substr(pos, 2) === "::") { result1 = "::"; pos += 2; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { if (input.charCodeAt(pos) === 58) { result7 = ":"; pos++; } else { result7 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result7 !== null) { result8 = parse_h16(); if (result8 !== null) { if (input.charCodeAt(pos) === 58) { result9 = ":"; pos++; } else { result9 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result9 !== null) { result10 = parse_ls32(); if (result10 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { if (input.substr(pos, 2) === "::") { result2 = "::"; pos += 2; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { if (input.charCodeAt(pos) === 58) { result8 = ":"; pos++; } else { result8 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result8 !== null) { result9 = parse_ls32(); if (result9 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { if (input.substr(pos, 2) === "::") { result3 = "::"; pos += 2; } else { result3 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { if (input.charCodeAt(pos) === 58) { result7 = ":"; pos++; } else { result7 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result7 !== null) { result8 = parse_ls32(); if (result8 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos2; } } else { result3 = null; pos = pos2; } result3 = result3 !== null ? result3 : ""; if (result3 !== null) { if (input.substr(pos, 2) === "::") { result4 = "::"; pos += 2; } else { result4 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_ls32(); if (result7 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos2; } } else { result3 = null; pos = pos2; } result3 = result3 !== null ? result3 : ""; if (result3 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos2; } } else { result4 = null; pos = pos2; } result4 = result4 !== null ? result4 : ""; if (result4 !== null) { if (input.substr(pos, 2) === "::") { result5 = "::"; pos += 2; } else { result5 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result5 !== null) { result6 = parse_ls32(); if (result6 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos2; } } else { result3 = null; pos = pos2; } result3 = result3 !== null ? result3 : ""; if (result3 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos2; } } else { result4 = null; pos = pos2; } result4 = result4 !== null ? result4 : ""; if (result4 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } result5 = result5 !== null ? result5 : ""; if (result5 !== null) { if (input.substr(pos, 2) === "::") { result6 = "::"; pos += 2; } else { result6 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { pos1 = pos; result0 = parse_h16(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result2 = ":"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result2 !== null) { result3 = parse_h16(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } result2 = result2 !== null ? result2 : ""; if (result2 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result3 = ":"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result3 !== null) { result4 = parse_h16(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos2; } } else { result3 = null; pos = pos2; } result3 = result3 !== null ? result3 : ""; if (result3 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result4 = ":"; pos++; } else { result4 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result4 !== null) { result5 = parse_h16(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos2; } } else { result4 = null; pos = pos2; } result4 = result4 !== null ? result4 : ""; if (result4 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result5 = ":"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result5 !== null) { result6 = parse_h16(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } result5 = result5 !== null ? result5 : ""; if (result5 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 58) { result6 = ":"; pos++; } else { result6 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result6 !== null) { result7 = parse_h16(); if (result7 !== null) { result6 = [result6, result7]; } else { result6 = null; pos = pos2; } } else { result6 = null; pos = pos2; } result6 = result6 !== null ? result6 : ""; if (result6 !== null) { if (input.substr(pos, 2) === "::") { result7 = "::"; pos += 2; } else { result7 = null; if (reportFailures === 0) { matchFailed("\"::\""); } } if (result7 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } } } } } } } } } } } } } } if (result0 !== null) { result0 = (function(offset) { data.host_type = 'IPv6'; return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_h16() { var result0, result1, result2, result3; var pos0; pos0 = pos; result0 = parse_HEXDIG(); if (result0 !== null) { result1 = parse_HEXDIG(); result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result2 = parse_HEXDIG(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_HEXDIG(); result3 = result3 !== null ? result3 : ""; if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_ls32() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_h16(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_h16(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { result0 = parse_IPv4address(); } return result0; } function parse_IPv4address() { var result0, result1, result2, result3, result4, result5, result6; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_dec_octet(); if (result0 !== null) { if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 !== null) { result2 = parse_dec_octet(); if (result2 !== null) { if (input.charCodeAt(pos) === 46) { result3 = "."; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result3 !== null) { result4 = parse_dec_octet(); if (result4 !== null) { if (input.charCodeAt(pos) === 46) { result5 = "."; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result5 !== null) { result6 = parse_dec_octet(); if (result6 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.host_type = 'IPv4'; return input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_dec_octet() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 2) === "25") { result0 = "25"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"25\""); } } if (result0 !== null) { if (/^[0-5]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[0-5]"); } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { pos0 = pos; if (input.charCodeAt(pos) === 50) { result0 = "2"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"2\""); } } if (result0 !== null) { if (/^[0-4]/.test(input.charAt(pos))) { result1 = input.charAt(pos); pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("[0-4]"); } } if (result1 !== null) { result2 = parse_DIGIT(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { pos0 = pos; if (input.charCodeAt(pos) === 49) { result0 = "1"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"1\""); } } if (result0 !== null) { result1 = parse_DIGIT(); if (result1 !== null) { result2 = parse_DIGIT(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { pos0 = pos; if (/^[1-9]/.test(input.charAt(pos))) { result0 = input.charAt(pos); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("[1-9]"); } } if (result0 !== null) { result1 = parse_DIGIT(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { result0 = parse_DIGIT(); } } } } return result0; } function parse_port() { var result0, result1, result2, result3, result4; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_DIGIT(); result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result1 = parse_DIGIT(); result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result2 = parse_DIGIT(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_DIGIT(); result3 = result3 !== null ? result3 : ""; if (result3 !== null) { result4 = parse_DIGIT(); result4 = result4 !== null ? result4 : ""; if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, port) { port = parseInt(port.join('')); data.port = port; return port; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_uri_parameters() { var result0, result1, result2; var pos0; result0 = []; pos0 = pos; if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 !== null) { result2 = parse_uri_parameter(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos0; } } else { result1 = null; pos = pos0; } while (result1 !== null) { result0.push(result1); pos0 = pos; if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 !== null) { result2 = parse_uri_parameter(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos0; } } else { result1 = null; pos = pos0; } } return result0; } function parse_uri_parameter() { var result0; result0 = parse_transport_param(); if (result0 === null) { result0 = parse_user_param(); if (result0 === null) { result0 = parse_method_param(); if (result0 === null) { result0 = parse_ttl_param(); if (result0 === null) { result0 = parse_maddr_param(); if (result0 === null) { result0 = parse_lr_param(); if (result0 === null) { result0 = parse_other_param(); } } } } } } return result0; } function parse_transport_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 10).toLowerCase() === "transport=") { result0 = input.substr(pos, 10); pos += 10; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"transport=\""); } } if (result0 !== null) { if (input.substr(pos, 3).toLowerCase() === "udp") { result1 = input.substr(pos, 3); pos += 3; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"udp\""); } } if (result1 === null) { if (input.substr(pos, 3).toLowerCase() === "tcp") { result1 = input.substr(pos, 3); pos += 3; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"tcp\""); } } if (result1 === null) { if (input.substr(pos, 4).toLowerCase() === "sctp") { result1 = input.substr(pos, 4); pos += 4; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"sctp\""); } } if (result1 === null) { if (input.substr(pos, 3).toLowerCase() === "tls") { result1 = input.substr(pos, 3); pos += 3; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"tls\""); } } if (result1 === null) { result1 = parse_token(); } } } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, transport) { if(!data.uri_params) data.uri_params={}; data.uri_params['transport'] = transport.toLowerCase(); })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_user_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "user=") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"user=\""); } } if (result0 !== null) { if (input.substr(pos, 5).toLowerCase() === "phone") { result1 = input.substr(pos, 5); pos += 5; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"phone\""); } } if (result1 === null) { if (input.substr(pos, 2).toLowerCase() === "ip") { result1 = input.substr(pos, 2); pos += 2; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"ip\""); } } if (result1 === null) { result1 = parse_token(); } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, user) { if(!data.uri_params) data.uri_params={}; data.uri_params['user'] = user.toLowerCase(); })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_method_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 7).toLowerCase() === "method=") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"method=\""); } } if (result0 !== null) { result1 = parse_Method(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, method) { if(!data.uri_params) data.uri_params={}; data.uri_params['method'] = method; })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_ttl_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 4).toLowerCase() === "ttl=") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"ttl=\""); } } if (result0 !== null) { result1 = parse_ttl(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, ttl) { if(!data.params) data.params={}; data.params['ttl'] = ttl; })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_maddr_param() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6).toLowerCase() === "maddr=") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"maddr=\""); } } if (result0 !== null) { result1 = parse_host(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, maddr) { if(!data.uri_params) data.uri_params={}; data.uri_params['maddr'] = maddr; })(pos0, result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_lr_param() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; if (input.substr(pos, 2).toLowerCase() === "lr") { result0 = input.substr(pos, 2); pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"lr\""); } } if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { if(!data.uri_params) data.uri_params={}; data.uri_params['lr'] = undefined; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_other_param() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_pname(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 !== null) { result2 = parse_pvalue(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, param, value) { if(!data.uri_params) data.uri_params = {}; if (typeof value === 'undefined'){ value = undefined; } else { value = value[1]; } data.uri_params[param.toLowerCase()] = value && value.toLowerCase();})(pos0, result0[0], result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_pname() { var result0, result1; var pos0; pos0 = pos; result1 = parse_paramchar(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_paramchar(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, pname) {return pname.join(''); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_pvalue() { var result0, result1; var pos0; pos0 = pos; result1 = parse_paramchar(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_paramchar(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, pvalue) {return pvalue.join(''); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_paramchar() { var result0; result0 = parse_param_unreserved(); if (result0 === null) { result0 = parse_unreserved(); if (result0 === null) { result0 = parse_escaped(); } } return result0; } function parse_param_unreserved() { var result0; if (input.charCodeAt(pos) === 91) { result0 = "["; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 93) { result0 = "]"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } } } } } } } return result0; } function parse_headers() { var result0, result1, result2, result3, result4; var pos0, pos1; pos0 = pos; if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 !== null) { result1 = parse_header(); if (result1 !== null) { result2 = []; pos1 = pos; if (input.charCodeAt(pos) === 38) { result3 = "&"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result3 !== null) { result4 = parse_header(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos1; } } else { result3 = null; pos = pos1; } while (result3 !== null) { result2.push(result3); pos1 = pos; if (input.charCodeAt(pos) === 38) { result3 = "&"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result3 !== null) { result4 = parse_header(); if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos1; } } else { result3 = null; pos = pos1; } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_header() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_hname(); if (result0 !== null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 !== null) { result2 = parse_hvalue(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, hname, hvalue) { hname = hname.join('').toLowerCase(); hvalue = hvalue.join(''); if(!data.uri_headers) data.uri_headers = {}; if (!data.uri_headers[hname]) { data.uri_headers[hname] = [hvalue]; } else { data.uri_headers[hname].push(hvalue); }})(pos0, result0[0], result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_hname() { var result0, result1; result1 = parse_hnv_unreserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_hnv_unreserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); } } } } else { result0 = null; } return result0; } function parse_hvalue() { var result0, result1; result0 = []; result1 = parse_hnv_unreserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); } } while (result1 !== null) { result0.push(result1); result1 = parse_hnv_unreserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); } } } return result0; } function parse_hnv_unreserved() { var result0; if (input.charCodeAt(pos) === 91) { result0 = "["; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"[\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 93) { result0 = "]"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"]\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } } } } } } } return result0; } function parse_Request_Response() { var result0; result0 = parse_Status_Line(); if (result0 === null) { result0 = parse_Request_Line(); } return result0; } function parse_Request_Line() { var result0, result1, result2, result3, result4; var pos0; pos0 = pos; result0 = parse_Method(); if (result0 !== null) { result1 = parse_SP(); if (result1 !== null) { result2 = parse_Request_URI(); if (result2 !== null) { result3 = parse_SP(); if (result3 !== null) { result4 = parse_SIP_Version(); if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Request_URI() { var result0; result0 = parse_SIP_URI(); if (result0 === null) { result0 = parse_absoluteURI(); } return result0; } function parse_absoluteURI() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_scheme(); if (result0 !== null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 !== null) { result2 = parse_hier_part(); if (result2 === null) { result2 = parse_opaque_part(); } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_hier_part() { var result0, result1, result2; var pos0, pos1; pos0 = pos; result0 = parse_net_path(); if (result0 === null) { result0 = parse_abs_path(); } if (result0 !== null) { pos1 = pos; if (input.charCodeAt(pos) === 63) { result1 = "?"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result1 !== null) { result2 = parse_query(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos1; } } else { result1 = null; pos = pos1; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_net_path() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 2) === "//") { result0 = "//"; pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"//\""); } } if (result0 !== null) { result1 = parse_authority(); if (result1 !== null) { result2 = parse_abs_path(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_abs_path() { var result0, result1; var pos0; pos0 = pos; if (input.charCodeAt(pos) === 47) { result0 = "/"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result0 !== null) { result1 = parse_path_segments(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_opaque_part() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_uric_no_slash(); if (result0 !== null) { result1 = []; result2 = parse_uric(); while (result2 !== null) { result1.push(result2); result2 = parse_uric(); } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_uric() { var result0; result0 = parse_reserved(); if (result0 === null) { result0 = parse_unreserved(); if (result0 === null) { result0 = parse_escaped(); } } return result0; } function parse_uric_no_slash() { var result0; result0 = parse_unreserved(); if (result0 === null) { result0 = parse_escaped(); if (result0 === null) { if (input.charCodeAt(pos) === 59) { result0 = ";"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 63) { result0 = "?"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"?\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 64) { result0 = "@"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } } } } } return result0; } function parse_path_segments() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_segment(); if (result0 !== null) { result1 = []; pos1 = pos; if (input.charCodeAt(pos) === 47) { result2 = "/"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result2 !== null) { result3 = parse_segment(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; if (input.charCodeAt(pos) === 47) { result2 = "/"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result2 !== null) { result3 = parse_segment(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_segment() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = []; result1 = parse_pchar(); while (result1 !== null) { result0.push(result1); result1 = parse_pchar(); } if (result0 !== null) { result1 = []; pos1 = pos; if (input.charCodeAt(pos) === 59) { result2 = ";"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result2 !== null) { result3 = parse_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; if (input.charCodeAt(pos) === 59) { result2 = ";"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result2 !== null) { result3 = parse_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_param() { var result0, result1; result0 = []; result1 = parse_pchar(); while (result1 !== null) { result0.push(result1); result1 = parse_pchar(); } return result0; } function parse_pchar() { var result0; result0 = parse_unreserved(); if (result0 === null) { result0 = parse_escaped(); if (result0 === null) { if (input.charCodeAt(pos) === 58) { result0 = ":"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 64) { result0 = "@"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 38) { result0 = "&"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 61) { result0 = "="; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 43) { result0 = "+"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 36) { result0 = "$"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result0 === null) { if (input.charCodeAt(pos) === 44) { result0 = ","; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\",\""); } } } } } } } } } } return result0; } function parse_scheme() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_ALPHA(); if (result0 !== null) { result1 = []; result2 = parse_ALPHA(); if (result2 === null) { result2 = parse_DIGIT(); if (result2 === null) { if (input.charCodeAt(pos) === 43) { result2 = "+"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } } } } } while (result2 !== null) { result1.push(result2); result2 = parse_ALPHA(); if (result2 === null) { result2 = parse_DIGIT(); if (result2 === null) { if (input.charCodeAt(pos) === 43) { result2 = "+"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 45) { result2 = "-"; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result2 === null) { if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } } } } } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.scheme= input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_authority() { var result0; result0 = parse_srvr(); if (result0 === null) { result0 = parse_reg_name(); } return result0; } function parse_srvr() { var result0, result1; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_userinfo(); if (result0 !== null) { if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result1 = parse_hostport(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } result0 = result0 !== null ? result0 : ""; return result0; } function parse_reg_name() { var result0, result1; result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { if (input.charCodeAt(pos) === 36) { result1 = "$"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 38) { result1 = "&"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } } } } } } } } } } if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { if (input.charCodeAt(pos) === 36) { result1 = "$"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"$\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 44) { result1 = ","; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 59) { result1 = ";"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\";\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 58) { result1 = ":"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\":\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 38) { result1 = "&"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"&\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 61) { result1 = "="; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"=\""); } } if (result1 === null) { if (input.charCodeAt(pos) === 43) { result1 = "+"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"+\""); } } } } } } } } } } } } } else { result0 = null; } return result0; } function parse_query() { var result0, result1; result0 = []; result1 = parse_uric(); while (result1 !== null) { result0.push(result1); result1 = parse_uric(); } return result0; } function parse_SIP_Version() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 3).toLowerCase() === "sip") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SIP\""); } } if (result0 !== null) { if (input.charCodeAt(pos) === 47) { result1 = "/"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"/\""); } } if (result1 !== null) { result3 = parse_DIGIT(); if (result3 !== null) { result2 = []; while (result3 !== null) { result2.push(result3); result3 = parse_DIGIT(); } } else { result2 = null; } if (result2 !== null) { if (input.charCodeAt(pos) === 46) { result3 = "."; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result3 !== null) { result5 = parse_DIGIT(); if (result5 !== null) { result4 = []; while (result5 !== null) { result4.push(result5); result5 = parse_DIGIT(); } } else { result4 = null; } if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data.sip_version = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_INVITEm() { var result0; if (input.substr(pos, 6) === "INVITE") { result0 = "INVITE"; pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"INVITE\""); } } return result0; } function parse_ACKm() { var result0; if (input.substr(pos, 3) === "ACK") { result0 = "ACK"; pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"ACK\""); } } return result0; } function parse_OPTIONSm() { var result0; if (input.substr(pos, 7) === "OPTIONS") { result0 = "OPTIONS"; pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"OPTIONS\""); } } return result0; } function parse_BYEm() { var result0; if (input.substr(pos, 3) === "BYE") { result0 = "BYE"; pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"BYE\""); } } return result0; } function parse_CANCELm() { var result0; if (input.substr(pos, 6) === "CANCEL") { result0 = "CANCEL"; pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"CANCEL\""); } } return result0; } function parse_REGISTERm() { var result0; if (input.substr(pos, 8) === "REGISTER") { result0 = "REGISTER"; pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"REGISTER\""); } } return result0; } function parse_SUBSCRIBEm() { var result0; if (input.substr(pos, 9) === "SUBSCRIBE") { result0 = "SUBSCRIBE"; pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SUBSCRIBE\""); } } return result0; } function parse_NOTIFYm() { var result0; if (input.substr(pos, 6) === "NOTIFY") { result0 = "NOTIFY"; pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"NOTIFY\""); } } return result0; } function parse_Method() { var result0; var pos0; pos0 = pos; result0 = parse_INVITEm(); if (result0 === null) { result0 = parse_ACKm(); if (result0 === null) { result0 = parse_OPTIONSm(); if (result0 === null) { result0 = parse_BYEm(); if (result0 === null) { result0 = parse_CANCELm(); if (result0 === null) { result0 = parse_REGISTERm(); if (result0 === null) { result0 = parse_SUBSCRIBEm(); if (result0 === null) { result0 = parse_NOTIFYm(); if (result0 === null) { result0 = parse_token(); } } } } } } } } if (result0 !== null) { result0 = (function(offset) { data.method = input.substring(pos, offset); return data.method; })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Status_Line() { var result0, result1, result2, result3, result4; var pos0; pos0 = pos; result0 = parse_SIP_Version(); if (result0 !== null) { result1 = parse_SP(); if (result1 !== null) { result2 = parse_Status_Code(); if (result2 !== null) { result3 = parse_SP(); if (result3 !== null) { result4 = parse_Reason_Phrase(); if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Status_Code() { var result0; var pos0; pos0 = pos; result0 = parse_extension_code(); if (result0 !== null) { result0 = (function(offset, status_code) { data.status_code = parseInt(status_code.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_extension_code() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_DIGIT(); if (result0 !== null) { result1 = parse_DIGIT(); if (result1 !== null) { result2 = parse_DIGIT(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Reason_Phrase() { var result0, result1; var pos0; pos0 = pos; result0 = []; result1 = parse_reserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { result1 = parse_UTF8_NONASCII(); if (result1 === null) { result1 = parse_UTF8_CONT(); if (result1 === null) { result1 = parse_SP(); if (result1 === null) { result1 = parse_HTAB(); } } } } } } while (result1 !== null) { result0.push(result1); result1 = parse_reserved(); if (result1 === null) { result1 = parse_unreserved(); if (result1 === null) { result1 = parse_escaped(); if (result1 === null) { result1 = parse_UTF8_NONASCII(); if (result1 === null) { result1 = parse_UTF8_CONT(); if (result1 === null) { result1 = parse_SP(); if (result1 === null) { result1 = parse_HTAB(); } } } } } } } if (result0 !== null) { result0 = (function(offset) { data.reason_phrase = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Allow_Events() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_event_type(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_event_type(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_event_type(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Call_ID() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_word(); if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 64) { result1 = "@"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"@\""); } } if (result1 !== null) { result2 = parse_word(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { data = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Contact() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; result0 = parse_STAR(); if (result0 === null) { pos1 = pos; result0 = parse_contact_param(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_contact_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_contact_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } if (result0 !== null) { result0 = (function(offset) { var idx, length; length = data.multi_header.length; for (idx = 0; idx < length; idx++) { if (data.multi_header[idx].parsed === null) { data = null; break; } } if (data !== null) { data = data.multi_header; } else { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_contact_param() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_SIP_URI_noparams(); if (result0 === null) { result0 = parse_name_addr(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_contact_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_contact_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var header; if(!data.multi_header) data.multi_header = []; try { header = new NameAddrHeader(data.uri, data.display_name, data.params); delete data.uri; delete data.display_name; delete data.params; } catch(e) { header = null; } data.multi_header.push( { 'possition': pos, 'offset': offset, 'parsed': header });})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_name_addr() { var result0, result1, result2, result3; var pos0; pos0 = pos; result0 = parse_display_name(); result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result1 = parse_LAQUOT(); if (result1 !== null) { result2 = parse_SIP_URI(); if (result2 !== null) { result3 = parse_RAQUOT(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_display_name() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_LWS(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_LWS(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 === null) { result0 = parse_quoted_string(); } if (result0 !== null) { result0 = (function(offset, display_name) { display_name = input.substring(pos, offset).trim(); if (display_name[0] === '\"') { display_name = display_name.substring(1, display_name.length-1); } data.display_name = display_name; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_contact_params() { var result0; result0 = parse_c_p_q(); if (result0 === null) { result0 = parse_c_p_expires(); if (result0 === null) { result0 = parse_generic_param(); } } return result0; } function parse_c_p_q() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 1).toLowerCase() === "q") { result0 = input.substr(pos, 1); pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"q\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_qvalue(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, q) { if(!data.params) data.params = {}; data.params['q'] = q; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_c_p_expires() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 7).toLowerCase() === "expires") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"expires\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_delta_seconds(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, expires) { if(!data.params) data.params = {}; data.params['expires'] = expires; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_delta_seconds() { var result0, result1; var pos0; pos0 = pos; result1 = parse_DIGIT(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_DIGIT(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, delta_seconds) { return parseInt(delta_seconds.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_qvalue() { var result0, result1, result2, result3, result4; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; if (input.charCodeAt(pos) === 48) { result0 = "0"; pos++; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"0\""); } } if (result0 !== null) { pos2 = pos; if (input.charCodeAt(pos) === 46) { result1 = "."; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result1 !== null) { result2 = parse_DIGIT(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_DIGIT(); result3 = result3 !== null ? result3 : ""; if (result3 !== null) { result4 = parse_DIGIT(); result4 = result4 !== null ? result4 : ""; if (result4 !== null) { result1 = [result1, result2, result3, result4]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { return parseFloat(input.substring(pos, offset)); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_generic_param() { var result0, result1, result2; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_token(); if (result0 !== null) { pos2 = pos; result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_gen_value(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, param, value) { if(!data.params) data.params = {}; if (typeof value === 'undefined'){ value = undefined; } else { value = value[1]; } data.params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]); } if (result0 === null) { pos = pos0; } return result0; } function parse_gen_value() { var result0; result0 = parse_token(); if (result0 === null) { result0 = parse_host(); if (result0 === null) { result0 = parse_quoted_string(); } } return result0; } function parse_Content_Disposition() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_disp_type(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_disp_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_disp_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_disp_type() { var result0; if (input.substr(pos, 6).toLowerCase() === "render") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"render\""); } } if (result0 === null) { if (input.substr(pos, 7).toLowerCase() === "session") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"session\""); } } if (result0 === null) { if (input.substr(pos, 4).toLowerCase() === "icon") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"icon\""); } } if (result0 === null) { if (input.substr(pos, 5).toLowerCase() === "alert") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"alert\""); } } if (result0 === null) { result0 = parse_token(); } } } } return result0; } function parse_disp_param() { var result0; result0 = parse_handling_param(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_handling_param() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 8).toLowerCase() === "handling") { result0 = input.substr(pos, 8); pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"handling\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { if (input.substr(pos, 8).toLowerCase() === "optional") { result2 = input.substr(pos, 8); pos += 8; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"optional\""); } } if (result2 === null) { if (input.substr(pos, 8).toLowerCase() === "required") { result2 = input.substr(pos, 8); pos += 8; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"required\""); } } if (result2 === null) { result2 = parse_token(); } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Content_Encoding() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Content_Length() { var result0, result1; var pos0; pos0 = pos; result1 = parse_DIGIT(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_DIGIT(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, length) { data = parseInt(length.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Content_Type() { var result0; var pos0; pos0 = pos; result0 = parse_media_type(); if (result0 !== null) { result0 = (function(offset) { data = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_media_type() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; result0 = parse_m_type(); if (result0 !== null) { result1 = parse_SLASH(); if (result1 !== null) { result2 = parse_m_subtype(); if (result2 !== null) { result3 = []; pos1 = pos; result4 = parse_SEMI(); if (result4 !== null) { result5 = parse_m_parameter(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } while (result4 !== null) { result3.push(result4); pos1 = pos; result4 = parse_SEMI(); if (result4 !== null) { result5 = parse_m_parameter(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } } if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_m_type() { var result0; result0 = parse_discrete_type(); if (result0 === null) { result0 = parse_composite_type(); } return result0; } function parse_discrete_type() { var result0; if (input.substr(pos, 4).toLowerCase() === "text") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"text\""); } } if (result0 === null) { if (input.substr(pos, 5).toLowerCase() === "image") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"image\""); } } if (result0 === null) { if (input.substr(pos, 5).toLowerCase() === "audio") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"audio\""); } } if (result0 === null) { if (input.substr(pos, 5).toLowerCase() === "video") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"video\""); } } if (result0 === null) { if (input.substr(pos, 11).toLowerCase() === "application") { result0 = input.substr(pos, 11); pos += 11; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"application\""); } } if (result0 === null) { result0 = parse_extension_token(); } } } } } return result0; } function parse_composite_type() { var result0; if (input.substr(pos, 7).toLowerCase() === "message") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"message\""); } } if (result0 === null) { if (input.substr(pos, 9).toLowerCase() === "multipart") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"multipart\""); } } if (result0 === null) { result0 = parse_extension_token(); } } return result0; } function parse_extension_token() { var result0; result0 = parse_token(); if (result0 === null) { result0 = parse_x_token(); } return result0; } function parse_x_token() { var result0, result1; var pos0; pos0 = pos; if (input.substr(pos, 2).toLowerCase() === "x-") { result0 = input.substr(pos, 2); pos += 2; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"x-\""); } } if (result0 !== null) { result1 = parse_token(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_m_subtype() { var result0; result0 = parse_extension_token(); if (result0 === null) { result0 = parse_token(); } return result0; } function parse_m_parameter() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_m_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_m_value() { var result0; result0 = parse_token(); if (result0 === null) { result0 = parse_quoted_string(); } return result0; } function parse_CSeq() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_CSeq_value(); if (result0 !== null) { result1 = parse_LWS(); if (result1 !== null) { result2 = parse_Method(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_CSeq_value() { var result0, result1; var pos0; pos0 = pos; result1 = parse_DIGIT(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_DIGIT(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, cseq_value) { data.value=parseInt(cseq_value.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Expires() { var result0; var pos0; pos0 = pos; result0 = parse_delta_seconds(); if (result0 !== null) { result0 = (function(offset, expires) {data = expires; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Event() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_event_type(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, event_type) { data.event = event_type.join('').toLowerCase(); })(pos0, result0[0]); } if (result0 === null) { pos = pos0; } return result0; } function parse_event_type() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token_nodot(); if (result0 !== null) { result1 = []; pos1 = pos; if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result2 !== null) { result3 = parse_token_nodot(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; if (input.charCodeAt(pos) === 46) { result2 = "."; pos++; } else { result2 = null; if (reportFailures === 0) { matchFailed("\".\""); } } if (result2 !== null) { result3 = parse_token_nodot(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_From() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_SIP_URI_noparams(); if (result0 === null) { result0 = parse_name_addr(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_from_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_from_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var tag = data.tag; try { data = new NameAddrHeader(data.uri, data.display_name, data.params); if (tag) {data.setParam('tag',tag)} } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_from_param() { var result0; result0 = parse_tag_param(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_tag_param() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 3).toLowerCase() === "tag") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"tag\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, tag) {data.tag = tag; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_Max_Forwards() { var result0, result1; var pos0; pos0 = pos; result1 = parse_DIGIT(); if (result1 !== null) { result0 = []; while (result1 !== null) { result0.push(result1); result1 = parse_DIGIT(); } } else { result0 = null; } if (result0 !== null) { result0 = (function(offset, forwards) { data = parseInt(forwards.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Min_Expires() { var result0; var pos0; pos0 = pos; result0 = parse_delta_seconds(); if (result0 !== null) { result0 = (function(offset, min_expires) {data = min_expires; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Name_Addr_Header() { var result0, result1, result2, result3, result4, result5, result6; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = []; result1 = parse_display_name(); while (result1 !== null) { result0.push(result1); result1 = parse_display_name(); } if (result0 !== null) { result1 = parse_LAQUOT(); if (result1 !== null) { result2 = parse_SIP_URI(); if (result2 !== null) { result3 = parse_RAQUOT(); if (result3 !== null) { result4 = []; pos2 = pos; result5 = parse_SEMI(); if (result5 !== null) { result6 = parse_generic_param(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } while (result5 !== null) { result4.push(result5); pos2 = pos; result5 = parse_SEMI(); if (result5 !== null) { result6 = parse_generic_param(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } } if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { try { data = new NameAddrHeader(data.uri, data.display_name, data.params); } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Proxy_Authenticate() { var result0; result0 = parse_challenge(); return result0; } function parse_challenge() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; if (input.substr(pos, 6).toLowerCase() === "digest") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"Digest\""); } } if (result0 !== null) { result1 = parse_LWS(); if (result1 !== null) { result2 = parse_digest_cln(); if (result2 !== null) { result3 = []; pos1 = pos; result4 = parse_COMMA(); if (result4 !== null) { result5 = parse_digest_cln(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } while (result4 !== null) { result3.push(result4); pos1 = pos; result4 = parse_COMMA(); if (result4 !== null) { result5 = parse_digest_cln(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } } if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } if (result0 === null) { result0 = parse_other_challenge(); } return result0; } function parse_other_challenge() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = parse_LWS(); if (result1 !== null) { result2 = parse_auth_param(); if (result2 !== null) { result3 = []; pos1 = pos; result4 = parse_COMMA(); if (result4 !== null) { result5 = parse_auth_param(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } while (result4 !== null) { result3.push(result4); pos1 = pos; result4 = parse_COMMA(); if (result4 !== null) { result5 = parse_auth_param(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } } if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_auth_param() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_token(); if (result2 === null) { result2 = parse_quoted_string(); } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_digest_cln() { var result0; result0 = parse_realm(); if (result0 === null) { result0 = parse_domain(); if (result0 === null) { result0 = parse_nonce(); if (result0 === null) { result0 = parse_opaque(); if (result0 === null) { result0 = parse_stale(); if (result0 === null) { result0 = parse_algorithm(); if (result0 === null) { result0 = parse_qop_options(); if (result0 === null) { result0 = parse_auth_param(); } } } } } } } return result0; } function parse_realm() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 5).toLowerCase() === "realm") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"realm\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_realm_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_realm_value() { var result0; var pos0; pos0 = pos; result0 = parse_quoted_string_clean(); if (result0 !== null) { result0 = (function(offset, realm) { data.realm = realm; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_domain() { var result0, result1, result2, result3, result4, result5, result6; var pos0, pos1; pos0 = pos; if (input.substr(pos, 6).toLowerCase() === "domain") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"domain\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_LDQUOT(); if (result2 !== null) { result3 = parse_URI(); if (result3 !== null) { result4 = []; pos1 = pos; result6 = parse_SP(); if (result6 !== null) { result5 = []; while (result6 !== null) { result5.push(result6); result6 = parse_SP(); } } else { result5 = null; } if (result5 !== null) { result6 = parse_URI(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos1; } } else { result5 = null; pos = pos1; } while (result5 !== null) { result4.push(result5); pos1 = pos; result6 = parse_SP(); if (result6 !== null) { result5 = []; while (result6 !== null) { result5.push(result6); result6 = parse_SP(); } } else { result5 = null; } if (result5 !== null) { result6 = parse_URI(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos1; } } else { result5 = null; pos = pos1; } } if (result4 !== null) { result5 = parse_RDQUOT(); if (result5 !== null) { result0 = [result0, result1, result2, result3, result4, result5]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_URI() { var result0; result0 = parse_absoluteURI(); if (result0 === null) { result0 = parse_abs_path(); } return result0; } function parse_nonce() { var result0, result1, result2; var pos0; pos0 = pos; if (input.substr(pos, 5).toLowerCase() === "nonce") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"nonce\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_nonce_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_nonce_value() { var result0; var pos0; pos0 = pos; result0 = parse_quoted_string_clean(); if (result0 !== null) { result0 = (function(offset, nonce) { data.nonce=nonce; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_opaque() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6).toLowerCase() === "opaque") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"opaque\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_quoted_string_clean(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, opaque) { data.opaque=opaque; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_stale() { var result0, result1, result2; var pos0, pos1; pos0 = pos; if (input.substr(pos, 5).toLowerCase() === "stale") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"stale\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { pos1 = pos; if (input.substr(pos, 4).toLowerCase() === "true") { result2 = input.substr(pos, 4); pos += 4; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"true\""); } } if (result2 !== null) { result2 = (function(offset) { data.stale=true; })(pos1); } if (result2 === null) { pos = pos1; } if (result2 === null) { pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "false") { result2 = input.substr(pos, 5); pos += 5; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"false\""); } } if (result2 !== null) { result2 = (function(offset) { data.stale=false; })(pos1); } if (result2 === null) { pos = pos1; } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_algorithm() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 9).toLowerCase() === "algorithm") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"algorithm\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { if (input.substr(pos, 3).toLowerCase() === "md5") { result2 = input.substr(pos, 3); pos += 3; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"MD5\""); } } if (result2 === null) { if (input.substr(pos, 8).toLowerCase() === "md5-sess") { result2 = input.substr(pos, 8); pos += 8; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"MD5-sess\""); } } if (result2 === null) { result2 = parse_token(); } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, algorithm) { data.algorithm=algorithm.toUpperCase(); })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_qop_options() { var result0, result1, result2, result3, result4, result5, result6; var pos0, pos1, pos2; pos0 = pos; if (input.substr(pos, 3).toLowerCase() === "qop") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"qop\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_LDQUOT(); if (result2 !== null) { pos1 = pos; result3 = parse_qop_value(); if (result3 !== null) { result4 = []; pos2 = pos; if (input.charCodeAt(pos) === 44) { result5 = ","; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result5 !== null) { result6 = parse_qop_value(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } while (result5 !== null) { result4.push(result5); pos2 = pos; if (input.charCodeAt(pos) === 44) { result5 = ","; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\",\""); } } if (result5 !== null) { result6 = parse_qop_value(); if (result6 !== null) { result5 = [result5, result6]; } else { result5 = null; pos = pos2; } } else { result5 = null; pos = pos2; } } if (result4 !== null) { result3 = [result3, result4]; } else { result3 = null; pos = pos1; } } else { result3 = null; pos = pos1; } if (result3 !== null) { result4 = parse_RDQUOT(); if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_qop_value() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 8).toLowerCase() === "auth-int") { result0 = input.substr(pos, 8); pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"auth-int\""); } } if (result0 === null) { if (input.substr(pos, 4).toLowerCase() === "auth") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"auth\""); } } if (result0 === null) { result0 = parse_token(); } } if (result0 !== null) { result0 = (function(offset, qop_value) { data.qop || (data.qop=[]); data.qop.push(qop_value.toLowerCase()); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Proxy_Require() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Record_Route() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_rec_route(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_rec_route(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_rec_route(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var idx, length; length = data.multi_header.length; for (idx = 0; idx < length; idx++) { if (data.multi_header[idx].parsed === null) { data = null; break; } } if (data !== null) { data = data.multi_header; } else { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_rec_route() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_name_addr(); if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var header; if(!data.multi_header) data.multi_header = []; try { header = new NameAddrHeader(data.uri, data.display_name, data.params); delete data.uri; delete data.display_name; delete data.params; } catch(e) { header = null; } data.multi_header.push( { 'possition': pos, 'offset': offset, 'parsed': header });})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_Reason() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; if (input.substr(pos, 3).toLowerCase() === "sip") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SIP\""); } } if (result0 === null) { result0 = parse_token(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_reason_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_reason_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, protocol) { data.protocol = protocol.toLowerCase(); if (!data.params) data.params = {}; if (data.params.text && data.params.text[0] === '"') { var text = data.params.text; data.text = text.substring(1, text.length-1); delete data.params.text; } })(pos0, result0[0]); } if (result0 === null) { pos = pos0; } return result0; } function parse_reason_param() { var result0; result0 = parse_reason_cause(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_reason_cause() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "cause") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"cause\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result3 = parse_DIGIT(); if (result3 !== null) { result2 = []; while (result3 !== null) { result2.push(result3); result3 = parse_DIGIT(); } } else { result2 = null; } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, cause) { data.cause = parseInt(cause.join('')); })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_Require() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Route() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_route_param(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_route_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_route_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_route_param() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_name_addr(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_generic_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_Subscription_State() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_substate_value(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_subexp_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_subexp_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_substate_value() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 6).toLowerCase() === "active") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"active\""); } } if (result0 === null) { if (input.substr(pos, 7).toLowerCase() === "pending") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"pending\""); } } if (result0 === null) { if (input.substr(pos, 10).toLowerCase() === "terminated") { result0 = input.substr(pos, 10); pos += 10; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"terminated\""); } } if (result0 === null) { result0 = parse_token(); } } } if (result0 !== null) { result0 = (function(offset) { data.state = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_subexp_params() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6).toLowerCase() === "reason") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"reason\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_event_reason_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, reason) { if (typeof reason !== 'undefined') data.reason = reason; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } if (result0 === null) { pos0 = pos; pos1 = pos; if (input.substr(pos, 7).toLowerCase() === "expires") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"expires\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_delta_seconds(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, expires) { if (typeof expires !== 'undefined') data.expires = expires; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } if (result0 === null) { pos0 = pos; pos1 = pos; if (input.substr(pos, 11).toLowerCase() === "retry_after") { result0 = input.substr(pos, 11); pos += 11; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"retry_after\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_delta_seconds(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, retry_after) { if (typeof retry_after !== 'undefined') data.retry_after = retry_after; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } if (result0 === null) { result0 = parse_generic_param(); } } } return result0; } function parse_event_reason_value() { var result0; if (input.substr(pos, 11).toLowerCase() === "deactivated") { result0 = input.substr(pos, 11); pos += 11; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"deactivated\""); } } if (result0 === null) { if (input.substr(pos, 9).toLowerCase() === "probation") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"probation\""); } } if (result0 === null) { if (input.substr(pos, 8).toLowerCase() === "rejected") { result0 = input.substr(pos, 8); pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"rejected\""); } } if (result0 === null) { if (input.substr(pos, 7).toLowerCase() === "timeout") { result0 = input.substr(pos, 7); pos += 7; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"timeout\""); } } if (result0 === null) { if (input.substr(pos, 6).toLowerCase() === "giveup") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"giveup\""); } } if (result0 === null) { if (input.substr(pos, 10).toLowerCase() === "noresource") { result0 = input.substr(pos, 10); pos += 10; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"noresource\""); } } if (result0 === null) { if (input.substr(pos, 9).toLowerCase() === "invariant") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"invariant\""); } } if (result0 === null) { result0 = parse_token(); } } } } } } } return result0; } function parse_Subject() { var result0; result0 = parse_TEXT_UTF8_TRIM(); result0 = result0 !== null ? result0 : ""; return result0; } function parse_Supported() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_token(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } result0 = result0 !== null ? result0 : ""; return result0; } function parse_To() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; result0 = parse_SIP_URI_noparams(); if (result0 === null) { result0 = parse_name_addr(); } if (result0 !== null) { result1 = []; pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_to_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } while (result2 !== null) { result1.push(result2); pos2 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_to_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos2; } } else { result2 = null; pos = pos2; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { var tag = data.tag; try { data = new NameAddrHeader(data.uri, data.display_name, data.params); if (tag) {data.setParam('tag',tag)} } catch(e) { data = -1; }})(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_to_param() { var result0; result0 = parse_tag_param(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_Via() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_via_param(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_via_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_COMMA(); if (result2 !== null) { result3 = parse_via_param(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_via_param() { var result0, result1, result2, result3, result4, result5; var pos0, pos1; pos0 = pos; result0 = parse_sent_protocol(); if (result0 !== null) { result1 = parse_LWS(); if (result1 !== null) { result2 = parse_sent_by(); if (result2 !== null) { result3 = []; pos1 = pos; result4 = parse_SEMI(); if (result4 !== null) { result5 = parse_via_params(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } while (result4 !== null) { result3.push(result4); pos1 = pos; result4 = parse_SEMI(); if (result4 !== null) { result5 = parse_via_params(); if (result5 !== null) { result4 = [result4, result5]; } else { result4 = null; pos = pos1; } } else { result4 = null; pos = pos1; } } if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_via_params() { var result0; result0 = parse_via_ttl(); if (result0 === null) { result0 = parse_via_maddr(); if (result0 === null) { result0 = parse_via_received(); if (result0 === null) { result0 = parse_via_branch(); if (result0 === null) { result0 = parse_response_port(); if (result0 === null) { result0 = parse_generic_param(); } } } } } return result0; } function parse_via_ttl() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 3).toLowerCase() === "ttl") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"ttl\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_ttl(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_ttl_value) { data.ttl = via_ttl_value; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_via_maddr() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "maddr") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"maddr\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_host(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_maddr) { data.maddr = via_maddr; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_via_received() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 8).toLowerCase() === "received") { result0 = input.substr(pos, 8); pos += 8; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"received\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_IPv4address(); if (result2 === null) { result2 = parse_IPv6address(); } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_received) { data.received = via_received; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_via_branch() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 6).toLowerCase() === "branch") { result0 = input.substr(pos, 6); pos += 6; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"branch\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_branch) { data.branch = via_branch; })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_response_port() { var result0, result1, result2, result3; var pos0, pos1, pos2; pos0 = pos; pos1 = pos; if (input.substr(pos, 5).toLowerCase() === "rport") { result0 = input.substr(pos, 5); pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"rport\""); } } if (result0 !== null) { pos2 = pos; result1 = parse_EQUAL(); if (result1 !== null) { result2 = []; result3 = parse_DIGIT(); while (result3 !== null) { result2.push(result3); result3 = parse_DIGIT(); } if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos2; } } else { result1 = null; pos = pos2; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset) { if(typeof response_port !== 'undefined') data.rport = response_port.join(''); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_sent_protocol() { var result0, result1, result2, result3, result4; var pos0; pos0 = pos; result0 = parse_protocol_name(); if (result0 !== null) { result1 = parse_SLASH(); if (result1 !== null) { result2 = parse_token(); if (result2 !== null) { result3 = parse_SLASH(); if (result3 !== null) { result4 = parse_transport(); if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_protocol_name() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 3).toLowerCase() === "sip") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SIP\""); } } if (result0 === null) { result0 = parse_token(); } if (result0 !== null) { result0 = (function(offset, via_protocol) { data.protocol = via_protocol; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_transport() { var result0; var pos0; pos0 = pos; if (input.substr(pos, 3).toLowerCase() === "udp") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"UDP\""); } } if (result0 === null) { if (input.substr(pos, 3).toLowerCase() === "tcp") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"TCP\""); } } if (result0 === null) { if (input.substr(pos, 3).toLowerCase() === "tls") { result0 = input.substr(pos, 3); pos += 3; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"TLS\""); } } if (result0 === null) { if (input.substr(pos, 4).toLowerCase() === "sctp") { result0 = input.substr(pos, 4); pos += 4; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"SCTP\""); } } if (result0 === null) { result0 = parse_token(); } } } } if (result0 !== null) { result0 = (function(offset, via_transport) { data.transport = via_transport; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_sent_by() { var result0, result1, result2; var pos0, pos1; pos0 = pos; result0 = parse_via_host(); if (result0 !== null) { pos1 = pos; result1 = parse_COLON(); if (result1 !== null) { result2 = parse_via_port(); if (result2 !== null) { result1 = [result1, result2]; } else { result1 = null; pos = pos1; } } else { result1 = null; pos = pos1; } result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_via_host() { var result0; var pos0; pos0 = pos; result0 = parse_IPv4address(); if (result0 === null) { result0 = parse_IPv6reference(); if (result0 === null) { result0 = parse_hostname(); } } if (result0 !== null) { result0 = (function(offset) { data.host = input.substring(pos, offset); })(pos0); } if (result0 === null) { pos = pos0; } return result0; } function parse_via_port() { var result0, result1, result2, result3, result4; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_DIGIT(); result0 = result0 !== null ? result0 : ""; if (result0 !== null) { result1 = parse_DIGIT(); result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result2 = parse_DIGIT(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result3 = parse_DIGIT(); result3 = result3 !== null ? result3 : ""; if (result3 !== null) { result4 = parse_DIGIT(); result4 = result4 !== null ? result4 : ""; if (result4 !== null) { result0 = [result0, result1, result2, result3, result4]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, via_sent_by_port) { data.port = parseInt(via_sent_by_port.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_ttl() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_DIGIT(); if (result0 !== null) { result1 = parse_DIGIT(); result1 = result1 !== null ? result1 : ""; if (result1 !== null) { result2 = parse_DIGIT(); result2 = result2 !== null ? result2 : ""; if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, ttl) { return parseInt(ttl.join('')); })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_WWW_Authenticate() { var result0; result0 = parse_challenge(); return result0; } function parse_Session_Expires() { var result0, result1, result2, result3; var pos0, pos1; pos0 = pos; result0 = parse_s_e_expires(); if (result0 !== null) { result1 = []; pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_s_e_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } while (result2 !== null) { result1.push(result2); pos1 = pos; result2 = parse_SEMI(); if (result2 !== null) { result3 = parse_s_e_params(); if (result3 !== null) { result2 = [result2, result3]; } else { result2 = null; pos = pos1; } } else { result2 = null; pos = pos1; } } if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_s_e_expires() { var result0; var pos0; pos0 = pos; result0 = parse_delta_seconds(); if (result0 !== null) { result0 = (function(offset, expires) { data.expires = expires; })(pos0, result0); } if (result0 === null) { pos = pos0; } return result0; } function parse_s_e_params() { var result0; result0 = parse_s_e_refresher(); if (result0 === null) { result0 = parse_generic_param(); } return result0; } function parse_s_e_refresher() { var result0, result1, result2; var pos0, pos1; pos0 = pos; pos1 = pos; if (input.substr(pos, 9).toLowerCase() === "refresher") { result0 = input.substr(pos, 9); pos += 9; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"refresher\""); } } if (result0 !== null) { result1 = parse_EQUAL(); if (result1 !== null) { if (input.substr(pos, 3).toLowerCase() === "uac") { result2 = input.substr(pos, 3); pos += 3; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"uac\""); } } if (result2 === null) { if (input.substr(pos, 3).toLowerCase() === "uas") { result2 = input.substr(pos, 3); pos += 3; } else { result2 = null; if (reportFailures === 0) { matchFailed("\"uas\""); } } } if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, s_e_refresher_value) { data.refresher = s_e_refresher_value.toLowerCase(); })(pos0, result0[2]); } if (result0 === null) { pos = pos0; } return result0; } function parse_extension_header() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_token(); if (result0 !== null) { result1 = parse_HCOLON(); if (result1 !== null) { result2 = parse_header_value(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_header_value() { var result0, result1; result0 = []; result1 = parse_TEXT_UTF8char(); if (result1 === null) { result1 = parse_UTF8_CONT(); if (result1 === null) { result1 = parse_LWS(); } } while (result1 !== null) { result0.push(result1); result1 = parse_TEXT_UTF8char(); if (result1 === null) { result1 = parse_UTF8_CONT(); if (result1 === null) { result1 = parse_LWS(); } } } return result0; } function parse_message_body() { var result0, result1; result0 = []; result1 = parse_OCTET(); while (result1 !== null) { result0.push(result1); result1 = parse_OCTET(); } return result0; } function parse_uuid_URI() { var result0, result1; var pos0; pos0 = pos; if (input.substr(pos, 5) === "uuid:") { result0 = "uuid:"; pos += 5; } else { result0 = null; if (reportFailures === 0) { matchFailed("\"uuid:\""); } } if (result0 !== null) { result1 = parse_uuid(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_uuid() { var result0, result1, result2, result3, result4, result5, result6, result7, result8; var pos0, pos1; pos0 = pos; pos1 = pos; result0 = parse_hex8(); if (result0 !== null) { if (input.charCodeAt(pos) === 45) { result1 = "-"; pos++; } else { result1 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result1 !== null) { result2 = parse_hex4(); if (result2 !== null) { if (input.charCodeAt(pos) === 45) { result3 = "-"; pos++; } else { result3 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result3 !== null) { result4 = parse_hex4(); if (result4 !== null) { if (input.charCodeAt(pos) === 45) { result5 = "-"; pos++; } else { result5 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result5 !== null) { result6 = parse_hex4(); if (result6 !== null) { if (input.charCodeAt(pos) === 45) { result7 = "-"; pos++; } else { result7 = null; if (reportFailures === 0) { matchFailed("\"-\""); } } if (result7 !== null) { result8 = parse_hex12(); if (result8 !== null) { result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8]; } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } } else { result0 = null; pos = pos1; } if (result0 !== null) { result0 = (function(offset, uuid) { data = input.substring(pos+5, offset); })(pos0, result0[0]); } if (result0 === null) { pos = pos0; } return result0; } function parse_hex4() { var result0, result1, result2, result3; var pos0; pos0 = pos; result0 = parse_HEXDIG(); if (result0 !== null) { result1 = parse_HEXDIG(); if (result1 !== null) { result2 = parse_HEXDIG(); if (result2 !== null) { result3 = parse_HEXDIG(); if (result3 !== null) { result0 = [result0, result1, result2, result3]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_hex8() { var result0, result1; var pos0; pos0 = pos; result0 = parse_hex4(); if (result0 !== null) { result1 = parse_hex4(); if (result1 !== null) { result0 = [result0, result1]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function parse_hex12() { var result0, result1, result2; var pos0; pos0 = pos; result0 = parse_hex4(); if (result0 !== null) { result1 = parse_hex4(); if (result1 !== null) { result2 = parse_hex4(); if (result2 !== null) { result0 = [result0, result1, result2]; } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } } else { result0 = null; pos = pos0; } return result0; } function cleanupExpected(expected) { expected.sort(); var lastExpected = null; var cleanExpected = []; for (var i = 0; i < expected.length; i++) { if (expected[i] !== lastExpected) { cleanExpected.push(expected[i]); lastExpected = expected[i]; } } return cleanExpected; } function computeErrorPosition() { /* * The first idea was to use |String.split| to break the input up to the * error position along newlines and derive the line and column from * there. However IE's |split| implementation is so broken that it was * enough to prevent it. */ var line = 1; var column = 1; var seenCR = false; for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) { var ch = input.charAt(i); if (ch === "\n") { if (!seenCR) { line++; } column = 1; seenCR = false; } else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") { line++; column = 1; seenCR = true; } else { column++; seenCR = false; } } return { line: line, column: column }; } var URI = require('./URI'); var NameAddrHeader = require('./NameAddrHeader'); var data = {}; var result = parseFunctions[startRule](); /* * The parser is now in one of the following three states: * * 1. The parser successfully parsed the whole input. * * - |result !== null| * - |pos === input.length| * - |rightmostFailuresExpected| may or may not contain something * * 2. The parser successfully parsed only a part of the input. * * - |result !== null| * - |pos < input.length| * - |rightmostFailuresExpected| may or may not contain something * * 3. The parser did not successfully parse any part of the input. * * - |result === null| * - |pos === 0| * - |rightmostFailuresExpected| contains at least one failure * * All code following this comment (including called functions) must * handle these states. */ if (result === null || pos !== input.length) { var offset = Math.max(pos, rightmostFailuresPos); var found = offset < input.length ? input.charAt(offset) : null; var errorPosition = computeErrorPosition(); new this.SyntaxError( cleanupExpected(rightmostFailuresExpected), found, offset, errorPosition.line, errorPosition.column ); return -1; } return data; }, /* Returns the parser source code. */ toSource: function() { return this._source; } }; /* Thrown when a parser encounters a syntax error. */ result.SyntaxError = function(expected, found, offset, line, column) { function buildMessage(expected, found) { var expectedHumanized, foundHumanized; switch (expected.length) { case 0: expectedHumanized = "end of input"; break; case 1: expectedHumanized = expected[0]; break; default: expectedHumanized = expected.slice(0, expected.length - 1).join(", ") + " or " + expected[expected.length - 1]; } foundHumanized = found ? quote(found) : "end of input"; return "Expected " + expectedHumanized + " but " + foundHumanized + " found."; } this.name = "SyntaxError"; this.expected = expected; this.found = found; this.message = buildMessage(expected, found); this.offset = offset; this.line = line; this.column = column; }; result.SyntaxError.prototype = Error.prototype; return result; })(); },{"./NameAddrHeader":9,"./URI":21}],7:[function(require,module,exports){ /** * Dependencies. */ var debug = require('debug')('JsSIP'); var pkg = require('../package.json'); debug('version %s', pkg.version); var rtcninja = require('rtcninja'); var C = require('./Constants'); var Exceptions = require('./Exceptions'); var Utils = require('./Utils'); var UA = require('./UA'); var URI = require('./URI'); var NameAddrHeader = require('./NameAddrHeader'); var Grammar = require('./Grammar'); /** * Expose the JsSIP module. */ var JsSIP = module.exports = { C: C, Exceptions: Exceptions, Utils: Utils, UA: UA, URI: URI, NameAddrHeader: NameAddrHeader, Grammar: Grammar, // Expose the debug module. debug: require('debug'), // Expose the rtcninja module. rtcninja: rtcninja }; Object.defineProperties(JsSIP, { name: { get: function() { return pkg.title; } }, version: { get: function() { return pkg.version; } } }); },{"../package.json":46,"./Constants":1,"./Exceptions":5,"./Grammar":6,"./NameAddrHeader":9,"./UA":20,"./URI":21,"./Utils":22,"debug":29,"rtcninja":34}],8:[function(require,module,exports){ module.exports = Message; /** * Dependencies. */ var util = require('util'); var events = require('events'); var JsSIP_C = require('./Constants'); var SIPMessage = require('./SIPMessage'); var Utils = require('./Utils'); var RequestSender = require('./RequestSender'); var Transactions = require('./Transactions'); var Exceptions = require('./Exceptions'); function Message(ua) { this.ua = ua; // Custom message empty object for high level use this.data = {}; events.EventEmitter.call(this); } util.inherits(Message, events.EventEmitter); Message.prototype.send = function(target, body, options) { var request_sender, event, contentType, eventHandlers, extraHeaders, originalTarget = target; if (target === undefined || body === undefined) { throw new TypeError('Not enough arguments'); } // Check target validity target = this.ua.normalizeTarget(target); if (!target) { throw new TypeError('Invalid target: '+ originalTarget); } // Get call options options = options || {}; extraHeaders = options.extraHeaders && options.extraHeaders.slice() || []; eventHandlers = options.eventHandlers || {}; contentType = options.contentType || 'text/plain'; this.content_type = contentType; // Set event handlers for (event in eventHandlers) { this.on(event, eventHandlers[event]); } this.closed = false; this.ua.applicants[this] = this; extraHeaders.push('Content-Type: '+ contentType); this.request = new SIPMessage.OutgoingRequest(JsSIP_C.MESSAGE, target, this.ua, null, extraHeaders); if(body) { this.request.body = body; this.content = body; } else { this.content = null; } request_sender = new RequestSender(this, this.ua); this.newMessage('local', this.request); request_sender.send(); }; Message.prototype.receiveResponse = function(response) { var cause; if(this.closed) { return; } switch(true) { case /^1[0-9]{2}$/.test(response.status_code): // Ignore provisional responses. break; case /^2[0-9]{2}$/.test(response.status_code): delete this.ua.applicants[this]; this.emit('succeeded', { originator: 'remote', response: response }); break; default: delete this.ua.applicants[this]; cause = Utils.sipErrorCause(response.status_code); this.emit('failed', { originator: 'remote', response: response, cause: cause }); break; } }; Message.prototype.onRequestTimeout = function() { if(this.closed) { return; } this.emit('failed', { originator: 'system', cause: JsSIP_C.causes.REQUEST_TIMEOUT }); }; Message.prototype.onTransportError = function() { if(this.closed) { return; } this.emit('failed', { originator: 'system', cause: JsSIP_C.causes.CONNECTION_ERROR }); }; Message.prototype.close = function() { this.closed = true; delete this.ua.applicants[this]; }; Message.prototype.init_incoming = function(request) { var transaction; this.request = request; this.content_type = request.getHeader('Content-Type'); if (request.body) { this.content = request.body; } else { this.content = null; } this.newMessage('remote', request); transaction = this.ua.transactions.nist[request.via_branch]; if (transaction && (transaction.state === Transactions.C.STATUS_TRYING || transaction.state === Transactions.C.STATUS_PROCEEDING)) { request.reply(200); } }; /** * Accept the incoming Message * Only valid for incoming Messages */ Message.prototype.accept = function(options) { options = options || {}; var extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body; if (this.direction !== 'incoming') { throw new Exceptions.NotSupportedError('"accept" not supported for outgoing Message'); } this.request.reply(200, null, extraHeaders, body); }; /** * Reject the incoming Message * Only valid for incoming Messages */ Message.prototype.reject = function(options) { options = options || {}; var status_code = options.status_code || 480, reason_phrase = options.reason_phrase, extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body; if (this.direction !== 'incoming') { throw new Exceptions.NotSupportedError('"reject" not supported for outgoing Message'); } if (status_code < 300 || status_code >= 700) { throw new TypeError('Invalid status_code: '+ status_code); } this.request.reply(status_code, reason_phrase, extraHeaders, body); }; /** * Internal Callbacks */ Message.prototype.newMessage = function(originator, request) { if (originator === 'remote') { this.direction = 'incoming'; this.local_identity = request.to; this.remote_identity = request.from; } else if (originator === 'local'){ this.direction = 'outgoing'; this.local_identity = request.from; this.remote_identity = request.to; } this.ua.newMessage({ originator: originator, message: this, request: request }); }; },{"./Constants":1,"./Exceptions":5,"./RequestSender":15,"./SIPMessage":16,"./Transactions":18,"./Utils":22,"events":24,"util":28}],9:[function(require,module,exports){ module.exports = NameAddrHeader; /** * Dependencies. */ var URI = require('./URI'); var Grammar = require('./Grammar'); function NameAddrHeader(uri, display_name, parameters) { var param; // Checks if(!uri || !(uri instanceof URI)) { throw new TypeError('missing or invalid "uri" parameter'); } // Initialize parameters this.uri = uri; this.parameters = {}; for (param in parameters) { this.setParam(param, parameters[param]); } Object.defineProperties(this, { display_name: { get: function() { return display_name; }, set: function(value) { display_name = (value === 0) ? '0' : value; } } }); } NameAddrHeader.prototype = { setParam: function(key, value) { if (key) { this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString(); } }, getParam: function(key) { if(key) { return this.parameters[key.toLowerCase()]; } }, hasParam: function(key) { if(key) { return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false; } }, deleteParam: function(parameter) { var value; parameter = parameter.toLowerCase(); if (this.parameters.hasOwnProperty(parameter)) { value = this.parameters[parameter]; delete this.parameters[parameter]; return value; } }, clearParams: function() { this.parameters = {}; }, clone: function() { return new NameAddrHeader( this.uri.clone(), this.display_name, JSON.parse(JSON.stringify(this.parameters))); }, toString: function() { var body, parameter; body = (this.display_name || this.display_name === 0) ? '"' + this.display_name + '" ' : ''; body += '<' + this.uri.toString() + '>'; for (parameter in this.parameters) { body += ';' + parameter; if (this.parameters[parameter] !== null) { body += '='+ this.parameters[parameter]; } } return body; } }; /** * Parse the given string and returns a NameAddrHeader instance or undefined if * it is an invalid NameAddrHeader. */ NameAddrHeader.parse = function(name_addr_header) { name_addr_header = Grammar.parse(name_addr_header,'Name_Addr_Header'); if (name_addr_header !== -1) { return name_addr_header; } else { return undefined; } }; },{"./Grammar":6,"./URI":21}],10:[function(require,module,exports){ var Parser = {}; module.exports = Parser; /** * Dependencies. */ var debugerror = require('debug')('JsSIP:ERROR:Parser'); debugerror.log = console.warn.bind(console); var sdp_transform = require('sdp-transform'); var Grammar = require('./Grammar'); var SIPMessage = require('./SIPMessage'); /** * Extract and parse every header of a SIP message. */ function getHeader(data, headerStart) { var // 'start' position of the header. start = headerStart, // 'end' position of the header. end = 0, // 'partial end' position of the header. partialEnd = 0; //End of message. if (data.substring(start, start + 2).match(/(^\r\n)/)) { return -2; } while(end === 0) { // Partial End of Header. partialEnd = data.indexOf('\r\n', start); // 'indexOf' returns -1 if the value to be found never occurs. if (partialEnd === -1) { return partialEnd; } if(!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && data.charAt(partialEnd + 2).match(/(^\s+)/)) { // Not the end of the message. Continue from the next position. start = partialEnd + 2; } else { end = partialEnd; } } return end; } function parseHeader(message, data, headerStart, headerEnd) { var header, idx, length, parsed, hcolonIndex = data.indexOf(':', headerStart), headerName = data.substring(headerStart, hcolonIndex).trim(), headerValue = data.substring(hcolonIndex + 1, headerEnd).trim(); // If header-field is well-known, parse it. switch(headerName.toLowerCase()) { case 'via': case 'v': message.addHeader('via', headerValue); if(message.getHeaders('via').length === 1) { parsed = message.parseHeader('Via'); if(parsed) { message.via = parsed; message.via_branch = parsed.branch; } } else { parsed = 0; } break; case 'from': case 'f': message.setHeader('from', headerValue); parsed = message.parseHeader('from'); if(parsed) { message.from = parsed; message.from_tag = parsed.getParam('tag'); } break; case 'to': case 't': message.setHeader('to', headerValue); parsed = message.parseHeader('to'); if(parsed) { message.to = parsed; message.to_tag = parsed.getParam('tag'); } break; case 'record-route': parsed = Grammar.parse(headerValue, 'Record_Route'); if (parsed === -1) { parsed = undefined; } length = parsed.length; for (idx = 0; idx < length; idx++) { header = parsed[idx]; message.addHeader('record-route', headerValue.substring(header.possition, header.offset)); message.headers['Record-Route'][message.getHeaders('record-route').length - 1].parsed = header.parsed; } break; case 'call-id': case 'i': message.setHeader('call-id', headerValue); parsed = message.parseHeader('call-id'); if(parsed) { message.call_id = headerValue; } break; case 'contact': case 'm': parsed = Grammar.parse(headerValue, 'Contact'); if (parsed === -1) { parsed = undefined; } length = parsed.length; for (idx = 0; idx < length; idx++) { header = parsed[idx]; message.addHeader('contact', headerValue.substring(header.possition, header.offset)); message.headers.Contact[message.getHeaders('contact').length - 1].parsed = header.parsed; } break; case 'content-length': case 'l': message.setHeader('content-length', headerValue); parsed = message.parseHeader('content-length'); break; case 'content-type': case 'c': message.setHeader('content-type', headerValue); parsed = message.parseHeader('content-type'); break; case 'cseq': message.setHeader('cseq', headerValue); parsed = message.parseHeader('cseq'); if(parsed) { message.cseq = parsed.value; } if(message instanceof SIPMessage.IncomingResponse) { message.method = parsed.method; } break; case 'max-forwards': message.setHeader('max-forwards', headerValue); parsed = message.parseHeader('max-forwards'); break; case 'www-authenticate': message.setHeader('www-authenticate', headerValue); parsed = message.parseHeader('www-authenticate'); break; case 'proxy-authenticate': message.setHeader('proxy-authenticate', headerValue); parsed = message.parseHeader('proxy-authenticate'); break; case 'session-expires': case 'x': message.setHeader('session-expires', headerValue); parsed = message.parseHeader('session-expires'); if (parsed) { message.session_expires = parsed.expires; message.session_expires_refresher = parsed.refresher; } break; default: // Do not parse this header. message.setHeader(headerName, headerValue); parsed = 0; } if (parsed === undefined) { return { error: 'error parsing header "'+ headerName +'"' }; } else { return true; } } /** * Parse SIP Message */ Parser.parseMessage = function(data, ua) { var message, firstLine, contentLength, bodyStart, parsed, headerStart = 0, headerEnd = data.indexOf('\r\n'); if(headerEnd === -1) { debugerror('parseMessage() | no CRLF found, not a SIP message'); return; } // Parse first line. Check if it is a Request or a Reply. firstLine = data.substring(0, headerEnd); parsed = Grammar.parse(firstLine, 'Request_Response'); if(parsed === -1) { debugerror('parseMessage() | error parsing first line of SIP message: "' + firstLine + '"'); return; } else if(!parsed.status_code) { message = new SIPMessage.IncomingRequest(ua); message.method = parsed.method; message.ruri = parsed.uri; } else { message = new SIPMessage.IncomingResponse(); message.status_code = parsed.status_code; message.reason_phrase = parsed.reason_phrase; } message.data = data; headerStart = headerEnd + 2; /* Loop over every line in data. Detect the end of each header and parse * it or simply add to the headers collection. */ while(true) { headerEnd = getHeader(data, headerStart); // The SIP message has normally finished. if(headerEnd === -2) { bodyStart = headerStart + 2; break; } // data.indexOf returned -1 due to a malformed message. else if(headerEnd === -1) { parsed.error('parseMessage() | malformed message'); return; } parsed = parseHeader(message, data, headerStart, headerEnd); if(parsed !== true) { debugerror('parseMessage() |', parsed.error); return; } headerStart = headerEnd + 2; } /* RFC3261 18.3. * If there are additional bytes in the transport packet * beyond the end of the body, they MUST be discarded. */ if(message.hasHeader('content-length')) { contentLength = message.getHeader('content-length'); message.body = data.substr(bodyStart, contentLength); } else { message.body = data.substring(bodyStart); } return message; }; /** * sdp-transform features. */ Parser.parseSDP = sdp_transform.parse; Parser.writeSDP = sdp_transform.write; Parser.parseFmtpConfig = sdp_transform.parseFmtpConfig; Parser.parsePayloads = sdp_transform.parsePayloads; Parser.parseRemoteCandidates = sdp_transform.parseRemoteCandidates; },{"./Grammar":6,"./SIPMessage":16,"debug":29,"sdp-transform":40}],11:[function(require,module,exports){ module.exports = RTCSession; var C = { // RTCSession states STATUS_NULL: 0, STATUS_INVITE_SENT: 1, STATUS_1XX_RECEIVED: 2, STATUS_INVITE_RECEIVED: 3, STATUS_WAITING_FOR_ANSWER: 4, STATUS_ANSWERED: 5, STATUS_WAITING_FOR_ACK: 6, STATUS_CANCELED: 7, STATUS_TERMINATED: 8, STATUS_CONFIRMED: 9 }; /** * Expose C object. */ RTCSession.C = C; /** * Dependencies. */ var util = require('util'); var events = require('events'); var debug = require('debug')('JsSIP:RTCSession'); var debugerror = require('debug')('JsSIP:ERROR:RTCSession'); debugerror.log = console.warn.bind(console); var rtcninja = require('rtcninja'); var JsSIP_C = require('./Constants'); var Exceptions = require('./Exceptions'); var Transactions = require('./Transactions'); var Parser = require('./Parser'); var Utils = require('./Utils'); var Timers = require('./Timers'); var SIPMessage = require('./SIPMessage'); var Dialog = require('./Dialog'); var RequestSender = require('./RequestSender'); var RTCSession_Request = require('./RTCSession/Request'); var RTCSession_DTMF = require('./RTCSession/DTMF'); function RTCSession(ua) { debug('new'); this.ua = ua; this.status = C.STATUS_NULL; this.dialog = null; this.earlyDialogs = {}; this.connection = null; // The rtcninja.RTCPeerConnection instance (public attribute). // RTCSession confirmation flag this.is_confirmed = false; // is late SDP being negotiated this.late_sdp = false; // Default rtcOfferConstraints and rtcAnswerConstrainsts (passed in connect() or answer()). this.rtcOfferConstraints = null; this.rtcAnswerConstraints = null; // Local MediaStream. this.localMediaStream = null; this.localMediaStreamLocallyGenerated = false; // Flag to indicate PeerConnection ready for new actions. this.rtcReady = true; // SIP Timers this.timers = { ackTimer: null, expiresTimer: null, invite2xxTimer: null, userNoAnswerTimer: null }; // Session info this.direction = null; this.local_identity = null; this.remote_identity = null; this.start_time = null; this.end_time = null; this.tones = null; // Mute/Hold state this.audioMuted = false; this.videoMuted = false; this.localHold = false; this.remoteHold = false; // Session Timers (RFC 4028) this.sessionTimers = { enabled: this.ua.configuration.session_timers, defaultExpires: JsSIP_C.SESSION_EXPIRES, currentExpires: null, running: false, refresher: false, timer: null // A setTimeout. }; // Custom session empty object for high level use this.data = {}; events.EventEmitter.call(this); } util.inherits(RTCSession, events.EventEmitter); /** * User API */ RTCSession.prototype.isInProgress = function() { switch(this.status) { case C.STATUS_NULL: case C.STATUS_INVITE_SENT: case C.STATUS_1XX_RECEIVED: case C.STATUS_INVITE_RECEIVED: case C.STATUS_WAITING_FOR_ANSWER: return true; default: return false; } }; RTCSession.prototype.isEstablished = function() { switch(this.status) { case C.STATUS_ANSWERED: case C.STATUS_WAITING_FOR_ACK: case C.STATUS_CONFIRMED: return true; default: return false; } }; RTCSession.prototype.isEnded = function() { switch(this.status) { case C.STATUS_CANCELED: case C.STATUS_TERMINATED: return true; default: return false; } }; RTCSession.prototype.isMuted = function() { return { audio: this.audioMuted, video: this.videoMuted }; }; RTCSession.prototype.isOnHold = function() { return { local: this.localHold, remote: this.remoteHold }; }; /** * Check if RTCSession is ready for an outgoing re-INVITE or UPDATE with SDP. */ RTCSession.prototype.isReadyToReOffer = function() { if (! this.rtcReady) { debug('isReadyToReOffer() | internal WebRTC status not ready'); return false; } // No established yet. if (! this.dialog) { debug('isReadyToReOffer() | session not established yet'); return false; } // Another INVITE transaction is in progress if (this.dialog.uac_pending_reply === true || this.dialog.uas_pending_reply === true) { debug('isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress'); return false; } return true; }; RTCSession.prototype.connect = function(target, options) { debug('connect()'); options = options || {}; var event, requestParams, originalTarget = target, eventHandlers = options.eventHandlers || {}, extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], mediaConstraints = options.mediaConstraints || {audio: true, video: true}, mediaStream = options.mediaStream || null, pcConfig = options.pcConfig || {iceServers:[]}, rtcConstraints = options.rtcConstraints || null, rtcOfferConstraints = options.rtcOfferConstraints || null; this.rtcOfferConstraints = rtcOfferConstraints; this.rtcAnswerConstraints = options.rtcAnswerConstraints || null; // Session Timers. if (this.sessionTimers.enabled) { if (Utils.isDecimal(options.sessionTimersExpires)) { if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) { this.sessionTimers.defaultExpires = options.sessionTimersExpires; } else { this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES; } } } this.data = options.data || this.data; if (target === undefined) { throw new TypeError('Not enough arguments'); } // Check WebRTC support. if (! rtcninja.hasWebRTC()) { throw new Exceptions.NotSupportedError('WebRTC not supported'); } // Check target validity target = this.ua.normalizeTarget(target); if (!target) { throw new TypeError('Invalid target: '+ originalTarget); } // Check Session Status if (this.status !== C.STATUS_NULL) { throw new Exceptions.InvalidStateError(this.status); } // Set event handlers for (event in eventHandlers) { this.on(event, eventHandlers[event]); } // Session parameter initialization this.from_tag = Utils.newTag(); // Set anonymous property this.anonymous = options.anonymous || false; // OutgoingSession specific parameters this.isCanceled = false; requestParams = {from_tag: this.from_tag}; this.contact = this.ua.contact.toString({ anonymous: this.anonymous, outbound: true }); if (this.anonymous) { requestParams.from_display_name = 'Anonymous'; requestParams.from_uri = 'sip:[email protected]'; extraHeaders.push('P-Preferred-Identity: '+ this.ua.configuration.uri.toString()); extraHeaders.push('Privacy: id'); } extraHeaders.push('Contact: '+ this.contact); extraHeaders.push('Content-Type: application/sdp'); if (this.sessionTimers.enabled) { extraHeaders.push('Session-Expires: ' + this.sessionTimers.defaultExpires); } this.request = new SIPMessage.OutgoingRequest(JsSIP_C.INVITE, target, this.ua, requestParams, extraHeaders); this.id = this.request.call_id + this.from_tag; // Create a new rtcninja.RTCPeerConnection instance. createRTCConnection.call(this, pcConfig, rtcConstraints); // Save the session into the ua sessions collection. this.ua.sessions[this.id] = this; newRTCSession.call(this, 'local', this.request); sendInitialRequest.call(this, mediaConstraints, rtcOfferConstraints, mediaStream); }; RTCSession.prototype.init_incoming = function(request) { debug('init_incoming()'); var expires, self = this, contentType = request.getHeader('Content-Type'); // Check body and content type if (request.body && (contentType !== 'application/sdp')) { request.reply(415); return; } // Session parameter initialization this.status = C.STATUS_INVITE_RECEIVED; this.from_tag = request.from_tag; this.id = request.call_id + this.from_tag; this.request = request; this.contact = this.ua.contact.toString(); // Save the session into the ua sessions collection. this.ua.sessions[this.id] = this; // Get the Expires header value if exists if (request.hasHeader('expires')) { expires = request.getHeader('expires') * 1000; } /* Set the to_tag before * replying a response code that will create a dialog. */ request.to_tag = Utils.newTag(); // An error on dialog creation will fire 'failed' event if (! createDialog.call(this, request, 'UAS', true)) { request.reply(500, 'Missing Contact header field'); return; } if (request.body) { this.late_sdp = false; } else { this.late_sdp = true; } this.status = C.STATUS_WAITING_FOR_ANSWER; // Set userNoAnswerTimer this.timers.userNoAnswerTimer = setTimeout(function() { request.reply(408); failed.call(self, 'local',null, JsSIP_C.causes.NO_ANSWER); }, this.ua.configuration.no_answer_timeout ); /* Set expiresTimer * RFC3261 13.3.1 */ if (expires) { this.timers.expiresTimer = setTimeout(function() { if(self.status === C.STATUS_WAITING_FOR_ANSWER) { request.reply(487); failed.call(self, 'system', null, JsSIP_C.causes.EXPIRES); } }, expires ); } // Fire 'newRTCSession' event. newRTCSession.call(this, 'remote', request); // The user may have rejected the call in the 'newRTCSession' event. if (this.status === C.STATUS_TERMINATED) { return; } // Reply 180. request.reply(180, null, ['Contact: ' + self.contact]); // Fire 'progress' event. // TODO: Document that 'response' field in 'progress' event is null for // incoming calls. progress.call(self, 'local', null); }; /** * Answer the call. */ RTCSession.prototype.answer = function(options) { debug('answer()'); options = options || {}; var idx, length, sdp, tracks, peerHasAudioLine = false, peerHasVideoLine = false, peerOffersFullAudio = false, peerOffersFullVideo = false, self = this, request = this.request, extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], mediaConstraints = options.mediaConstraints || {}, mediaStream = options.mediaStream || null, pcConfig = options.pcConfig || {iceServers:[]}, rtcConstraints = options.rtcConstraints || null, rtcAnswerConstraints = options.rtcAnswerConstraints || null; this.rtcAnswerConstraints = rtcAnswerConstraints; this.rtcOfferConstraints = options.rtcOfferConstraints || null; // Session Timers. if (this.sessionTimers.enabled) { if (Utils.isDecimal(options.sessionTimersExpires)) { if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) { this.sessionTimers.defaultExpires = options.sessionTimersExpires; } else { this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES; } } } this.data = options.data || this.data; // Check Session Direction and Status if (this.direction !== 'incoming') { throw new Exceptions.NotSupportedError('"answer" not supported for outgoing RTCSession'); } else if (this.status !== C.STATUS_WAITING_FOR_ANSWER) { throw new Exceptions.InvalidStateError(this.status); } this.status = C.STATUS_ANSWERED; // An error on dialog creation will fire 'failed' event if (! createDialog.call(this, request, 'UAS')) { request.reply(500, 'Error creating dialog'); return; } clearTimeout(this.timers.userNoAnswerTimer); extraHeaders.unshift('Contact: ' + self.contact); // Determine incoming media from incoming SDP offer (if any). sdp = Parser.parseSDP(request.body || ''); // Make sure sdp.media is an array, not the case if there is only one media if (! Array.isArray(sdp.media)) { sdp.media = [sdp.media]; } // Go through all medias in SDP to find offered capabilities to answer with idx = sdp.media.length; while(idx--) { var m = sdp.media[idx]; if (m.type === 'audio') { peerHasAudioLine = true; if (!m.direction || m.direction === 'sendrecv') { peerOffersFullAudio = true; } } if (m.type === 'video') { peerHasVideoLine = true; if (!m.direction || m.direction === 'sendrecv') { peerOffersFullVideo = true; } } } // Remove audio from mediaStream if suggested by mediaConstraints if (mediaStream && mediaConstraints.audio === false) { tracks = mediaStream.getAudioTracks(); length = tracks.length; for (idx=0; idx<length; idx++) { mediaStream.removeTrack(tracks[idx]); } } // Remove video from mediaStream if suggested by mediaConstraints if (mediaStream && mediaConstraints.video === false) { tracks = mediaStream.getVideoTracks(); length = tracks.length; for (idx=0; idx<length; idx++) { mediaStream.removeTrack(tracks[idx]); } } // Set audio constraints based on incoming stream if not supplied if (!mediaStream && mediaConstraints.audio === undefined) { mediaConstraints.audio = peerOffersFullAudio; } // Set video constraints based on incoming stream if not supplied if (!mediaStream && mediaConstraints.video === undefined) { mediaConstraints.video = peerOffersFullVideo; } // Don't ask for audio if the incoming offer has no audio section if (!mediaStream && !peerHasAudioLine) { mediaConstraints.audio = false; } // Don't ask for video if the incoming offer has no video section if (!mediaStream && !peerHasVideoLine) { mediaConstraints.video = false; } // Create a new rtcninja.RTCPeerConnection instance. // TODO: This may throw an error, should react. createRTCConnection.call(this, pcConfig, rtcConstraints); if (mediaStream) { userMediaSucceeded(mediaStream); } else { self.localMediaStreamLocallyGenerated = true; rtcninja.getUserMedia( mediaConstraints, userMediaSucceeded, userMediaFailed ); } // User media succeeded function userMediaSucceeded(stream) { if (self.status === C.STATUS_TERMINATED) { return; } self.localMediaStream = stream; self.connection.addStream(stream); if (! self.late_sdp) { self.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'offer', sdp:request.body}), // success remoteDescriptionSucceededOrNotNeeded, // failure function() { request.reply(488); failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR); } ); } else { remoteDescriptionSucceededOrNotNeeded(); } } // User media failed function userMediaFailed() { if (self.status === C.STATUS_TERMINATED) { return; } request.reply(480); failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS); } function remoteDescriptionSucceededOrNotNeeded() { connecting.call(self, request); if (! self.late_sdp) { createLocalDescription.call(self, 'answer', rtcSucceeded, rtcFailed, rtcAnswerConstraints); } else { createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, self.rtcOfferConstraints); } } function rtcSucceeded(sdp) { if (self.status === C.STATUS_TERMINATED) { return; } // run for reply success callback function replySucceeded() { self.status = C.STATUS_WAITING_FOR_ACK; setInvite2xxTimer.call(self, request, sdp); setACKTimer.call(self); accepted.call(self, 'local'); } // run for reply failure callback function replyFailed() { failed.call(self, 'system', null, JsSIP_C.causes.CONNECTION_ERROR); } handleSessionTimersInIncomingRequest.call(self, request, extraHeaders); request.reply(200, null, extraHeaders, sdp, replySucceeded, replyFailed ); } function rtcFailed() { if (self.status === C.STATUS_TERMINATED) { return; } request.reply(500); failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR); } }; /** * Terminate the call. */ RTCSession.prototype.terminate = function(options) { debug('terminate()'); options = options || {}; var cancel_reason, dialog, cause = options.cause || JsSIP_C.causes.BYE, status_code = options.status_code, reason_phrase = options.reason_phrase, extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body, self = this; // Check Session Status if (this.status === C.STATUS_TERMINATED) { throw new Exceptions.InvalidStateError(this.status); } switch(this.status) { // - UAC - case C.STATUS_NULL: case C.STATUS_INVITE_SENT: case C.STATUS_1XX_RECEIVED: debug('canceling sesssion'); if (status_code && (status_code < 200 || status_code >= 700)) { throw new TypeError('Invalid status_code: '+ status_code); } else if (status_code) { reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || ''; cancel_reason = 'SIP ;cause=' + status_code + ' ;text="' + reason_phrase + '"'; } // Check Session Status if (this.status === C.STATUS_NULL) { this.isCanceled = true; this.cancelReason = cancel_reason; } else if (this.status === C.STATUS_INVITE_SENT) { this.isCanceled = true; this.cancelReason = cancel_reason; } else if(this.status === C.STATUS_1XX_RECEIVED) { this.request.cancel(cancel_reason); } this.status = C.STATUS_CANCELED; failed.call(this, 'local', null, JsSIP_C.causes.CANCELED); break; // - UAS - case C.STATUS_WAITING_FOR_ANSWER: case C.STATUS_ANSWERED: debug('rejecting session'); status_code = status_code || 480; if (status_code < 300 || status_code >= 700) { throw new TypeError('Invalid status_code: '+ status_code); } this.request.reply(status_code, reason_phrase, extraHeaders, body); failed.call(this, 'local', null, JsSIP_C.causes.REJECTED); break; case C.STATUS_WAITING_FOR_ACK: case C.STATUS_CONFIRMED: debug('terminating session'); reason_phrase = options.reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || ''; if (status_code && (status_code < 200 || status_code >= 700)) { throw new TypeError('Invalid status_code: '+ status_code); } else if (status_code) { extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"'); } /* RFC 3261 section 15 (Terminating a session): * * "...the callee's UA MUST NOT send a BYE on a confirmed dialog * until it has received an ACK for its 2xx response or until the server * transaction times out." */ if (this.status === C.STATUS_WAITING_FOR_ACK && this.direction === 'incoming' && this.request.server_transaction.state !== Transactions.C.STATUS_TERMINATED) { // Save the dialog for later restoration dialog = this.dialog; // Send the BYE as soon as the ACK is received... this.receiveRequest = function(request) { if(request.method === JsSIP_C.ACK) { sendRequest.call(this, JsSIP_C.BYE, { extraHeaders: extraHeaders, body: body }); dialog.terminate(); } }; // .., or when the INVITE transaction times out this.request.server_transaction.on('stateChanged', function(){ if (this.state === Transactions.C.STATUS_TERMINATED) { sendRequest.call(self, JsSIP_C.BYE, { extraHeaders: extraHeaders, body: body }); dialog.terminate(); } }); ended.call(this, 'local', null, cause); // Restore the dialog into 'this' in order to be able to send the in-dialog BYE :-) this.dialog = dialog; // Restore the dialog into 'ua' so the ACK can reach 'this' session this.ua.dialogs[dialog.id.toString()] = dialog; } else { sendRequest.call(this, JsSIP_C.BYE, { extraHeaders: extraHeaders, body: body }); ended.call(this, 'local', null, cause); } } }; RTCSession.prototype.close = function() { debug('close()'); var idx; if (this.status === C.STATUS_TERMINATED) { return; } // Terminate RTC. if (this.connection) { try { this.connection.close(); } catch(error) { debugerror('close() | error closing the RTCPeerConnection: %o', error); } } // Close local MediaStream if it was not given by the user. if (this.localMediaStream && this.localMediaStreamLocallyGenerated) { debug('close() | closing local MediaStream'); rtcninja.closeMediaStream(this.localMediaStream); } // Terminate signaling. // Clear SIP timers for(idx in this.timers) { clearTimeout(this.timers[idx]); } // Clear Session Timers. clearTimeout(this.sessionTimers.timer); // Terminate confirmed dialog if (this.dialog) { this.dialog.terminate(); delete this.dialog; } // Terminate early dialogs for(idx in this.earlyDialogs) { this.earlyDialogs[idx].terminate(); delete this.earlyDialogs[idx]; } this.status = C.STATUS_TERMINATED; delete this.ua.sessions[this.id]; }; RTCSession.prototype.sendDTMF = function(tones, options) { debug('sendDTMF() | tones: %s', tones); var duration, interToneGap, position = 0, self = this; options = options || {}; duration = options.duration || null; interToneGap = options.interToneGap || null; if (tones === undefined) { throw new TypeError('Not enough arguments'); } // Check Session Status if (this.status !== C.STATUS_CONFIRMED && this.status !== C.STATUS_WAITING_FOR_ACK) { throw new Exceptions.InvalidStateError(this.status); } // Convert to string if(typeof tones === 'number') { tones = tones.toString(); } // Check tones if (!tones || typeof tones !== 'string' || !tones.match(/^[0-9A-D#*,]+$/i)) { throw new TypeError('Invalid tones: '+ tones); } // Check duration if (duration && !Utils.isDecimal(duration)) { throw new TypeError('Invalid tone duration: '+ duration); } else if (!duration) { duration = RTCSession_DTMF.C.DEFAULT_DURATION; } else if (duration < RTCSession_DTMF.C.MIN_DURATION) { debug('"duration" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_DURATION+ ' milliseconds'); duration = RTCSession_DTMF.C.MIN_DURATION; } else if (duration > RTCSession_DTMF.C.MAX_DURATION) { debug('"duration" value is greater than the maximum allowed, setting it to '+ RTCSession_DTMF.C.MAX_DURATION +' milliseconds'); duration = RTCSession_DTMF.C.MAX_DURATION; } else { duration = Math.abs(duration); } options.duration = duration; // Check interToneGap if (interToneGap && !Utils.isDecimal(interToneGap)) { throw new TypeError('Invalid interToneGap: '+ interToneGap); } else if (!interToneGap) { interToneGap = RTCSession_DTMF.C.DEFAULT_INTER_TONE_GAP; } else if (interToneGap < RTCSession_DTMF.C.MIN_INTER_TONE_GAP) { debug('"interToneGap" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_INTER_TONE_GAP +' milliseconds'); interToneGap = RTCSession_DTMF.C.MIN_INTER_TONE_GAP; } else { interToneGap = Math.abs(interToneGap); } if (this.tones) { // Tones are already queued, just add to the queue this.tones += tones; return; } this.tones = tones; // Send the first tone _sendDTMF(); function _sendDTMF() { var tone, timeout; if (self.status === C.STATUS_TERMINATED || !self.tones || position >= self.tones.length) { // Stop sending DTMF self.tones = null; return; } tone = self.tones[position]; position += 1; if (tone === ',') { timeout = 2000; } else { var dtmf = new RTCSession_DTMF(self); options.eventHandlers = { failed: function() { self.tones = null; } }; dtmf.send(tone, options); timeout = duration + interToneGap; } // Set timeout for the next tone setTimeout(_sendDTMF, timeout); } }; /** * Mute */ RTCSession.prototype.mute = function(options) { debug('mute()'); options = options || {audio:true, video:false}; var audioMuted = false, videoMuted = false; if (this.audioMuted === false && options.audio) { audioMuted = true; this.audioMuted = true; toogleMuteAudio.call(this, true); } if (this.videoMuted === false && options.video) { videoMuted = true; this.videoMuted = true; toogleMuteVideo.call(this, true); } if (audioMuted === true || videoMuted === true) { onmute.call(this, { audio: audioMuted, video: videoMuted }); } }; /** * Unmute */ RTCSession.prototype.unmute = function(options) { debug('unmute()'); options = options || {audio:true, video:true}; var audioUnMuted = false, videoUnMuted = false; if (this.audioMuted === true && options.audio) { audioUnMuted = true; this.audioMuted = false; if (this.localHold === false) { toogleMuteAudio.call(this, false); } } if (this.videoMuted === true && options.video) { videoUnMuted = true; this.videoMuted = false; if (this.localHold === false) { toogleMuteVideo.call(this, false); } } if (audioUnMuted === true || videoUnMuted === true) { onunmute.call(this, { audio: audioUnMuted, video: videoUnMuted }); } }; /** * Hold */ RTCSession.prototype.hold = function(options, done) { debug('hold()'); options = options || {}; var self = this, eventHandlers; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } if (this.localHold === true) { return false; } if (! this.isReadyToReOffer()) { return false; } this.localHold = true; onhold.call(this, 'local'); eventHandlers = { succeeded: function() { if (done) { done(); } }, failed: function() { self.terminate({ cause: JsSIP_C.causes.WEBRTC_ERROR, status_code: 500, reason_phrase: 'Hold Failed' }); } }; if (options.useUpdate) { sendUpdate.call(this, { sdpOffer: true, eventHandlers: eventHandlers, extraHeaders: options.extraHeaders }); } else { sendReinvite.call(this, { eventHandlers: eventHandlers, extraHeaders: options.extraHeaders }); } return true; }; RTCSession.prototype.unhold = function(options, done) { debug('unhold()'); options = options || {}; var self = this, eventHandlers; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } if (this.localHold === false) { return false; } if (! this.isReadyToReOffer()) { return false; } this.localHold = false; onunhold.call(this, 'local'); eventHandlers = { succeeded: function() { if (done) { done(); } }, failed: function() { self.terminate({ cause: JsSIP_C.causes.WEBRTC_ERROR, status_code: 500, reason_phrase: 'Unhold Failed' }); } }; if (options.useUpdate) { sendUpdate.call(this, { sdpOffer: true, eventHandlers: eventHandlers, extraHeaders: options.extraHeaders }); } else { sendReinvite.call(this, { eventHandlers: eventHandlers, extraHeaders: options.extraHeaders }); } return true; }; RTCSession.prototype.renegotiate = function(options, done) { debug('renegotiate()'); options = options || {}; var self = this, eventHandlers, rtcOfferConstraints = options.rtcOfferConstraints || null; if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) { return false; } if (! this.isReadyToReOffer()) { return false; } eventHandlers = { succeeded: function() { if (done) { done(); } }, failed: function() { self.terminate({ cause: JsSIP_C.causes.WEBRTC_ERROR, status_code: 500, reason_phrase: 'Media Renegotiation Failed' }); } }; setLocalMediaStatus.call(this); if (options.useUpdate) { sendUpdate.call(this, { sdpOffer: true, eventHandlers: eventHandlers, rtcOfferConstraints: rtcOfferConstraints, extraHeaders: options.extraHeaders }); } else { sendReinvite.call(this, { eventHandlers: eventHandlers, rtcOfferConstraints: rtcOfferConstraints, extraHeaders: options.extraHeaders }); } return true; }; /** * In dialog Request Reception */ RTCSession.prototype.receiveRequest = function(request) { debug('receiveRequest()'); var contentType, self = this; if(request.method === JsSIP_C.CANCEL) { /* RFC3261 15 States that a UAS may have accepted an invitation while a CANCEL * was in progress and that the UAC MAY continue with the session established by * any 2xx response, or MAY terminate with BYE. JsSIP does continue with the * established session. So the CANCEL is processed only if the session is not yet * established. */ /* * Terminate the whole session in case the user didn't accept (or yet send the answer) * nor reject the request opening the session. */ if(this.status === C.STATUS_WAITING_FOR_ANSWER || this.status === C.STATUS_ANSWERED) { this.status = C.STATUS_CANCELED; this.request.reply(487); failed.call(this, 'remote', request, JsSIP_C.causes.CANCELED); } } else { // Requests arriving here are in-dialog requests. switch(request.method) { case JsSIP_C.ACK: if(this.status === C.STATUS_WAITING_FOR_ACK) { clearTimeout(this.timers.ackTimer); clearTimeout(this.timers.invite2xxTimer); if (this.late_sdp) { if (!request.body) { ended.call(this, 'remote', request, JsSIP_C.causes.MISSING_SDP); break; } this.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'answer', sdp:request.body}), // success function() { self.status = C.STATUS_CONFIRMED; }, // failure function() { ended.call(self, 'remote', request, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION); } ); } else { this.status = C.STATUS_CONFIRMED; } if (this.status === C.STATUS_CONFIRMED && !this.is_confirmed) { confirmed.call(this, 'remote', request); } } break; case JsSIP_C.BYE: if(this.status === C.STATUS_CONFIRMED) { request.reply(200); ended.call(this, 'remote', request, JsSIP_C.causes.BYE); } else if (this.status === C.STATUS_INVITE_RECEIVED) { request.reply(200); this.request.reply(487, 'BYE Received'); ended.call(this, 'remote', request, JsSIP_C.causes.BYE); } else { request.reply(403, 'Wrong Status'); } break; case JsSIP_C.INVITE: if(this.status === C.STATUS_CONFIRMED) { receiveReinvite.call(this, request); } else { request.reply(403, 'Wrong Status'); } break; case JsSIP_C.INFO: if(this.status === C.STATUS_CONFIRMED || this.status === C.STATUS_WAITING_FOR_ACK || this.status === C.STATUS_INVITE_RECEIVED) { contentType = request.getHeader('content-type'); if (contentType && (contentType.match(/^application\/dtmf-relay/i))) { new RTCSession_DTMF(this).init_incoming(request); } else { request.reply(415); } } else { request.reply(403, 'Wrong Status'); } break; case JsSIP_C.UPDATE: if(this.status === C.STATUS_CONFIRMED) { receiveUpdate.call(this, request); } else { request.reply(403, 'Wrong Status'); } break; default: request.reply(501); } } }; /** * Session Callbacks */ RTCSession.prototype.onTransportError = function() { debugerror('onTransportError()'); if(this.status !== C.STATUS_TERMINATED) { this.terminate({ status_code: 500, reason_phrase: JsSIP_C.causes.CONNECTION_ERROR, cause: JsSIP_C.causes.CONNECTION_ERROR }); } }; RTCSession.prototype.onRequestTimeout = function() { debug('onRequestTimeout'); if(this.status !== C.STATUS_TERMINATED) { this.terminate({ status_code: 408, reason_phrase: JsSIP_C.causes.REQUEST_TIMEOUT, cause: JsSIP_C.causes.REQUEST_TIMEOUT }); } }; RTCSession.prototype.onDialogError = function() { debugerror('onDialogError()'); if(this.status !== C.STATUS_TERMINATED) { this.terminate({ status_code: 500, reason_phrase: JsSIP_C.causes.DIALOG_ERROR, cause: JsSIP_C.causes.DIALOG_ERROR }); } }; // Called from DTMF handler. RTCSession.prototype.newDTMF = function(data) { debug('newDTMF()'); this.emit('newDTMF', data); }; /** * Private API. */ /** * RFC3261 13.3.1.4 * Response retransmissions cannot be accomplished by transaction layer * since it is destroyed when receiving the first 2xx answer */ function setInvite2xxTimer(request, body) { var self = this, timeout = Timers.T1; this.timers.invite2xxTimer = setTimeout(function invite2xxRetransmission() { if (self.status !== C.STATUS_WAITING_FOR_ACK) { return; } request.reply(200, null, ['Contact: '+ self.contact], body); if (timeout < Timers.T2) { timeout = timeout * 2; if (timeout > Timers.T2) { timeout = Timers.T2; } } self.timers.invite2xxTimer = setTimeout( invite2xxRetransmission, timeout ); }, timeout); } /** * RFC3261 14.2 * If a UAS generates a 2xx response and never receives an ACK, * it SHOULD generate a BYE to terminate the dialog. */ function setACKTimer() { var self = this; this.timers.ackTimer = setTimeout(function() { if(self.status === C.STATUS_WAITING_FOR_ACK) { debug('no ACK received, terminating the session'); clearTimeout(self.timers.invite2xxTimer); sendRequest.call(self, JsSIP_C.BYE); ended.call(self, 'remote', null, JsSIP_C.causes.NO_ACK); } }, Timers.TIMER_H); } function createRTCConnection(pcConfig, rtcConstraints) { var self = this; this.connection = new rtcninja.RTCPeerConnection(pcConfig, rtcConstraints); this.connection.onaddstream = function(event, stream) { self.emit('addstream', {stream: stream}); }; this.connection.onremovestream = function(event, stream) { self.emit('removestream', {stream: stream}); }; this.connection.oniceconnectionstatechange = function(event, state) { self.emit('iceconnetionstatechange', {state: state}); // TODO: Do more with different states. if (state === 'failed') { self.terminate({ cause: JsSIP_C.causes.RTP_TIMEOUT, status_code: 200, reason_phrase: JsSIP_C.causes.RTP_TIMEOUT }); } }; } function createLocalDescription(type, onSuccess, onFailure, constraints) { debug('createLocalDescription()'); var self = this; var connection = this.connection; this.rtcReady = false; if (type === 'offer') { connection.createOffer( // success createSucceeded, // failure function(error) { self.rtcReady = true; if (onFailure) { onFailure(error); } }, // constraints constraints ); } else if (type === 'answer') { connection.createAnswer( // success createSucceeded, // failure function(error) { self.rtcReady = true; if (onFailure) { onFailure(error); } }, // constraints constraints ); } else { throw new Error('createLocalDescription() | type must be "offer" or "answer", but "' +type+ '" was given'); } // createAnswer or createOffer succeeded function createSucceeded(desc) { connection.onicecandidate = function(event, candidate) { if (! candidate) { connection.onicecandidate = null; self.rtcReady = true; if (onSuccess) { onSuccess(connection.localDescription.sdp); } onSuccess = null; } }; connection.setLocalDescription(desc, // success function() { if (connection.iceGatheringState === 'complete') { self.rtcReady = true; if (onSuccess) { onSuccess(connection.localDescription.sdp); } onSuccess = null; } }, // failure function(error) { self.rtcReady = true; if (onFailure) { onFailure(error); } } ); } } /** * Dialog Management */ function createDialog(message, type, early) { var dialog, early_dialog, local_tag = (type === 'UAS') ? message.to_tag : message.from_tag, remote_tag = (type === 'UAS') ? message.from_tag : message.to_tag, id = message.call_id + local_tag + remote_tag; early_dialog = this.earlyDialogs[id]; // Early Dialog if (early) { if (early_dialog) { return true; } else { early_dialog = new Dialog(this, message, type, Dialog.C.STATUS_EARLY); // Dialog has been successfully created. if(early_dialog.error) { debug(early_dialog.error); failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR); return false; } else { this.earlyDialogs[id] = early_dialog; return true; } } } // Confirmed Dialog else { // In case the dialog is in _early_ state, update it if (early_dialog) { early_dialog.update(message, type); this.dialog = early_dialog; delete this.earlyDialogs[id]; return true; } // Otherwise, create a _confirmed_ dialog dialog = new Dialog(this, message, type); if(dialog.error) { debug(dialog.error); failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR); return false; } else { this.dialog = dialog; return true; } } } /** * In dialog INVITE Reception */ function receiveReinvite(request) { debug('receiveReinvite()'); var sdp, idx, direction, self = this, contentType = request.getHeader('Content-Type'), hold = false; // Emit 'reinvite'. this.emit('reinvite', {request: request}); if (request.body) { this.late_sdp = false; if (contentType !== 'application/sdp') { debug('invalid Content-Type'); request.reply(415); return; } sdp = Parser.parseSDP(request.body); for (idx=0; idx < sdp.media.length; idx++) { direction = sdp.media[idx].direction || sdp.direction || 'sendrecv'; if (direction === 'sendonly' || direction === 'inactive') { hold = true; } // If at least one of the streams is active don't emit 'hold'. else { hold = false; break; } } this.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'offer', sdp:request.body}), // success answer, // failure function() { request.reply(488); } ); } else { this.late_sdp = true; answer(); } function answer() { createSdp( // onSuccess function(sdp) { var extraHeaders = ['Contact: ' + self.contact]; handleSessionTimersInIncomingRequest.call(self, request, extraHeaders); if (self.late_sdp) { sdp = mangleOffer.call(self, sdp); } request.reply(200, null, extraHeaders, sdp, function() { self.status = C.STATUS_WAITING_FOR_ACK; setInvite2xxTimer.call(self, request, sdp); setACKTimer.call(self); } ); }, // onFailure function() { request.reply(500); } ); } function createSdp(onSuccess, onFailure) { if (! self.late_sdp) { if (self.remoteHold === true && hold === false) { self.remoteHold = false; onunhold.call(self, 'remote'); } else if (self.remoteHold === false && hold === true) { self.remoteHold = true; onhold.call(self, 'remote'); } createLocalDescription.call(self, 'answer', onSuccess, onFailure, self.rtcAnswerConstraints); } else { createLocalDescription.call(self, 'offer', onSuccess, onFailure, self.rtcOfferConstraints); } } } /** * In dialog UPDATE Reception */ function receiveUpdate(request) { debug('receiveUpdate()'); var sdp, idx, direction, self = this, contentType = request.getHeader('Content-Type'), hold = false; // Emit 'update'. this.emit('update', {request: request}); if (! request.body) { var extraHeaders = []; handleSessionTimersInIncomingRequest.call(this, request, extraHeaders); request.reply(200, null, extraHeaders); return; } if (contentType !== 'application/sdp') { debug('invalid Content-Type'); request.reply(415); return; } sdp = Parser.parseSDP(request.body); for (idx=0; idx < sdp.media.length; idx++) { direction = sdp.media[idx].direction || sdp.direction || 'sendrecv'; if (direction === 'sendonly' || direction === 'inactive') { hold = true; } // If at least one of the streams is active don't emit 'hold'. else { hold = false; break; } } this.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'offer', sdp:request.body}), // success function() { if (self.remoteHold === true && hold === false) { self.remoteHold = false; onunhold.call(self, 'remote'); } else if (self.remoteHold === false && hold === true) { self.remoteHold = true; onhold.call(self, 'remote'); } createLocalDescription.call(self, 'answer', // success function(sdp) { var extraHeaders = ['Contact: ' + self.contact]; handleSessionTimersInIncomingRequest.call(self, request, extraHeaders); request.reply(200, null, extraHeaders, sdp); }, // failure function() { request.reply(500); } ); }, // failure function() { request.reply(488); }, // Constraints. this.rtcAnswerConstraints ); } /** * Initial Request Sender */ function sendInitialRequest(mediaConstraints, rtcOfferConstraints, mediaStream) { var self = this; var request_sender = new RequestSender(self, this.ua); this.receiveResponse = function(response) { receiveInviteResponse.call(self, response); }; // If a local MediaStream is given use it. if (mediaStream) { userMediaSucceeded(mediaStream); // If at least audio or video is requested prompt getUserMedia. } else if (mediaConstraints.audio || mediaConstraints.video) { this.localMediaStreamLocallyGenerated = true; rtcninja.getUserMedia( mediaConstraints, userMediaSucceeded, userMediaFailed ); } // Otherwise don't prompt getUserMedia. else { userMediaSucceeded(null); } // User media succeeded function userMediaSucceeded(stream) { if (self.status === C.STATUS_TERMINATED) { return; } self.localMediaStream = stream; if (stream) { self.connection.addStream(stream); } connecting.call(self, self.request); createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, rtcOfferConstraints); } // User media failed function userMediaFailed() { if (self.status === C.STATUS_TERMINATED) { return; } failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS); } function rtcSucceeded(sdp) { if (self.isCanceled || self.status === C.STATUS_TERMINATED) { return; } self.request.body = sdp; self.status = C.STATUS_INVITE_SENT; request_sender.send(); } function rtcFailed() { if (self.status === C.STATUS_TERMINATED) { return; } failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR); } } /** * Reception of Response for Initial INVITE */ function receiveInviteResponse(response) { debug('receiveInviteResponse()'); var cause, dialog, self = this; // Handle 2XX retransmissions and responses from forked requests if (this.dialog && (response.status_code >=200 && response.status_code <=299)) { /* * If it is a retransmission from the endpoint that established * the dialog, send an ACK */ if (this.dialog.id.call_id === response.call_id && this.dialog.id.local_tag === response.from_tag && this.dialog.id.remote_tag === response.to_tag) { sendRequest.call(this, JsSIP_C.ACK); return; } // If not, send an ACK and terminate else { dialog = new Dialog(this, response, 'UAC'); if (dialog.error !== undefined) { debug(dialog.error); return; } dialog.sendRequest({ owner: {status: C.STATUS_TERMINATED}, onRequestTimeout: function(){}, onTransportError: function(){}, onDialogError: function(){}, receiveResponse: function(){} }, JsSIP_C.ACK); dialog.sendRequest({ owner: {status: C.STATUS_TERMINATED}, onRequestTimeout: function(){}, onTransportError: function(){}, onDialogError: function(){}, receiveResponse: function(){} }, JsSIP_C.BYE); return; } } // Proceed to cancellation if the user requested. if(this.isCanceled) { // Remove the flag. We are done. this.isCanceled = false; if(response.status_code >= 100 && response.status_code < 200) { this.request.cancel(this.cancelReason); } else if(response.status_code >= 200 && response.status_code < 299) { acceptAndTerminate.call(this, response); } return; } if(this.status !== C.STATUS_INVITE_SENT && this.status !== C.STATUS_1XX_RECEIVED) { return; } switch(true) { case /^100$/.test(response.status_code): this.status = C.STATUS_1XX_RECEIVED; break; case /^1[0-9]{2}$/.test(response.status_code): // Do nothing with 1xx responses without To tag. if (!response.to_tag) { debug('1xx response received without to tag'); break; } // Create Early Dialog if 1XX comes with contact if (response.hasHeader('contact')) { // An error on dialog creation will fire 'failed' event if(! createDialog.call(this, response, 'UAC', true)) { break; } } this.status = C.STATUS_1XX_RECEIVED; progress.call(this, 'remote', response); if (!response.body) { break; } this.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'pranswer', sdp:response.body}), // success null, // failure null ); break; case /^2[0-9]{2}$/.test(response.status_code): this.status = C.STATUS_CONFIRMED; if(!response.body) { acceptAndTerminate.call(this, response, 400, JsSIP_C.causes.MISSING_SDP); failed.call(this, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION); break; } // An error on dialog creation will fire 'failed' event if (! createDialog.call(this, response, 'UAC')) { break; } this.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'answer', sdp:response.body}), // success function() { // Handle Session Timers. handleSessionTimersInIncomingResponse.call(self, response); accepted.call(self, 'remote', response); sendRequest.call(self, JsSIP_C.ACK); confirmed.call(self, 'local', null); }, // failure function() { acceptAndTerminate.call(self, response, 488, 'Not Acceptable Here'); failed.call(self, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION); } ); break; default: cause = Utils.sipErrorCause(response.status_code); failed.call(this, 'remote', response, cause); } } /** * Send Re-INVITE */ function sendReinvite(options) { debug('sendReinvite()'); options = options || {}; var self = this, extraHeaders = options.extraHeaders || [], eventHandlers = options.eventHandlers || {}, rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null, succeeded = false; extraHeaders.push('Contact: ' + this.contact); extraHeaders.push('Content-Type: application/sdp'); // Session Timers. if (this.sessionTimers.running) { extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas')); } createLocalDescription.call(this, 'offer', // success function(sdp) { sdp = mangleOffer.call(self, sdp); var request = new RTCSession_Request(self, JsSIP_C.INVITE); request.send({ extraHeaders: extraHeaders, body: sdp, eventHandlers: { onSuccessResponse: function(response) { onSucceeded(response); succeeded = true; }, onErrorResponse: function(response) { onFailed(response); }, onTransportError: function() { self.onTransportError(); // Do nothing because session ends. }, onRequestTimeout: function() { self.onRequestTimeout(); // Do nothing because session ends. }, onDialogError: function() { self.onDialogError(); // Do nothing because session ends. } } }); }, // failure function() { onFailed(); }, // RTC constraints. rtcOfferConstraints ); function onSucceeded(response) { if (self.status === C.STATUS_TERMINATED) { return; } sendRequest.call(self, JsSIP_C.ACK); // If it is a 2XX retransmission exit now. if (succeeded) { return; } // Handle Session Timers. handleSessionTimersInIncomingResponse.call(self, response); // Must have SDP answer. if(! response.body) { onFailed(); return; } else if (response.getHeader('Content-Type') !== 'application/sdp') { onFailed(); return; } self.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'answer', sdp:response.body}), // success function() { if (eventHandlers.succeeded) { eventHandlers.succeeded(response); } }, // failure function() { onFailed(); } ); } function onFailed(response) { if (eventHandlers.failed) { eventHandlers.failed(response); } } } /** * Send UPDATE */ function sendUpdate(options) { debug('sendUpdate()'); options = options || {}; var self = this, extraHeaders = options.extraHeaders || [], eventHandlers = options.eventHandlers || {}, rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null, sdpOffer = options.sdpOffer || false, succeeded = false; extraHeaders.push('Contact: ' + this.contact); // Session Timers. if (this.sessionTimers.running) { extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas')); } if (sdpOffer) { extraHeaders.push('Content-Type: application/sdp'); createLocalDescription.call(this, 'offer', // success function(sdp) { sdp = mangleOffer.call(self, sdp); var request = new RTCSession_Request(self, JsSIP_C.UPDATE); request.send({ extraHeaders: extraHeaders, body: sdp, eventHandlers: { onSuccessResponse: function(response) { onSucceeded(response); succeeded = true; }, onErrorResponse: function(response) { onFailed(response); }, onTransportError: function() { self.onTransportError(); // Do nothing because session ends. }, onRequestTimeout: function() { self.onRequestTimeout(); // Do nothing because session ends. }, onDialogError: function() { self.onDialogError(); // Do nothing because session ends. } } }); }, // failure function() { onFailed(); }, // RTC constraints. rtcOfferConstraints ); } // No SDP. else { var request = new RTCSession_Request(self, JsSIP_C.UPDATE); request.send({ extraHeaders: extraHeaders, eventHandlers: { onSuccessResponse: function(response) { onSucceeded(response); }, onErrorResponse: function(response) { onFailed(response); }, onTransportError: function() { self.onTransportError(); // Do nothing because session ends. }, onRequestTimeout: function() { self.onRequestTimeout(); // Do nothing because session ends. }, onDialogError: function() { self.onDialogError(); // Do nothing because session ends. } } }); } function onSucceeded(response) { if (self.status === C.STATUS_TERMINATED) { return; } // If it is a 2XX retransmission exit now. if (succeeded) { return; } // Handle Session Timers. handleSessionTimersInIncomingResponse.call(self, response); // Must have SDP answer. if (sdpOffer) { if(! response.body) { onFailed(); return; } else if (response.getHeader('Content-Type') !== 'application/sdp') { onFailed(); return; } self.connection.setRemoteDescription( new rtcninja.RTCSessionDescription({type:'answer', sdp:response.body}), // success function() { if (eventHandlers.succeeded) { eventHandlers.succeeded(response); } }, // failure function() { onFailed(); } ); } // No SDP answer. else { if (eventHandlers.succeeded) { eventHandlers.succeeded(response); } } } function onFailed(response) { if (eventHandlers.failed) { eventHandlers.failed(response); } } } function acceptAndTerminate(response, status_code, reason_phrase) { debug('acceptAndTerminate()'); var extraHeaders = []; if (status_code) { reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || ''; extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"'); } // An error on dialog creation will fire 'failed' event if (this.dialog || createDialog.call(this, response, 'UAC')) { sendRequest.call(this, JsSIP_C.ACK); sendRequest.call(this, JsSIP_C.BYE, { extraHeaders: extraHeaders }); } // Update session status. this.status = C.STATUS_TERMINATED; } /** * Send a generic in-dialog Request */ function sendRequest(method, options) { debug('sendRequest()'); var request = new RTCSession_Request(this, method); request.send(options); } /** * Correctly set the SDP direction attributes if the call is on local hold */ function mangleOffer(sdp) { var idx, length, m; if (! this.localHold && ! this.remoteHold) { return sdp; } sdp = Parser.parseSDP(sdp); // Local hold. if (this.localHold && ! this.remoteHold) { debug('mangleOffer() | me on hold, mangling offer'); length = sdp.media.length; for (idx=0; idx<length; idx++) { m = sdp.media[idx]; if (!m.direction) { m.direction = 'sendonly'; } else if (m.direction === 'sendrecv') { m.direction = 'sendonly'; } else if (m.direction === 'recvonly') { m.direction = 'inactive'; } } } // Local and remote hold. else if (this.localHold && this.remoteHold) { debug('mangleOffer() | both on hold, mangling offer'); length = sdp.media.length; for (idx=0; idx<length; idx++) { m = sdp.media[idx]; m.direction = 'inactive'; } } // Remote hold. else if (this.remoteHold) { debug('mangleOffer() | remote on hold, mangling offer'); length = sdp.media.length; for (idx=0; idx<length; idx++) { m = sdp.media[idx]; if (!m.direction) { m.direction = 'recvonly'; } else if (m.direction === 'sendrecv') { m.direction = 'recvonly'; } else if (m.direction === 'recvonly') { m.direction = 'inactive'; } } } return Parser.writeSDP(sdp); } function setLocalMediaStatus() { if (this.localHold) { debug('setLocalMediaStatus() | me on hold, mutting my media'); toogleMuteAudio.call(this, true); toogleMuteVideo.call(this, true); return; } else if (this.remoteHold) { debug('setLocalMediaStatus() | remote on hold, mutting my media'); toogleMuteAudio.call(this, true); toogleMuteVideo.call(this, true); return; } if (this.audioMuted) { toogleMuteAudio.call(this, true); } else { toogleMuteAudio.call(this, false); } if (this.videoMuted) { toogleMuteVideo.call(this, true); } else { toogleMuteVideo.call(this, false); } } /** * Handle SessionTimers for an incoming INVITE or UPDATE. * @param {IncomingRequest} request * @param {Array} responseExtraHeaders Extra headers for the 200 response. */ function handleSessionTimersInIncomingRequest(request, responseExtraHeaders) { if (! this.sessionTimers.enabled) { return; } var session_expires_refresher; if (request.session_expires && request.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) { this.sessionTimers.currentExpires = request.session_expires; session_expires_refresher = request.session_expires_refresher || 'uas'; } else { this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires; session_expires_refresher = 'uas'; } responseExtraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + session_expires_refresher); this.sessionTimers.refresher = (session_expires_refresher === 'uas'); runSessionTimer.call(this); } /** * Handle SessionTimers for an incoming response to INVITE or UPDATE. * @param {IncomingResponse} response */ function handleSessionTimersInIncomingResponse(response) { if (! this.sessionTimers.enabled) { return; } var session_expires_refresher; if (response.session_expires && response.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) { this.sessionTimers.currentExpires = response.session_expires; session_expires_refresher = response.session_expires_refresher || 'uac'; } else { this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires; session_expires_refresher = 'uac'; } this.sessionTimers.refresher = (session_expires_refresher === 'uac'); runSessionTimer.call(this); } function runSessionTimer() { var self = this; var expires = this.sessionTimers.currentExpires; this.sessionTimers.running = true; clearTimeout(this.sessionTimers.timer); // I'm the refresher. if (this.sessionTimers.refresher) { this.sessionTimers.timer = setTimeout(function() { if (self.status === C.STATUS_TERMINATED) { return; } debug('runSessionTimer() | sending session refresh request'); sendUpdate.call(self, { eventHandlers: { succeeded: function(response) { handleSessionTimersInIncomingResponse.call(self, response); } } }); }, expires * 500); // Half the given interval (as the RFC states). } // I'm not the refresher. else { this.sessionTimers.timer = setTimeout(function() { if (self.status === C.STATUS_TERMINATED) { return; } debugerror('runSessionTimer() | timer expired, terminating the session'); self.terminate({ cause: JsSIP_C.causes.REQUEST_TIMEOUT, status_code: 408, reason_phrase: 'Session Timer Expired' }); }, expires * 1100); } } function toogleMuteAudio(mute) { var streamIdx, trackIdx, streamsLength, tracksLength, tracks, localStreams = this.connection.getLocalStreams(); streamsLength = localStreams.length; for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) { tracks = localStreams[streamIdx].getAudioTracks(); tracksLength = tracks.length; for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) { tracks[trackIdx].enabled = !mute; } } } function toogleMuteVideo(mute) { var streamIdx, trackIdx, streamsLength, tracksLength, tracks, localStreams = this.connection.getLocalStreams(); streamsLength = localStreams.length; for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) { tracks = localStreams[streamIdx].getVideoTracks(); tracksLength = tracks.length; for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) { tracks[trackIdx].enabled = !mute; } } } function newRTCSession(originator, request) { debug('newRTCSession'); if (originator === 'remote') { this.direction = 'incoming'; this.local_identity = request.to; this.remote_identity = request.from; } else if (originator === 'local'){ this.direction = 'outgoing'; this.local_identity = request.from; this.remote_identity = request.to; } this.ua.newRTCSession({ originator: originator, session: this, request: request }); } function connecting(request) { debug('session connecting'); this.emit('connecting', { request: request }); } function progress(originator, response) { debug('session progress'); this.emit('progress', { originator: originator, response: response || null }); } function accepted(originator, message) { debug('session accepted'); this.start_time = new Date(); this.emit('accepted', { originator: originator, response: message || null }); } function confirmed(originator, ack) { debug('session confirmed'); this.is_confirmed = true; this.emit('confirmed', { originator: originator, ack: ack || null }); } function ended(originator, message, cause) { debug('session ended'); this.end_time = new Date(); this.close(); this.emit('ended', { originator: originator, message: message || null, cause: cause }); } function failed(originator, message, cause) { debug('session failed'); this.close(); this.emit('failed', { originator: originator, message: message || null, cause: cause }); } function onhold(originator) { debug('session onhold'); setLocalMediaStatus.call(this); this.emit('hold', { originator: originator }); } function onunhold(originator) { debug('session onunhold'); setLocalMediaStatus.call(this); this.emit('unhold', { originator: originator }); } function onmute(options) { debug('session onmute'); setLocalMediaStatus.call(this); this.emit('muted', { audio: options.audio, video: options.video }); } function onunmute(options) { debug('session onunmute'); setLocalMediaStatus.call(this); this.emit('unmuted', { audio: options.audio, video: options.video }); } },{"./Constants":1,"./Dialog":2,"./Exceptions":5,"./Parser":10,"./RTCSession/DTMF":12,"./RTCSession/Request":13,"./RequestSender":15,"./SIPMessage":16,"./Timers":17,"./Transactions":18,"./Utils":22,"debug":29,"events":24,"rtcninja":34,"util":28}],12:[function(require,module,exports){ module.exports = DTMF; var C = { MIN_DURATION: 70, MAX_DURATION: 6000, DEFAULT_DURATION: 100, MIN_INTER_TONE_GAP: 50, DEFAULT_INTER_TONE_GAP: 500 }; /** * Expose C object. */ DTMF.C = C; /** * Dependencies. */ var debug = require('debug')('JsSIP:RTCSession:DTMF'); var debugerror = require('debug')('JsSIP:ERROR:RTCSession:DTMF'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('../Constants'); var Exceptions = require('../Exceptions'); var RTCSession = require('../RTCSession'); function DTMF(session) { this.owner = session; this.direction = null; this.tone = null; this.duration = null; } DTMF.prototype.send = function(tone, options) { var extraHeaders, body; if (tone === undefined) { throw new TypeError('Not enough arguments'); } this.direction = 'outgoing'; // Check RTCSession Status if (this.owner.status !== RTCSession.C.STATUS_CONFIRMED && this.owner.status !== RTCSession.C.STATUS_WAITING_FOR_ACK) { throw new Exceptions.InvalidStateError(this.owner.status); } // Get DTMF options options = options || {}; extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : []; this.eventHandlers = options.eventHandlers || {}; // Check tone type if (typeof tone === 'string' ) { tone = tone.toUpperCase(); } else if (typeof tone === 'number') { tone = tone.toString(); } else { throw new TypeError('Invalid tone: '+ tone); } // Check tone value if (!tone.match(/^[0-9A-D#*]$/)) { throw new TypeError('Invalid tone: '+ tone); } else { this.tone = tone; } // Duration is checked/corrected in RTCSession this.duration = options.duration; extraHeaders.push('Content-Type: application/dtmf-relay'); body = 'Signal=' + this.tone + '\r\n'; body += 'Duration=' + this.duration; this.owner.newDTMF({ originator: 'local', dtmf: this, request: this.request }); this.owner.dialog.sendRequest(this, JsSIP_C.INFO, { extraHeaders: extraHeaders, body: body }); }; DTMF.prototype.receiveResponse = function(response) { switch(true) { case /^1[0-9]{2}$/.test(response.status_code): // Ignore provisional responses. break; case /^2[0-9]{2}$/.test(response.status_code): debug('onSuccessResponse'); if (this.eventHandlers.onSuccessResponse) { this.eventHandlers.onSuccessResponse(response); } break; default: if (this.eventHandlers.onErrorResponse) { this.eventHandlers.onErrorResponse(response); } break; } }; DTMF.prototype.onRequestTimeout = function() { debugerror('onRequestTimeout'); if (this.eventHandlers.onRequestTimeout) { this.eventHandlers.onRequestTimeout(); } }; DTMF.prototype.onTransportError = function() { debugerror('onTransportError'); if (this.eventHandlers.onTransportError) { this.eventHandlers.onTransportError(); } }; DTMF.prototype.onDialogError = function() { debugerror('onDialogError'); if (this.eventHandlers.onDialogError) { this.eventHandlers.onDialogError(); } }; DTMF.prototype.init_incoming = function(request) { var body, reg_tone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/, reg_duration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/; this.direction = 'incoming'; this.request = request; request.reply(200); if (request.body) { body = request.body.split('\n'); if (body.length >= 1) { if (reg_tone.test(body[0])) { this.tone = body[0].replace(reg_tone,'$2'); } } if (body.length >=2) { if (reg_duration.test(body[1])) { this.duration = parseInt(body[1].replace(reg_duration,'$2'), 10); } } } if (!this.duration) { this.duration = C.DEFAULT_DURATION; } if (!this.tone) { debug('invalid INFO DTMF received, discarded'); } else { this.owner.newDTMF({ originator: 'remote', dtmf: this, request: request }); } }; },{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":29}],13:[function(require,module,exports){ module.exports = Request; /** * Dependencies. */ var debug = require('debug')('JsSIP:RTCSession:Request'); var debugerror = require('debug')('JsSIP:ERROR:RTCSession:Request'); debugerror.log = console.warn.bind(console); var JsSIP_C = require('../Constants'); var Exceptions = require('../Exceptions'); var RTCSession = require('../RTCSession'); function Request(session, method) { debug('new | %s', method); this.session = session; this.method = method; // Check RTCSession Status if (this.session.status !== RTCSession.C.STATUS_1XX_RECEIVED && this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ANSWER && this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ACK && this.session.status !== RTCSession.C.STATUS_CONFIRMED && this.session.status !== RTCSession.C.STATUS_TERMINATED) { throw new Exceptions.InvalidStateError(this.session.status); } /* * Allow sending BYE in TERMINATED status since the RTCSession * could had been terminated before the ACK had arrived. * RFC3261 Section 15, Paragraph 2 */ else if (this.session.status === RTCSession.C.STATUS_TERMINATED && method !== JsSIP_C.BYE) { throw new Exceptions.InvalidStateError(this.session.status); } } Request.prototype.send = function(options) { options = options || {}; var extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [], body = options.body || null; this.eventHandlers = options.eventHandlers || {}; this.session.dialog.sendRequest(this, this.method, { extraHeaders: extraHeaders, body: body }); }; Request.prototype.receiveResponse = function(response) { switch(true) { case /^1[0-9]{2}$/.test(response.status_code): debug('onProgressResponse'); if (this.eventHandlers.onProgressResponse) { this.eventHandlers.onProgressResponse(response); } break; case /^2[0-9]{2}$/.test(response.status_code): debug('onSuccessResponse'); if (this.eventHandlers.onSuccessResponse) { this.eventHandlers.onSuccessResponse(response); } break; default: debug('onErrorResponse'); if (this.eventHandlers.onErrorResponse) { this.eventHandlers.onErrorResponse(response); } break; } }; Request.prototype.onRequestTimeout = function() { debugerror('onRequestTimeout'); if (this.eventHandlers.onRequestTimeout) { this.eventHandlers.onRequestTimeout(); } }; Request.prototype.onTransportError = function() { debugerror('onTransportError'); if (this.eventHandlers.onTransportError) { this.eventHandlers.onTransportError(); } }; Request.prototype.onDialogError = function() { debugerror('onDialogError'); if (this.eventHandlers.onDialogError) { this.eventHandlers.onDialogError(); } }; },{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":29}],14:[function(require,module,exports){ module.exports = Registrator; /** * Dependecies */ var debug = require('debug')('JsSIP:Registrator'); var Utils = require('./Utils'); var JsSIP_C = require('./Constants'); var SIPMessage = require('./SIPMessage'); var RequestSender = require('./RequestSender'); function Registrator(ua, transport) { var reg_id=1; //Force reg_id to 1. this.ua = ua; this.transport = transport; this.registrar = ua.configuration.registrar_server; this.expires = ua.configuration.register_expires; // Call-ID and CSeq values RFC3261 10.2 this.call_id = Utils.createRandomToken(22); this.cseq = 0; // this.to_uri this.to_uri = ua.configuration.uri; this.registrationTimer = null; // Set status this.registered = false; // Contact header this.contact = this.ua.contact.toString(); // sip.ice media feature tag (RFC 5768) this.contact += ';+sip.ice'; // Custom headers for REGISTER and un-REGISTER. this.extraHeaders = []; // Custom Contact header params for REGISTER and un-REGISTER. this.extraContactParams = ''; if(reg_id) { this.contact += ';reg-id='+ reg_id; this.contact += ';+sip.instance="<urn:uuid:'+ this.ua.configuration.instance_id+'>"'; } } Registrator.prototype = { setExtraHeaders: function(extraHeaders) { if (! Array.isArray(extraHeaders)) { extraHeaders = []; } this.extraHeaders = extraHeaders.slice(); }, setExtraContactParams: function(extraContactParams) { if (! (extraContactParams instanceof Object)) { extraContactParams = {}; } // Reset it. this.extraContactParams = ''; for(var param_key in extraContactParams) { var param_value = extraContactParams[param_key]; this.extraContactParams += (';' + param_key); if (param_value) { this.extraContactParams += ('=' + param_value); } } }, register: function() { var request_sender, cause, extraHeaders, self = this; extraHeaders = this.extraHeaders.slice(); extraHeaders.push('Contact: ' + this.contact + ';expires=' + this.expires + this.extraContactParams); extraHeaders.push('Expires: '+ this.expires); this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, { 'to_uri': this.to_uri, 'call_id': this.call_id, 'cseq': (this.cseq += 1) }, extraHeaders); request_sender = new RequestSender(this, this.ua); this.receiveResponse = function(response) { var contact, expires, contacts = response.getHeaders('contact').length; // Discard responses to older REGISTER/un-REGISTER requests. if(response.cseq !== this.cseq) { return; } // Clear registration timer if (this.registrationTimer !== null) { clearTimeout(this.registrationTimer); this.registrationTimer = null; } switch(true) { case /^1[0-9]{2}$/.test(response.status_code): // Ignore provisional responses. break; case /^2[0-9]{2}$/.test(response.status_code): if(response.hasHeader('expires')) { expires = response.getHeader('expires'); } // Search the Contact pointing to us and update the expires value accordingly. if (!contacts) { debug('no Contact header in response to REGISTER, response ignored'); break; } while(contacts--) { contact = response.parseHeader('contact', contacts); if(contact.uri.user === this.ua.contact.uri.user) { expires = contact.getParam('expires'); break; } else { contact = null; } } if (!contact) { debug('no Contact header pointing to us, response ignored'); break; } if(!expires) { expires = this.expires; } // Re-Register before the expiration interval has elapsed. // For that, decrease the expires value. ie: 3 seconds this.registrationTimer = setTimeout(function() { self.registrationTimer = null; self.register(); }, (expires * 1000) - 3000); //Save gruu values if (contact.hasParam('temp-gruu')) { this.ua.contact.temp_gruu = contact.getParam('temp-gruu').replace(/"/g,''); } if (contact.hasParam('pub-gruu')) { this.ua.contact.pub_gruu = contact.getParam('pub-gruu').replace(/"/g,''); } if (! this.registered) { this.registered = true; this.ua.registered({ response: response }); } break; // Interval too brief RFC3261 10.2.8 case /^423$/.test(response.status_code): if(response.hasHeader('min-expires')) { // Increase our registration interval to the suggested minimum this.expires = response.getHeader('min-expires'); // Attempt the registration again immediately this.register(); } else { //This response MUST contain a Min-Expires header field debug('423 response received for REGISTER without Min-Expires'); this.registrationFailure(response, JsSIP_C.causes.SIP_FAILURE_CODE); } break; default: cause = Utils.sipErrorCause(response.status_code); this.registrationFailure(response, cause); } }; this.onRequestTimeout = function() { this.registrationFailure(null, JsSIP_C.causes.REQUEST_TIMEOUT); }; this.onTransportError = function() { this.registrationFailure(null, JsSIP_C.causes.CONNECTION_ERROR); }; request_sender.send(); }, unregister: function(options) { var extraHeaders; if(!this.registered) { debug('already unregistered'); return; } options = options || {}; this.registered = false; // Clear the registration timer. if (this.registrationTimer !== null) { clearTimeout(this.registrationTimer); this.registrationTimer = null; } extraHeaders = this.extraHeaders.slice(); if(options.all) { extraHeaders.push('Contact: *' + this.extraContactParams); extraHeaders.push('Expires: 0'); this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, { 'to_uri': this.to_uri, 'call_id': this.call_id, 'cseq': (this.cseq += 1) }, extraHeaders); } else { extraHeaders.push('Contact: '+ this.contact + ';expires=0' + this.extraContactParams); extraHeaders.push('Expires: 0'); this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, { 'to_uri': this.to_uri, 'call_id': this.call_id, 'cseq': (this.cseq += 1) }, extraHeaders); } var request_sender = new RequestSender(this, this.ua); this.receiveResponse = function(response) { var cause; switch(true) { case /^1[0-9]{2}$/.test(response.status_code): // Ignore provisional responses. break; case /^2[0-9]{2}$/.test(response.status_code): this.unregistered(response); break; default: cause = Utils.sipErrorCause(response.status_code); this.unregistered(response, cause); } }; this.onRequestTimeout = function() { this.unregistered(null, JsSIP_C.causes.REQUEST_TIMEOUT); }; this.onTransportError = function() { this.unregistered(null, JsSIP_C.causes.CONNECTION_ERROR); }; request_sender.send(); }, registrationFailure: function(response, cause) { this.ua.registrationFailed({ response: response || null, cause: cause }); if (this.registered) { this.registered = false; this.ua.unregistered({ response: response || null, cause: cause }); } }, unregistered: function(response, cause) { this.registered = false; this.ua.unregistered({ response: response || null, cause: cause || null }); }, onTransportClosed: function() { if (this.registrationTimer !== null) { clearTimeout(this.registrationTimer); this.registrationTimer = null; } if(this.registered) { this.registered = false; this.ua.unregistered({}); } }, close: function() { if (this.registered) { this.unregister(); } } }; },{"./Constants":1,"./RequestSender":15,"./SIPMessage":16,"./Utils":22,"debug":29}],15:[function(require,module,exports){ module.exports = RequestSender; /** * Dependencies. */ var debug = require('debug')('JsSIP:RequestSender'); var JsSIP_C = require('./Constants'); var UA = require('./UA'); var DigestAuthentication = require('./DigestAuthentication'); var Transactions = require('./Transactions'); function RequestSender(applicant, ua) { this.ua = ua; this.applicant = applicant; this.method = applicant.request.method; this.request = applicant.request; this.credentials = null; this.challenged = false; this.staled = false; // If ua is in closing process or even closed just allow sending Bye and ACK if (ua.status === UA.C.STATUS_USER_CLOSED && (this.method !== JsSIP_C.BYE || this.method !== JsSIP_C.ACK)) { this.onTransportError(); } } /** * Create the client transaction and send the message. */ RequestSender.prototype = { send: function() { switch(this.method) { case 'INVITE': this.clientTransaction = new Transactions.InviteClientTransaction(this, this.request, this.ua.transport); break; case 'ACK': this.clientTransaction = new Transactions.AckClientTransaction(this, this.request, this.ua.transport); break; default: this.clientTransaction = new Transactions.NonInviteClientTransaction(this, this.request, this.ua.transport); } this.clientTransaction.send(); }, /** * Callback fired when receiving a request timeout error from the client transaction. * To be re-defined by the applicant. */ onRequestTimeout: function() { this.applicant.onRequestTimeout(); }, /** * Callback fired when receiving a transport error from the client transaction. * To be re-defined by the applicant. */ onTransportError: function() { this.applicant.onTransportError(); }, /** * Called from client transaction when receiving a correct response to the request. * Authenticate request if needed or pass the response back to the applicant. */ receiveResponse: function(response) { var cseq, challenge, authorization_header_name, status_code = response.status_code; /* * Authentication * Authenticate once. _challenged_ flag used to avoid infinite authentications. */ if ((status_code === 401 || status_code === 407) && this.ua.configuration.password !== null) { // Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header. if (response.status_code === 401) { challenge = response.parseHeader('www-authenticate'); authorization_header_name = 'authorization'; } else { challenge = response.parseHeader('proxy-authenticate'); authorization_header_name = 'proxy-authorization'; } // Verify it seems a valid challenge. if (! challenge) { debug(response.status_code + ' with wrong or missing challenge, cannot authenticate'); this.applicant.receiveResponse(response); return; } if (!this.challenged || (!this.staled && challenge.stale === true)) { if (!this.credentials) { this.credentials = new DigestAuthentication(this.ua); } // Verify that the challenge is really valid. if (!this.credentials.authenticate(this.request, challenge)) { this.applicant.receiveResponse(response); return; } this.challenged = true; if (challenge.stale) { this.staled = true; } if (response.method === JsSIP_C.REGISTER) { cseq = this.applicant.cseq += 1; } else if (this.request.dialog){ cseq = this.request.dialog.local_seqnum += 1; } else { cseq = this.request.cseq + 1; this.request.cseq = cseq; } this.request.setHeader('cseq', cseq +' '+ this.method); this.request.setHeader(authorization_header_name, this.credentials.toString()); this.send(); } else { this.applicant.receiveResponse(response); } } else { this.applicant.receiveResponse(response); } } }; },{"./Constants":1,"./DigestAuthentication":4,"./Transactions":18,"./UA":20,"debug":29}],16:[function(require,module,exports){ module.exports = { OutgoingRequest: OutgoingRequest, IncomingRequest: IncomingRequest, IncomingResponse: IncomingResponse }; /** * Dependencies. */ var debug = require('debug')('JsSIP:SIPMessage'); var JsSIP_C = require('./Constants'); var Utils = require('./Utils'); var NameAddrHeader = require('./NameAddrHeader'); var Grammar = require('./Grammar'); /** * -param {String} method request method * -param {String} ruri request uri * -param {UA} ua * -param {Object} params parameters that will have priority over ua.configuration parameters: * <br> * - cseq, call_id, from_tag, from_uri, from_display_name, to_uri, to_tag, route_set * -param {Object} [headers] extra headers * -param {String} [body] */ function OutgoingRequest(method, ruri, ua, params, extraHeaders, body) { var to, from, call_id, cseq; params = params || {}; // Mandatory parameters check if(!method || !ruri || !ua) { return null; } this.ua = ua; this.headers = {}; this.method = method; this.ruri = ruri; this.body = body; this.extraHeaders = extraHeaders && extraHeaders.slice() || []; // Fill the Common SIP Request Headers // Route if (params.route_set) { this.setHeader('route', params.route_set); } else if (ua.configuration.use_preloaded_route){ this.setHeader('route', ua.transport.server.sip_uri); } // Via // Empty Via header. Will be filled by the client transaction. this.setHeader('via', ''); // Max-Forwards this.setHeader('max-forwards', JsSIP_C.MAX_FORWARDS); // To to = (params.to_display_name || params.to_display_name === 0) ? '"' + params.to_display_name + '" ' : ''; to += '<' + (params.to_uri || ruri) + '>'; to += params.to_tag ? ';tag=' + params.to_tag : ''; this.to = new NameAddrHeader.parse(to); this.setHeader('to', to); // From if (params.from_display_name || params.from_display_name === 0) { from = '"' + params.from_display_name + '" '; } else if (ua.configuration.display_name) { from = '"' + ua.configuration.display_name + '" '; } else { from = ''; } from += '<' + (params.from_uri || ua.configuration.uri) + '>;tag='; from += params.from_tag || Utils.newTag(); this.from = new NameAddrHeader.parse(from); this.setHeader('from', from); // Call-ID call_id = params.call_id || (ua.configuration.jssip_id + Utils.createRandomToken(15)); this.call_id = call_id; this.setHeader('call-id', call_id); // CSeq cseq = params.cseq || Math.floor(Math.random() * 10000); this.cseq = cseq; this.setHeader('cseq', cseq + ' ' + method); } OutgoingRequest.prototype = { /** * Replace the the given header by the given value. * -param {String} name header name * -param {String | Array} value header value */ setHeader: function(name, value) { this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value]; }, /** * Get the value of the given header name at the given position. * -param {String} name header name * -returns {String|undefined} Returns the specified header, null if header doesn't exist. */ getHeader: function(name) { var regexp, idx, length = this.extraHeaders.length, header = this.headers[Utils.headerize(name)]; if(header) { if(header[0]) { return header[0]; } } else { regexp = new RegExp('^\\s*'+ name +'\\s*:','i'); for (idx=0; idx<length; idx++) { header = this.extraHeaders[idx]; if (regexp.test(header)) { return header.substring(header.indexOf(':')+1).trim(); } } } return; }, /** * Get the header/s of the given name. * -param {String} name header name * -returns {Array} Array with all the headers of the specified name. */ getHeaders: function(name) { var idx, length, regexp, header = this.headers[Utils.headerize(name)], result = []; if (header) { length = header.length; for (idx = 0; idx < length; idx++) { result.push(header[idx]); } return result; } else { length = this.extraHeaders.length; regexp = new RegExp('^\\s*'+ name +'\\s*:','i'); for (idx=0; idx<length; idx++) { header = this.extraHeaders[idx]; if (regexp.test(header)) { result.push(header.substring(header.indexOf(':')+1).trim()); } } return result; } }, /** * Verify the existence of the given header. * -param {String} name header name * -returns {boolean} true if header with given name exists, false otherwise */ hasHeader: function(name) { var regexp, idx, length = this.extraHeaders.length; if (this.headers[Utils.headerize(name)]) { return true; } else { regexp = new RegExp('^\\s*'+ name +'\\s*:','i'); for (idx=0; idx<length; idx++) { if (regexp.test(this.extraHeaders[idx])) { return true; } } } return false; }, toString: function() { var msg = '', header, length, idx, supported = []; msg += this.method + ' ' + this.ruri + ' SIP/2.0\r\n'; for (header in this.headers) { length = this.headers[header].length; for (idx = 0; idx < length; idx++) { msg += header + ': ' + this.headers[header][idx] + '\r\n'; } } length = this.extraHeaders.length; for (idx = 0; idx < length; idx++) { msg += this.extraHeaders[idx].trim() +'\r\n'; } // Supported switch (this.method) { case JsSIP_C.REGISTER: supported.push('path', 'gruu'); break; case JsSIP_C.INVITE: if (this.ua.configuration.session_timers) { supported.push('timer'); } if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) { supported.push('gruu'); } supported.push('ice'); break; case JsSIP_C.UPDATE: if (this.ua.configuration.session_timers) { supported.push('timer'); } supported.push('ice'); break; } supported.push('outbound'); // Allow msg += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n'; msg += 'Supported: ' + supported +'\r\n'; msg += 'User-Agent: ' + JsSIP_C.USER_AGENT +'\r\n'; if (this.body) { length = Utils.str_utf8_length(this.body); msg += 'Content-Length: ' + length + '\r\n\r\n'; msg += this.body; } else { msg += 'Content-Length: 0\r\n\r\n'; } return msg; } }; function IncomingMessage(){ this.data = null; this.headers = null; this.method = null; this.via = null; this.via_branch = null; this.call_id = null; this.cseq = null; this.from = null; this.from_tag = null; this.to = null; this.to_tag = null; this.body = null; } IncomingMessage.prototype = { /** * Insert a header of the given name and value into the last position of the * header array. */ addHeader: function(name, value) { var header = { raw: value }; name = Utils.headerize(name); if(this.headers[name]) { this.headers[name].push(header); } else { this.headers[name] = [header]; } }, /** * Get the value of the given header name at the given position. */ getHeader: function(name) { var header = this.headers[Utils.headerize(name)]; if(header) { if(header[0]) { return header[0].raw; } } else { return; } }, /** * Get the header/s of the given name. */ getHeaders: function(name) { var idx, length, header = this.headers[Utils.headerize(name)], result = []; if(!header) { return []; } length = header.length; for (idx = 0; idx < length; idx++) { result.push(header[idx].raw); } return result; }, /** * Verify the existence of the given header. */ hasHeader: function(name) { return(this.headers[Utils.headerize(name)]) ? true : false; }, /** * Parse the given header on the given index. * -param {String} name header name * -param {Number} [idx=0] header index * -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error. */ parseHeader: function(name, idx) { var header, value, parsed; name = Utils.headerize(name); idx = idx || 0; if(!this.headers[name]) { debug('header "' + name + '" not present'); return; } else if(idx >= this.headers[name].length) { debug('not so many "' + name + '" headers present'); return; } header = this.headers[name][idx]; value = header.raw; if(header.parsed) { return header.parsed; } //substitute '-' by '_' for grammar rule matching. parsed = Grammar.parse(value, name.replace(/-/g, '_')); if(parsed === -1) { this.headers[name].splice(idx, 1); //delete from headers debug('error parsing "' + name + '" header field with value "' + value + '"'); return; } else { header.parsed = parsed; return parsed; } }, /** * Message Header attribute selector. Alias of parseHeader. * -param {String} name header name * -param {Number} [idx=0] header index * -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error. * * -example * message.s('via',3).port */ s: function(name, idx) { return this.parseHeader(name, idx); }, /** * Replace the value of the given header by the value. * -param {String} name header name * -param {String} value header value */ setHeader: function(name, value) { var header = { raw: value }; this.headers[Utils.headerize(name)] = [header]; }, toString: function() { return this.data; } }; function IncomingRequest(ua) { this.ua = ua; this.headers = {}; this.ruri = null; this.transport = null; this.server_transaction = null; } IncomingRequest.prototype = new IncomingMessage(); /** * Stateful reply. * -param {Number} code status code * -param {String} reason reason phrase * -param {Object} headers extra headers * -param {String} body body * -param {Function} [onSuccess] onSuccess callback * -param {Function} [onFailure] onFailure callback */ IncomingRequest.prototype.reply = function(code, reason, extraHeaders, body, onSuccess, onFailure) { var rr, vias, length, idx, response, supported = [], to = this.getHeader('To'), r = 0, v = 0; code = code || null; reason = reason || null; // Validate code and reason values if (!code || (code < 100 || code > 699)) { throw new TypeError('Invalid status_code: '+ code); } else if (reason && typeof reason !== 'string' && !(reason instanceof String)) { throw new TypeError('Invalid reason_phrase: '+ reason); } reason = reason || JsSIP_C.REASON_PHRASE[code] || ''; extraHeaders = extraHeaders && extraHeaders.slice() || []; response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n'; if(this.method === JsSIP_C.INVITE && code > 100 && code <= 200) { rr = this.getHeaders('record-route'); length = rr.length; for(r; r < length; r++) { response += 'Record-Route: ' + rr[r] + '\r\n'; } } vias = this.getHeaders('via'); length = vias.length; for(v; v < length; v++) { response += 'Via: ' + vias[v] + '\r\n'; } if(!this.to_tag && code > 100) { to += ';tag=' + Utils.newTag(); } else if(this.to_tag && !this.s('to').hasParam('tag')) { to += ';tag=' + this.to_tag; } response += 'To: ' + to + '\r\n'; response += 'From: ' + this.getHeader('From') + '\r\n'; response += 'Call-ID: ' + this.call_id + '\r\n'; response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n'; length = extraHeaders.length; for (idx = 0; idx < length; idx++) { response += extraHeaders[idx].trim() +'\r\n'; } // Supported switch (this.method) { case JsSIP_C.INVITE: if (this.ua.configuration.session_timers) { supported.push('timer'); } if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) { supported.push('gruu'); } supported.push('ice'); break; case JsSIP_C.UPDATE: if (this.ua.configuration.session_timers) { supported.push('timer'); } if (body) { supported.push('ice'); } } supported.push('outbound'); // Allow and Accept if (this.method === JsSIP_C.OPTIONS) { response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n'; response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n'; } else if (code === 405) { response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n'; } else if (code === 415 ) { response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n'; } response += 'Supported: ' + supported +'\r\n'; if(body) { length = Utils.str_utf8_length(body); response += 'Content-Type: application/sdp\r\n'; response += 'Content-Length: ' + length + '\r\n\r\n'; response += body; } else { response += 'Content-Length: ' + 0 + '\r\n\r\n'; } this.server_transaction.receiveResponse(code, response, onSuccess, onFailure); }; /** * Stateless reply. * -param {Number} code status code * -param {String} reason reason phrase */ IncomingRequest.prototype.reply_sl = function(code, reason) { var to, response, v = 0, vias = this.getHeaders('via'), length = vias.length; code = code || null; reason = reason || null; // Validate code and reason values if (!code || (code < 100 || code > 699)) { throw new TypeError('Invalid status_code: '+ code); } else if (reason && typeof reason !== 'string' && !(reason instanceof String)) { throw new TypeError('Invalid reason_phrase: '+ reason); } reason = reason || JsSIP_C.REASON_PHRASE[code] || ''; response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n'; for(v; v < length; v++) { response += 'Via: ' + vias[v] + '\r\n'; } to = this.getHeader('To'); if(!this.to_tag && code > 100) { to += ';tag=' + Utils.newTag(); } else if(this.to_tag && !this.s('to').hasParam('tag')) { to += ';tag=' + this.to_tag; } response += 'To: ' + to + '\r\n'; response += 'From: ' + this.getHeader('From') + '\r\n'; response += 'Call-ID: ' + this.call_id + '\r\n'; response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n'; response += 'Content-Length: ' + 0 + '\r\n\r\n'; this.transport.send(response); }; function IncomingResponse() { this.headers = {}; this.status_code = null; this.reason_phrase = null; } IncomingResponse.prototype = new IncomingMessage(); },{"./Constants":1,"./Grammar":6,"./NameAddrHeader":9,"./Utils":22,"debug":29}],17:[function(require,module,exports){ var T1 = 500, T2 = 4000, T4 = 5000; var Timers = { T1: T1, T2: T2, T4: T4, TIMER_B: 64 * T1, TIMER_D: 0 * T1, TIMER_F: 64 * T1, TIMER_H: 64 * T1, TIMER_I: 0 * T1, TIMER_J: 0 * T1, TIMER_K: 0 * T4, TIMER_L: 64 * T1, TIMER_M: 64 * T1, PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1 }; module.exports = Timers; },{}],18:[function(require,module,exports){ module.exports = { C: null, NonInviteClientTransaction: NonInviteClientTransaction, InviteClientTransaction: InviteClientTransaction, AckClientTransaction: AckClientTransaction, NonInviteServerTransaction: NonInviteServerTransaction, InviteServerTransaction: InviteServerTransaction, checkTransaction: checkTransaction }; var C = { // Transaction states STATUS_TRYING: 1, STATUS_PROCEEDING: 2, STATUS_CALLING: 3, STATUS_ACCEPTED: 4, STATUS_COMPLETED: 5, STATUS_TERMINATED: 6, STATUS_CONFIRMED: 7, // Transaction types NON_INVITE_CLIENT: 'nict', NON_INVITE_SERVER: 'nist', INVITE_CLIENT: 'ict', INVITE_SERVER: 'ist' }; /** * Expose C object. */ module.exports.C = C; /** * Dependencies. */ var util = require('util'); var events = require('events'); var debugnict = require('debug')('JsSIP:NonInviteClientTransaction'); var debugict = require('debug')('JsSIP:InviteClientTransaction'); var debugact = require('debug')('JsSIP:AckClientTransaction'); var debugnist = require('debug')('JsSIP:NonInviteServerTransaction'); var debugist = require('debug')('JsSIP:InviteServerTransaction'); var JsSIP_C = require('./Constants'); var Timers = require('./Timers'); function NonInviteClientTransaction(request_sender, request, transport) { var via, via_transport; this.type = C.NON_INVITE_CLIENT; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; if (request_sender.ua.configuration.hack_via_tcp) { via_transport = 'TCP'; } else if (request_sender.ua.configuration.hack_via_ws) { via_transport = 'WS'; } else { via_transport = transport.server.scheme; } via = 'SIP/2.0/' + via_transport; via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; this.request.setHeader('via', via); this.request_sender.ua.newTransaction(this); events.EventEmitter.call(this); } util.inherits(NonInviteClientTransaction, events.EventEmitter); NonInviteClientTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged'); }; NonInviteClientTransaction.prototype.send = function() { var tr = this; this.stateChanged(C.STATUS_TRYING); this.F = setTimeout(function() {tr.timer_F();}, Timers.TIMER_F); if(!this.transport.send(this.request)) { this.onTransportError(); } }; NonInviteClientTransaction.prototype.onTransportError = function() { debugnict('transport error occurred, deleting transaction ' + this.id); clearTimeout(this.F); clearTimeout(this.K); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); this.request_sender.onTransportError(); }; NonInviteClientTransaction.prototype.timer_F = function() { debugnict('Timer F expired for transaction ' + this.id); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); this.request_sender.onRequestTimeout(); }; NonInviteClientTransaction.prototype.timer_K = function() { this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); }; NonInviteClientTransaction.prototype.receiveResponse = function(response) { var tr = this, status_code = response.status_code; if(status_code < 200) { switch(this.state) { case C.STATUS_TRYING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_PROCEEDING); this.request_sender.receiveResponse(response); break; } } else { switch(this.state) { case C.STATUS_TRYING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_COMPLETED); clearTimeout(this.F); if(status_code === 408) { this.request_sender.onRequestTimeout(); } else { this.request_sender.receiveResponse(response); } this.K = setTimeout(function() {tr.timer_K();}, Timers.TIMER_K); break; case C.STATUS_COMPLETED: break; } } }; function InviteClientTransaction(request_sender, request, transport) { var via, tr = this, via_transport; this.type = C.INVITE_CLIENT; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; if (request_sender.ua.configuration.hack_via_tcp) { via_transport = 'TCP'; } else if (request_sender.ua.configuration.hack_via_ws) { via_transport = 'WS'; } else { via_transport = transport.server.scheme; } via = 'SIP/2.0/' + via_transport; via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; this.request.setHeader('via', via); this.request_sender.ua.newTransaction(this); // TODO: Adding here the cancel() method is a hack that must be fixed. // Add the cancel property to the request. //Will be called from the request instance, not the transaction itself. this.request.cancel = function(reason) { tr.cancel_request(tr, reason); }; events.EventEmitter.call(this); } util.inherits(InviteClientTransaction, events.EventEmitter); InviteClientTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged'); }; InviteClientTransaction.prototype.send = function() { var tr = this; this.stateChanged(C.STATUS_CALLING); this.B = setTimeout(function() { tr.timer_B(); }, Timers.TIMER_B); if(!this.transport.send(this.request)) { this.onTransportError(); } }; InviteClientTransaction.prototype.onTransportError = function() { clearTimeout(this.B); clearTimeout(this.D); clearTimeout(this.M); if (this.state !== C.STATUS_ACCEPTED) { debugict('transport error occurred, deleting transaction ' + this.id); this.request_sender.onTransportError(); } this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); }; // RFC 6026 7.2 InviteClientTransaction.prototype.timer_M = function() { debugict('Timer M expired for transaction ' + this.id); if(this.state === C.STATUS_ACCEPTED) { clearTimeout(this.B); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); } }; // RFC 3261 17.1.1 InviteClientTransaction.prototype.timer_B = function() { debugict('Timer B expired for transaction ' + this.id); if(this.state === C.STATUS_CALLING) { this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); this.request_sender.onRequestTimeout(); } }; InviteClientTransaction.prototype.timer_D = function() { debugict('Timer D expired for transaction ' + this.id); clearTimeout(this.B); this.stateChanged(C.STATUS_TERMINATED); this.request_sender.ua.destroyTransaction(this); }; InviteClientTransaction.prototype.sendACK = function(response) { var tr = this; this.ack = 'ACK ' + this.request.ruri + ' SIP/2.0\r\n'; this.ack += 'Via: ' + this.request.headers.Via.toString() + '\r\n'; if(this.request.headers.Route) { this.ack += 'Route: ' + this.request.headers.Route.toString() + '\r\n'; } this.ack += 'To: ' + response.getHeader('to') + '\r\n'; this.ack += 'From: ' + this.request.headers.From.toString() + '\r\n'; this.ack += 'Call-ID: ' + this.request.headers['Call-ID'].toString() + '\r\n'; this.ack += 'CSeq: ' + this.request.headers.CSeq.toString().split(' ')[0]; this.ack += ' ACK\r\n'; this.ack += 'Content-Length: 0\r\n\r\n'; this.D = setTimeout(function() {tr.timer_D();}, Timers.TIMER_D); this.transport.send(this.ack); }; InviteClientTransaction.prototype.cancel_request = function(tr, reason) { var request = tr.request; this.cancel = JsSIP_C.CANCEL + ' ' + request.ruri + ' SIP/2.0\r\n'; this.cancel += 'Via: ' + request.headers.Via.toString() + '\r\n'; if(this.request.headers.Route) { this.cancel += 'Route: ' + request.headers.Route.toString() + '\r\n'; } this.cancel += 'To: ' + request.headers.To.toString() + '\r\n'; this.cancel += 'From: ' + request.headers.From.toString() + '\r\n'; this.cancel += 'Call-ID: ' + request.headers['Call-ID'].toString() + '\r\n'; this.cancel += 'CSeq: ' + request.headers.CSeq.toString().split(' ')[0] + ' CANCEL\r\n'; if(reason) { this.cancel += 'Reason: ' + reason + '\r\n'; } this.cancel += 'Content-Length: 0\r\n\r\n'; // Send only if a provisional response (>100) has been received. if(this.state === C.STATUS_PROCEEDING) { this.transport.send(this.cancel); } }; InviteClientTransaction.prototype.receiveResponse = function(response) { var tr = this, status_code = response.status_code; if(status_code >= 100 && status_code <= 199) { switch(this.state) { case C.STATUS_CALLING: this.stateChanged(C.STATUS_PROCEEDING); this.request_sender.receiveResponse(response); break; case C.STATUS_PROCEEDING: this.request_sender.receiveResponse(response); break; } } else if(status_code >= 200 && status_code <= 299) { switch(this.state) { case C.STATUS_CALLING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_ACCEPTED); this.M = setTimeout(function() { tr.timer_M(); }, Timers.TIMER_M); this.request_sender.receiveResponse(response); break; case C.STATUS_ACCEPTED: this.request_sender.receiveResponse(response); break; } } else if(status_code >= 300 && status_code <= 699) { switch(this.state) { case C.STATUS_CALLING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_COMPLETED); this.sendACK(response); this.request_sender.receiveResponse(response); break; case C.STATUS_COMPLETED: this.sendACK(response); break; } } }; function AckClientTransaction(request_sender, request, transport) { var via, via_transport; this.transport = transport; this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000); this.request_sender = request_sender; this.request = request; if (request_sender.ua.configuration.hack_via_tcp) { via_transport = 'TCP'; } else if (request_sender.ua.configuration.hack_via_ws) { via_transport = 'WS'; } else { via_transport = transport.server.scheme; } via = 'SIP/2.0/' + via_transport; via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id; this.request.setHeader('via', via); events.EventEmitter.call(this); } util.inherits(AckClientTransaction, events.EventEmitter); AckClientTransaction.prototype.send = function() { if(!this.transport.send(this.request)) { this.onTransportError(); } }; AckClientTransaction.prototype.onTransportError = function() { debugact('transport error occurred for transaction ' + this.id); this.request_sender.onTransportError(); }; function NonInviteServerTransaction(request, ua) { this.type = C.NON_INVITE_SERVER; this.id = request.via_branch; this.request = request; this.transport = request.transport; this.ua = ua; this.last_response = ''; request.server_transaction = this; this.state = C.STATUS_TRYING; ua.newTransaction(this); events.EventEmitter.call(this); } util.inherits(NonInviteServerTransaction, events.EventEmitter); NonInviteServerTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged'); }; NonInviteServerTransaction.prototype.timer_J = function() { debugnist('Timer J expired for transaction ' + this.id); this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); }; NonInviteServerTransaction.prototype.onTransportError = function() { if (!this.transportError) { this.transportError = true; debugnist('transport error occurred, deleting transaction ' + this.id); clearTimeout(this.J); this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); } }; NonInviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) { var tr = this; if(status_code === 100) { /* RFC 4320 4.1 * 'A SIP element MUST NOT * send any provisional response with a * Status-Code other than 100 to a non-INVITE request.' */ switch(this.state) { case C.STATUS_TRYING: this.stateChanged(C.STATUS_PROCEEDING); if(!this.transport.send(response)) { this.onTransportError(); } break; case C.STATUS_PROCEEDING: this.last_response = response; if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else if (onSuccess) { onSuccess(); } break; } } else if(status_code >= 200 && status_code <= 699) { switch(this.state) { case C.STATUS_TRYING: case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_COMPLETED); this.last_response = response; this.J = setTimeout(function() { tr.timer_J(); }, Timers.TIMER_J); if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else if (onSuccess) { onSuccess(); } break; case C.STATUS_COMPLETED: break; } } }; function InviteServerTransaction(request, ua) { this.type = C.INVITE_SERVER; this.id = request.via_branch; this.request = request; this.transport = request.transport; this.ua = ua; this.last_response = ''; request.server_transaction = this; this.state = C.STATUS_PROCEEDING; ua.newTransaction(this); this.resendProvisionalTimer = null; request.reply(100); events.EventEmitter.call(this); } util.inherits(InviteServerTransaction, events.EventEmitter); InviteServerTransaction.prototype.stateChanged = function(state) { this.state = state; this.emit('stateChanged'); }; InviteServerTransaction.prototype.timer_H = function() { debugist('Timer H expired for transaction ' + this.id); if(this.state === C.STATUS_COMPLETED) { debugist('ACK not received, dialog will be terminated'); } this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); }; InviteServerTransaction.prototype.timer_I = function() { this.stateChanged(C.STATUS_TERMINATED); }; // RFC 6026 7.1 InviteServerTransaction.prototype.timer_L = function() { debugist('Timer L expired for transaction ' + this.id); if(this.state === C.STATUS_ACCEPTED) { this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); } }; InviteServerTransaction.prototype.onTransportError = function() { if (!this.transportError) { this.transportError = true; debugist('transport error occurred, deleting transaction ' + this.id); if (this.resendProvisionalTimer !== null) { clearInterval(this.resendProvisionalTimer); this.resendProvisionalTimer = null; } clearTimeout(this.L); clearTimeout(this.H); clearTimeout(this.I); this.stateChanged(C.STATUS_TERMINATED); this.ua.destroyTransaction(this); } }; InviteServerTransaction.prototype.resend_provisional = function() { if(!this.transport.send(this.last_response)) { this.onTransportError(); } }; // INVITE Server Transaction RFC 3261 17.2.1 InviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) { var tr = this; if(status_code >= 100 && status_code <= 199) { switch(this.state) { case C.STATUS_PROCEEDING: if(!this.transport.send(response)) { this.onTransportError(); } this.last_response = response; break; } } if(status_code > 100 && status_code <= 199 && this.state === C.STATUS_PROCEEDING) { // Trigger the resendProvisionalTimer only for the first non 100 provisional response. if(this.resendProvisionalTimer === null) { this.resendProvisionalTimer = setInterval(function() { tr.resend_provisional();}, Timers.PROVISIONAL_RESPONSE_INTERVAL); } } else if(status_code >= 200 && status_code <= 299) { switch(this.state) { case C.STATUS_PROCEEDING: this.stateChanged(C.STATUS_ACCEPTED); this.last_response = response; this.L = setTimeout(function() { tr.timer_L(); }, Timers.TIMER_L); if (this.resendProvisionalTimer !== null) { clearInterval(this.resendProvisionalTimer); this.resendProvisionalTimer = null; } /* falls through */ case C.STATUS_ACCEPTED: // Note that this point will be reached for proceeding tr.state also. if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else if (onSuccess) { onSuccess(); } break; } } else if(status_code >= 300 && status_code <= 699) { switch(this.state) { case C.STATUS_PROCEEDING: if (this.resendProvisionalTimer !== null) { clearInterval(this.resendProvisionalTimer); this.resendProvisionalTimer = null; } if(!this.transport.send(response)) { this.onTransportError(); if (onFailure) { onFailure(); } } else { this.stateChanged(C.STATUS_COMPLETED); this.H = setTimeout(function() { tr.timer_H(); }, Timers.TIMER_H); if (onSuccess) { onSuccess(); } } break; } } }; /** * INVITE: * _true_ if retransmission * _false_ new request * * ACK: * _true_ ACK to non2xx response * _false_ ACK must be passed to TU (accepted state) * ACK to 2xx response * * CANCEL: * _true_ no matching invite transaction * _false_ matching invite transaction and no final response sent * * OTHER: * _true_ retransmission * _false_ new request */ function checkTransaction(ua, request) { var tr; switch(request.method) { case JsSIP_C.INVITE: tr = ua.transactions.ist[request.via_branch]; if(tr) { switch(tr.state) { case C.STATUS_PROCEEDING: tr.transport.send(tr.last_response); break; // RFC 6026 7.1 Invite retransmission //received while in C.STATUS_ACCEPTED state. Absorb it. case C.STATUS_ACCEPTED: break; } return true; } break; case JsSIP_C.ACK: tr = ua.transactions.ist[request.via_branch]; // RFC 6026 7.1 if(tr) { if(tr.state === C.STATUS_ACCEPTED) { return false; } else if(tr.state === C.STATUS_COMPLETED) { tr.state = C.STATUS_CONFIRMED; tr.I = setTimeout(function() {tr.timer_I();}, Timers.TIMER_I); return true; } } // ACK to 2XX Response. else { return false; } break; case JsSIP_C.CANCEL: tr = ua.transactions.ist[request.via_branch]; if(tr) { request.reply_sl(200); if(tr.state === C.STATUS_PROCEEDING) { return false; } else { return true; } } else { request.reply_sl(481); return true; } break; default: // Non-INVITE Server Transaction RFC 3261 17.2.2 tr = ua.transactions.nist[request.via_branch]; if(tr) { switch(tr.state) { case C.STATUS_TRYING: break; case C.STATUS_PROCEEDING: case C.STATUS_COMPLETED: tr.transport.send(tr.last_response); break; } return true; } break; } } },{"./Constants":1,"./Timers":17,"debug":29,"events":24,"util":28}],19:[function(require,module,exports){ module.exports = Transport; var C = { // Transport status codes STATUS_READY: 0, STATUS_DISCONNECTED: 1, STATUS_ERROR: 2 }; /** * Expose C object. */ Transport.C = C; /** * Dependencies. */ var debug = require('debug')('JsSIP:Transport'); var JsSIP_C = require('./Constants'); var Parser = require('./Parser'); var UA = require('./UA'); var SIPMessage = require('./SIPMessage'); var sanityCheck = require('./sanityCheck'); // 'websocket' module uses the native WebSocket interface when bundled to run in a browser. var W3CWebSocket = require('websocket').w3cwebsocket; function Transport(ua, server) { this.ua = ua; this.ws = null; this.server = server; this.reconnection_attempts = 0; this.closed = false; this.connected = false; this.reconnectTimer = null; this.lastTransportError = {}; /** * Options for the Node "websocket" library. */ this.node_websocket_options = this.ua.configuration.node_websocket_options || {}; // Add our User-Agent header. this.node_websocket_options.headers = this.node_websocket_options.headers || {}; this.node_websocket_options.headers['User-Agent'] = JsSIP_C.USER_AGENT; } Transport.prototype = { /** * Connect socket. */ connect: function() { var transport = this; if(this.ws && (this.ws.readyState === this.ws.OPEN || this.ws.readyState === this.ws.CONNECTING)) { debug('WebSocket ' + this.server.ws_uri + ' is already connected'); return false; } if(this.ws) { this.ws.close(); } debug('connecting to WebSocket ' + this.server.ws_uri); this.ua.onTransportConnecting(this, (this.reconnection_attempts === 0)?1:this.reconnection_attempts); try { this.ws = new W3CWebSocket(this.server.ws_uri, 'sip', this.node_websocket_options.origin, this.node_websocket_options.headers, this.node_websocket_options.requestOptions, this.node_websocket_options.clientConfig); this.ws.binaryType = 'arraybuffer'; this.ws.onopen = function() { transport.onOpen(); }; this.ws.onclose = function(e) { transport.onClose(e); }; this.ws.onmessage = function(e) { transport.onMessage(e); }; this.ws.onerror = function(e) { transport.onError(e); }; } catch(e) { debug('error connecting to WebSocket ' + this.server.ws_uri + ': ' + e); this.lastTransportError.code = null; this.lastTransportError.reason = e.message; this.ua.onTransportError(this); } }, /** * Disconnect socket. */ disconnect: function() { if(this.ws) { // Clear reconnectTimer clearTimeout(this.reconnectTimer); // TODO: should make this.reconnectTimer = null here? this.closed = true; debug('closing WebSocket ' + this.server.ws_uri); this.ws.close(); } // TODO: Why this?? if (this.reconnectTimer !== null) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; this.ua.onTransportDisconnected({ transport: this, code: this.lastTransportError.code, reason: this.lastTransportError.reason }); } }, /** * Send a message. */ send: function(msg) { var message = msg.toString(); if(this.ws && this.ws.readyState === this.ws.OPEN) { debug('sending WebSocket message:\n\n' + message + '\n'); this.ws.send(message); return true; } else { debug('unable to send message, WebSocket is not open'); return false; } }, // Transport Event Handlers onOpen: function() { this.connected = true; debug('WebSocket ' + this.server.ws_uri + ' connected'); // Clear reconnectTimer since we are not disconnected if (this.reconnectTimer !== null) { clearTimeout(this.reconnectTimer); this.reconnectTimer = null; } // Reset reconnection_attempts this.reconnection_attempts = 0; // Disable closed this.closed = false; // Trigger onTransportConnected callback this.ua.onTransportConnected(this); }, onClose: function(e) { var connected_before = this.connected; this.connected = false; this.lastTransportError.code = e.code; this.lastTransportError.reason = e.reason; debug('WebSocket disconnected (code: ' + e.code + (e.reason? '| reason: ' + e.reason : '') +')'); if(e.wasClean === false) { debug('WebSocket abrupt disconnection'); } // Transport was connected if (connected_before === true) { this.ua.onTransportClosed(this); // Check whether the user requested to close. if(!this.closed) { this.reConnect(); } } else { // This is the first connection attempt // May be a network error (or may be UA.stop() was called) this.ua.onTransportError(this); } }, onMessage: function(e) { var message, transaction, data = e.data; // CRLF Keep Alive response from server. Ignore it. if(data === '\r\n') { debug('received WebSocket message with CRLF Keep Alive response'); return; } // WebSocket binary message. else if (typeof data !== 'string') { try { data = String.fromCharCode.apply(null, new Uint8Array(data)); } catch(evt) { debug('received WebSocket binary message failed to be converted into string, message discarded'); return; } debug('received WebSocket binary message:\n\n' + data + '\n'); } // WebSocket text message. else { debug('received WebSocket text message:\n\n' + data + '\n'); } message = Parser.parseMessage(data, this.ua); if (! message) { return; } if(this.ua.status === UA.C.STATUS_USER_CLOSED && message instanceof SIPMessage.IncomingRequest) { return; } // Do some sanity check if(! sanityCheck(message, this.ua, this)) { return; } if(message instanceof SIPMessage.IncomingRequest) { message.transport = this; this.ua.receiveRequest(message); } else if(message instanceof SIPMessage.IncomingResponse) { /* Unike stated in 18.1.2, if a response does not match * any transaction, it is discarded here and no passed to the core * in order to be discarded there. */ switch(message.method) { case JsSIP_C.INVITE: transaction = this.ua.transactions.ict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; case JsSIP_C.ACK: // Just in case ;-) break; default: transaction = this.ua.transactions.nict[message.via_branch]; if(transaction) { transaction.receiveResponse(message); } break; } } }, onError: function(e) { debug('WebSocket connection error: %o', e); }, /** * Reconnection attempt logic. */ reConnect: function() { var transport = this; this.reconnection_attempts += 1; if(this.reconnection_attempts > this.ua.configuration.ws_server_max_reconnection) { debug('maximum reconnection attempts for WebSocket ' + this.server.ws_uri); this.ua.onTransportError(this); } else { debug('trying to reconnect to WebSocket ' + this.server.ws_uri + ' (reconnection attempt ' + this.reconnection_attempts + ')'); this.reconnectTimer = setTimeout(function() { transport.connect(); transport.reconnectTimer = null; }, this.ua.configuration.ws_server_reconnection_timeout * 1000); } } }; },{"./Constants":1,"./Parser":10,"./SIPMessage":16,"./UA":20,"./sanityCheck":23,"debug":29,"websocket":43}],20:[function(require,module,exports){ module.exports = UA; var C = { // UA status codes STATUS_INIT : 0, STATUS_READY: 1, STATUS_USER_CLOSED: 2, STATUS_NOT_READY: 3, // UA error codes CONFIGURATION_ERROR: 1, NETWORK_ERROR: 2 }; /** * Expose C object. */ UA.C = C; /** * Dependencies. */ var util = require('util'); var events = require('events'); var debug = require('debug')('JsSIP:UA'); var rtcninja = require('rtcninja'); var JsSIP_C = require('./Constants'); var Registrator = require('./Registrator'); var RTCSession = require('./RTCSession'); var Message = require('./Message'); var Transport = require('./Transport'); var Transactions = require('./Transactions'); var Transactions = require('./Transactions'); var Utils = require('./Utils'); var Exceptions = require('./Exceptions'); var URI = require('./URI'); var Grammar = require('./Grammar'); /** * The User-Agent class. * @class JsSIP.UA * @param {Object} configuration Configuration parameters. * @throws {JsSIP.Exceptions.ConfigurationError} If a configuration parameter is invalid. * @throws {TypeError} If no configuration is given. */ function UA(configuration) { this.cache = { credentials: {} }; this.configuration = {}; this.dynConfiguration = {}; this.dialogs = {}; //User actions outside any session/dialog (MESSAGE) this.applicants = {}; this.sessions = {}; this.transport = null; this.contact = null; this.status = C.STATUS_INIT; this.error = null; this.transactions = { nist: {}, nict: {}, ist: {}, ict: {} }; // Custom UA empty object for high level use this.data = {}; this.transportRecoverAttempts = 0; this.transportRecoveryTimer = null; Object.defineProperties(this, { transactionsCount: { get: function() { var type, transactions = ['nist','nict','ist','ict'], count = 0; for (type in transactions) { count += Object.keys(this.transactions[transactions[type]]).length; } return count; } }, nictTransactionsCount: { get: function() { return Object.keys(this.transactions.nict).length; } }, nistTransactionsCount: { get: function() { return Object.keys(this.transactions.nist).length; } }, ictTransactionsCount: { get: function() { return Object.keys(this.transactions.ict).length; } }, istTransactionsCount: { get: function() { return Object.keys(this.transactions.ist).length; } } }); /** * Load configuration */ if(configuration === undefined) { throw new TypeError('Not enough arguments'); } try { this.loadConfig(configuration); } catch(e) { this.status = C.STATUS_NOT_READY; this.error = C.CONFIGURATION_ERROR; throw e; } // Initialize registrator this._registrator = new Registrator(this); events.EventEmitter.call(this); // Initialize rtcninja if not yet done. if (! rtcninja.called) { rtcninja(); } } util.inherits(UA, events.EventEmitter); //================= // High Level API //================= /** * Connect to the WS server if status = STATUS_INIT. * Resume UA after being closed. */ UA.prototype.start = function() { debug('start()'); var server; if (this.status === C.STATUS_INIT) { server = this.getNextWsServer(); this.transport = new Transport(this, server); this.transport.connect(); } else if(this.status === C.STATUS_USER_CLOSED) { debug('restarting UA'); this.status = C.STATUS_READY; this.transport.connect(); } else if (this.status === C.STATUS_READY) { debug('UA is in READY status, not restarted'); } else { debug('ERROR: connection is down, Auto-Recovery system is trying to reconnect'); } // Set dynamic configuration. this.dynConfiguration.register = this.configuration.register; }; /** * Register. */ UA.prototype.register = function() { debug('register()'); this.dynConfiguration.register = true; this._registrator.register(); }; /** * Unregister. */ UA.prototype.unregister = function(options) { debug('unregister()'); this.dynConfiguration.register = false; this._registrator.unregister(options); }; /** * Get the Registrator instance. */ UA.prototype.registrator = function() { return this._registrator; }; /** * Registration state. */ UA.prototype.isRegistered = function() { if(this._registrator.registered) { return true; } else { return false; } }; /** * Connection state. */ UA.prototype.isConnected = function() { if(this.transport) { return this.transport.connected; } else { return false; } }; /** * Make an outgoing call. * * -param {String} target * -param {Object} views * -param {Object} [options] * * -throws {TypeError} * */ UA.prototype.call = function(target, options) { debug('call()'); var session; session = new RTCSession(this); session.connect(target, options); return session; }; /** * Send a message. * * -param {String} target * -param {String} body * -param {Object} [options] * * -throws {TypeError} * */ UA.prototype.sendMessage = function(target, body, options) { debug('sendMessage()'); var message; message = new Message(this); message.send(target, body, options); return message; }; /** * Terminate ongoing sessions. */ UA.prototype.terminateSessions = function(options) { debug('terminateSessions()'); for(var idx in this.sessions) { if (!this.sessions[idx].isEnded()) { this.sessions[idx].terminate(options); } } }; /** * Gracefully close. * */ UA.prototype.stop = function() { debug('stop()'); var session; var applicant; var num_sessions; var ua = this; // Remove dynamic settings. this.dynConfiguration = {}; if(this.status === C.STATUS_USER_CLOSED) { debug('UA already closed'); return; } // Clear transportRecoveryTimer clearTimeout(this.transportRecoveryTimer); // Close registrator this._registrator.close(); // If there are session wait a bit so CANCEL/BYE can be sent and their responses received. num_sessions = Object.keys(this.sessions).length; // Run _terminate_ on every Session for(session in this.sessions) { debug('closing session ' + session); try { this.sessions[session].terminate(); } catch(error) {} } // Run _close_ on every applicant for(applicant in this.applicants) { try { this.applicants[applicant].close(); } catch(error) {} } this.status = C.STATUS_USER_CLOSED; // If there are no pending non-INVITE client or server transactions and no // sessions, then disconnect now. Otherwise wait for 2 seconds. // TODO: This fails if sotp() is called once an outgoing is cancelled (no time // to send ACK for 487), so leave 2 seconds until properly re-designed. // if (this.nistTransactionsCount === 0 && this.nictTransactionsCount === 0 && num_sessions === 0) { // ua.transport.disconnect(); // } // else { setTimeout(function() { ua.transport.disconnect(); }, 2000); // } }; /** * Normalice a string into a valid SIP request URI * -param {String} target * -returns {JsSIP.URI|undefined} */ UA.prototype.normalizeTarget = function(target) { return Utils.normalizeTarget(target, this.configuration.hostport_params); }; //=============================== // Private (For internal use) //=============================== UA.prototype.saveCredentials = function(credentials) { this.cache.credentials[credentials.realm] = this.cache.credentials[credentials.realm] || {}; this.cache.credentials[credentials.realm][credentials.uri] = credentials; }; UA.prototype.getCredentials = function(request) { var realm, credentials; realm = request.ruri.host; if (this.cache.credentials[realm] && this.cache.credentials[realm][request.ruri]) { credentials = this.cache.credentials[realm][request.ruri]; credentials.method = request.method; } return credentials; }; //========================== // Event Handlers //========================== /** * Transport Close event. */ UA.prototype.onTransportClosed = function(transport) { // Run _onTransportError_ callback on every client transaction using _transport_ var type, idx, length, client_transactions = ['nict', 'ict', 'nist', 'ist']; transport.server.status = Transport.C.STATUS_DISCONNECTED; length = client_transactions.length; for (type = 0; type < length; type++) { for(idx in this.transactions[client_transactions[type]]) { this.transactions[client_transactions[type]][idx].onTransportError(); } } this.emit('disconnected', { transport: transport, code: transport.lastTransportError.code, reason: transport.lastTransportError.reason }); }; /** * Unrecoverable transport event. * Connection reattempt logic has been done and didn't success. */ UA.prototype.onTransportError = function(transport) { var server; debug('transport ' + transport.server.ws_uri + ' failed | connection state set to '+ Transport.C.STATUS_ERROR); // Close sessions. // Mark this transport as 'down' and try the next one transport.server.status = Transport.C.STATUS_ERROR; this.emit('disconnected', { transport: transport, code: transport.lastTransportError.code, reason: transport.lastTransportError.reason }); // Don't attempt to recover the connection if the user closes the UA. if (this.status === C.STATUS_USER_CLOSED) { return; } server = this.getNextWsServer(); if(server) { this.transport = new Transport(this, server); this.transport.connect(); } else { this.closeSessionsOnTransportError(); if (!this.error || this.error !== C.NETWORK_ERROR) { this.status = C.STATUS_NOT_READY; this.error = C.NETWORK_ERROR; } // Transport Recovery process this.recoverTransport(); } }; /** * Transport connection event. */ UA.prototype.onTransportConnected = function(transport) { this.transport = transport; // Reset transport recovery counter this.transportRecoverAttempts = 0; transport.server.status = Transport.C.STATUS_READY; if(this.status === C.STATUS_USER_CLOSED) { return; } this.status = C.STATUS_READY; this.error = null; if(this.dynConfiguration.register) { this._registrator.register(); } this.emit('connected', { transport: transport }); }; /** * Transport connecting event */ UA.prototype.onTransportConnecting = function(transport, attempts) { this.emit('connecting', { transport: transport, attempts: attempts }); }; /** * Transport connected event */ UA.prototype.onTransportDisconnected = function(data) { this.emit('disconnected', data); }; /** * new Transaction */ UA.prototype.newTransaction = function(transaction) { this.transactions[transaction.type][transaction.id] = transaction; this.emit('newTransaction', { transaction: transaction }); }; /** * Transaction destroyed. */ UA.prototype.destroyTransaction = function(transaction) { delete this.transactions[transaction.type][transaction.id]; this.emit('transactionDestroyed', { transaction: transaction }); }; /** * new Message */ UA.prototype.newMessage = function(data) { this.emit('newMessage', data); }; /** * new RTCSession */ UA.prototype.newRTCSession = function(data) { this.emit('newRTCSession', data); }; /** * Registered */ UA.prototype.registered = function(data) { this.emit('registered', data); }; /** * Unregistered */ UA.prototype.unregistered = function(data) { this.emit('unregistered', data); }; /** * Registration Failed */ UA.prototype.registrationFailed = function(data) { this.emit('registrationFailed', data); }; //========================= // receiveRequest //========================= /** * Request reception */ UA.prototype.receiveRequest = function(request) { var dialog, session, message, method = request.method; // Check that request URI points to us if(request.ruri.user !== this.configuration.uri.user && request.ruri.user !== this.contact.uri.user) { debug('Request-URI does not point to us'); if (request.method !== JsSIP_C.ACK) { request.reply_sl(404); } return; } // Check request URI scheme if(request.ruri.scheme === JsSIP_C.SIPS) { request.reply_sl(416); return; } // Check transaction if(Transactions.checkTransaction(this, request)) { return; } // Create the server transaction if(method === JsSIP_C.INVITE) { new Transactions.InviteServerTransaction(request, this); } else if(method !== JsSIP_C.ACK && method !== JsSIP_C.CANCEL) { new Transactions.NonInviteServerTransaction(request, this); } /* RFC3261 12.2.2 * Requests that do not change in any way the state of a dialog may be * received within a dialog (for example, an OPTIONS request). * They are processed as if they had been received outside the dialog. */ if(method === JsSIP_C.OPTIONS) { request.reply(200); } else if (method === JsSIP_C.MESSAGE) { if (this.listeners('newMessage').length === 0) { request.reply(405); return; } message = new Message(this); message.init_incoming(request); } else if (method === JsSIP_C.INVITE) { // Initial INVITE if(!request.to_tag && this.listeners('newRTCSession').length === 0) { request.reply(405); return; } } // Initial Request if(!request.to_tag) { switch(method) { case JsSIP_C.INVITE: if (rtcninja.hasWebRTC()) { session = new RTCSession(this); session.init_incoming(request); } else { debug('INVITE received but WebRTC is not supported'); request.reply(488); } break; case JsSIP_C.BYE: // Out of dialog BYE received request.reply(481); break; case JsSIP_C.CANCEL: session = this.findSession(request); if (session) { session.receiveRequest(request); } else { debug('received CANCEL request for a non existent session'); } break; case JsSIP_C.ACK: /* Absorb it. * ACK request without a corresponding Invite Transaction * and without To tag. */ break; default: request.reply(405); break; } } // In-dialog request else { dialog = this.findDialog(request); if(dialog) { dialog.receiveRequest(request); } else if (method === JsSIP_C.NOTIFY) { session = this.findSession(request); if(session) { session.receiveRequest(request); } else { debug('received NOTIFY request for a non existent subscription'); request.reply(481, 'Subscription does not exist'); } } /* RFC3261 12.2.2 * Request with to tag, but no matching dialog found. * Exception: ACK for an Invite request for which a dialog has not * been created. */ else { if(method !== JsSIP_C.ACK) { request.reply(481); } } } }; //================= // Utils //================= /** * Get the session to which the request belongs to, if any. */ UA.prototype.findSession = function(request) { var sessionIDa = request.call_id + request.from_tag, sessionA = this.sessions[sessionIDa], sessionIDb = request.call_id + request.to_tag, sessionB = this.sessions[sessionIDb]; if(sessionA) { return sessionA; } else if(sessionB) { return sessionB; } else { return null; } }; /** * Get the dialog to which the request belongs to, if any. */ UA.prototype.findDialog = function(request) { var id = request.call_id + request.from_tag + request.to_tag, dialog = this.dialogs[id]; if(dialog) { return dialog; } else { id = request.call_id + request.to_tag + request.from_tag; dialog = this.dialogs[id]; if(dialog) { return dialog; } else { return null; } } }; /** * Retrieve the next server to which connect. */ UA.prototype.getNextWsServer = function() { // Order servers by weight var idx, length, ws_server, candidates = []; length = this.configuration.ws_servers.length; for (idx = 0; idx < length; idx++) { ws_server = this.configuration.ws_servers[idx]; if (ws_server.status === Transport.C.STATUS_ERROR) { continue; } else if (candidates.length === 0) { candidates.push(ws_server); } else if (ws_server.weight > candidates[0].weight) { candidates = [ws_server]; } else if (ws_server.weight === candidates[0].weight) { candidates.push(ws_server); } } idx = Math.floor((Math.random()* candidates.length)); return candidates[idx]; }; /** * Close all sessions on transport error. */ UA.prototype.closeSessionsOnTransportError = function() { var idx; // Run _transportError_ for every Session for(idx in this.sessions) { this.sessions[idx].onTransportError(); } // Call registrator _onTransportClosed_ this._registrator.onTransportClosed(); }; UA.prototype.recoverTransport = function(ua) { var idx, length, k, nextRetry, count, server; ua = ua || this; count = ua.transportRecoverAttempts; length = ua.configuration.ws_servers.length; for (idx = 0; idx < length; idx++) { ua.configuration.ws_servers[idx].status = 0; } server = ua.getNextWsServer(); k = Math.floor((Math.random() * Math.pow(2,count)) +1); nextRetry = k * ua.configuration.connection_recovery_min_interval; if (nextRetry > ua.configuration.connection_recovery_max_interval) { debug('time for next connection attempt exceeds connection_recovery_max_interval, resetting counter'); nextRetry = ua.configuration.connection_recovery_min_interval; count = 0; } debug('next connection attempt in '+ nextRetry +' seconds'); this.transportRecoveryTimer = setTimeout(function() { ua.transportRecoverAttempts = count + 1; ua.transport = new Transport(ua, server); ua.transport.connect(); }, nextRetry * 1000); }; UA.prototype.loadConfig = function(configuration) { // Settings and default values var parameter, value, checked_value, hostport_params, registrar_server, settings = { /* Host address * Value to be set in Via sent_by and host part of Contact FQDN */ via_host: Utils.createRandomToken(12) + '.invalid', // Password password: null, // Registration parameters register_expires: 600, register: true, registrar_server: null, // Transport related parameters ws_server_max_reconnection: 3, ws_server_reconnection_timeout: 4, connection_recovery_min_interval: 2, connection_recovery_max_interval: 30, use_preloaded_route: false, // Session parameters no_answer_timeout: 60, session_timers: true, // Hacks hack_via_tcp: false, hack_via_ws: false, hack_ip_in_contact: false, // Options for Node. node_websocket_options: {} }; // Pre-Configuration // Check Mandatory parameters for(parameter in UA.configuration_check.mandatory) { if(!configuration.hasOwnProperty(parameter)) { throw new Exceptions.ConfigurationError(parameter); } else { value = configuration[parameter]; checked_value = UA.configuration_check.mandatory[parameter].call(this, value); if (checked_value !== undefined) { settings[parameter] = checked_value; } else { throw new Exceptions.ConfigurationError(parameter, value); } } } // Check Optional parameters for(parameter in UA.configuration_check.optional) { if(configuration.hasOwnProperty(parameter)) { value = configuration[parameter]; /* If the parameter value is null, empty string, undefined, empty array * or it's a number with NaN value, then apply its default value. */ if (Utils.isEmpty(value)) { continue; } checked_value = UA.configuration_check.optional[parameter].call(this, value); if (checked_value !== undefined) { settings[parameter] = checked_value; } else { throw new Exceptions.ConfigurationError(parameter, value); } } } // Sanity Checks // Connection recovery intervals. if(settings.connection_recovery_max_interval < settings.connection_recovery_min_interval) { throw new Exceptions.ConfigurationError('connection_recovery_max_interval', settings.connection_recovery_max_interval); } // Post Configuration Process // Allow passing 0 number as display_name. if (settings.display_name === 0) { settings.display_name = '0'; } // Instance-id for GRUU. if (!settings.instance_id) { settings.instance_id = Utils.newUUID(); } // jssip_id instance parameter. Static random tag of length 5. settings.jssip_id = Utils.createRandomToken(5); // String containing settings.uri without scheme and user. hostport_params = settings.uri.clone(); hostport_params.user = null; settings.hostport_params = hostport_params.toString().replace(/^sip:/i, ''); // Check whether authorization_user is explicitly defined. // Take 'settings.uri.user' value if not. if (!settings.authorization_user) { settings.authorization_user = settings.uri.user; } // If no 'registrar_server' is set use the 'uri' value without user portion. if (!settings.registrar_server) { registrar_server = settings.uri.clone(); registrar_server.user = null; settings.registrar_server = registrar_server; } // User no_answer_timeout. settings.no_answer_timeout = settings.no_answer_timeout * 1000; // Via Host if (settings.hack_ip_in_contact) { settings.via_host = Utils.getRandomTestNetIP(); } this.contact = { pub_gruu: null, temp_gruu: null, uri: new URI('sip', Utils.createRandomToken(8), settings.via_host, null, {transport: 'ws'}), toString: function(options) { options = options || {}; var anonymous = options.anonymous || null, outbound = options.outbound || null, contact = '<'; if (anonymous) { contact += this.temp_gruu || 'sip:[email protected];transport=ws'; } else { contact += this.pub_gruu || this.uri.toString(); } if (outbound && (anonymous ? !this.temp_gruu : !this.pub_gruu)) { contact += ';ob'; } contact += '>'; return contact; } }; // Fill the value of the configuration_skeleton for(parameter in settings) { UA.configuration_skeleton[parameter].value = settings[parameter]; } Object.defineProperties(this.configuration, UA.configuration_skeleton); // Clean UA.configuration_skeleton for(parameter in settings) { UA.configuration_skeleton[parameter].value = ''; } debug('configuration parameters after validation:'); for(parameter in settings) { switch(parameter) { case 'uri': case 'registrar_server': debug('- ' + parameter + ': ' + settings[parameter]); break; case 'password': debug('- ' + parameter + ': ' + 'NOT SHOWN'); break; default: debug('- ' + parameter + ': ' + JSON.stringify(settings[parameter])); } } return; }; /** * Configuration Object skeleton. */ UA.configuration_skeleton = (function() { var idx, parameter, skeleton = {}, parameters = [ // Internal parameters 'jssip_id', 'ws_server_max_reconnection', 'ws_server_reconnection_timeout', 'hostport_params', // Mandatory user configurable parameters 'uri', 'ws_servers', // Optional user configurable parameters 'authorization_user', 'connection_recovery_max_interval', 'connection_recovery_min_interval', 'display_name', 'hack_via_tcp', // false 'hack_via_ws', // false 'hack_ip_in_contact', //false 'instance_id', 'no_answer_timeout', // 30 seconds 'session_timers', // true 'node_websocket_options', 'password', 'register_expires', // 600 seconds 'registrar_server', 'use_preloaded_route', // Post-configuration generated parameters 'via_core_value', 'via_host' ]; for(idx in parameters) { parameter = parameters[idx]; skeleton[parameter] = { value: '', writable: false, configurable: false }; } skeleton.register = { value: '', writable: true, configurable: false }; return skeleton; }()); /** * Configuration checker. */ UA.configuration_check = { mandatory: { uri: function(uri) { var parsed; if (!/^sip:/i.test(uri)) { uri = JsSIP_C.SIP + ':' + uri; } parsed = URI.parse(uri); if(!parsed) { return; } else if(!parsed.user) { return; } else { return parsed; } }, ws_servers: function(ws_servers) { var idx, length, url; /* Allow defining ws_servers parameter as: * String: "host" * Array of Strings: ["host1", "host2"] * Array of Objects: [{ws_uri:"host1", weight:1}, {ws_uri:"host2", weight:0}] * Array of Objects and Strings: [{ws_uri:"host1"}, "host2"] */ if (typeof ws_servers === 'string') { ws_servers = [{ws_uri: ws_servers}]; } else if (Array.isArray(ws_servers)) { length = ws_servers.length; for (idx = 0; idx < length; idx++) { if (typeof ws_servers[idx] === 'string') { ws_servers[idx] = {ws_uri: ws_servers[idx]}; } } } else { return; } if (ws_servers.length === 0) { return false; } length = ws_servers.length; for (idx = 0; idx < length; idx++) { if (!ws_servers[idx].ws_uri) { debug('ERROR: missing "ws_uri" attribute in ws_servers parameter'); return; } if (ws_servers[idx].weight && !Number(ws_servers[idx].weight)) { debug('ERROR: "weight" attribute in ws_servers parameter must be a Number'); return; } url = Grammar.parse(ws_servers[idx].ws_uri, 'absoluteURI'); if(url === -1) { debug('ERROR: invalid "ws_uri" attribute in ws_servers parameter: ' + ws_servers[idx].ws_uri); return; } else if(url.scheme !== 'wss' && url.scheme !== 'ws') { debug('ERROR: invalid URI scheme in ws_servers parameter: ' + url.scheme); return; } else { ws_servers[idx].sip_uri = '<sip:' + url.host + (url.port ? ':' + url.port : '') + ';transport=ws;lr>'; if (!ws_servers[idx].weight) { ws_servers[idx].weight = 0; } ws_servers[idx].status = 0; ws_servers[idx].scheme = url.scheme.toUpperCase(); } } return ws_servers; } }, optional: { authorization_user: function(authorization_user) { if(Grammar.parse('"'+ authorization_user +'"', 'quoted_string') === -1) { return; } else { return authorization_user; } }, connection_recovery_max_interval: function(connection_recovery_max_interval) { var value; if(Utils.isDecimal(connection_recovery_max_interval)) { value = Number(connection_recovery_max_interval); if(value > 0) { return value; } } }, connection_recovery_min_interval: function(connection_recovery_min_interval) { var value; if(Utils.isDecimal(connection_recovery_min_interval)) { value = Number(connection_recovery_min_interval); if(value > 0) { return value; } } }, display_name: function(display_name) { if(Grammar.parse('"' + display_name + '"', 'display_name') === -1) { return; } else { return display_name; } }, hack_via_tcp: function(hack_via_tcp) { if (typeof hack_via_tcp === 'boolean') { return hack_via_tcp; } }, hack_via_ws: function(hack_via_ws) { if (typeof hack_via_ws === 'boolean') { return hack_via_ws; } }, hack_ip_in_contact: function(hack_ip_in_contact) { if (typeof hack_ip_in_contact === 'boolean') { return hack_ip_in_contact; } }, instance_id: function(instance_id) { if ((/^uuid:/i.test(instance_id))) { instance_id = instance_id.substr(5); } if(Grammar.parse(instance_id, 'uuid') === -1) { return; } else { return instance_id; } }, no_answer_timeout: function(no_answer_timeout) { var value; if (Utils.isDecimal(no_answer_timeout)) { value = Number(no_answer_timeout); if (value > 0) { return value; } } }, session_timers: function(session_timers) { if (typeof session_timers === 'boolean') { return session_timers; } }, node_websocket_options: function(node_websocket_options) { return (typeof node_websocket_options === 'object') ? node_websocket_options : {}; }, password: function(password) { return String(password); }, register: function(register) { if (typeof register === 'boolean') { return register; } }, register_expires: function(register_expires) { var value; if (Utils.isDecimal(register_expires)) { value = Number(register_expires); if (value > 0) { return value; } } }, registrar_server: function(registrar_server) { var parsed; if (!/^sip:/i.test(registrar_server)) { registrar_server = JsSIP_C.SIP + ':' + registrar_server; } parsed = URI.parse(registrar_server); if(!parsed) { return; } else if(parsed.user) { return; } else { return parsed; } }, use_preloaded_route: function(use_preloaded_route) { if (typeof use_preloaded_route === 'boolean') { return use_preloaded_route; } } } }; },{"./Constants":1,"./Exceptions":5,"./Grammar":6,"./Message":8,"./RTCSession":11,"./Registrator":14,"./Transactions":18,"./Transport":19,"./URI":21,"./Utils":22,"debug":29,"events":24,"rtcninja":34,"util":28}],21:[function(require,module,exports){ module.exports = URI; /** * Dependencies. */ var JsSIP_C = require('./Constants'); var Utils = require('./Utils'); var Grammar = require('./Grammar'); /** * -param {String} [scheme] * -param {String} [user] * -param {String} host * -param {String} [port] * -param {Object} [parameters] * -param {Object} [headers] * */ function URI(scheme, user, host, port, parameters, headers) { var param, header; // Checks if(!host) { throw new TypeError('missing or invalid "host" parameter'); } // Initialize parameters scheme = scheme || JsSIP_C.SIP; this.parameters = {}; this.headers = {}; for (param in parameters) { this.setParam(param, parameters[param]); } for (header in headers) { this.setHeader(header, headers[header]); } Object.defineProperties(this, { scheme: { get: function(){ return scheme; }, set: function(value){ scheme = value.toLowerCase(); } }, user: { get: function(){ return user; }, set: function(value){ user = value; } }, host: { get: function(){ return host; }, set: function(value){ host = value.toLowerCase(); } }, port: { get: function(){ return port; }, set: function(value){ port = value === 0 ? value : (parseInt(value,10) || null); } } }); } URI.prototype = { setParam: function(key, value) { if(key) { this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString().toLowerCase(); } }, getParam: function(key) { if(key) { return this.parameters[key.toLowerCase()]; } }, hasParam: function(key) { if(key) { return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false; } }, deleteParam: function(parameter) { var value; parameter = parameter.toLowerCase(); if (this.parameters.hasOwnProperty(parameter)) { value = this.parameters[parameter]; delete this.parameters[parameter]; return value; } }, clearParams: function() { this.parameters = {}; }, setHeader: function(name, value) { this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value]; }, getHeader: function(name) { if(name) { return this.headers[Utils.headerize(name)]; } }, hasHeader: function(name) { if(name) { return (this.headers.hasOwnProperty(Utils.headerize(name)) && true) || false; } }, deleteHeader: function(header) { var value; header = Utils.headerize(header); if(this.headers.hasOwnProperty(header)) { value = this.headers[header]; delete this.headers[header]; return value; } }, clearHeaders: function() { this.headers = {}; }, clone: function() { return new URI( this.scheme, this.user, this.host, this.port, JSON.parse(JSON.stringify(this.parameters)), JSON.parse(JSON.stringify(this.headers))); }, toString: function(){ var header, parameter, idx, uri, headers = []; uri = this.scheme + ':'; if (this.user) { uri += Utils.escapeUser(this.user) + '@'; } uri += this.host; if (this.port || this.port === 0) { uri += ':' + this.port; } for (parameter in this.parameters) { uri += ';' + parameter; if (this.parameters[parameter] !== null) { uri += '='+ this.parameters[parameter]; } } for(header in this.headers) { for(idx = 0; idx < this.headers[header].length; idx++) { headers.push(header + '=' + this.headers[header][idx]); } } if (headers.length > 0) { uri += '?' + headers.join('&'); } return uri; }, toAor: function(show_port){ var aor; aor = this.scheme + ':'; if (this.user) { aor += Utils.escapeUser(this.user) + '@'; } aor += this.host; if (show_port && (this.port || this.port === 0)) { aor += ':' + this.port; } return aor; } }; /** * Parse the given string and returns a JsSIP.URI instance or undefined if * it is an invalid URI. */ URI.parse = function(uri) { uri = Grammar.parse(uri,'SIP_URI'); if (uri !== -1) { return uri; } else { return undefined; } }; },{"./Constants":1,"./Grammar":6,"./Utils":22}],22:[function(require,module,exports){ var Utils = {}; module.exports = Utils; /** * Dependencies. */ var JsSIP_C = require('./Constants'); var URI = require('./URI'); var Grammar = require('./Grammar'); Utils.str_utf8_length = function(string) { return unescape(encodeURIComponent(string)).length; }; Utils.isFunction = function(fn) { if (fn !== undefined) { return (Object.prototype.toString.call(fn) === '[object Function]')? true : false; } else { return false; } }; Utils.isDecimal = function(num) { return !isNaN(num) && (parseFloat(num) === parseInt(num,10)); }; Utils.isEmpty = function(value) { if (value === null || value === '' || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof(value) === 'number' && isNaN(value))) { return true; } }; Utils.createRandomToken = function(size, base) { var i, r, token = ''; base = base || 32; for( i=0; i < size; i++ ) { r = Math.random() * base|0; token += r.toString(base); } return token; }; Utils.newTag = function() { return Utils.createRandomToken(10); }; // http://stackoverflow.com/users/109538/broofa Utils.newUUID = function() { var UUID = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8); return v.toString(16); }); return UUID; }; Utils.hostType = function(host) { if (!host) { return; } else { host = Grammar.parse(host,'host'); if (host !== -1) { return host.host_type; } } }; /** * Normalize SIP URI. * NOTE: It does not allow a SIP URI without username. * Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'. * Detects the domain part (if given) and properly hex-escapes the user portion. * If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators. */ Utils.normalizeTarget = function(target, domain) { var uri, target_array, target_user, target_domain; // If no target is given then raise an error. if (!target) { return; // If a URI instance is given then return it. } else if (target instanceof URI) { return target; // If a string is given split it by '@': // - Last fragment is the desired domain. // - Otherwise append the given domain argument. } else if (typeof target === 'string') { target_array = target.split('@'); switch(target_array.length) { case 1: if (!domain) { return; } target_user = target; target_domain = domain; break; case 2: target_user = target_array[0]; target_domain = target_array[1]; break; default: target_user = target_array.slice(0, target_array.length-1).join('@'); target_domain = target_array[target_array.length-1]; } // Remove the URI scheme (if present). target_user = target_user.replace(/^(sips?|tel):/i, ''); // Remove 'tel' visual separators if the user portion just contains 'tel' number symbols. if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(target_user)) { target_user = target_user.replace(/[\-\.\(\)]/g, ''); } // Build the complete SIP URI. target = JsSIP_C.SIP + ':' + Utils.escapeUser(target_user) + '@' + target_domain; // Finally parse the resulting URI. if ((uri = URI.parse(target))) { return uri; } else { return; } } else { return; } }; /** * Hex-escape a SIP URI user. */ Utils.escapeUser = function(user) { // Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F). return encodeURIComponent(decodeURIComponent(user)).replace(/%3A/ig, ':').replace(/%2B/ig, '+').replace(/%3F/ig, '?').replace(/%2F/ig, '/'); }; Utils.headerize = function(string) { var exceptions = { 'Call-Id': 'Call-ID', 'Cseq': 'CSeq', 'Www-Authenticate': 'WWW-Authenticate' }, name = string.toLowerCase().replace(/_/g,'-').split('-'), hname = '', parts = name.length, part; for (part = 0; part < parts; part++) { if (part !== 0) { hname +='-'; } hname += name[part].charAt(0).toUpperCase()+name[part].substring(1); } if (exceptions[hname]) { hname = exceptions[hname]; } return hname; }; Utils.sipErrorCause = function(status_code) { var cause; for (cause in JsSIP_C.SIP_ERROR_CAUSES) { if (JsSIP_C.SIP_ERROR_CAUSES[cause].indexOf(status_code) !== -1) { return JsSIP_C.causes[cause]; } } return JsSIP_C.causes.SIP_FAILURE_CODE; }; /** * Generate a random Test-Net IP (http://tools.ietf.org/html/rfc5735) */ Utils.getRandomTestNetIP = function() { function getOctet(from,to) { return Math.floor(Math.random()*(to-from+1)+from); } return '192.0.2.' + getOctet(1, 254); }; // MD5 (Message-Digest Algorithm) http://www.webtoolkit.info Utils.calculateMD5 = function(string) { function rotateLeft(lValue, iShiftBits) { return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits)); } function addUnsigned(lX,lY) { var lX4,lY4,lX8,lY8,lResult; lX8 = (lX & 0x80000000); lY8 = (lY & 0x80000000); lX4 = (lX & 0x40000000); lY4 = (lY & 0x40000000); lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF); if (lX4 & lY4) { return (lResult ^ 0x80000000 ^ lX8 ^ lY8); } if (lX4 | lY4) { if (lResult & 0x40000000) { return (lResult ^ 0xC0000000 ^ lX8 ^ lY8); } else { return (lResult ^ 0x40000000 ^ lX8 ^ lY8); } } else { return (lResult ^ lX8 ^ lY8); } } function doF(x,y,z) { return (x & y) | ((~x) & z); } function doG(x,y,z) { return (x & z) | (y & (~z)); } function doH(x,y,z) { return (x ^ y ^ z); } function doI(x,y,z) { return (y ^ (x | (~z))); } function doFF(a,b,c,d,x,s,ac) { a = addUnsigned(a, addUnsigned(addUnsigned(doF(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); } function doGG(a,b,c,d,x,s,ac) { a = addUnsigned(a, addUnsigned(addUnsigned(doG(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); } function doHH(a,b,c,d,x,s,ac) { a = addUnsigned(a, addUnsigned(addUnsigned(doH(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); } function doII(a,b,c,d,x,s,ac) { a = addUnsigned(a, addUnsigned(addUnsigned(doI(b, c, d), x), ac)); return addUnsigned(rotateLeft(a, s), b); } function convertToWordArray(string) { var lWordCount; var lMessageLength = string.length; var lNumberOfWords_temp1=lMessageLength + 8; var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64; var lNumberOfWords = (lNumberOfWords_temp2+1)*16; var lWordArray = new Array(lNumberOfWords-1); var lBytePosition = 0; var lByteCount = 0; while ( lByteCount < lMessageLength ) { lWordCount = (lByteCount-(lByteCount % 4))/4; lBytePosition = (lByteCount % 4)*8; lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition)); lByteCount++; } lWordCount = (lByteCount-(lByteCount % 4))/4; lBytePosition = (lByteCount % 4)*8; lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition); lWordArray[lNumberOfWords-2] = lMessageLength<<3; lWordArray[lNumberOfWords-1] = lMessageLength>>>29; return lWordArray; } function wordToHex(lValue) { var wordToHexValue='',wordToHexValue_temp='',lByte,lCount; for (lCount = 0;lCount<=3;lCount++) { lByte = (lValue>>>(lCount*8)) & 255; wordToHexValue_temp = '0' + lByte.toString(16); wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length-2,2); } return wordToHexValue; } function utf8Encode(string) { string = string.replace(/\r\n/g, '\n'); var utftext = ''; for (var n = 0; n < string.length; n++) { var c = string.charCodeAt(n); if (c < 128) { utftext += String.fromCharCode(c); } else if((c > 127) && (c < 2048)) { utftext += String.fromCharCode((c >> 6) | 192); utftext += String.fromCharCode((c & 63) | 128); } else { utftext += String.fromCharCode((c >> 12) | 224); utftext += String.fromCharCode(((c >> 6) & 63) | 128); utftext += String.fromCharCode((c & 63) | 128); } } return utftext; } var x=[]; var k,AA,BB,CC,DD,a,b,c,d; var S11=7, S12=12, S13=17, S14=22; var S21=5, S22=9 , S23=14, S24=20; var S31=4, S32=11, S33=16, S34=23; var S41=6, S42=10, S43=15, S44=21; string = utf8Encode(string); x = convertToWordArray(string); a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476; for (k=0;k<x.length;k+=16) { AA=a; BB=b; CC=c; DD=d; a=doFF(a,b,c,d,x[k+0], S11,0xD76AA478); d=doFF(d,a,b,c,x[k+1], S12,0xE8C7B756); c=doFF(c,d,a,b,x[k+2], S13,0x242070DB); b=doFF(b,c,d,a,x[k+3], S14,0xC1BDCEEE); a=doFF(a,b,c,d,x[k+4], S11,0xF57C0FAF); d=doFF(d,a,b,c,x[k+5], S12,0x4787C62A); c=doFF(c,d,a,b,x[k+6], S13,0xA8304613); b=doFF(b,c,d,a,x[k+7], S14,0xFD469501); a=doFF(a,b,c,d,x[k+8], S11,0x698098D8); d=doFF(d,a,b,c,x[k+9], S12,0x8B44F7AF); c=doFF(c,d,a,b,x[k+10],S13,0xFFFF5BB1); b=doFF(b,c,d,a,x[k+11],S14,0x895CD7BE); a=doFF(a,b,c,d,x[k+12],S11,0x6B901122); d=doFF(d,a,b,c,x[k+13],S12,0xFD987193); c=doFF(c,d,a,b,x[k+14],S13,0xA679438E); b=doFF(b,c,d,a,x[k+15],S14,0x49B40821); a=doGG(a,b,c,d,x[k+1], S21,0xF61E2562); d=doGG(d,a,b,c,x[k+6], S22,0xC040B340); c=doGG(c,d,a,b,x[k+11],S23,0x265E5A51); b=doGG(b,c,d,a,x[k+0], S24,0xE9B6C7AA); a=doGG(a,b,c,d,x[k+5], S21,0xD62F105D); d=doGG(d,a,b,c,x[k+10],S22,0x2441453); c=doGG(c,d,a,b,x[k+15],S23,0xD8A1E681); b=doGG(b,c,d,a,x[k+4], S24,0xE7D3FBC8); a=doGG(a,b,c,d,x[k+9], S21,0x21E1CDE6); d=doGG(d,a,b,c,x[k+14],S22,0xC33707D6); c=doGG(c,d,a,b,x[k+3], S23,0xF4D50D87); b=doGG(b,c,d,a,x[k+8], S24,0x455A14ED); a=doGG(a,b,c,d,x[k+13],S21,0xA9E3E905); d=doGG(d,a,b,c,x[k+2], S22,0xFCEFA3F8); c=doGG(c,d,a,b,x[k+7], S23,0x676F02D9); b=doGG(b,c,d,a,x[k+12],S24,0x8D2A4C8A); a=doHH(a,b,c,d,x[k+5], S31,0xFFFA3942); d=doHH(d,a,b,c,x[k+8], S32,0x8771F681); c=doHH(c,d,a,b,x[k+11],S33,0x6D9D6122); b=doHH(b,c,d,a,x[k+14],S34,0xFDE5380C); a=doHH(a,b,c,d,x[k+1], S31,0xA4BEEA44); d=doHH(d,a,b,c,x[k+4], S32,0x4BDECFA9); c=doHH(c,d,a,b,x[k+7], S33,0xF6BB4B60); b=doHH(b,c,d,a,x[k+10],S34,0xBEBFBC70); a=doHH(a,b,c,d,x[k+13],S31,0x289B7EC6); d=doHH(d,a,b,c,x[k+0], S32,0xEAA127FA); c=doHH(c,d,a,b,x[k+3], S33,0xD4EF3085); b=doHH(b,c,d,a,x[k+6], S34,0x4881D05); a=doHH(a,b,c,d,x[k+9], S31,0xD9D4D039); d=doHH(d,a,b,c,x[k+12],S32,0xE6DB99E5); c=doHH(c,d,a,b,x[k+15],S33,0x1FA27CF8); b=doHH(b,c,d,a,x[k+2], S34,0xC4AC5665); a=doII(a,b,c,d,x[k+0], S41,0xF4292244); d=doII(d,a,b,c,x[k+7], S42,0x432AFF97); c=doII(c,d,a,b,x[k+14],S43,0xAB9423A7); b=doII(b,c,d,a,x[k+5], S44,0xFC93A039); a=doII(a,b,c,d,x[k+12],S41,0x655B59C3); d=doII(d,a,b,c,x[k+3], S42,0x8F0CCC92); c=doII(c,d,a,b,x[k+10],S43,0xFFEFF47D); b=doII(b,c,d,a,x[k+1], S44,0x85845DD1); a=doII(a,b,c,d,x[k+8], S41,0x6FA87E4F); d=doII(d,a,b,c,x[k+15],S42,0xFE2CE6E0); c=doII(c,d,a,b,x[k+6], S43,0xA3014314); b=doII(b,c,d,a,x[k+13],S44,0x4E0811A1); a=doII(a,b,c,d,x[k+4], S41,0xF7537E82); d=doII(d,a,b,c,x[k+11],S42,0xBD3AF235); c=doII(c,d,a,b,x[k+2], S43,0x2AD7D2BB); b=doII(b,c,d,a,x[k+9], S44,0xEB86D391); a=addUnsigned(a,AA); b=addUnsigned(b,BB); c=addUnsigned(c,CC); d=addUnsigned(d,DD); } var temp = wordToHex(a)+wordToHex(b)+wordToHex(c)+wordToHex(d); return temp.toLowerCase(); }; },{"./Constants":1,"./Grammar":6,"./URI":21}],23:[function(require,module,exports){ module.exports = sanityCheck; /** * Dependencies. */ var debug = require('debug')('JsSIP:sanityCheck'); var JsSIP_C = require('./Constants'); var SIPMessage = require('./SIPMessage'); var Utils = require('./Utils'); var message, ua, transport, requests = [], responses = [], all = []; requests.push(rfc3261_8_2_2_1); requests.push(rfc3261_16_3_4); requests.push(rfc3261_18_3_request); requests.push(rfc3261_8_2_2_2); responses.push(rfc3261_8_1_3_3); responses.push(rfc3261_18_3_response); all.push(minimumHeaders); function sanityCheck(m, u, t) { var len, pass; message = m; ua = u; transport = t; len = all.length; while(len--) { pass = all[len](message); if(pass === false) { return false; } } if(message instanceof SIPMessage.IncomingRequest) { len = requests.length; while(len--) { pass = requests[len](message); if(pass === false) { return false; } } } else if(message instanceof SIPMessage.IncomingResponse) { len = responses.length; while(len--) { pass = responses[len](message); if(pass === false) { return false; } } } //Everything is OK return true; } /* * Sanity Check for incoming Messages * * Requests: * - _rfc3261_8_2_2_1_ Receive a Request with a non supported URI scheme * - _rfc3261_16_3_4_ Receive a Request already sent by us * Does not look at via sent-by but at jssip_id, which is inserted as * a prefix in all initial requests generated by the ua * - _rfc3261_18_3_request_ Body Content-Length * - _rfc3261_8_2_2_2_ Merged Requests * * Responses: * - _rfc3261_8_1_3_3_ Multiple Via headers * - _rfc3261_18_3_response_ Body Content-Length * * All: * - Minimum headers in a SIP message */ // Sanity Check functions for requests function rfc3261_8_2_2_1() { if(message.s('to').uri.scheme !== 'sip') { reply(416); return false; } } function rfc3261_16_3_4() { if(!message.to_tag) { if(message.call_id.substr(0, 5) === ua.configuration.jssip_id) { reply(482); return false; } } } function rfc3261_18_3_request() { var len = Utils.str_utf8_length(message.body), contentLength = message.getHeader('content-length'); if(len < contentLength) { reply(400); return false; } } function rfc3261_8_2_2_2() { var tr, idx, fromTag = message.from_tag, call_id = message.call_id, cseq = message.cseq; // Accept any in-dialog request. if(message.to_tag) { return; } // INVITE request. if (message.method === JsSIP_C.INVITE) { // If the branch matches the key of any IST then assume it is a retransmission // and ignore the INVITE. // TODO: we should reply the last response. if (ua.transactions.ist[message.via_branch]) { return false; } // Otherwise check whether it is a merged request. else { for(idx in ua.transactions.ist) { tr = ua.transactions.ist[idx]; if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) { reply(482); return false; } } } } // Non INVITE request. else { // If the branch matches the key of any NIST then assume it is a retransmission // and ignore the request. // TODO: we should reply the last response. if (ua.transactions.nist[message.via_branch]) { return false; } // Otherwise check whether it is a merged request. else { for(idx in ua.transactions.nist) { tr = ua.transactions.nist[idx]; if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) { reply(482); return false; } } } } } // Sanity Check functions for responses function rfc3261_8_1_3_3() { if(message.getHeaders('via').length > 1) { debug('more than one Via header field present in the response, dropping the response'); return false; } } function rfc3261_18_3_response() { var len = Utils.str_utf8_length(message.body), contentLength = message.getHeader('content-length'); if(len < contentLength) { debug('message body length is lower than the value in Content-Length header field, dropping the response'); return false; } } // Sanity Check functions for requests and responses function minimumHeaders() { var mandatoryHeaders = ['from', 'to', 'call_id', 'cseq', 'via'], idx = mandatoryHeaders.length; while(idx--) { if(!message.hasHeader(mandatoryHeaders[idx])) { debug('missing mandatory header field : ' + mandatoryHeaders[idx] + ', dropping the response'); return false; } } } // Reply function reply(status_code) { var to, response = 'SIP/2.0 ' + status_code + ' ' + JsSIP_C.REASON_PHRASE[status_code] + '\r\n', vias = message.getHeaders('via'), length = vias.length, idx = 0; for(idx; idx < length; idx++) { response += 'Via: ' + vias[idx] + '\r\n'; } to = message.getHeader('To'); if(!message.to_tag) { to += ';tag=' + Utils.newTag(); } response += 'To: ' + to + '\r\n'; response += 'From: ' + message.getHeader('From') + '\r\n'; response += 'Call-ID: ' + message.call_id + '\r\n'; response += 'CSeq: ' + message.cseq + ' ' + message.method + '\r\n'; response += '\r\n'; transport.send(response); } },{"./Constants":1,"./SIPMessage":16,"./Utils":22,"debug":29}],24:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } throw TypeError('Uncaught, unspecified "error" event.'); } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { var m; if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],25:[function(require,module,exports){ if (typeof Object.create === 'function') { // implementation from standard node.js 'util' module module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { // old school shim for old browsers module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } },{}],26:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = setTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { 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'); }; // TODO(shtylman) process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],27:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],28:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = require('inherits'); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":27,"_process":26,"inherits":25}],29:[function(require,module,exports){ /** * This is the web browser implementation of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = require('./debug'); exports.log = log; exports.formatArgs = formatArgs; exports.save = save; exports.load = load; exports.useColors = useColors; exports.storage = 'undefined' != typeof chrome && 'undefined' != typeof chrome.storage ? chrome.storage.local : localstorage(); /** * Colors. */ exports.colors = [ 'lightseagreen', 'forestgreen', 'goldenrod', 'dodgerblue', 'darkorchid', 'crimson' ]; /** * Currently only WebKit-based Web Inspectors, Firefox >= v31, * and the Firebug extension (any Firefox version) are known * to support "%c" CSS customizations. * * TODO: add a `localStorage` variable to explicitly enable/disable colors */ function useColors() { // is webkit? http://stackoverflow.com/a/16459606/376773 return ('WebkitAppearance' in document.documentElement.style) || // is firebug? http://stackoverflow.com/a/398120/376773 (window.console && (console.firebug || (console.exception && console.table))) || // is firefox >= v31? // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31); } /** * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. */ exports.formatters.j = function(v) { return JSON.stringify(v); }; /** * Colorize log arguments if enabled. * * @api public */ function formatArgs() { var args = arguments; var useColors = this.useColors; args[0] = (useColors ? '%c' : '') + this.namespace + (useColors ? ' %c' : ' ') + args[0] + (useColors ? '%c ' : ' ') + '+' + exports.humanize(this.diff); if (!useColors) return args; var c = 'color: ' + this.color; args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1)); // the final "%c" is somewhat tricky, because there could be other // arguments passed either before or after the %c, so we need to // figure out the correct index to insert the CSS into var index = 0; var lastC = 0; args[0].replace(/%[a-z%]/g, function(match) { if ('%%' === match) return; index++; if ('%c' === match) { // we only are interested in the *last* %c // (the user may have provided their own) lastC = index; } }); args.splice(lastC, 0, c); return args; } /** * Invokes `console.log()` when available. * No-op when `console.log` is not a "function". * * @api public */ function log() { // this hackery is required for IE8/9, where // the `console.log` function doesn't have 'apply' return 'object' === typeof console && console.log && Function.prototype.apply.call(console.log, console, arguments); } /** * Save `namespaces`. * * @param {String} namespaces * @api private */ function save(namespaces) { try { if (null == namespaces) { exports.storage.removeItem('debug'); } else { exports.storage.debug = namespaces; } } catch(e) {} } /** * Load `namespaces`. * * @return {String} returns the previously persisted debug modes * @api private */ function load() { var r; try { r = exports.storage.debug; } catch(e) {} return r; } /** * Enable namespaces listed in `localStorage.debug` initially. */ exports.enable(load()); /** * Localstorage attempts to return the localstorage. * * This is necessary because safari throws * when a user disables cookies/localstorage * and you attempt to access it. * * @return {LocalStorage} * @api private */ function localstorage(){ try { return window.localStorage; } catch (e) {} } },{"./debug":30}],30:[function(require,module,exports){ /** * This is the common logic for both the Node.js and web browser * implementations of `debug()`. * * Expose `debug()` as the module. */ exports = module.exports = debug; exports.coerce = coerce; exports.disable = disable; exports.enable = enable; exports.enabled = enabled; exports.humanize = require('ms'); /** * The currently active debug mode names, and names to skip. */ exports.names = []; exports.skips = []; /** * Map of special "%n" handling functions, for the debug "format" argument. * * Valid key names are a single, lowercased letter, i.e. "n". */ exports.formatters = {}; /** * Previously assigned color. */ var prevColor = 0; /** * Previous log timestamp. */ var prevTime; /** * Select a color. * * @return {Number} * @api private */ function selectColor() { return exports.colors[prevColor++ % exports.colors.length]; } /** * Create a debugger with the given `namespace`. * * @param {String} namespace * @return {Function} * @api public */ function debug(namespace) { // define the `disabled` version function disabled() { } disabled.enabled = false; // define the `enabled` version function enabled() { var self = enabled; // set `diff` timestamp var curr = +new Date(); var ms = curr - (prevTime || curr); self.diff = ms; self.prev = prevTime; self.curr = curr; prevTime = curr; // add the `color` if not set if (null == self.useColors) self.useColors = exports.useColors(); if (null == self.color && self.useColors) self.color = selectColor(); var args = Array.prototype.slice.call(arguments); args[0] = exports.coerce(args[0]); if ('string' !== typeof args[0]) { // anything else let's inspect with %o args = ['%o'].concat(args); } // apply any `formatters` transformations var index = 0; args[0] = args[0].replace(/%([a-z%])/g, function(match, format) { // if we encounter an escaped % then don't increase the array index if (match === '%%') return match; index++; var formatter = exports.formatters[format]; if ('function' === typeof formatter) { var val = args[index]; match = formatter.call(self, val); // now we need to remove `args[index]` since it's inlined in the `format` args.splice(index, 1); index--; } return match; }); if ('function' === typeof exports.formatArgs) { args = exports.formatArgs.apply(self, args); } var logFn = enabled.log || exports.log || console.log.bind(console); logFn.apply(self, args); } enabled.enabled = true; var fn = exports.enabled(namespace) ? enabled : disabled; fn.namespace = namespace; return fn; } /** * Enables a debug mode by namespaces. This can include modes * separated by a colon and wildcards. * * @param {String} namespaces * @api public */ function enable(namespaces) { exports.save(namespaces); var split = (namespaces || '').split(/[\s,]+/); var len = split.length; for (var i = 0; i < len; i++) { if (!split[i]) continue; // ignore empty strings namespaces = split[i].replace(/\*/g, '.*?'); if (namespaces[0] === '-') { exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); } else { exports.names.push(new RegExp('^' + namespaces + '$')); } } } /** * Disable debug output. * * @api public */ function disable() { exports.enable(''); } /** * Returns true if the given mode name is enabled, false otherwise. * * @param {String} name * @return {Boolean} * @api public */ function enabled(name) { var i, len; for (i = 0, len = exports.skips.length; i < len; i++) { if (exports.skips[i].test(name)) { return false; } } for (i = 0, len = exports.names.length; i < len; i++) { if (exports.names[i].test(name)) { return true; } } return false; } /** * Coerce `val`. * * @param {Mixed} val * @return {Mixed} * @api private */ function coerce(val) { if (val instanceof Error) return val.stack || val.message; return val; } },{"ms":31}],31:[function(require,module,exports){ /** * Helpers. */ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; var y = d * 365.25; /** * Parse or format the given `val`. * * Options: * * - `long` verbose formatting [false] * * @param {String|Number} val * @param {Object} options * @return {String|Number} * @api public */ module.exports = function(val, options){ options = options || {}; if ('string' == typeof val) return parse(val); return options.long ? long(val) : short(val); }; /** * Parse the given `str` and return milliseconds. * * @param {String} str * @return {Number} * @api private */ function parse(str) { str = '' + str; if (str.length > 10000) return; var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str); if (!match) return; var n = parseFloat(match[1]); var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'yrs': case 'yr': case 'y': return n * y; case 'days': case 'day': case 'd': return n * d; case 'hours': case 'hour': case 'hrs': case 'hr': case 'h': return n * h; case 'minutes': case 'minute': case 'mins': case 'min': case 'm': return n * m; case 'seconds': case 'second': case 'secs': case 'sec': case 's': return n * s; case 'milliseconds': case 'millisecond': case 'msecs': case 'msec': case 'ms': return n; } } /** * Short format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function short(ms) { if (ms >= d) return Math.round(ms / d) + 'd'; if (ms >= h) return Math.round(ms / h) + 'h'; if (ms >= m) return Math.round(ms / m) + 'm'; if (ms >= s) return Math.round(ms / s) + 's'; return ms + 'ms'; } /** * Long format for `ms`. * * @param {Number} ms * @return {String} * @api private */ function long(ms) { return plural(ms, d, 'day') || plural(ms, h, 'hour') || plural(ms, m, 'minute') || plural(ms, s, 'second') || ms + ' ms'; } /** * Pluralization helper. */ function plural(ms, n, name) { if (ms < n) return; if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name; return Math.ceil(ms / n) + ' ' + name + 's'; } },{}],32:[function(require,module,exports){ (function (global){ 'use strict'; // Expose the Adapter function/object. module.exports = Adapter; // Dependencies var browser = require('bowser').browser, debug = require('debug')('rtcninja:Adapter'), debugerror = require('debug')('rtcninja:ERROR:Adapter'), // Internal vars getUserMedia = null, RTCPeerConnection = null, RTCSessionDescription = null, RTCIceCandidate = null, MediaStreamTrack = null, getMediaDevices = null, attachMediaStream = null, canRenegotiate = false, oldSpecRTCOfferOptions = false, browserVersion = Number(browser.version) || 0, isDesktop = !!(!browser.mobile || !browser.tablet), hasWebRTC = false, virtGlobal, virtNavigator; debugerror.log = console.warn.bind(console); // Dirty trick to get this library working in a Node-webkit env with browserified libs virtGlobal = global.window || global; // Don't fail in Node virtNavigator = virtGlobal.navigator || {}; // Constructor. function Adapter(options) { // Chrome desktop, Chrome Android, Opera desktop, Opera Android, Android native browser // or generic Webkit browser. if ( (isDesktop && browser.chrome && browserVersion >= 32) || (browser.android && browser.chrome && browserVersion >= 39) || (isDesktop && browser.opera && browserVersion >= 27) || (browser.android && browser.opera && browserVersion >= 24) || (browser.android && browser.webkit && !browser.chrome && browserVersion >= 37) || (virtNavigator.webkitGetUserMedia && virtGlobal.webkitRTCPeerConnection) ) { hasWebRTC = true; getUserMedia = virtNavigator.webkitGetUserMedia.bind(virtNavigator); RTCPeerConnection = virtGlobal.webkitRTCPeerConnection; RTCSessionDescription = virtGlobal.RTCSessionDescription; RTCIceCandidate = virtGlobal.RTCIceCandidate; MediaStreamTrack = virtGlobal.MediaStreamTrack; if (MediaStreamTrack && MediaStreamTrack.getSources) { getMediaDevices = MediaStreamTrack.getSources.bind(MediaStreamTrack); } else if (virtNavigator.getMediaDevices) { getMediaDevices = virtNavigator.getMediaDevices.bind(virtNavigator); } attachMediaStream = function (element, stream) { element.src = URL.createObjectURL(stream); return element; }; canRenegotiate = true; oldSpecRTCOfferOptions = false; // Firefox desktop, Firefox Android. } else if ( (isDesktop && browser.firefox && browserVersion >= 22) || (browser.android && browser.firefox && browserVersion >= 33) || (virtNavigator.mozGetUserMedia && virtGlobal.mozRTCPeerConnection) ) { hasWebRTC = true; getUserMedia = virtNavigator.mozGetUserMedia.bind(virtNavigator); RTCPeerConnection = virtGlobal.mozRTCPeerConnection; RTCSessionDescription = virtGlobal.mozRTCSessionDescription; RTCIceCandidate = virtGlobal.mozRTCIceCandidate; MediaStreamTrack = virtGlobal.MediaStreamTrack; attachMediaStream = function (element, stream) { element.src = URL.createObjectURL(stream); return element; }; canRenegotiate = false; oldSpecRTCOfferOptions = false; // WebRTC plugin required. For example IE or Safari with the Temasys plugin. } else if ( options.plugin && typeof options.plugin.isRequired === 'function' && options.plugin.isRequired() && typeof options.plugin.isInstalled === 'function' && options.plugin.isInstalled() ) { var pluginiface = options.plugin.interface; hasWebRTC = true; getUserMedia = pluginiface.getUserMedia; RTCPeerConnection = pluginiface.RTCPeerConnection; RTCSessionDescription = pluginiface.RTCSessionDescription; RTCIceCandidate = pluginiface.RTCIceCandidate; MediaStreamTrack = pluginiface.MediaStreamTrack; // TODO: getSources() freezes IE so disable it. if (browser.safari) { if (MediaStreamTrack && MediaStreamTrack.getSources) { getMediaDevices = MediaStreamTrack.getSources.bind(MediaStreamTrack); } else if (virtNavigator.getMediaDevices) { getMediaDevices = virtNavigator.getMediaDevices.bind(virtNavigator); } } attachMediaStream = pluginiface.attachMediaStream; canRenegotiate = pluginiface.canRenegotiate; oldSpecRTCOfferOptions = true; // TODO: Update when fixed in the plugin. // Best effort (may be adater.js is loaded). } else if (virtNavigator.getUserMedia && virtGlobal.RTCPeerConnection) { hasWebRTC = true; getUserMedia = virtNavigator.getUserMedia.bind(virtNavigator); RTCPeerConnection = virtGlobal.RTCPeerConnection; RTCSessionDescription = virtGlobal.RTCSessionDescription; RTCIceCandidate = virtGlobal.RTCIceCandidate; MediaStreamTrack = virtGlobal.MediaStreamTrack; if (MediaStreamTrack && MediaStreamTrack.getSources) { getMediaDevices = MediaStreamTrack.getSources.bind(MediaStreamTrack); } else if (virtNavigator.getMediaDevices) { getMediaDevices = virtNavigator.getMediaDevices.bind(virtNavigator); } attachMediaStream = virtGlobal.attachMediaStream || function (element, stream) { element.src = URL.createObjectURL(stream); return element; }; canRenegotiate = false; oldSpecRTCOfferOptions = false; } function throwNonSupported(item) { return function () { throw new Error('rtcninja: WebRTC not supported, missing ' + item + ' [browser: ' + browser.name + ' ' + browser.version + ']'); }; } // Public API. // Expose a WebRTC checker. Adapter.hasWebRTC = function () { return hasWebRTC; }; // Expose getUserMedia. if (getUserMedia) { Adapter.getUserMedia = function (constraints, successCallback, errorCallback) { debug('getUserMedia() | constraints: %o', constraints); try { getUserMedia(constraints, function (stream) { debug('getUserMedia() | success'); if (successCallback) { successCallback(stream); } }, function (error) { debug('getUserMedia() | error:', error); if (errorCallback) { errorCallback(error); } } ); } catch (error) { debugerror('getUserMedia() | error:', error); if (errorCallback) { errorCallback(error); } } }; } else { Adapter.getUserMedia = function (constraints, successCallback, errorCallback) { debugerror('getUserMedia() | WebRTC not supported'); if (errorCallback) { errorCallback(new Error('rtcninja: WebRTC not supported, missing ' + 'getUserMedia [browser: ' + browser.name + ' ' + browser.version + ']')); } else { throwNonSupported('getUserMedia'); } }; } // Expose RTCPeerConnection. Adapter.RTCPeerConnection = RTCPeerConnection || throwNonSupported('RTCPeerConnection'); // Expose RTCSessionDescription. Adapter.RTCSessionDescription = RTCSessionDescription || throwNonSupported('RTCSessionDescription'); // Expose RTCIceCandidate. Adapter.RTCIceCandidate = RTCIceCandidate || throwNonSupported('RTCIceCandidate'); // Expose MediaStreamTrack. Adapter.MediaStreamTrack = MediaStreamTrack || throwNonSupported('MediaStreamTrack'); // Expose getMediaDevices. Adapter.getMediaDevices = getMediaDevices; // Expose MediaStreamTrack. Adapter.attachMediaStream = attachMediaStream || throwNonSupported('attachMediaStream'); // Expose canRenegotiate attribute. Adapter.canRenegotiate = canRenegotiate; // Expose closeMediaStream. Adapter.closeMediaStream = function (stream) { if (!stream) { return; } // Latest spec states that MediaStream has no stop() method and instead must // call stop() on every MediaStreamTrack. if (MediaStreamTrack && MediaStreamTrack.prototype && MediaStreamTrack.prototype.stop) { debug('closeMediaStream() | calling stop() on all the MediaStreamTrack'); var tracks, i, len; if (stream.getTracks) { tracks = stream.getTracks(); for (i = 0, len = tracks.length; i < len; i += 1) { tracks[i].stop(); } } else { tracks = stream.getAudioTracks(); for (i = 0, len = tracks.length; i < len; i += 1) { tracks[i].stop(); } tracks = stream.getVideoTracks(); for (i = 0, len = tracks.length; i < len; i += 1) { tracks[i].stop(); } } // Deprecated by the spec, but still in use. } else if (typeof stream.stop === 'function') { debug('closeMediaStream() | calling stop() on the MediaStream'); stream.stop(); } }; // Expose fixPeerConnectionConfig. Adapter.fixPeerConnectionConfig = function (pcConfig) { var i, len, iceServer, hasUrls, hasUrl; if (!Array.isArray(pcConfig.iceServers)) { pcConfig.iceServers = []; } for (i = 0, len = pcConfig.iceServers.length; i < len; i += 1) { iceServer = pcConfig.iceServers[i]; hasUrls = iceServer.hasOwnProperty('urls'); hasUrl = iceServer.hasOwnProperty('url'); if (typeof iceServer === 'object') { // Has .urls but not .url, so add .url with a single string value. if (hasUrls && !hasUrl) { iceServer.url = (Array.isArray(iceServer.urls) ? iceServer.urls[0] : iceServer.urls); // Has .url but not .urls, so add .urls with same value. } else if (!hasUrls && hasUrl) { iceServer.urls = (Array.isArray(iceServer.url) ? iceServer.url.slice() : iceServer.url); } // Ensure .url is a single string. if (hasUrl && Array.isArray(iceServer.url)) { iceServer.url = iceServer.url[0]; } } } }; // Expose fixRTCOfferOptions. Adapter.fixRTCOfferOptions = function (options) { options = options || {}; // New spec. if (!oldSpecRTCOfferOptions) { if (options.mandatory && options.mandatory.OfferToReceiveAudio) { options.offerToReceiveAudio = 1; } if (options.mandatory && options.mandatory.OfferToReceiveVideo) { options.offerToReceiveVideo = 1; } delete options.mandatory; // Old spec. } else { if (options.offerToReceiveAudio) { options.mandatory = options.mandatory || {}; options.mandatory.OfferToReceiveAudio = true; } if (options.offerToReceiveVideo) { options.mandatory = options.mandatory || {}; options.mandatory.OfferToReceiveVideo = true; } } }; return Adapter; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"bowser":36,"debug":29}],33:[function(require,module,exports){ 'use strict'; // Expose the RTCPeerConnection class. module.exports = RTCPeerConnection; // Dependencies. var merge = require('merge'), debug = require('debug')('rtcninja:RTCPeerConnection'), debugerror = require('debug')('rtcninja:ERROR:RTCPeerConnection'), Adapter = require('./Adapter'), // Internal constants. C = { REGEXP_NORMALIZED_CANDIDATE: new RegExp(/^candidate:/i), REGEXP_FIX_CANDIDATE: new RegExp(/(^a=|\r|\n)/gi), REGEXP_RELAY_CANDIDATE: new RegExp(/ relay /i), REGEXP_SDP_CANDIDATES: new RegExp(/^a=candidate:.*\r\n/igm), REGEXP_SDP_NON_RELAY_CANDIDATES: new RegExp(/^a=candidate:(.(?!relay ))*\r\n/igm) }, // Internal variables. VAR = { normalizeCandidate: null }; debugerror.log = console.warn.bind(console); // Constructor function RTCPeerConnection(pcConfig, pcConstraints) { debug('new | pcConfig: %o', pcConfig); // Set this.pcConfig and this.options. setConfigurationAndOptions.call(this, pcConfig); // NOTE: Deprecated pcConstraints argument. this.pcConstraints = pcConstraints; // Own version of the localDescription. this.ourLocalDescription = null; // Latest values of PC attributes to avoid events with same value. this.ourSignalingState = null; this.ourIceConnectionState = null; this.ourIceGatheringState = null; // Timer for options.gatheringTimeout. this.timerGatheringTimeout = null; // Timer for options.gatheringTimeoutAfterRelay. this.timerGatheringTimeoutAfterRelay = null; // Flag to ignore new gathered ICE candidates. this.ignoreIceGathering = false; // Flag set when closed. this.closed = false; // Set RTCPeerConnection. setPeerConnection.call(this); // Set properties. setProperties.call(this); } // Public API. RTCPeerConnection.prototype.createOffer = function (successCallback, failureCallback, options) { debug('createOffer()'); var self = this; Adapter.fixRTCOfferOptions(options); this.pc.createOffer( function (offer) { if (isClosed.call(self)) { return; } debug('createOffer() | success'); if (successCallback) { successCallback(offer); } }, function (error) { if (isClosed.call(self)) { return; } debugerror('createOffer() | error:', error); if (failureCallback) { failureCallback(error); } }, options ); }; RTCPeerConnection.prototype.createAnswer = function (successCallback, failureCallback, options) { debug('createAnswer()'); var self = this; this.pc.createAnswer( function (answer) { if (isClosed.call(self)) { return; } debug('createAnswer() | success'); if (successCallback) { successCallback(answer); } }, function (error) { if (isClosed.call(self)) { return; } debugerror('createAnswer() | error:', error); if (failureCallback) { failureCallback(error); } }, options ); }; RTCPeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) { debug('setLocalDescription()'); var self = this; this.pc.setLocalDescription( description, // success. function () { if (isClosed.call(self)) { return; } debug('setLocalDescription() | success'); // Clear gathering timers. clearTimeout(self.timerGatheringTimeout); delete self.timerGatheringTimeout; clearTimeout(self.timerGatheringTimeoutAfterRelay); delete self.timerGatheringTimeoutAfterRelay; runTimerGatheringTimeout(); if (successCallback) { successCallback(); } }, // failure function (error) { if (isClosed.call(self)) { return; } debugerror('setLocalDescription() | error:', error); if (failureCallback) { failureCallback(error); } } ); // Enable (again) ICE gathering. this.ignoreIceGathering = false; // Handle gatheringTimeout. function runTimerGatheringTimeout() { if (typeof self.options.gatheringTimeout !== 'number') { return; } // If setLocalDescription was already called, it may happen that // ICE gathering is not needed, so don't run this timer. if (self.pc.iceGatheringState === 'complete') { return; } debug('setLocalDescription() | ending gathering in %d ms (gatheringTimeout option)', self.options.gatheringTimeout); self.timerGatheringTimeout = setTimeout(function () { if (isClosed.call(self)) { return; } debug('forced end of candidates after gatheringTimeout timeout'); // Clear gathering timers. delete self.timerGatheringTimeout; clearTimeout(self.timerGatheringTimeoutAfterRelay); delete self.timerGatheringTimeoutAfterRelay; // Ignore new candidates. self.ignoreIceGathering = true; if (self.onicecandidate) { self.onicecandidate({ candidate: null }, null); } }, self.options.gatheringTimeout); } }; RTCPeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) { debug('setRemoteDescription()'); var self = this; this.pc.setRemoteDescription( description, function () { if (isClosed.call(self)) { return; } debug('setRemoteDescription() | success'); if (successCallback) { successCallback(); } }, function (error) { if (isClosed.call(self)) { return; } debugerror('setRemoteDescription() | error:', error); if (failureCallback) { failureCallback(error); } } ); }; RTCPeerConnection.prototype.updateIce = function (pcConfig) { debug('updateIce() | pcConfig: %o', pcConfig); // Update this.pcConfig and this.options. setConfigurationAndOptions.call(this, pcConfig); this.pc.updateIce(this.pcConfig); // Enable (again) ICE gathering. this.ignoreIceGathering = false; }; RTCPeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) { debug('addIceCandidate() | candidate: %o', candidate); var self = this; this.pc.addIceCandidate( candidate, function () { if (isClosed.call(self)) { return; } debug('addIceCandidate() | success'); if (successCallback) { successCallback(); } }, function (error) { if (isClosed.call(self)) { return; } debugerror('addIceCandidate() | error:', error); if (failureCallback) { failureCallback(error); } } ); }; RTCPeerConnection.prototype.getConfiguration = function () { debug('getConfiguration()'); return this.pc.getConfiguration(); }; RTCPeerConnection.prototype.getLocalStreams = function () { debug('getLocalStreams()'); return this.pc.getLocalStreams(); }; RTCPeerConnection.prototype.getRemoteStreams = function () { debug('getRemoteStreams()'); return this.pc.getRemoteStreams(); }; RTCPeerConnection.prototype.getStreamById = function (streamId) { debug('getStreamById() | streamId: %s', streamId); return this.pc.getStreamById(streamId); }; RTCPeerConnection.prototype.addStream = function (stream) { debug('addStream() | stream: %s', stream); this.pc.addStream(stream); }; RTCPeerConnection.prototype.removeStream = function (stream) { debug('removeStream() | stream: %o', stream); this.pc.removeStream(stream); }; RTCPeerConnection.prototype.close = function () { debug('close()'); this.closed = true; // Clear gathering timers. clearTimeout(this.timerGatheringTimeout); delete this.timerGatheringTimeout; clearTimeout(this.timerGatheringTimeoutAfterRelay); delete this.timerGatheringTimeoutAfterRelay; this.pc.close(); }; RTCPeerConnection.prototype.createDataChannel = function () { debug('createDataChannel()'); return this.pc.createDataChannel.apply(this.pc, arguments); }; RTCPeerConnection.prototype.createDTMFSender = function (track) { debug('createDTMFSender()'); return this.pc.createDTMFSender(track); }; RTCPeerConnection.prototype.getStats = function () { debug('getStats()'); return this.pc.getStats.apply(this.pc, arguments); }; RTCPeerConnection.prototype.setIdentityProvider = function () { debug('setIdentityProvider()'); return this.pc.setIdentityProvider.apply(this.pc, arguments); }; RTCPeerConnection.prototype.getIdentityAssertion = function () { debug('getIdentityAssertion()'); return this.pc.getIdentityAssertion(); }; RTCPeerConnection.prototype.reset = function (pcConfig) { debug('reset() | pcConfig: %o', pcConfig); var pc = this.pc; // Remove events in the old PC. pc.onnegotiationneeded = null; pc.onicecandidate = null; pc.onaddstream = null; pc.onremovestream = null; pc.ondatachannel = null; pc.onsignalingstatechange = null; pc.oniceconnectionstatechange = null; pc.onicegatheringstatechange = null; pc.onidentityresult = null; pc.onpeeridentity = null; pc.onidpassertionerror = null; pc.onidpvalidationerror = null; // Clear gathering timers. clearTimeout(this.timerGatheringTimeout); delete this.timerGatheringTimeout; clearTimeout(this.timerGatheringTimeoutAfterRelay); delete this.timerGatheringTimeoutAfterRelay; // Silently close the old PC. debug('reset() | closing current peerConnection'); pc.close(); // Set this.pcConfig and this.options. setConfigurationAndOptions.call(this, pcConfig); // Create a new PC. setPeerConnection.call(this); }; // Private Helpers. function setConfigurationAndOptions(pcConfig) { // Clone pcConfig. this.pcConfig = merge(true, pcConfig); // Fix pcConfig. Adapter.fixPeerConnectionConfig(this.pcConfig); this.options = { iceTransportsRelay: (this.pcConfig.iceTransports === 'relay'), iceTransportsNone: (this.pcConfig.iceTransports === 'none'), gatheringTimeout: this.pcConfig.gatheringTimeout, gatheringTimeoutAfterRelay: this.pcConfig.gatheringTimeoutAfterRelay }; // Remove custom rtcninja.RTCPeerConnection options from pcConfig. delete this.pcConfig.gatheringTimeout; delete this.pcConfig.gatheringTimeoutAfterRelay; debug('setConfigurationAndOptions | processed pcConfig: %o', this.pcConfig); } function isClosed() { return ((this.closed) || (this.pc && this.pc.iceConnectionState === 'closed')); } function setEvents() { var self = this, pc = this.pc; pc.onnegotiationneeded = function (event) { if (isClosed.call(self)) { return; } debug('onnegotiationneeded()'); if (self.onnegotiationneeded) { self.onnegotiationneeded(event); } }; pc.onicecandidate = function (event) { var candidate, isRelay, newCandidate; if (isClosed.call(self)) { return; } if (self.ignoreIceGathering) { return; } // Ignore any candidate (event the null one) if iceTransports:'none' is set. if (self.options.iceTransportsNone) { return; } candidate = event.candidate; if (candidate) { isRelay = C.REGEXP_RELAY_CANDIDATE.test(candidate.candidate); // Ignore if just relay candidates are requested. if (self.options.iceTransportsRelay && !isRelay) { return; } // Handle gatheringTimeoutAfterRelay. if (isRelay && !self.timerGatheringTimeoutAfterRelay && (typeof self.options.gatheringTimeoutAfterRelay === 'number')) { debug('onicecandidate() | first relay candidate found, ending gathering in %d ms', self.options.gatheringTimeoutAfterRelay); self.timerGatheringTimeoutAfterRelay = setTimeout(function () { if (isClosed.call(self)) { return; } debug('forced end of candidates after timeout'); // Clear gathering timers. delete self.timerGatheringTimeoutAfterRelay; clearTimeout(self.timerGatheringTimeout); delete self.timerGatheringTimeout; // Ignore new candidates. self.ignoreIceGathering = true; if (self.onicecandidate) { self.onicecandidate({candidate: null}, null); } }, self.options.gatheringTimeoutAfterRelay); } newCandidate = new Adapter.RTCIceCandidate({ sdpMid: candidate.sdpMid, sdpMLineIndex: candidate.sdpMLineIndex, candidate: candidate.candidate }); // Force correct candidate syntax (just check it once). if (VAR.normalizeCandidate === null) { if (C.REGEXP_NORMALIZED_CANDIDATE.test(candidate.candidate)) { VAR.normalizeCandidate = false; } else { debug('onicecandidate() | normalizing ICE candidates syntax (remove "a=" and "\\r\\n")'); VAR.normalizeCandidate = true; } } if (VAR.normalizeCandidate) { newCandidate.candidate = candidate.candidate.replace(C.REGEXP_FIX_CANDIDATE, ''); } debug( 'onicecandidate() | m%d(%s) %s', newCandidate.sdpMLineIndex, newCandidate.sdpMid || 'no mid', newCandidate.candidate); if (self.onicecandidate) { self.onicecandidate(event, newCandidate); } // Null candidate (end of candidates). } else { debug('onicecandidate() | end of candidates'); // Clear gathering timers. clearTimeout(self.timerGatheringTimeout); delete self.timerGatheringTimeout; clearTimeout(self.timerGatheringTimeoutAfterRelay); delete self.timerGatheringTimeoutAfterRelay; if (self.onicecandidate) { self.onicecandidate(event, null); } } }; pc.onaddstream = function (event) { if (isClosed.call(self)) { return; } debug('onaddstream() | stream: %o', event.stream); if (self.onaddstream) { self.onaddstream(event, event.stream); } }; pc.onremovestream = function (event) { if (isClosed.call(self)) { return; } debug('onremovestream() | stream: %o', event.stream); if (self.onremovestream) { self.onremovestream(event, event.stream); } }; pc.ondatachannel = function (event) { if (isClosed.call(self)) { return; } debug('ondatachannel() | datachannel: %o', event.channel); if (self.ondatachannel) { self.ondatachannel(event, event.channel); } }; pc.onsignalingstatechange = function (event) { if (pc.signalingState === self.ourSignalingState) { return; } debug('onsignalingstatechange() | signalingState: %s', pc.signalingState); self.ourSignalingState = pc.signalingState; if (self.onsignalingstatechange) { self.onsignalingstatechange(event, pc.signalingState); } }; pc.oniceconnectionstatechange = function (event) { if (pc.iceConnectionState === self.ourIceConnectionState) { return; } debug('oniceconnectionstatechange() | iceConnectionState: %s', pc.iceConnectionState); self.ourIceConnectionState = pc.iceConnectionState; if (self.oniceconnectionstatechange) { self.oniceconnectionstatechange(event, pc.iceConnectionState); } }; pc.onicegatheringstatechange = function (event) { if (isClosed.call(self)) { return; } if (pc.iceGatheringState === self.ourIceGatheringState) { return; } debug('onicegatheringstatechange() | iceGatheringState: %s', pc.iceGatheringState); self.ourIceGatheringState = pc.iceGatheringState; if (self.onicegatheringstatechange) { self.onicegatheringstatechange(event, pc.iceGatheringState); } }; pc.onidentityresult = function (event) { if (isClosed.call(self)) { return; } debug('onidentityresult()'); if (self.onidentityresult) { self.onidentityresult(event); } }; pc.onpeeridentity = function (event) { if (isClosed.call(self)) { return; } debug('onpeeridentity()'); if (self.onpeeridentity) { self.onpeeridentity(event); } }; pc.onidpassertionerror = function (event) { if (isClosed.call(self)) { return; } debug('onidpassertionerror()'); if (self.onidpassertionerror) { self.onidpassertionerror(event); } }; pc.onidpvalidationerror = function (event) { if (isClosed.call(self)) { return; } debug('onidpvalidationerror()'); if (self.onidpvalidationerror) { self.onidpvalidationerror(event); } }; } function setPeerConnection() { // Create a RTCPeerConnection. if (!this.pcConstraints) { this.pc = new Adapter.RTCPeerConnection(this.pcConfig); } else { // NOTE: Deprecated. this.pc = new Adapter.RTCPeerConnection(this.pcConfig, this.pcConstraints); } // Set RTC events. setEvents.call(this); } function getLocalDescription() { var pc = this.pc, options = this.options, sdp = null; if (!pc.localDescription) { this.ourLocalDescription = null; return null; } // Mangle the SDP string. if (options.iceTransportsRelay) { sdp = pc.localDescription.sdp.replace(C.REGEXP_SDP_NON_RELAY_CANDIDATES, ''); } else if (options.iceTransportsNone) { sdp = pc.localDescription.sdp.replace(C.REGEXP_SDP_CANDIDATES, ''); } this.ourLocalDescription = new Adapter.RTCSessionDescription({ type: pc.localDescription.type, sdp: sdp || pc.localDescription.sdp }); return this.ourLocalDescription; } function setProperties() { var self = this; Object.defineProperties(this, { peerConnection: { get: function () { return self.pc; } }, signalingState: { get: function () { return self.pc.signalingState; } }, iceConnectionState: { get: function () { return self.pc.iceConnectionState; } }, iceGatheringState: { get: function () { return self.pc.iceGatheringState; } }, localDescription: { get: function () { return getLocalDescription.call(self); } }, remoteDescription: { get: function () { return self.pc.remoteDescription; } }, peerIdentity: { get: function () { return self.pc.peerIdentity; } } }); } },{"./Adapter":32,"debug":29,"merge":37}],34:[function(require,module,exports){ 'use strict'; module.exports = rtcninja; // Dependencies. var browser = require('bowser').browser, debug = require('debug')('rtcninja'), debugerror = require('debug')('rtcninja:ERROR'), version = require('./version'), Adapter = require('./Adapter'), RTCPeerConnection = require('./RTCPeerConnection'), // Internal vars. called = false; debugerror.log = console.warn.bind(console); debug('version %s', version); debug('detected browser: %s %s [mobile:%s, tablet:%s, android:%s, ios:%s]', browser.name, browser.version, !!browser.mobile, !!browser.tablet, !!browser.android, !!browser.ios); // Constructor. function rtcninja(options) { // Load adapter var iface = Adapter(options || {}); // jshint ignore:line called = true; // Expose RTCPeerConnection class. rtcninja.RTCPeerConnection = RTCPeerConnection; // Expose WebRTC API and utils. rtcninja.getUserMedia = iface.getUserMedia; rtcninja.RTCSessionDescription = iface.RTCSessionDescription; rtcninja.RTCIceCandidate = iface.RTCIceCandidate; rtcninja.MediaStreamTrack = iface.MediaStreamTrack; rtcninja.getMediaDevices = iface.getMediaDevices; rtcninja.attachMediaStream = iface.attachMediaStream; rtcninja.closeMediaStream = iface.closeMediaStream; rtcninja.canRenegotiate = iface.canRenegotiate; // Log WebRTC support. if (iface.hasWebRTC()) { debug('WebRTC supported'); return true; } else { debugerror('WebRTC not supported'); return false; } } // Public API. // If called without calling rtcninja(), call it. rtcninja.hasWebRTC = function () { if (!called) { rtcninja(); } return Adapter.hasWebRTC(); }; // Expose version property. Object.defineProperty(rtcninja, 'version', { get: function () { return version; } }); // Expose called property. Object.defineProperty(rtcninja, 'called', { get: function () { return called; } }); // Exposing stuff. rtcninja.debug = require('debug'); rtcninja.browser = browser; },{"./Adapter":32,"./RTCPeerConnection":33,"./version":35,"bowser":36,"debug":29}],35:[function(require,module,exports){ 'use strict'; // Expose the 'version' field of package.json. module.exports = require('../package.json').version; },{"../package.json":38}],36:[function(require,module,exports){ /*! * Bowser - a browser detector * https://github.com/ded/bowser * MIT License | (c) Dustin Diaz 2014 */ !function (name, definition) { if (typeof module != 'undefined' && module.exports) module.exports['browser'] = definition() else if (typeof define == 'function' && define.amd) define(definition) else this[name] = definition() }('bowser', function () { /** * See useragents.js for examples of navigator.userAgent */ var t = true function detect(ua) { function getFirstMatch(regex) { var match = ua.match(regex); return (match && match.length > 1 && match[1]) || ''; } function getSecondMatch(regex) { var match = ua.match(regex); return (match && match.length > 1 && match[2]) || ''; } var iosdevice = getFirstMatch(/(ipod|iphone|ipad)/i).toLowerCase() , likeAndroid = /like android/i.test(ua) , android = !likeAndroid && /android/i.test(ua) , edgeVersion = getFirstMatch(/edge\/(\d+(\.\d+)?)/i) , versionIdentifier = getFirstMatch(/version\/(\d+(\.\d+)?)/i) , tablet = /tablet/i.test(ua) , mobile = !tablet && /[^-]mobi/i.test(ua) , result if (/opera|opr/i.test(ua)) { result = { name: 'Opera' , opera: t , version: versionIdentifier || getFirstMatch(/(?:opera|opr)[\s\/](\d+(\.\d+)?)/i) } } else if (/windows phone/i.test(ua)) { result = { name: 'Windows Phone' , windowsphone: t } if (edgeVersion) { result.msedge = t result.version = edgeVersion } else { result.msie = t result.version = getFirstMatch(/iemobile\/(\d+(\.\d+)?)/i) } } else if (/msie|trident/i.test(ua)) { result = { name: 'Internet Explorer' , msie: t , version: getFirstMatch(/(?:msie |rv:)(\d+(\.\d+)?)/i) } } else if (/chrome.+? edge/i.test(ua)) { result = { name: 'Microsoft Edge' , msedge: t , version: edgeVersion } } else if (/chrome|crios|crmo/i.test(ua)) { result = { name: 'Chrome' , chrome: t , version: getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.\d+)?)/i) } } else if (iosdevice) { result = { name : iosdevice == 'iphone' ? 'iPhone' : iosdevice == 'ipad' ? 'iPad' : 'iPod' } // WTF: version is not part of user agent in web apps if (versionIdentifier) { result.version = versionIdentifier } } else if (/sailfish/i.test(ua)) { result = { name: 'Sailfish' , sailfish: t , version: getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i) } } else if (/seamonkey\//i.test(ua)) { result = { name: 'SeaMonkey' , seamonkey: t , version: getFirstMatch(/seamonkey\/(\d+(\.\d+)?)/i) } } else if (/firefox|iceweasel/i.test(ua)) { result = { name: 'Firefox' , firefox: t , version: getFirstMatch(/(?:firefox|iceweasel)[ \/](\d+(\.\d+)?)/i) } if (/\((mobile|tablet);[^\)]*rv:[\d\.]+\)/i.test(ua)) { result.firefoxos = t } } else if (/silk/i.test(ua)) { result = { name: 'Amazon Silk' , silk: t , version : getFirstMatch(/silk\/(\d+(\.\d+)?)/i) } } else if (android) { result = { name: 'Android' , version: versionIdentifier } } else if (/phantom/i.test(ua)) { result = { name: 'PhantomJS' , phantom: t , version: getFirstMatch(/phantomjs\/(\d+(\.\d+)?)/i) } } else if (/blackberry|\bbb\d+/i.test(ua) || /rim\stablet/i.test(ua)) { result = { name: 'BlackBerry' , blackberry: t , version: versionIdentifier || getFirstMatch(/blackberry[\d]+\/(\d+(\.\d+)?)/i) } } else if (/(web|hpw)os/i.test(ua)) { result = { name: 'WebOS' , webos: t , version: versionIdentifier || getFirstMatch(/w(?:eb)?osbrowser\/(\d+(\.\d+)?)/i) }; /touchpad\//i.test(ua) && (result.touchpad = t) } else if (/bada/i.test(ua)) { result = { name: 'Bada' , bada: t , version: getFirstMatch(/dolfin\/(\d+(\.\d+)?)/i) }; } else if (/tizen/i.test(ua)) { result = { name: 'Tizen' , tizen: t , version: getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.\d+)?)/i) || versionIdentifier }; } else if (/safari/i.test(ua)) { result = { name: 'Safari' , safari: t , version: versionIdentifier } } else { result = { name: getFirstMatch(/^(.*)\/(.*) /), version: getSecondMatch(/^(.*)\/(.*) /) }; } // set webkit or gecko flag for browsers based on these engines if (!result.msedge && /(apple)?webkit/i.test(ua)) { result.name = result.name || "Webkit" result.webkit = t if (!result.version && versionIdentifier) { result.version = versionIdentifier } } else if (!result.opera && /gecko\//i.test(ua)) { result.name = result.name || "Gecko" result.gecko = t result.version = result.version || getFirstMatch(/gecko\/(\d+(\.\d+)?)/i) } // set OS flags for platforms that have multiple browsers if (!result.msedge && (android || result.silk)) { result.android = t } else if (iosdevice) { result[iosdevice] = t result.ios = t } // OS version extraction var osVersion = ''; if (result.windowsphone) { osVersion = getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i); } else if (iosdevice) { osVersion = getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i); osVersion = osVersion.replace(/[_\s]/g, '.'); } else if (android) { osVersion = getFirstMatch(/android[ \/-](\d+(\.\d+)*)/i); } else if (result.webos) { osVersion = getFirstMatch(/(?:web|hpw)os\/(\d+(\.\d+)*)/i); } else if (result.blackberry) { osVersion = getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i); } else if (result.bada) { osVersion = getFirstMatch(/bada\/(\d+(\.\d+)*)/i); } else if (result.tizen) { osVersion = getFirstMatch(/tizen[\/\s](\d+(\.\d+)*)/i); } if (osVersion) { result.osversion = osVersion; } // device type extraction var osMajorVersion = osVersion.split('.')[0]; if (tablet || iosdevice == 'ipad' || (android && (osMajorVersion == 3 || (osMajorVersion == 4 && !mobile))) || result.silk) { result.tablet = t } else if (mobile || iosdevice == 'iphone' || iosdevice == 'ipod' || android || result.blackberry || result.webos || result.bada) { result.mobile = t } // Graded Browser Support // http://developer.yahoo.com/yui/articles/gbs if (result.msedge || (result.msie && result.version >= 10) || (result.chrome && result.version >= 20) || (result.firefox && result.version >= 20.0) || (result.safari && result.version >= 6) || (result.opera && result.version >= 10.0) || (result.ios && result.osversion && result.osversion.split(".")[0] >= 6) || (result.blackberry && result.version >= 10.1) ) { result.a = t; } else if ((result.msie && result.version < 10) || (result.chrome && result.version < 20) || (result.firefox && result.version < 20.0) || (result.safari && result.version < 6) || (result.opera && result.version < 10.0) || (result.ios && result.osversion && result.osversion.split(".")[0] < 6) ) { result.c = t } else result.x = t return result } var bowser = detect(typeof navigator !== 'undefined' ? navigator.userAgent : '') bowser.test = function (browserList) { for (var i = 0; i < browserList.length; ++i) { var browserItem = browserList[i]; if (typeof browserItem=== 'string') { if (browserItem in bowser) { return true; } } } return false; } /* * Set our detect method to the main bowser object so we can * reuse it to test other user agents. * This is needed to implement future tests. */ bowser._detect = detect; return bowser }); },{}],37:[function(require,module,exports){ /*! * @name JavaScript/NodeJS Merge v1.2.0 * @author yeikos * @repository https://github.com/yeikos/js.merge * Copyright 2014 yeikos - MIT license * https://raw.github.com/yeikos/js.merge/master/LICENSE */ ;(function(isNode) { /** * Merge one or more objects * @param bool? clone * @param mixed,... arguments * @return object */ var Public = function(clone) { return merge(clone === true, false, arguments); }, publicName = 'merge'; /** * Merge two or more objects recursively * @param bool? clone * @param mixed,... arguments * @return object */ Public.recursive = function(clone) { return merge(clone === true, true, arguments); }; /** * Clone the input removing any reference * @param mixed input * @return mixed */ Public.clone = function(input) { var output = input, type = typeOf(input), index, size; if (type === 'array') { output = []; size = input.length; for (index=0;index<size;++index) output[index] = Public.clone(input[index]); } else if (type === 'object') { output = {}; for (index in input) output[index] = Public.clone(input[index]); } return output; }; /** * Merge two objects recursively * @param mixed input * @param mixed extend * @return mixed */ function merge_recursive(base, extend) { if (typeOf(base) !== 'object') return extend; for (var key in extend) { if (typeOf(base[key]) === 'object' && typeOf(extend[key]) === 'object') { base[key] = merge_recursive(base[key], extend[key]); } else { base[key] = extend[key]; } } return base; } /** * Merge two or more objects * @param bool clone * @param bool recursive * @param array argv * @return object */ function merge(clone, recursive, argv) { var result = argv[0], size = argv.length; if (clone || typeOf(result) !== 'object') result = {}; for (var index=0;index<size;++index) { var item = argv[index], type = typeOf(item); if (type !== 'object') continue; for (var key in item) { var sitem = clone ? Public.clone(item[key]) : item[key]; if (recursive) { result[key] = merge_recursive(result[key], sitem); } else { result[key] = sitem; } } } return result; } /** * Get type of variable * @param mixed input * @return string * * @see http://jsperf.com/typeofvar */ function typeOf(input) { return ({}).toString.call(input).slice(8, -1).toLowerCase(); } if (isNode) { module.exports = Public; } else { window[publicName] = Public; } })(typeof module === 'object' && module && typeof module.exports === 'object' && module.exports); },{}],38:[function(require,module,exports){ module.exports={ "name": "rtcninja", "version": "0.6.1", "description": "WebRTC API wrapper to deal with different browsers", "author": { "name": "Iñaki Baz Castillo", "email": "[email protected]", "url": "http://eface2face.com" }, "contributors": [ { "name": "Jesús Pérez", "email": "[email protected]" } ], "license": "MIT", "main": "lib/rtcninja.js", "homepage": "https://github.com/eface2face/rtcninja.js", "repository": { "type": "git", "url": "https://github.com/eface2face/rtcninja.js.git" }, "keywords": [ "webrtc" ], "engines": { "node": ">=0.10.32" }, "dependencies": { "bowser": "^0.7.3", "debug": "^2.2.0", "merge": "^1.2.0" }, "devDependencies": { "browserify": "^10.2.3", "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", "gulp-expect-file": "0.0.7", "gulp-filelog": "^0.4.1", "gulp-header": "^1.2.2", "gulp-jscs": "^1.6.0", "gulp-jscs-stylish": "^1.1.0", "gulp-jshint": "^1.11.0", "gulp-rename": "^1.2.2", "gulp-uglify": "^1.2.0", "jshint-stylish": "^1.0.2", "retire": "^1.1.0", "shelljs": "^0.5.0", "vinyl-source-stream": "^1.1.0" }, "readme": "# rtcninja.js <img src=\"http://www.pubnub.com/blog/wp-content/uploads/2014/01/google-webrtc-logo.png\" height=\"30\" width=\"30\">\nWebRTC API wrapper to deal with different browsers transparently, [eventually](http://iswebrtcreadyyet.com/) this library shouldn't be needed. We only have to wait until W3C group in charge [finishes the specification](https://tools.ietf.org/wg/rtcweb/) and the different browsers implement it correctly :sweat_smile:.\n\n<img src=\"http://images4.fanpop.com/image/photos/21800000/browser-fight-google-chrome-21865454-600-531.jpg\" height=\"250\" width=\"250\">\n\nSupported environments:\n- [Google Chrome](https://www.google.com/chrome/browser/desktop/index.html) (desktop & mobile)\n- [Google Canary](https://www.google.com/chrome/browser/canary.html) (desktop & mobile)\n- [Mozilla Firefox](https://www.mozilla.org/en-GB/firefox/new) (desktop & mobile)\n- [Firefox Nigthly](https://nightly.mozilla.org/) (desktop & mobile)\n- [Opera](http://www.opera.com/)\n- [Vivaldi](https://vivaldi.com/)\n- [CrossWalk](https://crosswalk-project.org/)\n- [Cordova](cordova.apache.org): iOS support, you only have to use our plugin [following these steps](https://github.com/eface2face/cordova-plugin-iosrtc#usage).\n- [Node-webkit](https://github.com/nwjs/nw.js/)\n\n\n## Installation\n\n### **npm**:\n```bash\n$ npm install rtcninja\n```\n#### Usage\n```javascript\nvar rtcninja = require('rtcninja');\n```\n\n### **bower**:\n```bash\n$ bower install rtcninja\n```\n\n\n## Transpiled library\n\nTake a browserified version of the library from the `dist/` folder:\n\n* `dist/rtcninja-X.Y.Z.js`: The uncompressed version.\n* `dist/rtcninja-X.Y.Z.min.js`: The compressed production-ready version.\n* `dist/rtcninja.js`: A copy of the uncompressed version.\n* `dist/rtcninja.min.js`: A copy of the compressed version.\n\nThey expose the global `window.rtcninja` module.\n\n\n## Usage\n\nIn the [examples](./examples/) folder we provide a complete one.\n\n```javascript\n// Must first call it.\nrtcninja();\n\n// Then check.\nif (rtcninja.hasWebRTC()) {\n // Do something.\n}\nelse {\n // Do something.\n}\n```\n\n\n## Documentation\n\nYou can read the full [API documentation](docs/index.md) in the docs folder.\n\n\n## Issues\nhttps://github.com/eface2face/rtcninja.js/issues\n\n\n## Developer guide\n\n- Create a branch with a name including your user and a meaningful word about the fix/feature you're going to implement, ie: \"jesusprubio/fixstuff\"\n- Use [GitHub pull requests](https://help.github.com/articles/using-pull-requests).\n- Conventions:\n - We use [JSHint](http://jshint.com/) and [Crockford's Styleguide](http://javascript.crockford.com/code.html).\n - Please run `grunt lint` to be sure your code fits with them.\n\n### Debugging\n\nThe library includes the Node [debug](https://github.com/visionmedia/debug) module. In order to enable debugging:\n\nIn Node set the `DEBUG=rtcninja*` environment variable before running the application, or set it at the top of the script:\n\n```javascript\nprocess.env.DEBUG = 'rtcninja*';\n```\n\nIn the browser run `rtcninja.debug.enable('rtcninja*');` and reload the page. Note that the debugging settings are stored into the browser LocalStorage. To disable it run `rtcninja.debug.disable('rtcninja*');`.\n\n\n## Copyright & License\n\n* eFace2Face Inc.\n* [MIT](./LICENSE)", "readmeFilename": "README.md", "gitHead": "8fba936eb9d38e72dd9c2b79b9cc49ebebcef33a", "bugs": { "url": "https://github.com/eface2face/rtcninja.js/issues" }, "_id": "[email protected]", "scripts": {}, "_shasum": "4adcdf139d42809db6026138a6f2920fa21b820f", "_from": "rtcninja@>=0.6.1 <0.7.0" } },{}],39:[function(require,module,exports){ var grammar = module.exports = { v: [{ name: 'version', reg: /^(\d*)$/ }], o: [{ //o=- 20518 0 IN IP4 203.0.113.1 // NB: sessionId will be a String in most cases because it is huge name: 'origin', reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/, names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'], format: "%s %s %d %s IP%d %s" }], // default parsing of these only (though some of these feel outdated) s: [{ name: 'name' }], i: [{ name: 'description' }], u: [{ name: 'uri' }], e: [{ name: 'email' }], p: [{ name: 'phone' }], z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly.. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly //k: [{}], // outdated thing ignored t: [{ //t=0 0 name: 'timing', reg: /^(\d*) (\d*)/, names: ['start', 'stop'], format: "%d %d" }], c: [{ //c=IN IP4 10.47.197.26 name: 'connection', reg: /^IN IP(\d) (\S*)/, names: ['version', 'ip'], format: "IN IP%d %s" }], b: [{ //b=AS:4000 push: 'bandwidth', reg: /^(TIAS|AS|CT|RR|RS):(\d*)/, names: ['type', 'limit'], format: "%s:%s" }], m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31 // NB: special - pushes to session // TODO: rtp/fmtp should be filtered by the payloads found here? reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/, names: ['type', 'port', 'protocol', 'payloads'], format: "%s %d %s %s" }], a: [ { //a=rtpmap:110 opus/48000/2 push: 'rtp', reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/, names: ['payload', 'codec', 'rate', 'encoding'], format: function (o) { return (o.encoding) ? "rtpmap:%d %s/%s/%s": "rtpmap:%d %s/%s"; } }, { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000 push: 'fmtp', reg: /^fmtp:(\d*) (\S*)/, names: ['payload', 'config'], format: "fmtp:%d %s" }, { //a=control:streamid=0 name: 'control', reg: /^control:(.*)/, format: "control:%s" }, { //a=rtcp:65179 IN IP4 193.84.77.194 name: 'rtcp', reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/, names: ['port', 'netType', 'ipVer', 'address'], format: function (o) { return (o.address != null) ? "rtcp:%d %s IP%d %s": "rtcp:%d"; } }, { //a=rtcp-fb:98 trr-int 100 push: 'rtcpFbTrrInt', reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/, names: ['payload', 'value'], format: "rtcp-fb:%d trr-int %d" }, { //a=rtcp-fb:98 nack rpsi push: 'rtcpFb', reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/, names: ['payload', 'type', 'subtype'], format: function (o) { return (o.subtype != null) ? "rtcp-fb:%s %s %s": "rtcp-fb:%s %s"; } }, { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset //a=extmap:1/recvonly URI-gps-string push: 'ext', reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/, names: ['value', 'uri', 'config'], // value may include "/direction" suffix format: function (o) { return (o.config != null) ? "extmap:%s %s %s": "extmap:%s %s"; } }, { //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32 push: 'crypto', reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/, names: ['id', 'suite', 'config', 'sessionConfig'], format: function (o) { return (o.sessionConfig != null) ? "crypto:%d %s %s %s": "crypto:%d %s %s"; } }, { //a=setup:actpass name: 'setup', reg: /^setup:(\w*)/, format: "setup:%s" }, { //a=mid:1 name: 'mid', reg: /^mid:([^\s]*)/, format: "mid:%s" }, { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a name: 'msid', reg: /^msid:(.*)/, format: "msid:%s" }, { //a=ptime:20 name: 'ptime', reg: /^ptime:(\d*)/, format: "ptime:%d" }, { //a=maxptime:60 name: 'maxptime', reg: /^maxptime:(\d*)/, format: "maxptime:%d" }, { //a=sendrecv name: 'direction', reg: /^(sendrecv|recvonly|sendonly|inactive)/ }, { //a=ice-lite name: 'icelite', reg: /^(ice-lite)/ }, { //a=ice-ufrag:F7gI name: 'iceUfrag', reg: /^ice-ufrag:(\S*)/, format: "ice-ufrag:%s" }, { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g name: 'icePwd', reg: /^ice-pwd:(\S*)/, format: "ice-pwd:%s" }, { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33 name: 'fingerprint', reg: /^fingerprint:(\S*) (\S*)/, names: ['type', 'hash'], format: "fingerprint:%s %s" }, { //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0 //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0 push:'candidates', reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/, names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'], format: function (o) { var str = "candidate:%s %d %s %d %s %d typ %s"; // NB: candidate has two optional chunks, so %void middle one if it's missing str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v"; if (o.generation != null) { str += " generation %d"; } return str; } }, { //a=end-of-candidates (keep after the candidates line for readability) name: 'endOfCandidates', reg: /^(end-of-candidates)/ }, { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ... name: 'remoteCandidates', reg: /^remote-candidates:(.*)/, format: "remote-candidates:%s" }, { //a=ice-options:google-ice name: 'iceOptions', reg: /^ice-options:(\S*)/, format: "ice-options:%s" }, { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1 push: "ssrcs", reg: /^ssrc:(\d*) ([\w_]*):(.*)/, names: ['id', 'attribute', 'value'], format: "ssrc:%d %s:%s" }, { //a=ssrc-group:FEC 1 2 push: "ssrcGroups", reg: /^ssrc-group:(\w*) (.*)/, names: ['semantics', 'ssrcs'], format: "ssrc-group:%s %s" }, { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV name: "msidSemantic", reg: /^msid-semantic:\s?(\w*) (\S*)/, names: ['semantic', 'token'], format: "msid-semantic: %s %s" // space after ":" is not accidental }, { //a=group:BUNDLE audio video push: 'groups', reg: /^group:(\w*) (.*)/, names: ['type', 'mids'], format: "group:%s %s" }, { //a=rtcp-mux name: 'rtcpMux', reg: /^(rtcp-mux)/ }, { //a=rtcp-rsize name: 'rtcpRsize', reg: /^(rtcp-rsize)/ }, { // any a= that we don't understand is kepts verbatim on media.invalid push: 'invalid', names: ["value"] } ] }; // set sensible defaults to avoid polluting the grammar with boring details Object.keys(grammar).forEach(function (key) { var objs = grammar[key]; objs.forEach(function (obj) { if (!obj.reg) { obj.reg = /(.*)/; } if (!obj.format) { obj.format = "%s"; } }); }); },{}],40:[function(require,module,exports){ var parser = require('./parser'); var writer = require('./writer'); exports.write = writer; exports.parse = parser.parse; exports.parseFmtpConfig = parser.parseFmtpConfig; exports.parsePayloads = parser.parsePayloads; exports.parseRemoteCandidates = parser.parseRemoteCandidates; },{"./parser":41,"./writer":42}],41:[function(require,module,exports){ var toIntIfInt = function (v) { return String(Number(v)) === v ? Number(v) : v; }; var attachProperties = function (match, location, names, rawName) { if (rawName && !names) { location[rawName] = toIntIfInt(match[1]); } else { for (var i = 0; i < names.length; i += 1) { if (match[i+1] != null) { location[names[i]] = toIntIfInt(match[i+1]); } } } }; var parseReg = function (obj, location, content) { var needsBlank = obj.name && obj.names; if (obj.push && !location[obj.push]) { location[obj.push] = []; } else if (needsBlank && !location[obj.name]) { location[obj.name] = {}; } var keyLocation = obj.push ? {} : // blank object that will be pushed needsBlank ? location[obj.name] : location; // otherwise, named location or root attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name); if (obj.push) { location[obj.push].push(keyLocation); } }; var grammar = require('./grammar'); var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/); exports.parse = function (sdp) { var session = {} , media = [] , location = session; // points at where properties go under (one of the above) // parse lines we understand sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) { var type = l[0]; var content = l.slice(2); if (type === 'm') { media.push({rtp: [], fmtp: []}); location = media[media.length-1]; // point at latest media line } for (var j = 0; j < (grammar[type] || []).length; j += 1) { var obj = grammar[type][j]; if (obj.reg.test(content)) { return parseReg(obj, location, content); } } }); session.media = media; // link it up return session; }; var fmtpReducer = function (acc, expr) { var s = expr.split('='); if (s.length === 2) { acc[s[0]] = toIntIfInt(s[1]); } return acc; }; exports.parseFmtpConfig = function (str) { return str.split(';').reduce(fmtpReducer, {}); }; exports.parsePayloads = function (str) { return str.split(' ').map(Number); }; exports.parseRemoteCandidates = function (str) { var candidates = []; var parts = str.split(' ').map(toIntIfInt); for (var i = 0; i < parts.length; i += 3) { candidates.push({ component: parts[i], ip: parts[i + 1], port: parts[i + 2] }); } return candidates; }; },{"./grammar":39}],42:[function(require,module,exports){ var grammar = require('./grammar'); // customized util.format - discards excess arguments and can void middle ones var formatRegExp = /%[sdv%]/g; var format = function (formatStr) { var i = 1; var args = arguments; var len = args.length; return formatStr.replace(formatRegExp, function (x) { if (i >= len) { return x; // missing argument } var arg = args[i]; i += 1; switch (x) { case '%%': return '%'; case '%s': return String(arg); case '%d': return Number(arg); case '%v': return ''; } }); // NB: we discard excess arguments - they are typically undefined from makeLine }; var makeLine = function (type, obj, location) { var str = obj.format instanceof Function ? (obj.format(obj.push ? location : location[obj.name])) : obj.format; var args = [type + '=' + str]; if (obj.names) { for (var i = 0; i < obj.names.length; i += 1) { var n = obj.names[i]; if (obj.name) { args.push(location[obj.name][n]); } else { // for mLine and push attributes args.push(location[obj.names[i]]); } } } else { args.push(location[obj.name]); } return format.apply(null, args); }; // RFC specified order // TODO: extend this with all the rest var defaultOuterOrder = [ 'v', 'o', 's', 'i', 'u', 'e', 'p', 'c', 'b', 't', 'r', 'z', 'a' ]; var defaultInnerOrder = ['i', 'c', 'b', 'a']; module.exports = function (session, opts) { opts = opts || {}; // ensure certain properties exist if (session.version == null) { session.version = 0; // "v=0" must be there (only defined version atm) } if (session.name == null) { session.name = " "; // "s= " must be there if no meaningful name set } session.media.forEach(function (mLine) { if (mLine.payloads == null) { mLine.payloads = ""; } }); var outerOrder = opts.outerOrder || defaultOuterOrder; var innerOrder = opts.innerOrder || defaultInnerOrder; var sdp = []; // loop through outerOrder for matching properties on session outerOrder.forEach(function (type) { grammar[type].forEach(function (obj) { if (obj.name in session && session[obj.name] != null) { sdp.push(makeLine(type, obj, session)); } else if (obj.push in session && session[obj.push] != null) { session[obj.push].forEach(function (el) { sdp.push(makeLine(type, obj, el)); }); } }); }); // then for each media line, follow the innerOrder session.media.forEach(function (mLine) { sdp.push(makeLine('m', grammar.m[0], mLine)); innerOrder.forEach(function (type) { grammar[type].forEach(function (obj) { if (obj.name in mLine && mLine[obj.name] != null) { sdp.push(makeLine(type, obj, mLine)); } else if (obj.push in mLine && mLine[obj.push] != null) { mLine[obj.push].forEach(function (el) { sdp.push(makeLine(type, obj, el)); }); } }); }); }); return sdp.join('\r\n') + '\r\n'; }; },{"./grammar":39}],43:[function(require,module,exports){ var _global = (function() { return this; })(); var nativeWebSocket = _global.WebSocket || _global.MozWebSocket; /** * Expose a W3C WebSocket class with just one or two arguments. */ function W3CWebSocket(uri, protocols) { var native_instance; if (protocols) { native_instance = new nativeWebSocket(uri, protocols); } else { native_instance = new nativeWebSocket(uri); } /** * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket * class). Since it is an Object it will be returned as it is when creating an * instance of W3CWebSocket via 'new W3CWebSocket()'. * * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2 */ return native_instance; } /** * Module exports. */ module.exports = { 'w3cwebsocket' : nativeWebSocket ? W3CWebSocket : null, 'version' : require('./version') }; },{"./version":44}],44:[function(require,module,exports){ module.exports = require('../package.json').version; },{"../package.json":45}],45:[function(require,module,exports){ module.exports={ "name": "websocket", "description": "Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.", "keywords": [ "websocket", "websockets", "socket", "networking", "comet", "push", "RFC-6455", "realtime", "server", "client" ], "author": { "name": "Brian McKelvey", "email": "[email protected]", "url": "https://www.worlize.com/" }, "version": "1.0.19", "repository": { "type": "git", "url": "git+https://github.com/theturtle32/WebSocket-Node.git" }, "homepage": "https://github.com/theturtle32/WebSocket-Node", "engines": { "node": ">=0.8.0" }, "dependencies": { "debug": "~2.1.0", "nan": "1.8.x", "typedarray-to-buffer": "~3.0.0" }, "devDependencies": { "buffer-equal": "0.0.1", "faucet": "0.0.1", "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", "gulp-jshint": "^1.9.0", "jshint-stylish": "^1.0.0", "tape": "^3.0.0" }, "config": { "verbose": false }, "scripts": { "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", "test": "faucet test/unit", "gulp": "gulp" }, "main": "index", "directories": { "lib": "./lib" }, "browser": "lib/browser.js", "license": "Apache-2.0", "gitHead": "da3bd5b04e9442c84881b2e9c13432cdbbae1f16", "bugs": { "url": "https://github.com/theturtle32/WebSocket-Node/issues" }, "_id": "[email protected]", "_shasum": "e62dbf1a3c5e0767425db7187cfa38f921dfb42c", "_from": "websocket@>=1.0.19 <2.0.0", "_npmVersion": "2.10.1", "_nodeVersion": "0.12.4", "_npmUser": { "name": "theturtle32", "email": "[email protected]" }, "maintainers": [ { "name": "theturtle32", "email": "[email protected]" } ], "dist": { "shasum": "e62dbf1a3c5e0767425db7187cfa38f921dfb42c", "tarball": "http://registry.npmjs.org/websocket/-/websocket-1.0.19.tgz" }, "_resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.19.tgz" } },{}],46:[function(require,module,exports){ module.exports={ "name": "jssip", "title": "JsSIP", "description": "the Javascript SIP library", "version": "0.6.31", "homepage": "http://jssip.net", "author": "José Luis Millán <[email protected]> (https://github.com/jmillan)", "contributors": [ "Iñaki Baz Castillo <[email protected]> (https://github.com/ibc)", "Saúl Ibarra Corretgé <[email protected]> (https://github.com/saghul)" ], "main": "lib/JsSIP.js", "keywords": [ "sip", "websocket", "webrtc", "node", "browser", "library" ], "license": "MIT", "repository": { "type": "git", "url": "https://github.com/versatica/JsSIP.git" }, "bugs": { "url": "https://github.com/versatica/JsSIP/issues" }, "dependencies": { "debug": "^2.2.0", "rtcninja": "^0.6.1", "sdp-transform": "~1.4.0", "websocket": "^1.0.19" }, "devDependencies": { "browserify": "^10.2.3", "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", "gulp-expect-file": "0.0.7", "gulp-filelog": "^0.4.1", "gulp-header": "^1.2.2", "gulp-jshint": "^1.11.0", "gulp-nodeunit-runner": "^0.2.2", "gulp-rename": "^1.2.2", "gulp-uglify": "^1.2.0", "gulp-util": "^3.0.5", "jshint-stylish": "^1.0.1", "pegjs": "0.7.0", "vinyl-source-stream": "^1.1.0" }, "scripts": { "test": "gulp test" } } },{}]},{},[7])(7) });
src/components/ShipmentDetailsContainer/ShipmentDetailsComponent.js
alexhawkins/trackingWidget
import React from 'react'; import Item from './ItemComponent'; import 'styles//ShipmentDetails.scss'; class ShipmentDetailsComponent extends React.Component { constructor(props) { super(props); } getItems(){ let packages = this.props.shipment.packing.packages; return packages.map((pkg) =>{ return pkg.package_items.map((item, index) => { return ( <li key={index} className="shipmentdetails-item"> <Item item={item} /> </li> ); }); }); } render() { let shipment = this.props.shipment; let delivery = shipment.delivery; let items = this.getItems(); let carrier = shipment.carrier_name.toLowerCase().split(' ').join('_') + '.png'; let imageUrl = 'https://s3-us-west-1.amazonaws.com/shiphawk/src/images/' + carrier; return ( <div className="shipmentdetails-component"> <div className="shipmentdetails-image"> <img src={imageUrl} alt={carrier}/> </div> <h4> Carrier: <span className="shipmentdetails-carrier"> {shipment.carrier_name} </span> </h4> <div> <h4> Tracking: <span href={shipment.tracking_url || '#'} className="shipmentdetails-tracking-number"> {shipment.tracking_number} </span> </h4> </div> <div> <h4> Destination:&nbsp; <span className="shipmentdetails-delivery-address"> {delivery.city}, &nbsp; {delivery.state} &nbsp; {delivery.zip} </span> </h4> </div> <div className="shipmentdetails-items"> <h4>Items: </h4> <ul> {items} </ul> </div> </div> ); } } ShipmentDetailsComponent.displayName = 'ShipmentDetailsComponent'; ShipmentDetailsComponent.propTypes = { shipment: React.PropTypes.object.isRequired }; // Uncomment properties you need // ShipmentDetailsComponent.propTypes = {}; // ShipmentDetailsComponent.defaultProps = {}; export default ShipmentDetailsComponent;
public/controllers/management/components/management/configuration/osquery/osquery.js
wazuh/wazuh-kibana-app
/* * Wazuh app - React component for show configuration of Osquery. * Copyright (C) 2015-2022 Wazuh, Inc. * * 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 2 of the License, or * (at your option) any later version. * * Find more information about this on the LICENSE file. */ import React, { Component, Fragment } from 'react'; import { EuiBasicTable } from '@elastic/eui'; import WzConfigurationSettingsTabSelector from '../util-components/configuration-settings-tab-selector'; import withWzConfig from '../util-hocs/wz-config'; import WzConfigurationSettingsGroup from '../util-components/configuration-settings-group'; import WzNoConfig from '../util-components/no-config'; import WzConfigurationSettingsHeader from '../util-components/configuration-settings-header'; import { isString, isArray, renderValueNoThenEnabled } from '../utils/utils'; import { wodleBuilder } from '../utils/builders'; const mainSettings = [ { field: 'disabled', label: 'Osquery integration status', render: renderValueNoThenEnabled }, { field: 'run_daemon', label: 'Auto-run the Osquery daemon' }, { field: 'bin_path', label: 'Path to the Osquery executable' }, { field: 'log_path', label: 'Path to the Osquery results log file' }, { field: 'config_path', label: 'Path to the Osquery configuration file' }, { field: 'add_labels', label: 'Use defined labels as decorators' } ]; const helpLinks = [ { text: 'Osquery module documentation', href: 'https://documentation.wazuh.com/current/user-manual/capabilities/osquery.html' }, { text: 'Osquery module reference', href: 'https://documentation.wazuh.com/current/user-manual/reference/ossec-conf/wodle-osquery.html' } ]; const columns = [ { field: 'name', name: 'Name' }, { field: 'path', name: 'Path' } ]; class WzConfigurationOsquery extends Component { constructor(props) { super(props); this.wodleConfig = wodleBuilder(this.props.currentConfig, 'osquery'); } componentDidMount() { this.props.updateBadge(this.badgeEnabled()); } badgeEnabled() { return ( this.wodleConfig && this.wodleConfig.osquery && this.wodleConfig.osquery.disabled === 'no' ); } render() { const { currentConfig } = this.props; return ( <Fragment> {currentConfig['wmodules-wmodules'] && isString(currentConfig['wmodules-wmodules']) && ( <WzNoConfig error={currentConfig['wmodules-wmodules']} help={helpLinks} /> )} {currentConfig && !this.wodleConfig.osquery && !isString(currentConfig['wmodules-wmodules']) && ( <WzNoConfig error="not-present" help={helpLinks} /> )} {currentConfig && this.wodleConfig && this.wodleConfig.osquery && ( <WzConfigurationSettingsTabSelector title="Main settings" description="General Osquery integration settings" currentConfig={this.wodleConfig} minusHeight={this.props.agent.id === '000' ? 260 : 355} helpLinks={helpLinks} > <WzConfigurationSettingsGroup config={this.wodleConfig.osquery} items={mainSettings} ks /> {this.wodleConfig.osquery.packs && isArray(this.wodleConfig.osquery.packs) && this.wodleConfig.osquery.packs.length && ( <Fragment> <WzConfigurationSettingsHeader title="Osquery packs" description="A pack contains multiple queries to quickly retrieve system information" /> <EuiBasicTable items={this.wodleConfig.osquery.packs} columns={columns} /> </Fragment> )} </WzConfigurationSettingsTabSelector> )} </Fragment> ); } } const sections = [{ component: 'wmodules', configuration: 'wmodules' }]; WzConfigurationOsquery.propTypes = { // currentConfig: PropTypes.object.isRequired }; export default withWzConfig(sections)(WzConfigurationOsquery);
test/specs/elements/Flag/Flag-test.js
koenvg/Semantic-UI-React
import React from 'react' import Flag from 'src/elements/Flag/Flag' import * as common from 'test/specs/commonTests' const requiredProps = { name: 'us' } describe('Flag', () => { common.isConformant(Flag, { requiredProps }) common.implementsCreateMethod(Flag) common.propValueOnlyToClassName(Flag, 'name', [], { requiredProps }) it('renders an <i /> element', () => { shallow(<Flag {...requiredProps} />) .should.have.tagName('i') }) })
src/components/fleet/vehicles/VehicleUpsert.js
fusionalliance/autorenter-react
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Field, reduxForm, formValueSelector } from 'redux-form'; import { Col, Form, FormGroup } from 'react-bootstrap'; import inputField from '../../common/form/inputField'; import dropdownField from '../../common/form/dropdownField'; import dropZone from '../../common/form/dropZone'; import validate from './vehicleFieldValidate'; let VehicleUpsert = ({ action, colors, handleSubmit, handleCancel, lookupModels, lookupYears, lookupColors, makes, models, pristine, submitting, years }) => { function cancel (e) { e.preventDefault(); handleCancel(); } return ( <div> <Form onSubmit={handleSubmit} horizontal> <legend>{action} Vehicle</legend> <Col md={8}> <FormGroup controlId="formInputVin"> <Col sm={2}> VIN </Col> <Col sm={10}> <Field name="vin" component={inputField} /> </Col> </FormGroup> <FormGroup controlId="formInputMake"> <Col sm={2}> Make </Col> <Col sm={10}> <Field name="makeId" options={makes} change={lookupModels} component={dropdownField} /> </Col> </FormGroup> <FormGroup controlId="formInputModel"> <Col sm={2}> Model </Col> <Col sm={10}> <Field name="modelId" options={models} change={lookupYears} component={dropdownField} /> </Col> </FormGroup> <FormGroup controlId="formInputYear"> <Col sm={2}> Year </Col> <Col sm={10}> <Field name="year" options={years} change={lookupColors} component={dropdownField} /> </Col> </FormGroup> <FormGroup controlId="formInputMiles"> <Col sm={2}> Miles </Col> <Col sm={10}> <Field name="miles" component={inputField} /> </Col> </FormGroup> <FormGroup controlId="formInputColor"> <Col sm={2}> Color </Col> <Col sm={10}> <Field name="color" options={colors} component={dropdownField} /> </Col> </FormGroup> <FormGroup controlId="formInputRent"> <Col sm={2}> Rent To Own? </Col> <Col sm={10} style={{ display: 'flex' }}> <Field name="isRentToOwn" id="isRentToOwn" component="input" type="checkbox" /> </Col> </FormGroup> </Col> <Col md={4}> <Field name="image" component={dropZone} /> </Col> <FormGroup> <Col xsOffset={8} xs={2}> <button className="btn btn-default pull-right" disabled={submitting} onClick={cancel}> Cancel </button> </Col> <Col xs={2}> <button type="submit" className="btn btn-primary pull-right" disabled={pristine || submitting}> Submit </button> </Col> </FormGroup> </Form> </div> ); }; VehicleUpsert.propTypes = { handleSubmit: PropTypes.func, handleCancel: PropTypes.func, lookupModels: PropTypes.func, lookupYears: PropTypes.func, lookupColors: PropTypes.func, submitting: PropTypes.bool, pristine: PropTypes.bool, vehicle: PropTypes.object, action: PropTypes.string, makes: PropTypes.array, models: PropTypes.array, years: PropTypes.array, colors: PropTypes.array, lookupData: PropTypes.shape({ makes: PropTypes.array, models: PropTypes.array }) }; VehicleUpsert = reduxForm({ form: 'UpsertVehicle', enableReinitialize: true, validate })(VehicleUpsert); const selector = formValueSelector('UpsertVehicle'); VehicleUpsert = connect((state, props) => { const colorValue = selector(state, 'color'); const imageValue = selector(state, 'image'); const makeValue = selector(state, 'make'); const milesValue = selector(state, 'miles'); const modelValue = selector(state, 'model'); const vinValue = selector(state, 'vin'); const yearValue = selector(state, 'year'); const { vehicle } = props; const initialValues = vehicle || {}; return { initialValues, colorValue, imageValue, makeValue, milesValue, modelValue, vinValue, yearValue }; })(VehicleUpsert); export default VehicleUpsert;
js/components/MainSectionPlaylist.js
ChrisMLee/relay-mongoose-plair
import Relay from 'react-relay'; import React from 'react'; import MainSectionPlaylistSong from './MainSectionPlaylistSong'; class MainSectionPlaylist extends React.Component { constructor(props){ super(props); console.log('MainSectionPlaylist', props); } componentWillReceiveProps(nextProps){ console.log('MainSectionPlaylist received nextProps', nextProps); } render(){ let {playlist, actions} = this.props; let songs = playlist.songs.map((song) => { return <MainSectionPlaylistSong key={song.__dataID__} playlist={playlist} song={song} actions={actions}/>; }); return ( <div> <p>{playlist.title}</p> <ul> {songs} </ul> </div> ); } } // <div id="todo-list"> // { // this.props.todos.map( (todo, index) => { // return ( // <div key={index}> // <span>{todo}</span> // <button data-id={index} onClick={this.handleDelete}> // X // </button> // <button data-id={index} onClick={this.handleEdit}> // Edit // </button> // </div> // ); // }) // } // </div> // TODO // songs - some component get fragment songs // song - ^ get the fragment off of this - click and it plays the track export default Relay.createContainer(MainSectionPlaylist, { fragments: { playlist: () => Relay.QL` fragment on Playlist { title id type songs{ id title youtubeLink ${MainSectionPlaylistSong.getFragment('song')} } } ` } });
public/js/report.js
IsmailM/sequenceserver
import _ from 'underscore'; import React from 'react'; import d3 from 'd3'; import './graphicaloverview'; import './kablammo'; import './sequence'; /** * Pretty formats number */ var Utils = { /** * Prettifies numbers and arrays. */ prettify: function (data){ if (this.isTuple(data)) { return this.prettify_tuple(data); } if (this.isFloat(data)) { return this.prettify_float(data); } return data }, /** * Formats float as "a.bc" or "a x b^c". The latter if float is in * scientific notation. Former otherwise. */ prettify_float: function (data) { var matches = data.toString().split("e"); var base = matches[0]; var power = matches[1]; if (power) { var s = parseFloat(base).toFixed(2); var element = <span>{s} &times; 10<sup>{power}</sup></span>; return element; } else { if(!(base % 1==0)) return parseFloat(base).toFixed(2); else return base; } }, // Formats an array of two elements as "first (last)". prettify_tuple: function (tuple) { return (tuple[0] + " (" + tuple[tuple.length - 1] + ")"); }, // Checks if data is an array. isTuple: function (data) { return (Array.isArray(data) && data.length == 2) }, // Checks if data if float. isFloat: function (data) { return (typeof(data) == 'number' || (typeof(data) == 'string' && data.match(/(\d*\.\d*)e?([+-]\d+)?/))) }, /** * Render URL for sequence-viewer. */ a: function (link , hitlength) { if (link.title && link.url) { return ( <a href={link.url} className={link.class} target='_blank'> {link.icon && <i className={"fa " + link.icon}></i>} {" " + link.title + " "} </a> ); } }, /** * Returns fraction as percentage */ inPercentage: function (num , den) { return (num * 100.0 / den).toFixed(2); }, /** * Returns fractional representation as String. */ inFraction: function (num , den) { return num + "/" + den; }, /** * Returns given Float as String formatted to two decimal places. */ inTwoDecimal: function (num) { return parseFloat(num).toFixed(2) }, /** * Formats the given number as "1e-3" if the number is less than 1 or * greater than 10. */ inScientificOrTwodecimal: function (num) { if(num >= 1 && num < 10) { return this.inTwoDecimal(num) } return num.toExponential(2); }, }; /** * Renders Kablammo visualization * * JSON received from server side is modified as JSON expected by kablammo's * graph.js. All the relevant information including a SVG container where * visual needs to be rendered, is delegated to graph.js. graph.js renders * kablammo visualization and has all event handlers for events performed on * the visual. * * Event handlers related to downloading and viewing of alignments and images * have been extracted from grapher.js and interface.js and directly included * here. */ var Kablammo = (function () { var SEQ_TYPES = { blastn: { query_seq_type: 'nucleic_acid', subject_seq_type: 'nucleic_acid' }, blastp: { query_seq_type: 'amino_acid', subject_seq_type: 'amino_acid' }, blastx: { query_seq_type: 'nucleic_acid', subject_seq_type: 'amino_acid' }, tblastx: { query_seq_type: 'nucleic_acid', subject_seq_type: 'nucleic_acid' }, tblastn: { query_seq_type: 'amino_acid', subject_seq_type: 'nucleic_acid' } }; /** * Mock Kablammo's grapher.js. */ var grapher = { use_complement_coords: false, /** * Coverts colour from RGBA to RGB. * * Taken from grapher.js. */ _rgba_to_rgb: function (rgba, matte_rgb) { // Algorithm taken from http://stackoverflow.com/a/2049362/1691611. var normalize = function (colour) { return colour.map(function (channel) { return channel / 255; }); }; var denormalize = function (colour) { return colour.map(function (channel) { return Math.round(Math.min(255, channel * 255)); });; }; var norm = normalize(rgba.slice(0, 3)); matte_rgb = normalize(matte_rgb); var alpha = rgba[3] / 255; var rgb = [ (alpha * norm[0]) + (1 - alpha) * matte_rgb[0], (alpha * norm[1]) + (1 - alpha) * matte_rgb[1], (alpha * norm[2]) + (1 - alpha) * matte_rgb[2], ]; return denormalize(rgb); }, /** * Determines colour of a hsp based on normalized bit-score. * * Taken from grapher.js */ determine_colour: function (level) { var graph_colour = { r: 30, g: 139, b: 195 }; var matte_colour = { r: 255, g: 255, b: 255 }; var min_opacity = 0.3; var opacity = ((1 - min_opacity) * level) + min_opacity; var rgb = this._rgba_to_rgb([ graph_colour.r, graph_colour.g, graph_colour.b, 255 * opacity ], [ matte_colour.r, matte_colour.g, matte_colour.b, ]); return 'rgb(' + rgb.join(',') + ')'; }, }; return React.createClass({ mixins: [Utils], // Internal helpers. // /** * Adapter to convert server-side JSON into a form expected by Kablammo. * This is done by changing keys of JSON. */ toKablammo: function (hsps, query) { var maxBitScore = query.hits[0].hsps[0].bit_score; var hspKeyMap = { 'qstart': 'query_start', 'qend': 'query_end', 'qframe': 'query_frame' , 'sstart': 'subject_start', 'send': 'subject_end', 'sframe': 'subject_frame', 'length': 'alignment_length', 'qseq': 'query_seq', 'sseq': 'subject_seq', 'midline': 'midline_seq' }; return _.map(hsps, function (hsp) { var _hsp = {}; $.each(hsp, function (key, value) { key = hspKeyMap[key] || key; _hsp[key] = value; _hsp.normalized_bit_score = hsp.bit_score / maxBitScore; }) return _hsp; }); }, /** * Returns jQuery wrapped element that should hold Kablammo's svg. */ svgContainer: function () { return $(React.findDOMNode(this.refs.svgContainer)); }, isHspSelected: function (index , selected) { return index in selected }, /** * Event-handler for viewing alignments. * Calls relevant method on AlignmentViewer defined in alignment_viewer.js. */ showAlignment: function (hsps, query_seq_type, query_def, query_id, subject_seq_type, subject_def, subject_id) { event.preventDefault(); aln_viewer = new AlignmentViewer(); aln_viewer.view_alignments(hsps, query_seq_type, query_def, query_id, subject_seq_type, subject_def, subject_id); }, // Life-cycle methods // render: function () { return ( <div ref="svgContainer"> </div> ); }, /** * Invokes Graph method defined in graph.js to render kablammo visualization. * Also defines event handler for hovering on HSP polygon. */ componentDidMount: function (event) { var hsps = this.toKablammo(this.props.hit.hsps, this.props.query); var svgContainer = this.svgContainer(); Graph.prototype._canvas_width = svgContainer.width(); this._graph = new Graph( grapher, SEQ_TYPES[this.props.algorithm], this.props.query.id + ' ' + this.props.query.title, this.props.query.id, this.props.hit.id + ' ' + this.props.hit.title, this.props.hit.id, this.props.query.length, this.props.hit.length, hsps, svgContainer ); // Disable hover handlers and show alignment on selecting hsp. var selected = {} var polygons = d3.select(svgContainer[0]).selectAll('polygon'); polygons .on('mouseenter', null) .on('mouseleave', null) .on('click', _.bind(function (clicked_hsp , clicked_index) { if(!this.isHspSelected(clicked_index , selected)) { selected[clicked_index] = hsps[clicked_index]; var polygon = polygons[0][clicked_index]; polygon.parentNode.appendChild(polygon); d3.select(polygon).classed('selected', true); $("#Alignment_Query_" + this.props.query.number + "_hit_" + this.props.hit.number + "_" + (clicked_index + 1)).show(); } else { delete selected[clicked_index]; var polygon = polygons[0][clicked_index]; var firstChild = polygon.parentNode.firstChild; if (firstChild) { polygon.parentNode.insertBefore(polygon, firstChild); } d3.select(polygon).classed('selected', false); $("#Alignment_Query_" + this.props.query.number + "_hit_" + this.props.hit.number + "_" + (clicked_index + 1)).hide(); } }, this)) }, }); })(); /** * Component for sequence-viewer links. */ var SequenceViewer = (function () { var Viewer = React.createClass({ /** * The CSS class name that will be assigned to the widget container. ID * assigned to the widget container is derived from the same. */ widgetClass: 'biojs-vis-sequence', // Lifecycle methods. // render: function () { this.widgetID = this.widgetClass + '-' + (new Date().getUTCMilliseconds()); return ( <div className="fastan"> <div className="page-header"> <h4> {this.props.sequence.id} <small> &nbsp; {this.props.sequence.title} </small> </h4> </div> <div className="page-content"> <div className={this.widgetClass} id={this.widgetID}> </div> </div> </div> ); }, componentDidMount: function () { // attach BioJS sequence viewer var widget = new Sequence({ sequence: this.props.sequence.value, target: this.widgetID, format: 'PRIDE', columns: { size: 40, spacedEach: 5 }, formatOptions: { title: false, footer: false } }); widget.hideFormatSelector(); } }); return React.createClass({ // Kind of public API. // /** * Shows sequence viewer. */ show: function () { this.modal().modal('show'); }, /** * Hides sequence viewer. */ hide: function () { this.modal().modal('hide'); }, // Internal helpers. // modal: function () { return $('#sequence-viewer'); }, spinner: function () { return $(React.findDOMNode(this.refs.spinner)); }, renderErrors: function () { return ( _.map(this.state.error_msgs, _.bind(function (error_msg) { return ( <div className="fastan"> <div className="page-header"> <h4> {error_msg[0]} </h4> </div> <div className="page-content"> <pre className="pre-reset"> {error_msg[1]} </pre> </div> </div> ); }, this)) ); }, renderSequences: function () { return ( _.map(this.state.sequences, _.bind(function (sequence) { return (<Viewer sequence={sequence}/>); }, this)) ); }, // Lifecycle methods. // getInitialState: function () { return { error_msgs: [], sequences: [] }; }, render: function () { return ( <div className="modal-dialog"> <div className="modal-content"> <div className="modal-header"> <h3>View sequence</h3> </div> <div className="modal-body"> { this.renderErrors() } { this.renderSequences() } </div> <div className="spinner" ref="spinner"> <i className="fa fa-spinner fa-3x fa-spin"></i> </div> </div> </div> ); }, componentDidMount: function () { var $anchor = $(event.target).closest('a'); if (!$anchor.is(':disabled')) { this.show(); var url = $anchor.attr('href'); $.getJSON(url) .done(_.bind(function (response) { this.setState({ error_msgs: response.error_msgs, sequences: response.sequences }) this.spinner().hide(); }, this)) .fail(function (jqXHR, status, error) { SequenceServer.showErrorModal(jqXHR, function () { this.hide(); }); }); } }, }); })(); /** * Component for each hit. */ var Hit = React.createClass({ mixins: [Utils], // Internal helpers. // /** * Returns id that will be used for the DOM node corresponding to the hit. */ domID: function () { return "Query_" + this.props.query.number + "_hit_" + this.props.hit.number; }, /** * Return prettified stats for the given hsp and based on the BLAST * algorithm. */ getStats: function (hsp) { var stats = { 'Score': [ this.inTwoDecimal(hsp.bit_score), hsp.score ], 'E value': this.inScientificOrTwodecimal(hsp.evalue), 'Identities': [ this.inFraction(hsp.identity, hsp.length), this.inPercentage(hsp.identity, hsp.length) ], 'Gaps': [ this.inFraction(hsp.gaps, hsp.length), this.inPercentage(hsp.gaps, hsp.length) ], 'Coverage': hsp.qcovhsp }; switch (this.props.algorithm) { case 'tblastx': _.extend(stats, { 'Frame': in_fraction(hsp.qframe, hsp.sframe) }); // fall-through case 'blastp': _.extend(stats, { 'Positives': [ this.inFraction(hsp.positives, hsp.length), this.inPercentage(hsp.positives, hsp.length) ] }); break; case 'blastn': _.extend(stats, { 'Strand': (hsp.qframe > 0 ? '+' : '-') + "/" + (hsp.sframe > 0 ? '+' : '-') }); break; case 'blastx': _.extend(stats, { 'Query Frame': hsp.qframe }); break; case 'tblastn': _.extend(stats, { 'Hit Frame': hsp.sframe }); break; } return stats; }, // Life cycle methods // /** * Handles click event for exporting alignments. * Disables Sequenece viewer if hit length is greater than 10,000. */ componentDidMount: function () { //Disable sequence-viewer link if hit length is greater than 10,000 if (this.props.hit.length > 10000) { $("#" + this.domID()).find(".view-sequence").addClass('disabled'); } // Event-handler for exporting alignments. // Calls relevant method on AlignmentExporter defined in alignment_exporter.js. $("#" + this.domID()).find('.export-alignment').on('click',_.bind(function () { event.preventDefault(); var hsps = _.map(this.props.hit.hsps, function (hsp) { hsp['query_seq'] = hsp.qseq; hsp['subject_seq'] = hsp.sseq; return hsp; }) var aln_exporter = new AlignmentExporter(); aln_exporter.export_alignments(hsps, this.props.query.id + this.props.query.title, this.props.query.id, this.props.hit.id + this.props.hit.title, this.props.hit.id); }, this)) }, render: function () { // NOTE: // Adding 'subject' class to hit container is important for // Kablammo's ImageExporter to work. return ( <div className="hitn subject" id={this.domID()} data-hit-def={this.props.hit.id} data-hit-evalue={this.props.hit.evalue} data-hit-len={this.props.hit.length}> <div className="page-header"> <h4 data-toggle="collapse" data-target={ "#Query_" + this.props.query.number + "_hit_" + this.props.hit.number + "_alignment"} > <i className="fa fa-chevron-down"></i> &nbsp; <span> {this.props.hit.id} &nbsp; <small> {this.props.hit.title} </small> </span> </h4> <span className="label label-reset pos-label" title={"Query " + this.props.query.number + ". Hit " + this.props.hit.number + " of " + this.props.query.hits.length + "."} data-toggle="tooltip"> {this.props.hit.number + "/" + this.props.query.hits.length} </span> </div> <div className="page-content collapse in" id={"Query_" + this.props.query.number + "_hit_" + this.props.hit.number + "_alignment"}> <div className="hit-links"> <label> <input type="checkbox" id={this.domID() + "_checkbox"} value={this.props.hit.id} data-target={"#Query_" + this.props.query.number + "_hit_" + this.props.hit.number} onChange= { _.bind(function () { this.props.selectHit(this.domID() + "_checkbox"); }, this) } /> <span>{" Select "}</span> { _.map(this.props.hit.links, _.bind(function (link) { return [<span> | </span>, this.a(link)]; }, this)) } </label> </div> <br/> <Kablammo query={this.props.query} hit={this.props.hit} algorithm={this.props.algorithm}/> <table className="table hsps"> <tbody> { _.map (this.props.hit.hsps, _.bind( function (hsp) { stats_returned = this.getStats(hsp); return ( <tr id={"Alignment_Query_" + this.props.query.number + "_hit_" + this.props.hit.number + "_" + hsp.number} style={{display:'none'}}> <td> {hsp.number + "."} </td> <td style={{width: "100%"}}> <div className="hsp" id={"Query_" + this.props.query.number + "_hit_" + this.props.hit.number + "_" + hsp.number} data-hsp-evalue={hsp.evalue} data-hsp-start={hsp.qstart} data-hsp-end={hsp.qend} data-hsp-frame={hsp.sframe}> <table className="table table-condensed hsp-stats"> <thead> { _.map(stats_returned, function (value , key) { return(<th>{key}</th>); }) } </thead> <tbody> <tr> { _.map(stats_returned, _.bind(function (value , key) { return(<th>{this.prettify(value)}</th>); }, this)) } </tr> </tbody> </table> <div className="alignment">{hsp.pp}</div> </div> </td> </tr> ) }, this)) } </tbody> </table> </div> </div> ); } }); /** * Renders summary of all hits per query in a tabular form. */ var HitsTable = React.createClass({ mixins: [Utils], render: function () { var count = 0, hasName = _.every(this.props.query.hits, function(hit) { return hit.sciname !== "-"; }); return( <table className="table table-hover table-condensed tabular-view"> <thead> <th className="text-left"> Number </th> <th>Sequences producing significant alignments</th> {hasName && <th className="text-left"> Scientific name </th>} <th className="text-right"> Total score </th> <th className="text-right"> E value </th> <th className="text-right"> Coverage </th> <th className="text-right"> Length </th> </thead> <tbody> { _.map(this.props.query.hits, _.bind(function (hit) { return ( <tr> <td className="text-left">{hit.number + "."}</td> <td> <a href={"#Query_" + this.props.query.number + "_hit_" + hit.number}> {hit.id} </a> </td> {hasName && <td className="text-left">{this.prettify(hit.sciname)}</td>} <td className="text-right">{this.prettify(hit.score)}</td> <td className="text-right">{this.prettify(hit.evalue)}</td> <td className="text-right">{this.prettify(hit.qcovs)}</td> <td className="text-right">{this.prettify(hit.length)}</td> </tr> ) }, this)) } </tbody> </table> ); } }); /** * Component for graphical-overview per query. */ var GraphicalOverview = React.createClass({ // Internal helpers. // /** * Converts data into form accepted by graphical overview. */ toGraph : function (query_hits,number) { var hits = []; query_hits.map(function (hit) { var _hsps = []; var hsps = hit.hsps; _.each(hsps, function (hsp) { var _hsp = {}; _hsp.hspEvalue = hsp.evalue; _hsp.hspStart = hsp.qstart; _hsp.hspEnd = hsp.qend; _hsp.hspFrame = hsp.sframe; _hsp.hspId = "Query_"+number+"_hit_"+hit.number+"_hsp_"+hsp.number; _hsps.push(_hsp); }); _hsps.hitId = hit.id; _hsps.hitDef = "Query_"+number+"_hit_"+hit.number; _hsps.hitEvalue = hit.evalue; hits.push(_hsps); }); return hits; }, /** * Returns jQuery wrapped element that should hold graphical overview's * svg. */ svgContainer: function () { return $(React.findDOMNode(this.refs.svgContainer)); }, // Life-cycle methods // render: function () { return ( <div className="graphical-overview" ref="svgContainer"> </div> ); }, componentDidMount: function () { var hits = this.toGraph(this.props.query.hits, this.props.query.number); $.graphIt(this.svgContainer().parent().parent(), this.svgContainer(), 0, 20, null, hits); } }); /** * Renders report for each query sequence. * * Composed of graphical overview, tabular summary (HitsTable), * and a list of Hits. */ var Query = React.createClass({ // Kind of public API // /** * Returns the id of query. */ domID: function () { return "Query_" + this.props.query.number; }, /** * Returns number of hits. */ numhits: function () { return this.props.query.hits.length; }, // Life cycle methods // render: function () { // NOTE: // Adding 'subject' class to query container is required by // ImageExporter. return ( <div className="resultn subject" id={this.domID()} data-query-len={this.props.query.length} data-algorithm={this.props.data.program}> <div className="page-header"> <h3> Query= {this.props.query.id} &nbsp; <small> {this.props.query.title} </small> </h3> <span className="label label-reset pos-label" title={"Query" + this.props.query.number + "."} data-toggle="tooltip"> {this.props.query.number + "/" + this.props.data.queries.length} </span> </div> {this.numhits() && ( <div className="page-content"> <div className="hit-links"> <a href = "#" className="export-to-svg"> <i className="fa fa-download"/> <span>{" SVG "}</span> </a> <span>{" | "}</span> <a href = "#" className="export-to-png"> <i className="fa fa-download"/> <span>{" PNG "}</span> </a> </div> <GraphicalOverview query={this.props.query} program={this.props.data.program}/> <HitsTable query={this.props.query}/> <div id="hits"> { _.map(this.props.query.hits, _.bind(function (hit) { return ( <Hit hit={hit} algorithm={this.props.data.program} query={this.props.query} selectHit={this.props.selectHit}/> ); }, this)) } </div> </div> ) || ( <div className="page-content"> <p> Query length: {this.props.query.length} </p> <br/> <br/> <p> <strong> ****** No hits found ****** </strong> </p> </div> ) } </div> ) }, }); /** * Renders links for downloading hit information in different formats. * Renders links for navigating to each query. */ var SideBar = React.createClass({ /** * Dynamically create form and submit. */ postForm: function (sequence_ids, database_ids) { var form = $('<form/>').attr('method', 'post').attr('action', '/get_sequence'); addField("sequence_ids", sequence_ids); addField("database_ids", database_ids); form.appendTo('body').submit().remove(); function addField(name, val) { form.append( $('<input>').attr('type', 'hidden').attr('name', name).val(val) ); } }, /** * Event-handler for downloading fasta of all hits. */ downloadFastaOfAll: function () { var sequence_ids = $('.hit-links :checkbox').map(function () { return this.value; }).get(); var database_ids = _.map(this.props.data.querydb, _.iteratee('id')); this.postForm(sequence_ids, database_ids); }, /** * Handles downloading fasta of selected hits. */ downloadFastaOfSelected: function () { var sequence_ids = $('.hit-links :checkbox:checked').map(function () { return this.value; }).get(); var database_ids = _.map(this.props.data.querydb, _.iteratee('id')); this.postForm(sequence_ids, database_ids); }, summary: function () { var program = this.props.data.program; var numqueries = this.props.data.queries.length; var numquerydb = this.props.data.querydb.length; return ( program.toUpperCase() + ': ' + numqueries + ' ' + (numqueries > 1 ? 'queries' : 'query') + ", " + numquerydb + ' ' + (numquerydb > 1 ? 'databases' : 'database') ); }, // Life-cycle method. // render: function () { return ( <div className="sidebar"> <div className="page-header"> <h4> { this.summary() } </h4> </div> <ul className="nav hover-reset active-bold index"> { _.map(this.props.data.queries, _.bind(function (query) { return ( <li> <a className="nowrap-ellipsis hover-bold" href={"#Query_" + query.number} title={"Query= " + query.id + ' ' + query.title}> {"Query= " + query.id} </a> </li> ); }, this)) } </ul> <br/> <br/> <div className="page-header"> <h4> Download FASTA, XML, TSV </h4> </div> <ul className="downloads list-unstyled list-padded"> <li> <a className="download-fasta-of-all" onClick={this.downloadFastaOfAll}> FASTA of all hits </a> </li> <li> <a className="download-fasta-of-selected disabled" onClick={this.downloadFastaOfSelected}> FASTA of <span className="text-bold"></span> selected hit(s) </a> </li> <li> <a className="download" data-toggle="tooltip" title="15 columns: query and subject ID; scientific name, alignment length, mismatches, gaps, identity, start and end coordinates, e value, bitscore, query coverage per subject and per HSP." href={"download/" + this.props.data.search_id + ".std_tsv"}> Standard tabular report </a> </li> <li> <a className="download" data-toggle="tooltip" title="44 columns: query and subject ID, GI, accessions, and length; alignment details; taxonomy details of subject sequence(s) and query coverage per subject and per HSP." href={"download/" + this.props.data.search_id + ".full_tsv"}> Full tabular report </a> </li> <li> <a className="download" data-toggle="tooltip" title="Results in XML format." href={"download/" + this.props.data.search_id + ".xml"}> Full XML report </a> </li> </ul> </div> ) } }); /** * Renders entire report. * * Composed of Query and Sidebar components. */ var Report = React.createClass({ // Kind of public API // /** * Event-handler when hit is selected * Adds glow to hit component. * Updates number of Fasta that can be downloaded */ selectHit: function (id) { var checkbox = $("#" + id); var num_checked = $('.hit-links :checkbox:checked').length; if (!checkbox || !checkbox.val()) { return; } var $hitn = $(checkbox.data('target')); // Highlight selected hit and sync checkboxes if sequence viewer is open. if (checkbox.is(":checked")) { $hitn .addClass('glow') .find(":checkbox").not(checkbox).check(); var $a = $('.download-fasta-of-selected'); var $n = $a.find('span'); $a .enable() } else { $hitn .removeClass('glow') .find(":checkbox").not(checkbox).uncheck(); } if (num_checked >= 1) { var $a = $('.download-fasta-of-selected'); $a.find('.text-bold').html(num_checked); } if (num_checked == 0) { var $a = $('.download-fasta-of-selected'); $a.addClass('disabled').find('.text-bold').html(''); } }, // Internal helpers. // /** * Fetch results. */ fetch_results: function () { $.getJSON(location.href + '.json') .complete(_.bind(function (jqXHR) { switch (jqXHR.status) { case 202: setTimeout(fetch_results, 5000); break; case 200: this.setState(jqXHR.responseJSON); break; case 500: SequenceServer.showErrorModal(jqXHR, function () {}); break; } }, this)); }, /** * Returns true if results have been fetched. * * A holding message is shown till results are fetched. */ isResultAvailable: function () { return this.state.queries.length >= 1; }, /** * Returns true if sidebar should be shown. * * Sidebar is not shown if there is only one query and there are no hits * corresponding to the query. */ shouldShowSidebar: function () { return !(this.state.queries.length == 1 && this.state.queries[0].hits.length == 0); }, loading: function () { return ( <div className="col-md-6 col-md-offset-3 text-center"> <h1> <i className="fa fa-cog fa-spin"></i> BLAST-ing </h1> <p> <br/> This can take some time depending on the size of your query and database(s). The page will update automatically when BLAST is done. <br/> <br/> You can bookmark the page and come back to it later or share the link with someone. </p> </div> ); }, /** * Renders report overview. */ overview: function () { return ( <div className="overview"> <h4> {this.state.program_version} </h4> <table className="table table-condensed"> <thead> <tr> <th> Database </th> <th className="text-right"> Number of sequences </th> <th className="text-right"> Number of characters </th> <th className="text-right"> Created or updated on </th> </tr> </thead> <tbody> { _.map(this.state.querydb, function (db) { return ( <tr> <td> { db.title } </td> <td className="text-right"> { db.nsequences } </td> <td className="text-right"> { db.ncharacters } </td> <td className="text-right"> { db.updated_on } </td> </tr> ); }) } <tr> <td className="text-right"> Total </td> <td className="text-right"> {this.state.stats.nsequences} </td> <td className="text-right"> {this.state.stats.ncharacters} </td> </tr> </tbody> </table> <table className="table table-condensed"> <thead> <tr> { _.map(_.keys(this.state.params), function (param) { return ( <th> { param } </th> ); }) } </tr> </thead> <tbody> <tr> { _.map(this.state.params, function (param) { return ( <td> { param } </td> ); }) } </tr> </tbody> </table> </div> ); }, /** * Renders results per query. */ results: function () { return ( <div className={this.shouldShowSidebar() ? 'col-md-9 main' : 'col-md-12'}> { this.overview() } { _.map(this.state.queries, _.bind(function (query) { return ( <Query query={query} data={this.state} selectHit={this.selectHit}/> ); }, this)) } </div> ); }, /** * Renders sidebar. */ sidebar: function () { return ( <div className="side col-md-3 hidden-xs hidden-sm"> <SideBar data={this.state}/> </div> ); }, /** * Affixes the sidebar. * * TODO: can't this be done with CSS? */ affixSidebar: function () { var $sidebar = $('.sidebar'); if ($sidebar.length !== 0) { $sidebar.affix({ offset: { top: $sidebar.offset().top } }) .width($sidebar.width()); } }, /** * For the query in viewport, highlights corresponding entry in the index. */ setupScrollSpy: function () { $('body').scrollspy({target: '.sidebar'}); }, /** * Prevents folding of hits during text-selection. */ setupHitSelection: function () { $('.result').on('mousedown', ".hitn > .page-header > h4", function (event) { var $this = $(this); $this.on('mouseup mousemove', function handler(event) { if (event.type === 'mouseup') { // user wants to toggle $this.attr('data-toggle', 'collapse'); $this.find('.fa-chevron-down').toggleClass('fa-rotate-270'); } else { // user wants to select $this.attr('data-toggle', ''); } $this.off('mouseup mousemove', handler); }); }); }, // Download links. // // Handles downloading files referenced by links with class 'download'. setupDownloadLinks: function () { $(document).on('click', '.download', function (event) { event.preventDefault(); event.stopPropagation(); var $anchor = $(this); if ($anchor.is(':disabled')) return; var url = $anchor.attr('href'); $.get(url) .done(function (data) { window.location.href = url; }) .fail(function (jqXHR, status, error) { SequenceServer.showErrorModal(jqXHR, function () {}); }); }); }, // Handles sequence-viewer links. setupSequenceViewer: function (event) { $(document).on('click', '.view-sequence', function (event) { event.preventDefault(); event.stopPropagation(); React.render(<SequenceViewer event={event}/>, document.getElementById('sequence-viewer')); }); }, // SVG and PNG download links. setupKablammoImageExporter: function () { new ImageExporter('#report', '.export-to-svg', '.export-to-png'); }, // Life-cycle methods. // getInitialState: function () { return { search_id: '', program: '', program_version: '', queries: [], querydb: [], params: [], stats: [] }; }, render: function () { return ( <div className="row"> { this.isResultAvailable() && this.results() || this.loading() } { this.shouldShowSidebar() && this.sidebar() } </div> ); }, componentDidMount: function () { this.fetch_results(); }, /** * Locks Sidebar in its position. * Prevents folding of hits during text-selection */ componentDidUpdate: function () { this.affixSidebar(); this.setupScrollSpy(); this.setupHitSelection(); this.setupDownloadLinks(); this.setupSequenceViewer(); this.setupKablammoImageExporter(); } }); var Page = React.createClass({ render: function () { return ( <div> <div className="container"> <Report ref="report"/> </div> <div id="sequence-viewer" className="modal" tabIndex="-1"> </div> <canvas id="png-exporter" hidden> </canvas> </div> ); } }); export {Page};
src/smart/wo_editor/WOEditor.js
jeckhummer/wf-constructor
import React from 'react'; import {connect} from 'react-redux'; import {EditorModal} from "../../dumb/editor/EditorModal"; import {WOEditorContent} from "./WOEditorContent"; import {getWOEditorState} from "../../selectors/ui"; import {getWO} from "../../selectors/WO"; import {WO_EDITOR_TABS} from "../../reducers/ui/WOEditor"; import {closeWOEditor, openWOEditorTab} from "../../actions/WOEditor"; import {saveWOFromEditor} from "../../actions/WO"; const mapStateToProps = (state) => { const {name} = getWO(state); const {activeTab} = getWOEditorState(state); const tabs = [ { name: 'Custom fields', value: WO_EDITOR_TABS.CUSTOM_FIELDS, active: activeTab === WO_EDITOR_TABS.CUSTOM_FIELDS }, { name: 'Notifications', value: WO_EDITOR_TABS.NOTIFICATIONS, active: activeTab === WO_EDITOR_TABS.NOTIFICATIONS, }, ]; return { isActive: true, header: name, content: <WOEditorContent/>, saveButtonDisabled: false, errorMessage: null, tabs }; }; const mapDispatchToProps = (dispatch) => { return { onSaveClick: () => { dispatch(saveWOFromEditor()); dispatch(closeWOEditor()); }, onCloseClick: () => dispatch(closeWOEditor()), onTabClick: (_, {value}) => dispatch(openWOEditorTab(value)) }; }; export const WOEditor = connect( mapStateToProps, mapDispatchToProps )(EditorModal);
ajax/libs/styled-components/1.2.1/styled-components.js
dakshshah96/cdnjs
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react')) : typeof define === 'function' && define.amd ? define(['exports', 'react'], factory) : (factory((global.styled = global.styled || {}),global.React)); }(this, (function (exports,React) { 'use strict'; var React__default = 'default' in React ? React['default'] : React; // var chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); /* Some high number, usually 9-digit base-10. Map it to base-😎 */ var generateAlphabeticName = function generateAlphabeticName(code) { var lastDigit = chars[code % chars.length]; return code > chars.length ? '' + generateAlphabeticName(Math.floor(code / chars.length)) + lastDigit : lastDigit; }; // var interleave = (function (strings, interpolations) { return interpolations.reduce(function (array, interp, i) { return array.concat(interp, strings[i + 1]); }, [strings[0]]); }); /** * 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$1(string) { return string.replace(_uppercasePattern, '-$1').toLowerCase(); } var hyphenate_1 = hyphenate$1; var hyphenate = hyphenate_1; 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-'); } var hyphenateStyleName_1 = hyphenateStyleName; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var classCallCheck = function (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }; var createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var defineProperty = function (obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }; var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var get$1 = function get$1(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get$1(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var inherits = function (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }; var possibleConstructorReturn = function (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }; var set$1 = function set$1(object, property, value, receiver) { var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent !== null) { set$1(parent, property, value, receiver); } } else if ("value" in desc && desc.writable) { desc.value = value; } else { var setter = desc.set; if (setter !== undefined) { setter.call(receiver, value); } } return value; }; var toConsumableArray = function (arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; return arr2; } else { return Array.from(arr); } }; /*! * isobject <https://github.com/jonschlinkert/isobject> * * Copyright (c) 2014-2015, Jon Schlinkert. * Licensed under the MIT License. */ var index$2 = function isObject(val) { return val != null && (typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object' && !Array.isArray(val); }; var isObject$1 = index$2; function isObjectObject(o) { return isObject$1(o) === true && Object.prototype.toString.call(o) === '[object Object]'; } var index$1 = function isPlainObject(o) { var ctor, prot; if (isObjectObject(o) === false) return false; // If has modified constructor ctor = o.constructor; if (typeof ctor !== 'function') return false; // If has modified prototype prot = ctor.prototype; if (isObjectObject(prot) === false) return false; // If constructor does not have an Object-specific method if (prot.hasOwnProperty('isPrototypeOf') === false) { return false; } // Most likely a plain Object return true; }; // var objToCss = function objToCss(obj, prevKey) { var css = Object.keys(obj).map(function (key) { if (index$1(obj[key])) return objToCss(obj[key], key); return hyphenateStyleName_1(key) + ': ' + obj[key] + ';'; }).join(' '); return prevKey ? prevKey + ' {\n ' + css + '\n}' : css; }; var flatten = function flatten(chunks, executionContext) { return chunks.reduce(function (ruleSet, chunk) { /* Remove falsey values */ if (chunk === undefined || chunk === null || chunk === false || chunk === '') return ruleSet; /* Flatten ruleSet */ if (Array.isArray(chunk)) return [].concat(toConsumableArray(ruleSet), toConsumableArray(flatten(chunk, executionContext))); /* Either execute or defer the function */ if (typeof chunk === 'function') { return executionContext ? ruleSet.concat.apply(ruleSet, toConsumableArray(flatten([chunk(executionContext)], executionContext))) : ruleSet.concat(chunk); } /* Handle objects */ // $FlowIssue have to add %checks somehow to isPlainObject return ruleSet.concat(index$1(chunk) ? objToCss(chunk) : chunk.toString()); }, []); }; // var css = (function (strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } return flatten(interleave(strings, interpolations)); }); var printed = {}; function warnOnce(message) { if (printed[message]) return; printed[message] = true; if (typeof console !== 'undefined' && console.warn) console.warn(message); } var process$1 = { argv: [], env: {} }; var index$5 = function index$5(flag, argv) { argv = argv || process$1.argv; var terminatorPos = argv.indexOf('--'); var prefix = /^--/.test(flag) ? '' : '--'; var pos = argv.indexOf(prefix + flag); return pos !== -1 && (terminatorPos !== -1 ? pos < terminatorPos : true); }; var hasFlag = index$5; var support = function support(level) { if (level === 0) { return false; } return { level: level, hasBasic: true, has256: level >= 2, has16m: level >= 3 }; }; var supportLevel = function () { if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { return 0; } if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) { return 3; } if (hasFlag('color=256')) { return 2; } if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) { return 1; } if (process$1.stdout && !process$1.stdout.isTTY) { return 0; } if (process$1.platform === 'win32') { return 1; } if ('COLORTERM' in process$1.env) { return 1; } if (process$1.env.TERM === 'dumb') { return 0; } if (/^xterm-256(?:color)?/.test(process$1.env.TERM)) { return 2; } if (/^screen|^xterm|^vt100|color|ansi|cygwin|linux/i.test(process$1.env.TERM)) { return 1; } return 0; }(); if (supportLevel === 0 && 'FORCE_COLOR' in process$1.env) { supportLevel = 1; } var index$4 = process$1 && support(supportLevel); var SINGLE_QUOTE = '\''.charCodeAt(0); var DOUBLE_QUOTE = '"'.charCodeAt(0); var BACKSLASH = '\\'.charCodeAt(0); var SLASH = '/'.charCodeAt(0); var NEWLINE = '\n'.charCodeAt(0); var SPACE = ' '.charCodeAt(0); var FEED = '\f'.charCodeAt(0); var TAB = '\t'.charCodeAt(0); var CR = '\r'.charCodeAt(0); var OPEN_SQUARE = '['.charCodeAt(0); var CLOSE_SQUARE = ']'.charCodeAt(0); var OPEN_PARENTHESES = '('.charCodeAt(0); var CLOSE_PARENTHESES = ')'.charCodeAt(0); var OPEN_CURLY = '{'.charCodeAt(0); var CLOSE_CURLY = '}'.charCodeAt(0); var SEMICOLON = ';'.charCodeAt(0); var ASTERISK = '*'.charCodeAt(0); var COLON = ':'.charCodeAt(0); var AT = '@'.charCodeAt(0); var RE_AT_END = /[ \n\t\r\f\{\(\)'"\\;/\[\]#]/g; var RE_WORD_END = /[ \n\t\r\f\(\)\{\}:;@!'"\\\]\[#]|\/(?=\*)/g; var RE_BAD_BRACKET = /.[\\\/\("'\n]/; function tokenize$1(input) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var tokens = []; var css = input.css.valueOf(); var ignore = options.ignoreErrors; var code = void 0, next = void 0, quote = void 0, lines = void 0, last = void 0, content = void 0, escape = void 0, nextLine = void 0, nextOffset = void 0, escaped = void 0, escapePos = void 0, prev = void 0, n = void 0; var length = css.length; var offset = -1; var line = 1; var pos = 0; function unclosed(what) { throw input.error('Unclosed ' + what, line, pos - offset); } while (pos < length) { code = css.charCodeAt(pos); if (code === NEWLINE || code === FEED || code === CR && css.charCodeAt(pos + 1) !== NEWLINE) { offset = pos; line += 1; } switch (code) { case NEWLINE: case SPACE: case TAB: case CR: case FEED: next = pos; do { next += 1; code = css.charCodeAt(next); if (code === NEWLINE) { offset = next; line += 1; } } while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED); tokens.push(['space', css.slice(pos, next)]); pos = next - 1; break; case OPEN_SQUARE: tokens.push(['[', '[', line, pos - offset]); break; case CLOSE_SQUARE: tokens.push([']', ']', line, pos - offset]); break; case OPEN_CURLY: tokens.push(['{', '{', line, pos - offset]); break; case CLOSE_CURLY: tokens.push(['}', '}', line, pos - offset]); break; case COLON: tokens.push([':', ':', line, pos - offset]); break; case SEMICOLON: tokens.push([';', ';', line, pos - offset]); break; case OPEN_PARENTHESES: prev = tokens.length ? tokens[tokens.length - 1][1] : ''; n = css.charCodeAt(pos + 1); if (prev === 'url' && n !== SINGLE_QUOTE && n !== DOUBLE_QUOTE && n !== SPACE && n !== NEWLINE && n !== TAB && n !== FEED && n !== CR) { next = pos; do { escaped = false; next = css.indexOf(')', next + 1); if (next === -1) { if (ignore) { next = pos; break; } else { unclosed('bracket'); } } escapePos = next; while (css.charCodeAt(escapePos - 1) === BACKSLASH) { escapePos -= 1; escaped = !escaped; } } while (escaped); tokens.push(['brackets', css.slice(pos, next + 1), line, pos - offset, line, next - offset]); pos = next; } else { next = css.indexOf(')', pos + 1); content = css.slice(pos, next + 1); if (next === -1 || RE_BAD_BRACKET.test(content)) { tokens.push(['(', '(', line, pos - offset]); } else { tokens.push(['brackets', content, line, pos - offset, line, next - offset]); pos = next; } } break; case CLOSE_PARENTHESES: tokens.push([')', ')', line, pos - offset]); break; case SINGLE_QUOTE: case DOUBLE_QUOTE: quote = code === SINGLE_QUOTE ? '\'' : '"'; next = pos; do { escaped = false; next = css.indexOf(quote, next + 1); if (next === -1) { if (ignore) { next = pos + 1; break; } else { unclosed('quote'); } } escapePos = next; while (css.charCodeAt(escapePos - 1) === BACKSLASH) { escapePos -= 1; escaped = !escaped; } } while (escaped); content = css.slice(pos, next + 1); lines = content.split('\n'); last = lines.length - 1; if (last > 0) { nextLine = line + last; nextOffset = next - lines[last].length; } else { nextLine = line; nextOffset = offset; } tokens.push(['string', css.slice(pos, next + 1), line, pos - offset, nextLine, next - nextOffset]); offset = nextOffset; line = nextLine; pos = next; break; case AT: RE_AT_END.lastIndex = pos + 1; RE_AT_END.test(css); if (RE_AT_END.lastIndex === 0) { next = css.length - 1; } else { next = RE_AT_END.lastIndex - 2; } tokens.push(['at-word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]); pos = next; break; case BACKSLASH: next = pos; escape = true; while (css.charCodeAt(next + 1) === BACKSLASH) { next += 1; escape = !escape; } code = css.charCodeAt(next + 1); if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) { next += 1; } tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]); pos = next; break; default: if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) { next = css.indexOf('*/', pos + 2) + 1; if (next === 0) { if (ignore) { next = css.length; } else { unclosed('comment'); } } content = css.slice(pos, next + 1); lines = content.split('\n'); last = lines.length - 1; if (last > 0) { nextLine = line + last; nextOffset = next - lines[last].length; } else { nextLine = line; nextOffset = offset; } tokens.push(['comment', content, line, pos - offset, nextLine, next - nextOffset]); offset = nextOffset; line = nextLine; pos = next; } else { RE_WORD_END.lastIndex = pos + 1; RE_WORD_END.test(css); if (RE_WORD_END.lastIndex === 0) { next = css.length - 1; } else { next = RE_WORD_END.lastIndex - 2; } tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]); pos = next; } break; } pos++; } return tokens; } var HIGHLIGHT_THEME = { 'brackets': [36, 39], // cyan 'string': [31, 39], // red 'at-word': [31, 39], // red 'comment': [90, 39], // gray '{': [32, 39], // green '}': [32, 39], // green ':': [1, 22], // bold ';': [1, 22], // bold '(': [1, 22], // bold ')': [1, 22] // bold }; function code(color) { return '\x1B[' + color + 'm'; } function terminalHighlight(css) { var tokens = tokenize$1(new Input(css), { ignoreErrors: true }); var result = []; tokens.forEach(function (token) { var color = HIGHLIGHT_THEME[token[0]]; if (color) { result.push(token[1].split(/\r?\n/).map(function (i) { return code(color[0]) + i + code(color[1]); }).join('\n')); } else { result.push(token[1]); } }); return result.join(''); } /** * The CSS parser throws this error for broken CSS. * * Custom parsers can throw this error for broken custom syntax using * the {@link Node#error} method. * * PostCSS will use the input source map to detect the original error location. * If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS, * PostCSS will show the original position in the Sass file. * * If you need the position in the PostCSS input * (e.g., to debug the previous compiler), use `error.input.file`. * * @example * // Catching and checking syntax error * try { * postcss.parse('a{') * } catch (error) { * if ( error.name === 'CssSyntaxError' ) { * error //=> CssSyntaxError * } * } * * @example * // Raising error from plugin * throw node.error('Unknown variable', { plugin: 'postcss-vars' }); */ var CssSyntaxError = function () { /** * @param {string} message - error message * @param {number} [line] - source line of the error * @param {number} [column] - source column of the error * @param {string} [source] - source code of the broken file * @param {string} [file] - absolute path to the broken file * @param {string} [plugin] - PostCSS plugin name, if error came from plugin */ function CssSyntaxError(message, line, column, source, file, plugin) { classCallCheck(this, CssSyntaxError); /** * @member {string} - Always equal to `'CssSyntaxError'`. You should * always check error type * by `error.name === 'CssSyntaxError'` instead of * `error instanceof CssSyntaxError`, because * npm could have several PostCSS versions. * * @example * if ( error.name === 'CssSyntaxError' ) { * error //=> CssSyntaxError * } */ this.name = 'CssSyntaxError'; /** * @member {string} - Error message. * * @example * error.message //=> 'Unclosed block' */ this.reason = message; if (file) { /** * @member {string} - Absolute path to the broken file. * * @example * error.file //=> 'a.sass' * error.input.file //=> 'a.css' */ this.file = file; } if (source) { /** * @member {string} - Source code of the broken file. * * @example * error.source //=> 'a { b {} }' * error.input.column //=> 'a b { }' */ this.source = source; } if (plugin) { /** * @member {string} - Plugin name, if error came from plugin. * * @example * error.plugin //=> 'postcss-vars' */ this.plugin = plugin; } if (typeof line !== 'undefined' && typeof column !== 'undefined') { /** * @member {number} - Source line of the error. * * @example * error.line //=> 2 * error.input.line //=> 4 */ this.line = line; /** * @member {number} - Source column of the error. * * @example * error.column //=> 1 * error.input.column //=> 4 */ this.column = column; } this.setMessage(); if (Error.captureStackTrace) { Error.captureStackTrace(this, CssSyntaxError); } } createClass(CssSyntaxError, [{ key: 'setMessage', value: function setMessage() { /** * @member {string} - Full error text in the GNU error format * with plugin, file, line and column. * * @example * error.message //=> 'a.css:1:1: Unclosed block' */ this.message = this.plugin ? this.plugin + ': ' : ''; this.message += this.file ? this.file : '<css input>'; if (typeof this.line !== 'undefined') { this.message += ':' + this.line + ':' + this.column; } this.message += ': ' + this.reason; } /** * Returns a few lines of CSS source that caused the error. * * If the CSS has an input source map without `sourceContent`, * this method will return an empty string. * * @param {boolean} [color] whether arrow will be colored red by terminal * color codes. By default, PostCSS will detect * color support by `process.stdout.isTTY` * and `process.env.NODE_DISABLE_COLORS`. * * @example * error.showSourceCode() //=> " 4 | } * // 5 | a { * // > 6 | bad * // | ^ * // 7 | } * // 8 | b {" * * @return {string} few lines of CSS source that caused the error */ }, { key: 'showSourceCode', value: function showSourceCode(color) { var _this = this; if (!this.source) return ''; var css = this.source; if (typeof color === 'undefined') color = index$4; if (color) css = terminalHighlight(css); var lines = css.split(/\r?\n/); var start = Math.max(this.line - 3, 0); var end = Math.min(this.line + 2, lines.length); var maxWidth = String(end).length; return lines.slice(start, end).map(function (line, index) { var number = start + 1 + index; var padded = (' ' + number).slice(-maxWidth); var gutter = ' ' + padded + ' | '; if (number === _this.line) { var spacing = gutter.replace(/\d/g, ' ') + line.slice(0, _this.column - 1).replace(/[^\t]/g, ' '); return '>' + gutter + line + '\n ' + spacing + '^'; } else { return ' ' + gutter + line; } }).join('\n'); } /** * Returns error position, message and source code of the broken part. * * @example * error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block * // > 1 | a { * // | ^" * * @return {string} error position, message and source code */ }, { key: 'toString', value: function toString() { var code = this.showSourceCode(); if (code) { code = '\n\n' + code + '\n'; } return this.name + ': ' + this.message + code; } }, { key: 'generated', get: function get() { warnOnce('CssSyntaxError#generated is depreacted. Use input instead.'); return this.input; } /** * @memberof CssSyntaxError# * @member {Input} input - Input object with PostCSS internal information * about input file. If input has source map * from previous tool, PostCSS will use origin * (for example, Sass) source. You can use this * object to get PostCSS input source. * * @example * error.input.file //=> 'a.css' * error.file //=> 'a.sass' */ }]); return CssSyntaxError; }(); /* eslint-disable valid-jsdoc */ var defaultRaw = { colon: ': ', indent: ' ', beforeDecl: '\n', beforeRule: '\n', beforeOpen: ' ', beforeClose: '\n', beforeComment: '\n', after: '\n', emptyBody: '', commentLeft: ' ', commentRight: ' ' }; function capitalize(str) { return str[0].toUpperCase() + str.slice(1); } var Stringifier = function () { function Stringifier(builder) { classCallCheck(this, Stringifier); this.builder = builder; } createClass(Stringifier, [{ key: 'stringify', value: function stringify(node, semicolon) { this[node.type](node, semicolon); } }, { key: 'root', value: function root(node) { this.body(node); if (node.raws.after) this.builder(node.raws.after); } }, { key: 'comment', value: function comment(node) { var left = this.raw(node, 'left', 'commentLeft'); var right = this.raw(node, 'right', 'commentRight'); this.builder('/*' + left + node.text + right + '*/', node); } }, { key: 'decl', value: function decl(node, semicolon) { var between = this.raw(node, 'between', 'colon'); var string = node.prop + between + this.rawValue(node, 'value'); if (node.important) { string += node.raws.important || ' !important'; } if (semicolon) string += ';'; this.builder(string, node); } }, { key: 'rule', value: function rule(node) { this.block(node, this.rawValue(node, 'selector')); } }, { key: 'atrule', value: function atrule(node, semicolon) { var name = '@' + node.name; var params = node.params ? this.rawValue(node, 'params') : ''; if (typeof node.raws.afterName !== 'undefined') { name += node.raws.afterName; } else if (params) { name += ' '; } if (node.nodes) { this.block(node, name + params); } else { var end = (node.raws.between || '') + (semicolon ? ';' : ''); this.builder(name + params + end, node); } } }, { key: 'body', value: function body(node) { var last = node.nodes.length - 1; while (last > 0) { if (node.nodes[last].type !== 'comment') break; last -= 1; } var semicolon = this.raw(node, 'semicolon'); for (var i = 0; i < node.nodes.length; i++) { var child = node.nodes[i]; var before = this.raw(child, 'before'); if (before) this.builder(before); this.stringify(child, last !== i || semicolon); } } }, { key: 'block', value: function block(node, start) { var between = this.raw(node, 'between', 'beforeOpen'); this.builder(start + between + '{', node, 'start'); var after = void 0; if (node.nodes && node.nodes.length) { this.body(node); after = this.raw(node, 'after'); } else { after = this.raw(node, 'after', 'emptyBody'); } if (after) this.builder(after); this.builder('}', node, 'end'); } }, { key: 'raw', value: function raw(node, own, detect) { var value = void 0; if (!detect) detect = own; // Already had if (own) { value = node.raws[own]; if (typeof value !== 'undefined') return value; } var parent = node.parent; // Hack for first rule in CSS if (detect === 'before') { if (!parent || parent.type === 'root' && parent.first === node) { return ''; } } // Floating child without parent if (!parent) return defaultRaw[detect]; // Detect style by other nodes var root = node.root(); if (!root.rawCache) root.rawCache = {}; if (typeof root.rawCache[detect] !== 'undefined') { return root.rawCache[detect]; } if (detect === 'before' || detect === 'after') { return this.beforeAfter(node, detect); } else { var method = 'raw' + capitalize(detect); if (this[method]) { value = this[method](root, node); } else { root.walk(function (i) { value = i.raws[own]; if (typeof value !== 'undefined') return false; }); } } if (typeof value === 'undefined') value = defaultRaw[detect]; root.rawCache[detect] = value; return value; } }, { key: 'rawSemicolon', value: function rawSemicolon(root) { var value = void 0; root.walk(function (i) { if (i.nodes && i.nodes.length && i.last.type === 'decl') { value = i.raws.semicolon; if (typeof value !== 'undefined') return false; } }); return value; } }, { key: 'rawEmptyBody', value: function rawEmptyBody(root) { var value = void 0; root.walk(function (i) { if (i.nodes && i.nodes.length === 0) { value = i.raws.after; if (typeof value !== 'undefined') return false; } }); return value; } }, { key: 'rawIndent', value: function rawIndent(root) { if (root.raws.indent) return root.raws.indent; var value = void 0; root.walk(function (i) { var p = i.parent; if (p && p !== root && p.parent && p.parent === root) { if (typeof i.raws.before !== 'undefined') { var parts = i.raws.before.split('\n'); value = parts[parts.length - 1]; value = value.replace(/[^\s]/g, ''); return false; } } }); return value; } }, { key: 'rawBeforeComment', value: function rawBeforeComment(root, node) { var value = void 0; root.walkComments(function (i) { if (typeof i.raws.before !== 'undefined') { value = i.raws.before; if (value.indexOf('\n') !== -1) { value = value.replace(/[^\n]+$/, ''); } return false; } }); if (typeof value === 'undefined') { value = this.raw(node, null, 'beforeDecl'); } return value; } }, { key: 'rawBeforeDecl', value: function rawBeforeDecl(root, node) { var value = void 0; root.walkDecls(function (i) { if (typeof i.raws.before !== 'undefined') { value = i.raws.before; if (value.indexOf('\n') !== -1) { value = value.replace(/[^\n]+$/, ''); } return false; } }); if (typeof value === 'undefined') { value = this.raw(node, null, 'beforeRule'); } return value; } }, { key: 'rawBeforeRule', value: function rawBeforeRule(root) { var value = void 0; root.walk(function (i) { if (i.nodes && (i.parent !== root || root.first !== i)) { if (typeof i.raws.before !== 'undefined') { value = i.raws.before; if (value.indexOf('\n') !== -1) { value = value.replace(/[^\n]+$/, ''); } return false; } } }); return value; } }, { key: 'rawBeforeClose', value: function rawBeforeClose(root) { var value = void 0; root.walk(function (i) { if (i.nodes && i.nodes.length > 0) { if (typeof i.raws.after !== 'undefined') { value = i.raws.after; if (value.indexOf('\n') !== -1) { value = value.replace(/[^\n]+$/, ''); } return false; } } }); return value; } }, { key: 'rawBeforeOpen', value: function rawBeforeOpen(root) { var value = void 0; root.walk(function (i) { if (i.type !== 'decl') { value = i.raws.between; if (typeof value !== 'undefined') return false; } }); return value; } }, { key: 'rawColon', value: function rawColon(root) { var value = void 0; root.walkDecls(function (i) { if (typeof i.raws.between !== 'undefined') { value = i.raws.between.replace(/[^\s:]/g, ''); return false; } }); return value; } }, { key: 'beforeAfter', value: function beforeAfter(node, detect) { var value = void 0; if (node.type === 'decl') { value = this.raw(node, null, 'beforeDecl'); } else if (node.type === 'comment') { value = this.raw(node, null, 'beforeComment'); } else if (detect === 'before') { value = this.raw(node, null, 'beforeRule'); } else { value = this.raw(node, null, 'beforeClose'); } var buf = node.parent; var depth = 0; while (buf && buf.type !== 'root') { depth += 1; buf = buf.parent; } if (value.indexOf('\n') !== -1) { var indent = this.raw(node, null, 'indent'); if (indent.length) { for (var step = 0; step < depth; step++) { value += indent; } } } return value; } }, { key: 'rawValue', value: function rawValue(node, prop) { var value = node[prop]; var raw = node.raws[prop]; if (raw && raw.value === value) { return raw.raw; } else { return value; } } }]); return Stringifier; }(); function stringify$1(node, builder) { var str = new Stringifier(builder); str.stringify(node); } /** * @typedef {object} position * @property {number} line - source line in file * @property {number} column - source column in file */ /** * @typedef {object} source * @property {Input} input - {@link Input} with input file * @property {position} start - The starting position of the node’s source * @property {position} end - The ending position of the node’s source */ var cloneNode = function cloneNode(obj, parent) { var cloned = new obj.constructor(); for (var i in obj) { if (!obj.hasOwnProperty(i)) continue; var value = obj[i]; var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); if (i === 'parent' && type === 'object') { if (parent) cloned[i] = parent; } else if (i === 'source') { cloned[i] = value; } else if (value instanceof Array) { cloned[i] = value.map(function (j) { return cloneNode(j, cloned); }); } else if (i !== 'before' && i !== 'after' && i !== 'between' && i !== 'semicolon') { if (type === 'object' && value !== null) value = cloneNode(value); cloned[i] = value; } } return cloned; }; /** * All node classes inherit the following common methods. * * @abstract */ var Node = function () { /** * @param {object} [defaults] - value for node properties */ function Node() { var defaults$$1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; classCallCheck(this, Node); this.raws = {}; for (var name in defaults$$1) { this[name] = defaults$$1[name]; } } /** * Returns a CssSyntaxError instance containing the original position * of the node in the source, showing line and column numbers and also * a small excerpt to facilitate debugging. * * If present, an input source map will be used to get the original position * of the source, even from a previous compilation step * (e.g., from Sass compilation). * * This method produces very useful error messages. * * @param {string} message - error description * @param {object} [opts] - options * @param {string} opts.plugin - plugin name that created this error. * PostCSS will set it automatically. * @param {string} opts.word - a word inside a node’s string that should * be highlighted as the source of the error * @param {number} opts.index - an index inside a node’s string that should * be highlighted as the source of the error * * @return {CssSyntaxError} error object to throw it * * @example * if ( !variables[name] ) { * throw decl.error('Unknown variable ' + name, { word: name }); * // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black * // color: $black * // a * // ^ * // background: white * } */ createClass(Node, [{ key: 'error', value: function error(message) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (this.source) { var pos = this.positionBy(opts); return this.source.input.error(message, pos.line, pos.column, opts); } else { return new CssSyntaxError(message); } } /** * This method is provided as a convenience wrapper for {@link Result#warn}. * * @param {Result} result - the {@link Result} instance * that will receive the warning * @param {string} text - warning message * @param {object} [opts] - options * @param {string} opts.plugin - plugin name that created this warning. * PostCSS will set it automatically. * @param {string} opts.word - a word inside a node’s string that should * be highlighted as the source of the warning * @param {number} opts.index - an index inside a node’s string that should * be highlighted as the source of the warning * * @return {Warning} created warning object * * @example * const plugin = postcss.plugin('postcss-deprecated', () => { * return (root, result) => { * root.walkDecls('bad', decl => { * decl.warn(result, 'Deprecated property bad'); * }); * }; * }); */ }, { key: 'warn', value: function warn(result, text, opts) { var data = { node: this }; for (var i in opts) { data[i] = opts[i]; }return result.warn(text, data); } /** * Removes the node from its parent and cleans the parent properties * from the node and its children. * * @example * if ( decl.prop.match(/^-webkit-/) ) { * decl.remove(); * } * * @return {Node} node to make calls chain */ }, { key: 'remove', value: function remove() { if (this.parent) { this.parent.removeChild(this); } this.parent = undefined; return this; } /** * Returns a CSS string representing the node. * * @param {stringifier|syntax} [stringifier] - a syntax to use * in string generation * * @return {string} CSS string of this node * * @example * postcss.rule({ selector: 'a' }).toString() //=> "a {}" */ }, { key: 'toString', value: function toString() { var stringifier = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : stringify$1; if (stringifier.stringify) stringifier = stringifier.stringify; var result = ''; stringifier(this, function (i) { result += i; }); return result; } /** * Returns a clone of the node. * * The resulting cloned node and its (cloned) children will have * a clean parent and code style properties. * * @param {object} [overrides] - new properties to override in the clone. * * @example * const cloned = decl.clone({ prop: '-moz-' + decl.prop }); * cloned.raws.before //=> undefined * cloned.parent //=> undefined * cloned.toString() //=> -moz-transform: scale(0) * * @return {Node} clone of the node */ }, { key: 'clone', value: function clone() { var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var cloned = cloneNode(this); for (var name in overrides) { cloned[name] = overrides[name]; } return cloned; } /** * Shortcut to clone the node and insert the resulting cloned node * before the current node. * * @param {object} [overrides] - new properties to override in the clone. * * @example * decl.cloneBefore({ prop: '-moz-' + decl.prop }); * * @return {Node} - new node */ }, { key: 'cloneBefore', value: function cloneBefore() { var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var cloned = this.clone(overrides); this.parent.insertBefore(this, cloned); return cloned; } /** * Shortcut to clone the node and insert the resulting cloned node * after the current node. * * @param {object} [overrides] - new properties to override in the clone. * * @return {Node} - new node */ }, { key: 'cloneAfter', value: function cloneAfter() { var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var cloned = this.clone(overrides); this.parent.insertAfter(this, cloned); return cloned; } /** * Inserts node(s) before the current node and removes the current node. * * @param {...Node} nodes - node(s) to replace current one * * @example * if ( atrule.name == 'mixin' ) { * atrule.replaceWith(mixinRules[atrule.params]); * } * * @return {Node} current node to methods chain */ }, { key: 'replaceWith', value: function replaceWith() { var _this = this; if (this.parent) { for (var _len = arguments.length, nodes = Array(_len), _key = 0; _key < _len; _key++) { nodes[_key] = arguments[_key]; } nodes.forEach(function (node) { _this.parent.insertBefore(_this, node); }); this.remove(); } return this; } /** * Removes the node from its current parent and inserts it * at the end of `newParent`. * * This will clean the `before` and `after` code {@link Node#raws} data * from the node and replace them with the indentation style of `newParent`. * It will also clean the `between` property * if `newParent` is in another {@link Root}. * * @param {Container} newParent - container node where the current node * will be moved * * @example * atrule.moveTo(atrule.root()); * * @return {Node} current node to methods chain */ }, { key: 'moveTo', value: function moveTo(newParent) { this.cleanRaws(this.root() === newParent.root()); this.remove(); newParent.append(this); return this; } /** * Removes the node from its current parent and inserts it into * a new parent before `otherNode`. * * This will also clean the node’s code style properties just as it would * in {@link Node#moveTo}. * * @param {Node} otherNode - node that will be before current node * * @return {Node} current node to methods chain */ }, { key: 'moveBefore', value: function moveBefore(otherNode) { this.cleanRaws(this.root() === otherNode.root()); this.remove(); otherNode.parent.insertBefore(otherNode, this); return this; } /** * Removes the node from its current parent and inserts it into * a new parent after `otherNode`. * * This will also clean the node’s code style properties just as it would * in {@link Node#moveTo}. * * @param {Node} otherNode - node that will be after current node * * @return {Node} current node to methods chain */ }, { key: 'moveAfter', value: function moveAfter(otherNode) { this.cleanRaws(this.root() === otherNode.root()); this.remove(); otherNode.parent.insertAfter(otherNode, this); return this; } /** * Returns the next child of the node’s parent. * Returns `undefined` if the current node is the last child. * * @return {Node|undefined} next node * * @example * if ( comment.text === 'delete next' ) { * const next = comment.next(); * if ( next ) { * next.remove(); * } * } */ }, { key: 'next', value: function next() { var index = this.parent.index(this); return this.parent.nodes[index + 1]; } /** * Returns the previous child of the node’s parent. * Returns `undefined` if the current node is the first child. * * @return {Node|undefined} previous node * * @example * const annotation = decl.prev(); * if ( annotation.type == 'comment' ) { * readAnnotation(annotation.text); * } */ }, { key: 'prev', value: function prev() { var index = this.parent.index(this); return this.parent.nodes[index - 1]; } }, { key: 'toJSON', value: function toJSON() { var fixed = {}; for (var name in this) { if (!this.hasOwnProperty(name)) continue; if (name === 'parent') continue; var value = this[name]; if (value instanceof Array) { fixed[name] = value.map(function (i) { if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && i.toJSON) { return i.toJSON(); } else { return i; } }); } else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value.toJSON) { fixed[name] = value.toJSON(); } else { fixed[name] = value; } } return fixed; } /** * Returns a {@link Node#raws} value. If the node is missing * the code style property (because the node was manually built or cloned), * PostCSS will try to autodetect the code style property by looking * at other nodes in the tree. * * @param {string} prop - name of code style property * @param {string} [defaultType] - name of default value, it can be missed * if the value is the same as prop * * @example * const root = postcss.parse('a { background: white }'); * root.nodes[0].append({ prop: 'color', value: 'black' }); * root.nodes[0].nodes[1].raws.before //=> undefined * root.nodes[0].nodes[1].raw('before') //=> ' ' * * @return {string} code style value */ }, { key: 'raw', value: function raw(prop, defaultType) { var str = new Stringifier(); return str.raw(this, prop, defaultType); } /** * Finds the Root instance of the node’s tree. * * @example * root.nodes[0].nodes[0].root() === root * * @return {Root} root parent */ }, { key: 'root', value: function root() { var result = this; while (result.parent) { result = result.parent; }return result; } }, { key: 'cleanRaws', value: function cleanRaws(keepBetween) { delete this.raws.before; delete this.raws.after; if (!keepBetween) delete this.raws.between; } }, { key: 'positionInside', value: function positionInside(index) { var string = this.toString(); var column = this.source.start.column; var line = this.source.start.line; for (var i = 0; i < index; i++) { if (string[i] === '\n') { column = 1; line += 1; } else { column += 1; } } return { line: line, column: column }; } }, { key: 'positionBy', value: function positionBy(opts) { var pos = this.source.start; if (opts.index) { pos = this.positionInside(opts.index); } else if (opts.word) { var index = this.toString().indexOf(opts.word); if (index !== -1) pos = this.positionInside(index); } return pos; } }, { key: 'removeSelf', value: function removeSelf() { warnOnce('Node#removeSelf is deprecated. Use Node#remove.'); return this.remove(); } }, { key: 'replace', value: function replace(nodes) { warnOnce('Node#replace is deprecated. Use Node#replaceWith'); return this.replaceWith(nodes); } }, { key: 'style', value: function style(own, detect) { warnOnce('Node#style() is deprecated. Use Node#raw()'); return this.raw(own, detect); } }, { key: 'cleanStyles', value: function cleanStyles(keepBetween) { warnOnce('Node#cleanStyles() is deprecated. Use Node#cleanRaws()'); return this.cleanRaws(keepBetween); } }, { key: 'before', get: function get() { warnOnce('Node#before is deprecated. Use Node#raws.before'); return this.raws.before; }, set: function set(val) { warnOnce('Node#before is deprecated. Use Node#raws.before'); this.raws.before = val; } }, { key: 'between', get: function get() { warnOnce('Node#between is deprecated. Use Node#raws.between'); return this.raws.between; }, set: function set(val) { warnOnce('Node#between is deprecated. Use Node#raws.between'); this.raws.between = val; } /** * @memberof Node# * @member {string} type - String representing the node’s type. * Possible values are `root`, `atrule`, `rule`, * `decl`, or `comment`. * * @example * postcss.decl({ prop: 'color', value: 'black' }).type //=> 'decl' */ /** * @memberof Node# * @member {Container} parent - the node’s parent node. * * @example * root.nodes[0].parent == root; */ /** * @memberof Node# * @member {source} source - the input source of the node * * The property is used in source map generation. * * If you create a node manually (e.g., with `postcss.decl()`), * that node will not have a `source` property and will be absent * from the source map. For this reason, the plugin developer should * consider cloning nodes to create new ones (in which case the new node’s * source will reference the original, cloned node) or setting * the `source` property manually. * * ```js * // Bad * const prefixed = postcss.decl({ * prop: '-moz-' + decl.prop, * value: decl.value * }); * * // Good * const prefixed = decl.clone({ prop: '-moz-' + decl.prop }); * ``` * * ```js * if ( atrule.name == 'add-link' ) { * const rule = postcss.rule({ selector: 'a', source: atrule.source }); * atrule.parent.insertBefore(atrule, rule); * } * ``` * * @example * decl.source.input.from //=> '/home/ai/a.sass' * decl.source.start //=> { line: 10, column: 2 } * decl.source.end //=> { line: 10, column: 12 } */ /** * @memberof Node# * @member {object} raws - Information to generate byte-to-byte equal * node string as it was in the origin input. * * Every parser saves its own properties, * but the default CSS parser uses: * * * `before`: the space symbols before the node. It also stores `*` * and `_` symbols before the declaration (IE hack). * * `after`: the space symbols after the last child of the node * to the end of the node. * * `between`: the symbols between the property and value * for declarations, selector and `{` for rules, or last parameter * and `{` for at-rules. * * `semicolon`: contains true if the last child has * an (optional) semicolon. * * `afterName`: the space between the at-rule name and its parameters. * * `left`: the space symbols between `/*` and the comment’s text. * * `right`: the space symbols between the comment’s text * and <code>*&#47;</code>. * * `important`: the content of the important statement, * if it is not just `!important`. * * PostCSS cleans selectors, declaration values and at-rule parameters * from comments and extra spaces, but it stores origin content in raws * properties. As such, if you don’t change a declaration’s value, * PostCSS will use the raw value with comments. * * @example * const root = postcss.parse('a {\n color:black\n}') * root.first.first.raws //=> { before: '\n ', between: ':' } */ }]); return Node; }(); /** * Represents a CSS declaration. * * @extends Node * * @example * const root = postcss.parse('a { color: black }'); * const decl = root.first.first; * decl.type //=> 'decl' * decl.toString() //=> ' color: black' */ var Declaration = function (_Node) { inherits(Declaration, _Node); function Declaration(defaults$$1) { classCallCheck(this, Declaration); var _this = possibleConstructorReturn(this, (Declaration.__proto__ || Object.getPrototypeOf(Declaration)).call(this, defaults$$1)); _this.type = 'decl'; return _this; } createClass(Declaration, [{ key: '_value', get: function get() { warnOnce('Node#_value was deprecated. Use Node#raws.value'); return this.raws.value; }, set: function set(val) { warnOnce('Node#_value was deprecated. Use Node#raws.value'); this.raws.value = val; } }, { key: '_important', get: function get() { warnOnce('Node#_important was deprecated. Use Node#raws.important'); return this.raws.important; }, set: function set(val) { warnOnce('Node#_important was deprecated. Use Node#raws.important'); this.raws.important = val; } /** * @memberof Declaration# * @member {string} prop - the declaration’s property name * * @example * const root = postcss.parse('a { color: black }'); * const decl = root.first.first; * decl.prop //=> 'color' */ /** * @memberof Declaration# * @member {string} value - the declaration’s value * * @example * const root = postcss.parse('a { color: black }'); * const decl = root.first.first; * decl.value //=> 'black' */ /** * @memberof Declaration# * @member {boolean} important - `true` if the declaration * has an !important annotation. * * @example * const root = postcss.parse('a { color: black !important; color: red }'); * root.first.first.important //=> true * root.first.last.important //=> undefined */ /** * @memberof Declaration# * @member {object} raws - Information to generate byte-to-byte equal * node string as it was in the origin input. * * Every parser saves its own properties, * but the default CSS parser uses: * * * `before`: the space symbols before the node. It also stores `*` * and `_` symbols before the declaration (IE hack). * * `between`: the symbols between the property and value * for declarations, selector and `{` for rules, or last parameter * and `{` for at-rules. * * `important`: the content of the important statement, * if it is not just `!important`. * * PostCSS cleans declaration from comments and extra spaces, * but it stores origin content in raws properties. * As such, if you don’t change a declaration’s value, * PostCSS will use the raw value with comments. * * @example * const root = postcss.parse('a {\n color:black\n}') * root.first.first.raws //=> { before: '\n ', between: ':' } */ }]); return Declaration; }(Node); /** * Represents a comment between declarations or statements (rule and at-rules). * * Comments inside selectors, at-rule parameters, or declaration values * will be stored in the `raws` properties explained above. * * @extends Node */ var Comment = function (_Node) { inherits(Comment, _Node); function Comment(defaults$$1) { classCallCheck(this, Comment); var _this = possibleConstructorReturn(this, (Comment.__proto__ || Object.getPrototypeOf(Comment)).call(this, defaults$$1)); _this.type = 'comment'; return _this; } createClass(Comment, [{ key: 'left', get: function get() { warnOnce('Comment#left was deprecated. Use Comment#raws.left'); return this.raws.left; }, set: function set(val) { warnOnce('Comment#left was deprecated. Use Comment#raws.left'); this.raws.left = val; } }, { key: 'right', get: function get() { warnOnce('Comment#right was deprecated. Use Comment#raws.right'); return this.raws.right; }, set: function set(val) { warnOnce('Comment#right was deprecated. Use Comment#raws.right'); this.raws.right = val; } /** * @memberof Comment# * @member {string} text - the comment’s text */ /** * @memberof Comment# * @member {object} raws - Information to generate byte-to-byte equal * node string as it was in the origin input. * * Every parser saves its own properties, * but the default CSS parser uses: * * * `before`: the space symbols before the node. * * `left`: the space symbols between `/*` and the comment’s text. * * `right`: the space symbols between the comment’s text. */ }]); return Comment; }(Node); var Parser = function () { function Parser(input) { classCallCheck(this, Parser); this.input = input; this.pos = 0; this.root = new Root(); this.current = this.root; this.spaces = ''; this.semicolon = false; this.root.source = { input: input, start: { line: 1, column: 1 } }; } createClass(Parser, [{ key: 'tokenize', value: function tokenize() { this.tokens = tokenize$1(this.input); } }, { key: 'loop', value: function loop() { var token = void 0; while (this.pos < this.tokens.length) { token = this.tokens[this.pos]; switch (token[0]) { case 'space': case ';': this.spaces += token[1]; break; case '}': this.end(token); break; case 'comment': this.comment(token); break; case 'at-word': this.atrule(token); break; case '{': this.emptyRule(token); break; default: this.other(); break; } this.pos += 1; } this.endFile(); } }, { key: 'comment', value: function comment(token) { var node = new Comment(); this.init(node, token[2], token[3]); node.source.end = { line: token[4], column: token[5] }; var text = token[1].slice(2, -2); if (/^\s*$/.test(text)) { node.text = ''; node.raws.left = text; node.raws.right = ''; } else { var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/); node.text = match[2]; node.raws.left = match[1]; node.raws.right = match[3]; } } }, { key: 'emptyRule', value: function emptyRule(token) { var node = new Rule(); this.init(node, token[2], token[3]); node.selector = ''; node.raws.between = ''; this.current = node; } }, { key: 'other', value: function other() { var token = void 0; var end = false; var type = null; var colon = false; var bracket = null; var brackets = []; var start = this.pos; while (this.pos < this.tokens.length) { token = this.tokens[this.pos]; type = token[0]; if (type === '(' || type === '[') { if (!bracket) bracket = token; brackets.push(type === '(' ? ')' : ']'); } else if (brackets.length === 0) { if (type === ';') { if (colon) { this.decl(this.tokens.slice(start, this.pos + 1)); return; } else { break; } } else if (type === '{') { this.rule(this.tokens.slice(start, this.pos + 1)); return; } else if (type === '}') { this.pos -= 1; end = true; break; } else if (type === ':') { colon = true; } } else if (type === brackets[brackets.length - 1]) { brackets.pop(); if (brackets.length === 0) bracket = null; } this.pos += 1; } if (this.pos === this.tokens.length) { this.pos -= 1; end = true; } if (brackets.length > 0) this.unclosedBracket(bracket); if (end && colon) { while (this.pos > start) { token = this.tokens[this.pos][0]; if (token !== 'space' && token !== 'comment') break; this.pos -= 1; } this.decl(this.tokens.slice(start, this.pos + 1)); return; } this.unknownWord(start); } }, { key: 'rule', value: function rule(tokens) { tokens.pop(); var node = new Rule(); this.init(node, tokens[0][2], tokens[0][3]); node.raws.between = this.spacesFromEnd(tokens); this.raw(node, 'selector', tokens); this.current = node; } }, { key: 'decl', value: function decl(tokens) { var node = new Declaration(); this.init(node); var last = tokens[tokens.length - 1]; if (last[0] === ';') { this.semicolon = true; tokens.pop(); } if (last[4]) { node.source.end = { line: last[4], column: last[5] }; } else { node.source.end = { line: last[2], column: last[3] }; } while (tokens[0][0] !== 'word') { node.raws.before += tokens.shift()[1]; } node.source.start = { line: tokens[0][2], column: tokens[0][3] }; node.prop = ''; while (tokens.length) { var type = tokens[0][0]; if (type === ':' || type === 'space' || type === 'comment') { break; } node.prop += tokens.shift()[1]; } node.raws.between = ''; var token = void 0; while (tokens.length) { token = tokens.shift(); if (token[0] === ':') { node.raws.between += token[1]; break; } else { node.raws.between += token[1]; } } if (node.prop[0] === '_' || node.prop[0] === '*') { node.raws.before += node.prop[0]; node.prop = node.prop.slice(1); } node.raws.between += this.spacesFromStart(tokens); this.precheckMissedSemicolon(tokens); for (var i = tokens.length - 1; i > 0; i--) { token = tokens[i]; if (token[1] === '!important') { node.important = true; var string = this.stringFrom(tokens, i); string = this.spacesFromEnd(tokens) + string; if (string !== ' !important') node.raws.important = string; break; } else if (token[1] === 'important') { var cache = tokens.slice(0); var str = ''; for (var j = i; j > 0; j--) { var _type = cache[j][0]; if (str.trim().indexOf('!') === 0 && _type !== 'space') { break; } str = cache.pop()[1] + str; } if (str.trim().indexOf('!') === 0) { node.important = true; node.raws.important = str; tokens = cache; } } if (token[0] !== 'space' && token[0] !== 'comment') { break; } } this.raw(node, 'value', tokens); if (node.value.indexOf(':') !== -1) this.checkMissedSemicolon(tokens); } }, { key: 'atrule', value: function atrule(token) { var node = new AtRule(); node.name = token[1].slice(1); if (node.name === '') { this.unnamedAtrule(node, token); } this.init(node, token[2], token[3]); var last = false; var open = false; var params = []; this.pos += 1; while (this.pos < this.tokens.length) { token = this.tokens[this.pos]; if (token[0] === ';') { node.source.end = { line: token[2], column: token[3] }; this.semicolon = true; break; } else if (token[0] === '{') { open = true; break; } else if (token[0] === '}') { this.end(token); break; } else { params.push(token); } this.pos += 1; } if (this.pos === this.tokens.length) { last = true; } node.raws.between = this.spacesFromEnd(params); if (params.length) { node.raws.afterName = this.spacesFromStart(params); this.raw(node, 'params', params); if (last) { token = params[params.length - 1]; node.source.end = { line: token[4], column: token[5] }; this.spaces = node.raws.between; node.raws.between = ''; } } else { node.raws.afterName = ''; node.params = ''; } if (open) { node.nodes = []; this.current = node; } } }, { key: 'end', value: function end(token) { if (this.current.nodes && this.current.nodes.length) { this.current.raws.semicolon = this.semicolon; } this.semicolon = false; this.current.raws.after = (this.current.raws.after || '') + this.spaces; this.spaces = ''; if (this.current.parent) { this.current.source.end = { line: token[2], column: token[3] }; this.current = this.current.parent; } else { this.unexpectedClose(token); } } }, { key: 'endFile', value: function endFile() { if (this.current.parent) this.unclosedBlock(); if (this.current.nodes && this.current.nodes.length) { this.current.raws.semicolon = this.semicolon; } this.current.raws.after = (this.current.raws.after || '') + this.spaces; } // Helpers }, { key: 'init', value: function init(node, line, column) { this.current.push(node); node.source = { start: { line: line, column: column }, input: this.input }; node.raws.before = this.spaces; this.spaces = ''; if (node.type !== 'comment') this.semicolon = false; } }, { key: 'raw', value: function raw(node, prop, tokens) { var token = void 0, type = void 0; var length = tokens.length; var value = ''; var clean = true; for (var i = 0; i < length; i += 1) { token = tokens[i]; type = token[0]; if (type === 'comment' || type === 'space' && i === length - 1) { clean = false; } else { value += token[1]; } } if (!clean) { var raw = tokens.reduce(function (all, i) { return all + i[1]; }, ''); node.raws[prop] = { value: value, raw: raw }; } node[prop] = value; } }, { key: 'spacesFromEnd', value: function spacesFromEnd(tokens) { var lastTokenType = void 0; var spaces = ''; while (tokens.length) { lastTokenType = tokens[tokens.length - 1][0]; if (lastTokenType !== 'space' && lastTokenType !== 'comment') break; spaces = tokens.pop()[1] + spaces; } return spaces; } }, { key: 'spacesFromStart', value: function spacesFromStart(tokens) { var next = void 0; var spaces = ''; while (tokens.length) { next = tokens[0][0]; if (next !== 'space' && next !== 'comment') break; spaces += tokens.shift()[1]; } return spaces; } }, { key: 'stringFrom', value: function stringFrom(tokens, from) { var result = ''; for (var i = from; i < tokens.length; i++) { result += tokens[i][1]; } tokens.splice(from, tokens.length - from); return result; } }, { key: 'colon', value: function colon(tokens) { var brackets = 0; var token = void 0, type = void 0, prev = void 0; for (var i = 0; i < tokens.length; i++) { token = tokens[i]; type = token[0]; if (type === '(') { brackets += 1; } else if (type === ')') { brackets -= 1; } else if (brackets === 0 && type === ':') { if (!prev) { this.doubleColon(token); } else if (prev[0] === 'word' && prev[1] === 'progid') { continue; } else { return i; } } prev = token; } return false; } // Errors }, { key: 'unclosedBracket', value: function unclosedBracket(bracket) { throw this.input.error('Unclosed bracket', bracket[2], bracket[3]); } }, { key: 'unknownWord', value: function unknownWord(start) { var token = this.tokens[start]; throw this.input.error('Unknown word', token[2], token[3]); } }, { key: 'unexpectedClose', value: function unexpectedClose(token) { throw this.input.error('Unexpected }', token[2], token[3]); } }, { key: 'unclosedBlock', value: function unclosedBlock() { var pos = this.current.source.start; throw this.input.error('Unclosed block', pos.line, pos.column); } }, { key: 'doubleColon', value: function doubleColon(token) { throw this.input.error('Double colon', token[2], token[3]); } }, { key: 'unnamedAtrule', value: function unnamedAtrule(node, token) { throw this.input.error('At-rule without name', token[2], token[3]); } }, { key: 'precheckMissedSemicolon', value: function precheckMissedSemicolon(tokens) { // Hook for Safe Parser tokens; } }, { key: 'checkMissedSemicolon', value: function checkMissedSemicolon(tokens) { var colon = this.colon(tokens); if (colon === false) return; var founded = 0; var token = void 0; for (var j = colon - 1; j >= 0; j--) { token = tokens[j]; if (token[0] !== 'space') { founded += 1; if (founded === 2) break; } } throw this.input.error('Missed semicolon', token[2], token[3]); } }]); return Parser; }(); function parse(css, opts) { if (opts && opts.safe) { throw new Error('Option safe was removed. ' + 'Use parser: require("postcss-safe-parser")'); } var input = new Input(css, opts); var parser = new Parser(input); try { parser.tokenize(); parser.loop(); } catch (e) { if (e.name === 'CssSyntaxError' && opts && opts.from) { if (/\.scss$/i.test(opts.from)) { e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser'; } else if (/\.less$/i.test(opts.from)) { e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser'; } } throw e; } return parser.root; } function cleanSource(nodes) { return nodes.map(function (i) { if (i.nodes) i.nodes = cleanSource(i.nodes); delete i.source; return i; }); } /** * @callback childCondition * @param {Node} node - container child * @param {number} index - child index * @param {Node[]} nodes - all container children * @return {boolean} */ /** * @callback childIterator * @param {Node} node - container child * @param {number} index - child index * @return {false|undefined} returning `false` will break iteration */ /** * The {@link Root}, {@link AtRule}, and {@link Rule} container nodes * inherit some common methods to help work with their children. * * Note that all containers can store any content. If you write a rule inside * a rule, PostCSS will parse it. * * @extends Node * @abstract */ var Container = function (_Node) { inherits(Container, _Node); function Container() { classCallCheck(this, Container); return possibleConstructorReturn(this, (Container.__proto__ || Object.getPrototypeOf(Container)).apply(this, arguments)); } createClass(Container, [{ key: 'push', value: function push(child) { child.parent = this; this.nodes.push(child); return this; } /** * Iterates through the container’s immediate children, * calling `callback` for each child. * * Returning `false` in the callback will break iteration. * * This method only iterates through the container’s immediate children. * If you need to recursively iterate through all the container’s descendant * nodes, use {@link Container#walk}. * * Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe * if you are mutating the array of child nodes during iteration. * PostCSS will adjust the current index to match the mutations. * * @param {childIterator} callback - iterator receives each node and index * * @return {false|undefined} returns `false` if iteration was broke * * @example * const root = postcss.parse('a { color: black; z-index: 1 }'); * const rule = root.first; * * for ( let decl of rule.nodes ) { * decl.cloneBefore({ prop: '-webkit-' + decl.prop }); * // Cycle will be infinite, because cloneBefore moves the current node * // to the next index * } * * rule.each(decl => { * decl.cloneBefore({ prop: '-webkit-' + decl.prop }); * // Will be executed only for color and z-index * }); */ }, { key: 'each', value: function each(callback) { if (!this.lastEach) this.lastEach = 0; if (!this.indexes) this.indexes = {}; this.lastEach += 1; var id = this.lastEach; this.indexes[id] = 0; if (!this.nodes) return undefined; var index = void 0, result = void 0; while (this.indexes[id] < this.nodes.length) { index = this.indexes[id]; result = callback(this.nodes[index], index); if (result === false) break; this.indexes[id] += 1; } delete this.indexes[id]; return result; } /** * Traverses the container’s descendant nodes, calling callback * for each node. * * Like container.each(), this method is safe to use * if you are mutating arrays during iteration. * * If you only need to iterate through the container’s immediate children, * use {@link Container#each}. * * @param {childIterator} callback - iterator receives each node and index * * @return {false|undefined} returns `false` if iteration was broke * * @example * root.walk(node => { * // Traverses all descendant nodes. * }); */ }, { key: 'walk', value: function walk(callback) { return this.each(function (child, i) { var result = callback(child, i); if (result !== false && child.walk) { result = child.walk(callback); } return result; }); } /** * Traverses the container’s descendant nodes, calling callback * for each declaration node. * * If you pass a filter, iteration will only happen over declarations * with matching properties. * * Like {@link Container#each}, this method is safe * to use if you are mutating arrays during iteration. * * @param {string|RegExp} [prop] - string or regular expression * to filter declarations by property name * @param {childIterator} callback - iterator receives each node and index * * @return {false|undefined} returns `false` if iteration was broke * * @example * root.walkDecls(decl => { * checkPropertySupport(decl.prop); * }); * * root.walkDecls('border-radius', decl => { * decl.remove(); * }); * * root.walkDecls(/^background/, decl => { * decl.value = takeFirstColorFromGradient(decl.value); * }); */ }, { key: 'walkDecls', value: function walkDecls(prop, callback) { if (!callback) { callback = prop; return this.walk(function (child, i) { if (child.type === 'decl') { return callback(child, i); } }); } else if (prop instanceof RegExp) { return this.walk(function (child, i) { if (child.type === 'decl' && prop.test(child.prop)) { return callback(child, i); } }); } else { return this.walk(function (child, i) { if (child.type === 'decl' && child.prop === prop) { return callback(child, i); } }); } } /** * Traverses the container’s descendant nodes, calling callback * for each rule node. * * If you pass a filter, iteration will only happen over rules * with matching selectors. * * Like {@link Container#each}, this method is safe * to use if you are mutating arrays during iteration. * * @param {string|RegExp} [selector] - string or regular expression * to filter rules by selector * @param {childIterator} callback - iterator receives each node and index * * @return {false|undefined} returns `false` if iteration was broke * * @example * const selectors = []; * root.walkRules(rule => { * selectors.push(rule.selector); * }); * console.log(`Your CSS uses ${selectors.length} selectors`); */ }, { key: 'walkRules', value: function walkRules(selector, callback) { if (!callback) { callback = selector; return this.walk(function (child, i) { if (child.type === 'rule') { return callback(child, i); } }); } else if (selector instanceof RegExp) { return this.walk(function (child, i) { if (child.type === 'rule' && selector.test(child.selector)) { return callback(child, i); } }); } else { return this.walk(function (child, i) { if (child.type === 'rule' && child.selector === selector) { return callback(child, i); } }); } } /** * Traverses the container’s descendant nodes, calling callback * for each at-rule node. * * If you pass a filter, iteration will only happen over at-rules * that have matching names. * * Like {@link Container#each}, this method is safe * to use if you are mutating arrays during iteration. * * @param {string|RegExp} [name] - string or regular expression * to filter at-rules by name * @param {childIterator} callback - iterator receives each node and index * * @return {false|undefined} returns `false` if iteration was broke * * @example * root.walkAtRules(rule => { * if ( isOld(rule.name) ) rule.remove(); * }); * * let first = false; * root.walkAtRules('charset', rule => { * if ( !first ) { * first = true; * } else { * rule.remove(); * } * }); */ }, { key: 'walkAtRules', value: function walkAtRules(name, callback) { if (!callback) { callback = name; return this.walk(function (child, i) { if (child.type === 'atrule') { return callback(child, i); } }); } else if (name instanceof RegExp) { return this.walk(function (child, i) { if (child.type === 'atrule' && name.test(child.name)) { return callback(child, i); } }); } else { return this.walk(function (child, i) { if (child.type === 'atrule' && child.name === name) { return callback(child, i); } }); } } /** * Traverses the container’s descendant nodes, calling callback * for each comment node. * * Like {@link Container#each}, this method is safe * to use if you are mutating arrays during iteration. * * @param {childIterator} callback - iterator receives each node and index * * @return {false|undefined} returns `false` if iteration was broke * * @example * root.walkComments(comment => { * comment.remove(); * }); */ }, { key: 'walkComments', value: function walkComments(callback) { return this.walk(function (child, i) { if (child.type === 'comment') { return callback(child, i); } }); } /** * Inserts new nodes to the start of the container. * * @param {...(Node|object|string|Node[])} children - new nodes * * @return {Node} this node for methods chain * * @example * const decl1 = postcss.decl({ prop: 'color', value: 'black' }); * const decl2 = postcss.decl({ prop: 'background-color', value: 'white' }); * rule.append(decl1, decl2); * * root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule * root.append({ selector: 'a' }); // rule * rule.append({ prop: 'color', value: 'black' }); // declaration * rule.append({ text: 'Comment' }) // comment * * root.append('a {}'); * root.first.append('color: black; z-index: 1'); */ }, { key: 'append', value: function append() { var _this2 = this; for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) { children[_key] = arguments[_key]; } children.forEach(function (child) { var nodes = _this2.normalize(child, _this2.last); nodes.forEach(function (node) { return _this2.nodes.push(node); }); }); return this; } /** * Inserts new nodes to the end of the container. * * @param {...(Node|object|string|Node[])} children - new nodes * * @return {Node} this node for methods chain * * @example * const decl1 = postcss.decl({ prop: 'color', value: 'black' }); * const decl2 = postcss.decl({ prop: 'background-color', value: 'white' }); * rule.prepend(decl1, decl2); * * root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule * root.append({ selector: 'a' }); // rule * rule.append({ prop: 'color', value: 'black' }); // declaration * rule.append({ text: 'Comment' }) // comment * * root.append('a {}'); * root.first.append('color: black; z-index: 1'); */ }, { key: 'prepend', value: function prepend() { var _this3 = this; for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { children[_key2] = arguments[_key2]; } children = children.reverse(); children.forEach(function (child) { var nodes = _this3.normalize(child, _this3.first, 'prepend').reverse(); nodes.forEach(function (node) { return _this3.nodes.unshift(node); }); for (var id in _this3.indexes) { _this3.indexes[id] = _this3.indexes[id] + nodes.length; } }); return this; } }, { key: 'cleanRaws', value: function cleanRaws(keepBetween) { get$1(Container.prototype.__proto__ || Object.getPrototypeOf(Container.prototype), 'cleanRaws', this).call(this, keepBetween); if (this.nodes) { this.nodes.forEach(function (node) { return node.cleanRaws(keepBetween); }); } } /** * Insert new node before old node within the container. * * @param {Node|number} exist - child or child’s index. * @param {Node|object|string|Node[]} add - new node * * @return {Node} this node for methods chain * * @example * rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop })); */ }, { key: 'insertBefore', value: function insertBefore(exist, add) { var _this4 = this; exist = this.index(exist); var type = exist === 0 ? 'prepend' : false; var nodes = this.normalize(add, this.nodes[exist], type).reverse(); nodes.forEach(function (node) { return _this4.nodes.splice(exist, 0, node); }); var index = void 0; for (var id in this.indexes) { index = this.indexes[id]; if (exist <= index) { this.indexes[id] = index + nodes.length; } } return this; } /** * Insert new node after old node within the container. * * @param {Node|number} exist - child or child’s index * @param {Node|object|string|Node[]} add - new node * * @return {Node} this node for methods chain */ }, { key: 'insertAfter', value: function insertAfter(exist, add) { var _this5 = this; exist = this.index(exist); var nodes = this.normalize(add, this.nodes[exist]).reverse(); nodes.forEach(function (node) { return _this5.nodes.splice(exist + 1, 0, node); }); var index = void 0; for (var id in this.indexes) { index = this.indexes[id]; if (exist < index) { this.indexes[id] = index + nodes.length; } } return this; } }, { key: 'remove', value: function remove(child) { if (typeof child !== 'undefined') { warnOnce('Container#remove is deprecated. ' + 'Use Container#removeChild'); this.removeChild(child); } else { get$1(Container.prototype.__proto__ || Object.getPrototypeOf(Container.prototype), 'remove', this).call(this); } return this; } /** * Removes node from the container and cleans the parent properties * from the node and its children. * * @param {Node|number} child - child or child’s index * * @return {Node} this node for methods chain * * @example * rule.nodes.length //=> 5 * rule.removeChild(decl); * rule.nodes.length //=> 4 * decl.parent //=> undefined */ }, { key: 'removeChild', value: function removeChild(child) { child = this.index(child); this.nodes[child].parent = undefined; this.nodes.splice(child, 1); var index = void 0; for (var id in this.indexes) { index = this.indexes[id]; if (index >= child) { this.indexes[id] = index - 1; } } return this; } /** * Removes all children from the container * and cleans their parent properties. * * @return {Node} this node for methods chain * * @example * rule.removeAll(); * rule.nodes.length //=> 0 */ }, { key: 'removeAll', value: function removeAll() { this.nodes.forEach(function (node) { return node.parent = undefined; }); this.nodes = []; return this; } /** * Passes all declaration values within the container that match pattern * through callback, replacing those values with the returned result * of callback. * * This method is useful if you are using a custom unit or function * and need to iterate through all values. * * @param {string|RegExp} pattern - replace pattern * @param {object} opts - options to speed up the search * @param {string|string[]} opts.props - an array of property names * @param {string} opts.fast - string that’s used * to narrow down values and speed up the regexp search * @param {function|string} callback - string to replace pattern * or callback that returns a new * value. * The callback will receive * the same arguments as those * passed to a function parameter * of `String#replace`. * * @return {Node} this node for methods chain * * @example * root.replaceValues(/\d+rem/, { fast: 'rem' }, string => { * return 15 * parseInt(string) + 'px'; * }); */ }, { key: 'replaceValues', value: function replaceValues(pattern, opts, callback) { if (!callback) { callback = opts; opts = {}; } this.walkDecls(function (decl) { if (opts.props && opts.props.indexOf(decl.prop) === -1) return; if (opts.fast && decl.value.indexOf(opts.fast) === -1) return; decl.value = decl.value.replace(pattern, callback); }); return this; } /** * Returns `true` if callback returns `true` * for all of the container’s children. * * @param {childCondition} condition - iterator returns true or false. * * @return {boolean} is every child pass condition * * @example * const noPrefixes = rule.every(i => i.prop[0] !== '-'); */ }, { key: 'every', value: function every(condition) { return this.nodes.every(condition); } /** * Returns `true` if callback returns `true` for (at least) one * of the container’s children. * * @param {childCondition} condition - iterator returns true or false. * * @return {boolean} is some child pass condition * * @example * const hasPrefix = rule.some(i => i.prop[0] === '-'); */ }, { key: 'some', value: function some(condition) { return this.nodes.some(condition); } /** * Returns a `child`’s index within the {@link Container#nodes} array. * * @param {Node} child - child of the current container. * * @return {number} child index * * @example * rule.index( rule.nodes[2] ) //=> 2 */ }, { key: 'index', value: function index(child) { if (typeof child === 'number') { return child; } else { return this.nodes.indexOf(child); } } /** * The container’s first child. * * @type {Node} * * @example * rule.first == rules.nodes[0]; */ }, { key: 'normalize', value: function normalize(nodes, sample) { var _this6 = this; if (typeof nodes === 'string') { nodes = cleanSource(parse(nodes).nodes); } else if (!Array.isArray(nodes)) { if (nodes.type === 'root') { nodes = nodes.nodes; } else if (nodes.type) { nodes = [nodes]; } else if (nodes.prop) { if (typeof nodes.value === 'undefined') { throw new Error('Value field is missed in node creation'); } else if (typeof nodes.value !== 'string') { nodes.value = String(nodes.value); } nodes = [new Declaration(nodes)]; } else if (nodes.selector) { nodes = [new Rule(nodes)]; } else if (nodes.name) { nodes = [new AtRule(nodes)]; } else if (nodes.text) { nodes = [new Comment(nodes)]; } else { throw new Error('Unknown node type in node creation'); } } var processed = nodes.map(function (i) { if (typeof i.raws === 'undefined') i = _this6.rebuild(i); if (i.parent) i = i.clone(); if (typeof i.raws.before === 'undefined') { if (sample && typeof sample.raws.before !== 'undefined') { i.raws.before = sample.raws.before.replace(/[^\s]/g, ''); } } i.parent = _this6; return i; }); return processed; } }, { key: 'rebuild', value: function rebuild(node, parent) { var _this7 = this; var fix = void 0; if (node.type === 'root') { fix = new Root(); } else if (node.type === 'atrule') { fix = new AtRule(); } else if (node.type === 'rule') { fix = new Rule(); } else if (node.type === 'decl') { fix = new Declaration(); } else if (node.type === 'comment') { fix = new Comment(); } for (var i in node) { if (i === 'nodes') { fix.nodes = node.nodes.map(function (j) { return _this7.rebuild(j, fix); }); } else if (i === 'parent' && parent) { fix.parent = parent; } else if (node.hasOwnProperty(i)) { fix[i] = node[i]; } } return fix; } }, { key: 'eachInside', value: function eachInside(callback) { warnOnce('Container#eachInside is deprecated. ' + 'Use Container#walk instead.'); return this.walk(callback); } }, { key: 'eachDecl', value: function eachDecl(prop, callback) { warnOnce('Container#eachDecl is deprecated. ' + 'Use Container#walkDecls instead.'); return this.walkDecls(prop, callback); } }, { key: 'eachRule', value: function eachRule(selector, callback) { warnOnce('Container#eachRule is deprecated. ' + 'Use Container#walkRules instead.'); return this.walkRules(selector, callback); } }, { key: 'eachAtRule', value: function eachAtRule(name, callback) { warnOnce('Container#eachAtRule is deprecated. ' + 'Use Container#walkAtRules instead.'); return this.walkAtRules(name, callback); } }, { key: 'eachComment', value: function eachComment(callback) { warnOnce('Container#eachComment is deprecated. ' + 'Use Container#walkComments instead.'); return this.walkComments(callback); } }, { key: 'first', get: function get() { if (!this.nodes) return undefined; return this.nodes[0]; } /** * The container’s last child. * * @type {Node} * * @example * rule.last == rule.nodes[rule.nodes.length - 1]; */ }, { key: 'last', get: function get() { if (!this.nodes) return undefined; return this.nodes[this.nodes.length - 1]; } }, { key: 'semicolon', get: function get() { warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon'); return this.raws.semicolon; }, set: function set(val) { warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon'); this.raws.semicolon = val; } }, { key: 'after', get: function get() { warnOnce('Node#after is deprecated. Use Node#raws.after'); return this.raws.after; }, set: function set(val) { warnOnce('Node#after is deprecated. Use Node#raws.after'); this.raws.after = val; } /** * @memberof Container# * @member {Node[]} nodes - an array containing the container’s children * * @example * const root = postcss.parse('a { color: black }'); * root.nodes.length //=> 1 * root.nodes[0].selector //=> 'a' * root.nodes[0].nodes[0].prop //=> 'color' */ }]); return Container; }(Node); /** * Represents an at-rule. * * If it’s followed in the CSS by a {} block, this node will have * a nodes property representing its children. * * @extends Container * * @example * const root = postcss.parse('@charset "UTF-8"; @media print {}'); * * const charset = root.first; * charset.type //=> 'atrule' * charset.nodes //=> undefined * * const media = root.last; * media.nodes //=> [] */ var AtRule = function (_Container) { inherits(AtRule, _Container); function AtRule(defaults$$1) { classCallCheck(this, AtRule); var _this = possibleConstructorReturn(this, (AtRule.__proto__ || Object.getPrototypeOf(AtRule)).call(this, defaults$$1)); _this.type = 'atrule'; return _this; } createClass(AtRule, [{ key: 'append', value: function append() { var _babelHelpers$get; if (!this.nodes) this.nodes = []; for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) { children[_key] = arguments[_key]; } return (_babelHelpers$get = get$1(AtRule.prototype.__proto__ || Object.getPrototypeOf(AtRule.prototype), 'append', this)).call.apply(_babelHelpers$get, [this].concat(children)); } }, { key: 'prepend', value: function prepend() { var _babelHelpers$get2; if (!this.nodes) this.nodes = []; for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { children[_key2] = arguments[_key2]; } return (_babelHelpers$get2 = get$1(AtRule.prototype.__proto__ || Object.getPrototypeOf(AtRule.prototype), 'prepend', this)).call.apply(_babelHelpers$get2, [this].concat(children)); } }, { key: 'afterName', get: function get() { warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName'); return this.raws.afterName; }, set: function set(val) { warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName'); this.raws.afterName = val; } }, { key: '_params', get: function get() { warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params'); return this.raws.params; }, set: function set(val) { warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params'); this.raws.params = val; } /** * @memberof AtRule# * @member {string} name - the at-rule’s name immediately follows the `@` * * @example * const root = postcss.parse('@media print {}'); * media.name //=> 'media' * const media = root.first; */ /** * @memberof AtRule# * @member {string} params - the at-rule’s parameters, the values * that follow the at-rule’s name but precede * any {} block * * @example * const root = postcss.parse('@media print, screen {}'); * const media = root.first; * media.params //=> 'print, screen' */ /** * @memberof AtRule# * @member {object} raws - Information to generate byte-to-byte equal * node string as it was in the origin input. * * Every parser saves its own properties, * but the default CSS parser uses: * * * `before`: the space symbols before the node. It also stores `*` * and `_` symbols before the declaration (IE hack). * * `after`: the space symbols after the last child of the node * to the end of the node. * * `between`: the symbols between the property and value * for declarations, selector and `{` for rules, or last parameter * and `{` for at-rules. * * `semicolon`: contains true if the last child has * an (optional) semicolon. * * `afterName`: the space between the at-rule name and its parameters. * * PostCSS cleans at-rule parameters from comments and extra spaces, * but it stores origin content in raws properties. * As such, if you don’t change a declaration’s value, * PostCSS will use the raw value with comments. * * @example * const root = postcss.parse(' @media\nprint {\n}') * root.first.first.raws //=> { before: ' ', * // between: ' ', * // afterName: '\n', * // after: '\n' } */ }]); return AtRule; }(Container); /** * Contains helpers for safely splitting lists of CSS values, * preserving parentheses and quotes. * * @example * const list = postcss.list; * * @namespace list */ var list = { split: function split(string, separators, last) { var array = []; var current = ''; var split = false; var func = 0; var quote = false; var escape = false; for (var i = 0; i < string.length; i++) { var letter = string[i]; if (quote) { if (escape) { escape = false; } else if (letter === '\\') { escape = true; } else if (letter === quote) { quote = false; } } else if (letter === '"' || letter === '\'') { quote = letter; } else if (letter === '(') { func += 1; } else if (letter === ')') { if (func > 0) func -= 1; } else if (func === 0) { if (separators.indexOf(letter) !== -1) split = true; } if (split) { if (current !== '') array.push(current.trim()); current = ''; split = false; } else { current += letter; } } if (last || current !== '') array.push(current.trim()); return array; }, /** * Safely splits space-separated values (such as those for `background`, * `border-radius`, and other shorthand properties). * * @param {string} string - space-separated values * * @return {string[]} splitted values * * @example * postcss.list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)'] */ space: function space(string) { var spaces = [' ', '\n', '\t']; return list.split(string, spaces); }, /** * Safely splits comma-separated values (such as those for `transition-*` * and `background` properties). * * @param {string} string - comma-separated values * * @return {string[]} splitted values * * @example * postcss.list.comma('black, linear-gradient(white, black)') * //=> ['black', 'linear-gradient(white, black)'] */ comma: function comma(string) { var comma = ','; return list.split(string, [comma], true); } }; /** * Represents a CSS rule: a selector followed by a declaration block. * * @extends Container * * @example * const root = postcss.parse('a{}'); * const rule = root.first; * rule.type //=> 'rule' * rule.toString() //=> 'a{}' */ var Rule = function (_Container) { inherits(Rule, _Container); function Rule(defaults$$1) { classCallCheck(this, Rule); var _this = possibleConstructorReturn(this, (Rule.__proto__ || Object.getPrototypeOf(Rule)).call(this, defaults$$1)); _this.type = 'rule'; if (!_this.nodes) _this.nodes = []; return _this; } /** * An array containing the rule’s individual selectors. * Groups of selectors are split at commas. * * @type {string[]} * * @example * const root = postcss.parse('a, b { }'); * const rule = root.first; * * rule.selector //=> 'a, b' * rule.selectors //=> ['a', 'b'] * * rule.selectors = ['a', 'strong']; * rule.selector //=> 'a, strong' */ createClass(Rule, [{ key: 'selectors', get: function get() { return list.comma(this.selector); }, set: function set(values) { var match = this.selector ? this.selector.match(/,\s*/) : null; var sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen'); this.selector = values.join(sep); } }, { key: '_selector', get: function get() { warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector'); return this.raws.selector; }, set: function set(val) { warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector'); this.raws.selector = val; } /** * @memberof Rule# * @member {string} selector - the rule’s full selector represented * as a string * * @example * const root = postcss.parse('a, b { }'); * const rule = root.first; * rule.selector //=> 'a, b' */ /** * @memberof Rule# * @member {object} raws - Information to generate byte-to-byte equal * node string as it was in the origin input. * * Every parser saves its own properties, * but the default CSS parser uses: * * * `before`: the space symbols before the node. It also stores `*` * and `_` symbols before the declaration (IE hack). * * `after`: the space symbols after the last child of the node * to the end of the node. * * `between`: the symbols between the property and value * for declarations, selector and `{` for rules, or last parameter * and `{` for at-rules. * * `semicolon`: contains true if the last child has * an (optional) semicolon. * * PostCSS cleans selectors from comments and extra spaces, * but it stores origin content in raws properties. * As such, if you don’t change a declaration’s value, * PostCSS will use the raw value with comments. * * @example * const root = postcss.parse('a {\n color:black\n}') * root.first.first.raws //=> { before: '', between: ' ', after: '\n' } */ }]); return Rule; }(Container); /** * Represents a plugin’s warning. It can be created using {@link Node#warn}. * * @example * if ( decl.important ) { * decl.warn(result, 'Avoid !important', { word: '!important' }); * } */ var Warning = function () { /** * @param {string} text - warning message * @param {Object} [opts] - warning options * @param {Node} opts.node - CSS node that caused the warning * @param {string} opts.word - word in CSS source that caused the warning * @param {number} opts.index - index in CSS node string that caused * the warning * @param {string} opts.plugin - name of the plugin that created * this warning. {@link Result#warn} fills * this property automatically. */ function Warning(text) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; classCallCheck(this, Warning); /** * @member {string} - Type to filter warnings from * {@link Result#messages}. Always equal * to `"warning"`. * * @example * const nonWarning = result.messages.filter(i => i.type !== 'warning') */ this.type = 'warning'; /** * @member {string} - The warning message. * * @example * warning.text //=> 'Try to avoid !important' */ this.text = text; if (opts.node && opts.node.source) { var pos = opts.node.positionBy(opts); /** * @member {number} - Line in the input file * with this warning’s source * * @example * warning.line //=> 5 */ this.line = pos.line; /** * @member {number} - Column in the input file * with this warning’s source. * * @example * warning.column //=> 6 */ this.column = pos.column; } for (var opt in opts) { this[opt] = opts[opt]; } } /** * Returns a warning position and message. * * @example * warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important' * * @return {string} warning position and message */ createClass(Warning, [{ key: 'toString', value: function toString() { if (this.node) { return this.node.error(this.text, { plugin: this.plugin, index: this.index, word: this.word }).message; } else if (this.plugin) { return this.plugin + ': ' + this.text; } else { return this.text; } } /** * @memberof Warning# * @member {string} plugin - The name of the plugin that created * it will fill this property automatically. * this warning. When you call {@link Node#warn} * * @example * warning.plugin //=> 'postcss-important' */ /** * @memberof Warning# * @member {Node} node - Contains the CSS node that caused the warning. * * @example * warning.node.toString() //=> 'color: white !important' */ }]); return Warning; }(); /** * @typedef {object} Message * @property {string} type - message type * @property {string} plugin - source PostCSS plugin name */ /** * Provides the result of the PostCSS transformations. * * A Result instance is returned by {@link LazyResult#then} * or {@link Root#toResult} methods. * * @example * postcss([cssnext]).process(css).then(function (result) { * console.log(result.css); * }); * * @example * var result2 = postcss.parse(css).toResult(); */ var Result = function () { /** * @param {Processor} processor - processor used for this transformation. * @param {Root} root - Root node after all transformations. * @param {processOptions} opts - options from the {@link Processor#process} * or {@link Root#toResult} */ function Result(processor, root, opts) { classCallCheck(this, Result); /** * @member {Processor} - The Processor instance used * for this transformation. * * @example * for ( let plugin of result.processor.plugins) { * if ( plugin.postcssPlugin === 'postcss-bad' ) { * throw 'postcss-good is incompatible with postcss-bad'; * } * }); */ this.processor = processor; /** * @member {Message[]} - Contains messages from plugins * (e.g., warnings or custom messages). * Each message should have type * and plugin properties. * * @example * postcss.plugin('postcss-min-browser', () => { * return (root, result) => { * var browsers = detectMinBrowsersByCanIUse(root); * result.messages.push({ * type: 'min-browser', * plugin: 'postcss-min-browser', * browsers: browsers * }); * }; * }); */ this.messages = []; /** * @member {Root} - Root node after all transformations. * * @example * root.toResult().root == root; */ this.root = root; /** * @member {processOptions} - Options from the {@link Processor#process} * or {@link Root#toResult} call * that produced this Result instance. * * @example * root.toResult(opts).opts == opts; */ this.opts = opts; /** * @member {string} - A CSS string representing of {@link Result#root}. * * @example * postcss.parse('a{}').toResult().css //=> "a{}" */ this.css = undefined; /** * @member {SourceMapGenerator} - An instance of `SourceMapGenerator` * class from the `source-map` library, * representing changes * to the {@link Result#root} instance. * * @example * result.map.toJSON() //=> { version: 3, file: 'a.css', … } * * @example * if ( result.map ) { * fs.writeFileSync(result.opts.to + '.map', result.map.toString()); * } */ this.map = undefined; } /** * Returns for @{link Result#css} content. * * @example * result + '' === result.css * * @return {string} string representing of {@link Result#root} */ createClass(Result, [{ key: 'toString', value: function toString() { return this.css; } /** * Creates an instance of {@link Warning} and adds it * to {@link Result#messages}. * * @param {string} text - warning message * @param {Object} [opts] - warning options * @param {Node} opts.node - CSS node that caused the warning * @param {string} opts.word - word in CSS source that caused the warning * @param {number} opts.index - index in CSS node string that caused * the warning * @param {string} opts.plugin - name of the plugin that created * this warning. {@link Result#warn} fills * this property automatically. * * @return {Warning} created warning */ }, { key: 'warn', value: function warn(text) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (!opts.plugin) { if (this.lastPlugin && this.lastPlugin.postcssPlugin) { opts.plugin = this.lastPlugin.postcssPlugin; } } var warning = new Warning(text, opts); this.messages.push(warning); return warning; } /** * Returns warnings from plugins. Filters {@link Warning} instances * from {@link Result#messages}. * * @example * result.warnings().forEach(warn => { * console.warn(warn.toString()); * }); * * @return {Warning[]} warnings from plugins */ }, { key: 'warnings', value: function warnings() { return this.messages.filter(function (i) { return i.type === 'warning'; }); } /** * An alias for the {@link Result#css} property. * Use it with syntaxes that generate non-CSS output. * @type {string} * * @example * result.css === result.content; */ }, { key: 'content', get: function get() { return this.css; } }]); return Result; }(); function isPromise(obj) { return (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && typeof obj.then === 'function'; } /** * @callback onFulfilled * @param {Result} result */ /** * @callback onRejected * @param {Error} error */ /** * A Promise proxy for the result of PostCSS transformations. * * A `LazyResult` instance is returned by {@link Processor#process}. * * @example * const lazy = postcss([cssnext]).process(css); */ var LazyResult = function () { function LazyResult(processor, css, opts) { classCallCheck(this, LazyResult); this.stringified = false; this.processed = false; var root = void 0; if ((typeof css === 'undefined' ? 'undefined' : _typeof(css)) === 'object' && css.type === 'root') { root = css; } else if (css instanceof LazyResult || css instanceof Result) { root = css.root; if (css.map) { if (typeof opts.map === 'undefined') opts.map = {}; if (!opts.map.inline) opts.map.inline = false; opts.map.prev = css.map; } } else { var parser = parse; if (opts.syntax) parser = opts.syntax.parse; if (opts.parser) parser = opts.parser; if (parser.parse) parser = parser.parse; try { root = parser(css, opts); } catch (error) { this.error = error; } } this.result = new Result(processor, root, opts); } /** * Returns a {@link Processor} instance, which will be used * for CSS transformations. * @type {Processor} */ createClass(LazyResult, [{ key: 'warnings', /** * Processes input CSS through synchronous plugins * and calls {@link Result#warnings()}. * * @return {Warning[]} warnings from plugins */ value: function warnings() { return this.sync().warnings(); } /** * Alias for the {@link LazyResult#css} property. * * @example * lazy + '' === lazy.css; * * @return {string} output CSS */ }, { key: 'toString', value: function toString() { return this.css; } /** * Processes input CSS through synchronous and asynchronous plugins * and calls `onFulfilled` with a Result instance. If a plugin throws * an error, the `onRejected` callback will be executed. * * It implements standard Promise API. * * @param {onFulfilled} onFulfilled - callback will be executed * when all plugins will finish work * @param {onRejected} onRejected - callback will be execited on any error * * @return {Promise} Promise API to make queue * * @example * postcss([cssnext]).process(css).then(result => { * console.log(result.css); * }); */ }, { key: 'then', value: function then(onFulfilled, onRejected) { return this.async().then(onFulfilled, onRejected); } /** * Processes input CSS through synchronous and asynchronous plugins * and calls onRejected for each error thrown in any plugin. * * It implements standard Promise API. * * @param {onRejected} onRejected - callback will be execited on any error * * @return {Promise} Promise API to make queue * * @example * postcss([cssnext]).process(css).then(result => { * console.log(result.css); * }).catch(error => { * console.error(error); * }); */ }, { key: 'catch', value: function _catch(onRejected) { return this.async().catch(onRejected); } }, { key: 'handleError', value: function handleError(error, plugin) { try { this.error = error; if (error.name === 'CssSyntaxError' && !error.plugin) { error.plugin = plugin.postcssPlugin; error.setMessage(); } else if (plugin.postcssVersion) { var pluginName = plugin.postcssPlugin; var pluginVer = plugin.postcssVersion; var runtimeVer = this.result.processor.version; var a = pluginVer.split('.'); var b = runtimeVer.split('.'); if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) { warnOnce('Your current PostCSS version ' + 'is ' + runtimeVer + ', but ' + pluginName + ' ' + 'uses ' + pluginVer + '. Perhaps this is ' + 'the source of the error below.'); } } } catch (err) { if (console && console.error) console.error(err); } } }, { key: 'asyncTick', value: function asyncTick(resolve, reject) { var _this = this; if (this.plugin >= this.processor.plugins.length) { this.processed = true; return resolve(); } try { (function () { var plugin = _this.processor.plugins[_this.plugin]; var promise = _this.run(plugin); _this.plugin += 1; if (isPromise(promise)) { promise.then(function () { _this.asyncTick(resolve, reject); }).catch(function (error) { _this.handleError(error, plugin); _this.processed = true; reject(error); }); } else { _this.asyncTick(resolve, reject); } })(); } catch (error) { this.processed = true; reject(error); } } }, { key: 'async', value: function async() { var _this2 = this; if (this.processed) { return new Promise(function (resolve, reject) { if (_this2.error) { reject(_this2.error); } else { resolve(_this2.stringify()); } }); } if (this.processing) { return this.processing; } this.processing = new Promise(function (resolve, reject) { if (_this2.error) return reject(_this2.error); _this2.plugin = 0; _this2.asyncTick(resolve, reject); }).then(function () { _this2.processed = true; return _this2.stringify(); }); return this.processing; } }, { key: 'sync', value: function sync() { var _this3 = this; if (this.processed) return this.result; this.processed = true; if (this.processing) { throw new Error('Use process(css).then(cb) to work with async plugins'); } if (this.error) throw this.error; this.result.processor.plugins.forEach(function (plugin) { var promise = _this3.run(plugin); if (isPromise(promise)) { throw new Error('Use process(css).then(cb) to work with async plugins'); } }); return this.result; } }, { key: 'run', value: function run(plugin) { this.result.lastPlugin = plugin; try { return plugin(this.result.root, this.result); } catch (error) { this.handleError(error, plugin); throw error; } } }, { key: 'stringify', value: function stringify() { if (this.stringified) return this.result; this.stringified = true; this.sync(); var opts = this.result.opts; var str = stringify$1; if (opts.syntax) str = opts.syntax.stringify; if (opts.stringifier) str = opts.stringifier; if (str.stringify) str = str.stringify; var result = ''; str(this.root, function (i) { result += i; }); this.result.css = result; return this.result; } }, { key: 'processor', get: function get() { return this.result.processor; } /** * Options from the {@link Processor#process} call. * @type {processOptions} */ }, { key: 'opts', get: function get() { return this.result.opts; } /** * Processes input CSS through synchronous plugins, converts `Root` * to a CSS string and returns {@link Result#css}. * * This property will only work with synchronous plugins. * If the processor contains any asynchronous plugins * it will throw an error. This is why this method is only * for debug purpose, you should always use {@link LazyResult#then}. * * @type {string} * @see Result#css */ }, { key: 'css', get: function get() { return this.stringify().css; } /** * An alias for the `css` property. Use it with syntaxes * that generate non-CSS output. * * This property will only work with synchronous plugins. * If the processor contains any asynchronous plugins * it will throw an error. This is why this method is only * for debug purpose, you should always use {@link LazyResult#then}. * * @type {string} * @see Result#content */ }, { key: 'content', get: function get() { return this.stringify().content; } /** * Processes input CSS through synchronous plugins * and returns {@link Result#map}. * * This property will only work with synchronous plugins. * If the processor contains any asynchronous plugins * it will throw an error. This is why this method is only * for debug purpose, you should always use {@link LazyResult#then}. * * @type {SourceMapGenerator} * @see Result#map */ }, { key: 'map', get: function get() { return this.stringify().map; } /** * Processes input CSS through synchronous plugins * and returns {@link Result#root}. * * This property will only work with synchronous plugins. If the processor * contains any asynchronous plugins it will throw an error. * * This is why this method is only for debug purpose, * you should always use {@link LazyResult#then}. * * @type {Root} * @see Result#root */ }, { key: 'root', get: function get() { return this.sync().root; } /** * Processes input CSS through synchronous plugins * and returns {@link Result#messages}. * * This property will only work with synchronous plugins. If the processor * contains any asynchronous plugins it will throw an error. * * This is why this method is only for debug purpose, * you should always use {@link LazyResult#then}. * * @type {Message[]} * @see Result#messages */ }, { key: 'messages', get: function get() { return this.sync().messages; } }]); return LazyResult; }(); /** * @callback builder * @param {string} part - part of generated CSS connected to this node * @param {Node} node - AST node * @param {"start"|"end"} [type] - node’s part type */ /** * @callback parser * * @param {string|toString} css - string with input CSS or any object * with toString() method, like a Buffer * @param {processOptions} [opts] - options with only `from` and `map` keys * * @return {Root} PostCSS AST */ /** * @callback stringifier * * @param {Node} node - start node for stringifing. Usually {@link Root}. * @param {builder} builder - function to concatenate CSS from node’s parts * or generate string and source map * * @return {void} */ /** * @typedef {object} syntax * @property {parser} parse - function to generate AST by string * @property {stringifier} stringify - function to generate string by AST */ /** * @typedef {object} toString * @property {function} toString */ /** * @callback pluginFunction * @param {Root} root - parsed input CSS * @param {Result} result - result to set warnings or check other plugins */ /** * @typedef {object} Plugin * @property {function} postcss - PostCSS plugin function */ /** * @typedef {object} processOptions * @property {string} from - the path of the CSS source file. * You should always set `from`, * because it is used in source map * generation and syntax error messages. * @property {string} to - the path where you’ll put the output * CSS file. You should always set `to` * to generate correct source maps. * @property {parser} parser - function to generate AST by string * @property {stringifier} stringifier - class to generate string by AST * @property {syntax} syntax - object with `parse` and `stringify` * @property {object} map - source map options * @property {boolean} map.inline - does source map should * be embedded in the output * CSS as a base64-encoded * comment * @property {string|object|false|function} map.prev - source map content * from a previous * processing step * (for example, Sass). * PostCSS will try to find * previous map * automatically, so you * could disable it by * `false` value. * @property {boolean} map.sourcesContent - does PostCSS should set * the origin content to map * @property {string|false} map.annotation - does PostCSS should set * annotation comment to map * @property {string} map.from - override `from` in map’s * `sources` */ /** * Contains plugins to process CSS. Create one `Processor` instance, * initialize its plugins, and then use that instance on numerous CSS files. * * @example * const processor = postcss([autoprefixer, precss]); * processor.process(css1).then(result => console.log(result.css)); * processor.process(css2).then(result => console.log(result.css)); */ var Processor = function () { /** * @param {Array.<Plugin|pluginFunction>|Processor} plugins - PostCSS * plugins. See {@link Processor#use} for plugin format. */ function Processor() { var plugins = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; classCallCheck(this, Processor); /** * @member {string} - Current PostCSS version. * * @example * if ( result.processor.version.split('.')[0] !== '5' ) { * throw new Error('This plugin works only with PostCSS 5'); * } */ this.version = '5.2.0'; /** * @member {pluginFunction[]} - Plugins added to this processor. * * @example * const processor = postcss([autoprefixer, precss]); * processor.plugins.length //=> 2 */ this.plugins = this.normalize(plugins); } /** * Adds a plugin to be used as a CSS processor. * * PostCSS plugin can be in 4 formats: * * A plugin created by {@link postcss.plugin} method. * * A function. PostCSS will pass the function a @{link Root} * as the first argument and current {@link Result} instance * as the second. * * An object with a `postcss` method. PostCSS will use that method * as described in #2. * * Another {@link Processor} instance. PostCSS will copy plugins * from that instance into this one. * * Plugins can also be added by passing them as arguments when creating * a `postcss` instance (see [`postcss(plugins)`]). * * Asynchronous plugins should return a `Promise` instance. * * @param {Plugin|pluginFunction|Processor} plugin - PostCSS plugin * or {@link Processor} * with plugins * * @example * const processor = postcss() * .use(autoprefixer) * .use(precss); * * @return {Processes} current processor to make methods chain */ createClass(Processor, [{ key: 'use', value: function use(plugin) { this.plugins = this.plugins.concat(this.normalize([plugin])); return this; } /** * Parses source CSS and returns a {@link LazyResult} Promise proxy. * Because some plugins can be asynchronous it doesn’t make * any transformations. Transformations will be applied * in the {@link LazyResult} methods. * * @param {string|toString|Result} css - String with input CSS or * any object with a `toString()` * method, like a Buffer. * Optionally, send a {@link Result} * instance and the processor will * take the {@link Root} from it. * @param {processOptions} [opts] - options * * @return {LazyResult} Promise proxy * * @example * processor.process(css, { from: 'a.css', to: 'a.out.css' }) * .then(result => { * console.log(result.css); * }); */ }, { key: 'process', value: function process(css) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; return new LazyResult(this, css, opts); } }, { key: 'normalize', value: function normalize(plugins) { var normalized = []; plugins.forEach(function (i) { if (i.postcss) i = i.postcss; if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && Array.isArray(i.plugins)) { normalized = normalized.concat(i.plugins); } else if (typeof i === 'function') { normalized.push(i); } else { throw new Error(i + ' is not a PostCSS plugin'); } }); return normalized; } }]); return Processor; }(); /** * Represents a CSS file and contains all its parsed nodes. * * @extends Container * * @example * const root = postcss.parse('a{color:black} b{z-index:2}'); * root.type //=> 'root' * root.nodes.length //=> 2 */ var Root = function (_Container) { inherits(Root, _Container); function Root(defaults$$1) { classCallCheck(this, Root); var _this = possibleConstructorReturn(this, (Root.__proto__ || Object.getPrototypeOf(Root)).call(this, defaults$$1)); _this.type = 'root'; if (!_this.nodes) _this.nodes = []; return _this; } createClass(Root, [{ key: 'removeChild', value: function removeChild(child) { child = this.index(child); if (child === 0 && this.nodes.length > 1) { this.nodes[1].raws.before = this.nodes[child].raws.before; } return get$1(Root.prototype.__proto__ || Object.getPrototypeOf(Root.prototype), 'removeChild', this).call(this, child); } }, { key: 'normalize', value: function normalize(child, sample, type) { var nodes = get$1(Root.prototype.__proto__ || Object.getPrototypeOf(Root.prototype), 'normalize', this).call(this, child); if (sample) { if (type === 'prepend') { if (this.nodes.length > 1) { sample.raws.before = this.nodes[1].raws.before; } else { delete sample.raws.before; } } else if (this.first !== sample) { nodes.forEach(function (node) { node.raws.before = sample.raws.before; }); } } return nodes; } /** * Returns a {@link Result} instance representing the root’s CSS. * * @param {processOptions} [opts] - options with only `to` and `map` keys * * @return {Result} result with current root’s CSS * * @example * const root1 = postcss.parse(css1, { from: 'a.css' }); * const root2 = postcss.parse(css2, { from: 'b.css' }); * root1.append(root2); * const result = root1.toResult({ to: 'all.css', map: true }); */ }, { key: 'toResult', value: function toResult() { var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var lazy = new LazyResult(new Processor(), this, opts); return lazy.stringify(); } }, { key: 'remove', value: function remove(child) { warnOnce('Root#remove is deprecated. Use Root#removeChild'); this.removeChild(child); } }, { key: 'prevMap', value: function prevMap() { warnOnce('Root#prevMap is deprecated. Use Root#source.input.map'); return this.source.input.map; } /** * @memberof Root# * @member {object} raws - Information to generate byte-to-byte equal * node string as it was in the origin input. * * Every parser saves its own properties, * but the default CSS parser uses: * * * `after`: the space symbols after the last child to the end of file. * * `semicolon`: is the last child has an (optional) semicolon. * * @example * postcss.parse('a {}\n').raws //=> { after: '\n' } * postcss.parse('a {}').raws //=> { after: '' } */ }]); return Root; }(Container); // import PreviousMap from './previous-map'; var sequence = 0; /** * @typedef {object} filePosition * @property {string} file - path to file * @property {number} line - source line in file * @property {number} column - source column in file */ /** * Represents the source CSS. * * @example * const root = postcss.parse(css, { from: file }); * const input = root.source.input; */ var Input = function () { /** * @param {string} css - input CSS source * @param {object} [opts] - {@link Processor#process} options */ function Input(css) { var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; classCallCheck(this, Input); /** * @member {string} - input CSS source * * @example * const input = postcss.parse('a{}', { from: file }).input; * input.css //=> "a{}"; */ this.css = css.toString(); if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') { this.css = this.css.slice(1); } if (opts.from) { if (/^\w+:\/\//.test(opts.from)) { /** * @member {string} - The absolute path to the CSS source file * defined with the `from` option. * * @example * const root = postcss.parse(css, { from: 'a.css' }); * root.source.input.file //=> '/home/ai/a.css' */ this.file = opts.from; } else { this.file = path.resolve(opts.from); } } /* let map = new PreviousMap(this.css, opts); if ( map.text ) { /!** * @member {PreviousMap} - The input source map passed from * a compilation step before PostCSS * (for example, from Sass compiler). * * @example * root.source.input.map.consumer().sources //=> ['a.sass'] *!/ this.map = map; let file = map.consumer().file; if ( !this.file && file ) this.file = this.mapResolve(file); } */ if (!this.file) { sequence += 1; /** * @member {string} - The unique ID of the CSS source. It will be * created if `from` option is not provided * (because PostCSS does not know the file path). * * @example * const root = postcss.parse(css); * root.source.input.file //=> undefined * root.source.input.id //=> "<input css 1>" */ this.id = '<input css ' + sequence + '>'; } if (this.map) this.map.file = this.from; } createClass(Input, [{ key: 'error', value: function error(message, line, column) { var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; var result = void 0; var origin = this.origin(line, column); if (origin) { result = new CssSyntaxError(message, origin.line, origin.column, origin.source, origin.file, opts.plugin); } else { result = new CssSyntaxError(message, line, column, this.css, this.file, opts.plugin); } result.input = { line: line, column: column, source: this.css }; if (this.file) result.input.file = this.file; return result; } /** * Reads the input source map and returns a symbol position * in the input source (e.g., in a Sass file that was compiled * to CSS before being passed to PostCSS). * * @param {number} line - line in input CSS * @param {number} column - column in input CSS * * @return {filePosition} position in input source * * @example * root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 } */ }, { key: 'origin', value: function origin(line, column) { if (!this.map) return false; var consumer = this.map.consumer(); var from = consumer.originalPositionFor({ line: line, column: column }); if (!from.source) return false; var result = { file: this.mapResolve(from.source), line: from.line, column: from.column }; var source = consumer.sourceContentFor(from.source); if (source) result.source = source; return result; } }, { key: 'mapResolve', value: function mapResolve(file) { if (/^\w+:\/\//.test(file)) { return file; } else { return path.resolve(this.map.consumer().sourceRoot || '.', file); } } /** * The CSS source identifier. Contains {@link Input#file} if the user * set the `from` option, or {@link Input#id} if they did not. * @type {string} * * @example * const root = postcss.parse(css, { from: 'a.css' }); * root.source.input.from //=> "/home/ai/a.css" * * const root = postcss.parse(css); * root.source.input.from //=> "<input css 1>" */ }, { key: 'from', get: function get() { return this.file || this.id; } }]); return Input; }(); var SafeParser = function (_Parser) { inherits(SafeParser, _Parser); function SafeParser() { classCallCheck(this, SafeParser); return possibleConstructorReturn(this, (SafeParser.__proto__ || Object.getPrototypeOf(SafeParser)).apply(this, arguments)); } createClass(SafeParser, [{ key: 'tokenize', value: function tokenize() { this.tokens = tokenize$1(this.input, { ignoreErrors: true }); } }, { key: 'comment', value: function comment(token) { var node = new Comment(); this.init(node, token[2], token[3]); node.source.end = { line: token[4], column: token[5] }; var text = token[1].slice(2); if (text.slice(-2) === '*/') text = text.slice(0, -2); if (/^\s*$/.test(text)) { node.text = ''; node.raws.left = text; node.raws.right = ''; } else { var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/); node.text = match[2]; node.raws.left = match[1]; node.raws.right = match[3]; } } }, { key: 'unclosedBracket', value: function unclosedBracket() {} }, { key: 'unknownWord', value: function unknownWord(start) { var buffer = this.tokens.slice(start, this.pos + 1); this.spaces += buffer.map(function (i) { return i[1]; }).join(''); } }, { key: 'unexpectedClose', value: function unexpectedClose() { this.current.raws.after += '}'; } }, { key: 'doubleColon', value: function doubleColon() {} }, { key: 'unnamedAtrule', value: function unnamedAtrule(node) { node.name = ''; } }, { key: 'precheckMissedSemicolon', value: function precheckMissedSemicolon(tokens) { var colon = this.colon(tokens); if (colon === false) return; var split = void 0; for (split = colon - 1; split >= 0; split--) { if (tokens[split][0] === 'word') break; } for (split -= 1; split >= 0; split--) { if (tokens[split][0] !== 'space') { split += 1; break; } } var other = tokens.splice(split, tokens.length - split); this.decl(other); } }, { key: 'checkMissedSemicolon', value: function checkMissedSemicolon() {} }, { key: 'endFile', value: function endFile() { if (this.current.nodes && this.current.nodes.length) { this.current.raws.semicolon = this.semicolon; } this.current.raws.after = (this.current.raws.after || '') + this.spaces; while (this.current.parent) { this.current = this.current.parent; this.current.raws.after = ''; } } }]); return SafeParser; }(Parser); function safeParse(css, opts) { var input = new Input(css, opts); var parser = new SafeParser(input); parser.tokenize(); parser.loop(); return parser.root; } function selectors(parent, node) { var result = []; parent.selectors.forEach(function (i) { node.selectors.forEach(function (j) { if (j.indexOf('&') === -1) { result.push(i + ' ' + j); } else { result.push(j.replace(/&/g, i)); } }); }); return result; } function pickComment(comment, after) { if (comment && comment.type === 'comment') { return comment.moveAfter(after); } else { return after; } } function atruleChilds(rule, atrule) { var children = []; atrule.each(function (child) { if (child.type === 'comment') { children.push(child); } if (child.type === 'decl') { children.push(child); } else if (child.type === 'rule') { child.selectors = selectors(rule, child); } else if (child.type === 'atrule') { atruleChilds(rule, child); } }); if (children.length) { var clone = rule.clone({ nodes: [] }); for (var i = 0; i < children.length; i++) { children[i].moveTo(clone); }atrule.prepend(clone); } } function processRule(rule, bubble) { var unwrapped = false; var after = rule; rule.each(function (child) { if (child.type === 'rule') { unwrapped = true; child.selectors = selectors(rule, child); after = pickComment(child.prev(), after); after = child.moveAfter(after); } else if (child.type === 'atrule') { if (bubble.indexOf(child.name) !== -1) { unwrapped = true; atruleChilds(rule, child); after = pickComment(child.prev(), after); after = child.moveAfter(after); } } }); if (unwrapped) { rule.raws.semicolon = true; if (rule.nodes.length === 0) rule.remove(); } } var bubble = ['media', 'supports', 'document']; var process$2 = function process$2(node) { node.each(function (child) { if (child.type === 'rule') { processRule(child, bubble); } else if (child.type === 'atrule') { process$2(child); } }); }; /* high performance StyleSheet for css-in-js systems - uses multiple style tags behind the scenes for millions of rules - uses `insertRule` for appending in production for *much* faster performance - 'polyfills' on server side // usage import StyleSheet from 'glamor/lib/sheet' let styleSheet = new StyleSheet() styleSheet.inject() - 'injects' the stylesheet into the page (or into memory if on server) styleSheet.insert('#box { border: 1px solid red; }') - appends a css rule into the stylesheet styleSheet.flush() - empties the stylesheet of all its contents */ function last(arr) { return arr[arr.length - 1]; } function sheetForTag(tag) { for (var i = 0; i < document.styleSheets.length; i++) { if (document.styleSheets[i].ownerNode === tag) { return document.styleSheets[i]; } } } var isBrowser = typeof document !== 'undefined'; var isDev = function (x) { return x === 'development' || !x; }("development"); var isTest = "development" === 'test'; var oldIE = function () { if (isBrowser) { var div = document.createElement('div'); div.innerHTML = '<!--[if lt IE 10]><i></i><![endif]-->'; return div.getElementsByTagName('i').length === 1; } }(); function makeStyleTag() { var tag = document.createElement('style'); tag.type = 'text/css'; tag.appendChild(document.createTextNode('')); (document.head || document.getElementsByTagName('head')[0]).appendChild(tag); return tag; } var StyleSheet = function () { function StyleSheet() { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, _ref$speedy = _ref.speedy, speedy = _ref$speedy === undefined ? !isDev && !isTest : _ref$speedy, _ref$maxLength = _ref.maxLength, maxLength = _ref$maxLength === undefined ? isBrowser && oldIE ? 4000 : 65000 : _ref$maxLength; classCallCheck(this, StyleSheet); this.isSpeedy = speedy; // the big drawback here is that the css won't be editable in devtools this.sheet = undefined; this.tags = []; this.maxLength = maxLength; this.ctr = 0; } createClass(StyleSheet, [{ key: 'inject', value: function inject() { var _this = this; if (this.injected) { throw new Error('already injected stylesheet!'); } if (isBrowser) { // this section is just weird alchemy I found online off many sources this.tags[0] = makeStyleTag(); // this weirdness brought to you by firefox this.sheet = sheetForTag(this.tags[0]); } else { // server side 'polyfill'. just enough behavior to be useful. this.sheet = { cssRules: [], insertRule: function insertRule(rule) { // enough 'spec compliance' to be able to extract the rules later // in other words, just the cssText field var serverRule = { cssText: rule }; _this.sheet.cssRules.push(serverRule); return { serverRule: serverRule, appendRule: function appendRule(newCss) { return serverRule.cssText += newCss; } }; } }; } this.injected = true; } }, { key: 'speedy', value: function speedy(bool) { if (this.ctr !== 0) { throw new Error('cannot change speedy mode after inserting any rule to sheet. Either call speedy(' + bool + ') earlier in your app, or call flush() before speedy(' + bool + ')'); } this.isSpeedy = !!bool; } }, { key: '_insert', value: function _insert(rule) { // this weirdness for perf, and chrome's weird bug // https://stackoverflow.com/questions/20007992/chrome-suddenly-stopped-accepting-insertrule try { this.sheet.insertRule(rule, this.sheet.cssRules.length); // todo - correct index here } catch (e) { if (isDev) { // might need beter dx for this console.warn('whoops, illegal rule inserted', rule); //eslint-disable-line no-console } } } }, { key: 'insert', value: function insert(rule) { var _this2 = this; var insertedRule = void 0; if (isBrowser) { // this is the ultrafast version, works across browsers if (this.isSpeedy && this.sheet.insertRule) { this._insert(rule); } else { (function () { var textNode = document.createTextNode(rule); last(_this2.tags).appendChild(textNode); insertedRule = { textNode: textNode, appendRule: function appendRule(newCss) { return textNode.appendData(newCss); } }; if (!_this2.isSpeedy) { // sighhh _this2.sheet = sheetForTag(last(_this2.tags)); } })(); } } else { // server side is pretty simple insertedRule = this.sheet.insertRule(rule); } this.ctr++; if (isBrowser && this.ctr % this.maxLength === 0) { this.tags.push(makeStyleTag()); this.sheet = sheetForTag(last(this.tags)); } return insertedRule; } }, { key: 'flush', value: function flush() { if (isBrowser) { this.tags.forEach(function (tag) { return tag.parentNode.removeChild(tag); }); this.tags = []; this.sheet = null; this.ctr = 0; // todo - look for remnants in document.styleSheets } else { // simpler on server this.sheet.cssRules = []; } this.injected = false; } }, { key: 'rules', value: function rules() { if (!isBrowser) { return this.sheet.cssRules; } var arr = []; this.tags.forEach(function (tag) { return arr.splice.apply(arr, [arr.length, 0].concat(toConsumableArray(Array.from(sheetForTag(tag).cssRules)))); }); return arr; } }]); return StyleSheet; }(); // /* Wraps glamor's stylesheet and exports a singleton for the rest * of the app to use. */ var styleSheet = new StyleSheet({ speedy: false, maxLength: 40 }); // var ComponentStyle = function () { function ComponentStyle(rules, selector) { classCallCheck(this, ComponentStyle); this.rules = rules; this.selector = selector; } createClass(ComponentStyle, [{ key: 'generateAndInject', value: function generateAndInject() { if (!styleSheet.injected) styleSheet.inject(); var flatCSS = flatten(this.rules).join(''); if (this.selector) { flatCSS = this.selector + ' {' + flatCSS + '\n}'; } var root = safeParse(flatCSS); process$2(root); styleSheet.insert(root.toResult().css); } }]); return ComponentStyle; }(); // var injectGlobal = function injectGlobal(strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var globalStyle = new ComponentStyle(css.apply(undefined, [strings].concat(interpolations))); globalStyle.generateAndInject(); }; // /* Trying to avoid the unknown-prop errors on styled components by filtering by React's attribute whitelist. */ /* Logic copied from ReactDOMUnknownPropertyHook */ var reactProps = { children: true, dangerouslySetInnerHTML: true, key: true, ref: true, autoFocus: true, defaultValue: true, valueLink: true, defaultChecked: true, checkedLink: true, innerHTML: true, suppressContentEditableWarning: true, onFocusIn: true, onFocusOut: true, className: true, /* List copied from https://facebook.github.io/react/docs/events.html */ onCopy: true, onCut: true, onPaste: true, onCompositionEnd: true, onCompositionStart: true, onCompositionUpdate: true, onKeyDown: true, onKeyPress: true, onKeyUp: true, onFocus: true, onBlur: true, onChange: true, onInput: true, onSubmit: true, onClick: true, onContextMenu: true, onDoubleClick: true, onDrag: true, onDragEnd: true, onDragEnter: true, onDragExit: true, onDragLeave: true, onDragOver: true, onDragStart: true, onDrop: true, onMouseDown: true, onMouseEnter: true, onMouseLeave: true, onMouseMove: true, onMouseOut: true, onMouseOver: true, onMouseUp: true, onSelect: true, onTouchCancel: true, onTouchEnd: true, onTouchMove: true, onTouchStart: true, onScroll: true, onWheel: true, onAbort: true, onCanPlay: true, onCanPlayThrough: true, onDurationChange: true, onEmptied: true, onEncrypted: true, onEnded: true, onError: true, onLoadedData: true, onLoadedMetadata: true, onLoadStart: true, onPause: true, onPlay: true, onPlaying: true, onProgress: true, onRateChange: true, onSeeked: true, onSeeking: true, onStalled: true, onSuspend: true, onTimeUpdate: true, onVolumeChange: true, onWaiting: true, onLoad: true, onAnimationStart: true, onAnimationEnd: true, onAnimationIteration: true, onTransitionEnd: true, onCopyCapture: true, onCutCapture: true, onPasteCapture: true, onCompositionEndCapture: true, onCompositionStartCapture: true, onCompositionUpdateCapture: true, onKeyDownCapture: true, onKeyPressCapture: true, onKeyUpCapture: true, onFocusCapture: true, onBlurCapture: true, onChangeCapture: true, onInputCapture: true, onSubmitCapture: true, onClickCapture: true, onContextMenuCapture: true, onDoubleClickCapture: true, onDragCapture: true, onDragEndCapture: true, onDragEnterCapture: true, onDragExitCapture: true, onDragLeaveCapture: true, onDragOverCapture: true, onDragStartCapture: true, onDropCapture: true, onMouseDownCapture: true, onMouseEnterCapture: true, onMouseLeaveCapture: true, onMouseMoveCapture: true, onMouseOutCapture: true, onMouseOverCapture: true, onMouseUpCapture: true, onSelectCapture: true, onTouchCancelCapture: true, onTouchEndCapture: true, onTouchMoveCapture: true, onTouchStartCapture: true, onScrollCapture: true, onWheelCapture: true, onAbortCapture: true, onCanPlayCapture: true, onCanPlayThroughCapture: true, onDurationChangeCapture: true, onEmptiedCapture: true, onEncryptedCapture: true, onEndedCapture: true, onErrorCapture: true, onLoadedDataCapture: true, onLoadedMetadataCapture: true, onLoadStartCapture: true, onPauseCapture: true, onPlayCapture: true, onPlayingCapture: true, onProgressCapture: true, onRateChangeCapture: true, onSeekedCapture: true, onSeekingCapture: true, onStalledCapture: true, onSuspendCapture: true, onTimeUpdateCapture: true, onVolumeChangeCapture: true, onWaitingCapture: true, onLoadCapture: true, onAnimationStartCapture: true, onAnimationEndCapture: true, onAnimationIterationCapture: true, onTransitionEndCapture: true }; /* From HTMLDOMPropertyConfig */ var htmlProps = { /** * Standard Properties */ accept: true, acceptCharset: true, accessKey: true, action: true, allowFullScreen: true, allowTransparency: true, alt: true, // specifies target context for links with `preload` type as: true, async: true, autoComplete: true, // autoFocus is polyfilled/normalized by AutoFocusUtils // autoFocus: true, autoPlay: true, capture: true, cellPadding: true, cellSpacing: true, charSet: true, challenge: true, checked: true, cite: true, classID: true, className: true, cols: true, colSpan: true, content: true, contentEditable: true, contextMenu: true, controls: true, coords: true, crossOrigin: true, data: true, // For `<object />` acts as `src`. dateTime: true, default: true, defer: true, dir: true, disabled: true, download: true, draggable: true, encType: true, form: true, formAction: true, formEncType: true, formMethod: true, formNoValidate: true, formTarget: true, frameBorder: true, headers: true, height: true, hidden: true, high: true, href: true, hrefLang: true, htmlFor: true, httpEquiv: true, icon: true, id: true, inputMode: true, integrity: true, is: true, keyParams: true, keyType: true, kind: true, label: true, lang: true, list: true, loop: true, low: true, manifest: true, marginHeight: true, marginWidth: true, max: true, maxLength: true, media: true, mediaGroup: true, method: true, min: true, minLength: true, // Caution; `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. multiple: true, muted: true, name: true, nonce: true, noValidate: true, open: true, optimum: true, pattern: true, placeholder: true, playsInline: true, poster: true, preload: true, profile: true, radioGroup: true, readOnly: true, referrerPolicy: true, rel: true, required: true, reversed: true, role: true, rows: true, rowSpan: true, sandbox: true, scope: true, scoped: true, scrolling: true, seamless: true, selected: true, shape: true, size: true, sizes: true, span: true, spellCheck: true, src: true, srcDoc: true, srcLang: true, srcSet: true, start: true, step: true, style: true, summary: true, tabIndex: true, target: true, title: true, // Setting .type throws on non-<input> tags type: true, useMap: true, value: true, width: true, wmode: true, wrap: true, /** * RDFa Properties */ about: true, datatype: true, inlist: true, prefix: true, // property is also supported for OpenGraph in meta tags. property: true, resource: true, typeof: true, vocab: true, /** * Non-standard Properties */ // autoCapitalize and autoCorrect are supported in Mobile Safari for // keyboard hints. autoCapitalize: true, autoCorrect: true, // autoSave allows WebKit/Blink to persist values of input fields on page reloads autoSave: true, // color is for Safari mask-icon link color: true, // itemProp, itemScope, itemType are for // Microdata support. See http://schema.org/docs/gs.html itemProp: true, itemScope: true, itemType: true, // 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: true, itemRef: true, // results show looking glass icon and recent searches on input // search fields in WebKit/Blink results: true, // IE-only attribute that specifies security restrictions on an iframe // as an alternative to the sandbox attribute on IE<10 security: true, // IE-only attribute that controls focus behavior unselectable: 0 }; var svgProps = { accentHeight: true, accumulate: true, additive: true, alignmentBaseline: true, allowReorder: true, alphabetic: true, amplitude: true, arabicForm: true, ascent: true, attributeName: true, attributeType: true, autoReverse: true, azimuth: true, baseFrequency: true, baseProfile: true, baselineShift: true, bbox: true, begin: true, bias: true, by: true, calcMode: true, capHeight: true, clip: true, clipPath: true, clipRule: true, clipPathUnits: true, colorInterpolation: true, colorInterpolationFilters: true, colorProfile: true, colorRendering: true, contentScriptType: true, contentStyleType: true, cursor: true, cx: true, cy: true, d: true, decelerate: true, descent: true, diffuseConstant: true, direction: true, display: true, divisor: true, dominantBaseline: true, dur: true, dx: true, dy: true, edgeMode: true, elevation: true, enableBackground: true, end: true, exponent: true, externalResourcesRequired: true, fill: true, fillOpacity: true, fillRule: true, filter: true, filterRes: true, filterUnits: true, floodColor: true, floodOpacity: true, focusable: true, fontFamily: true, fontSize: true, fontSizeAdjust: true, fontStretch: true, fontStyle: true, fontVariant: true, fontWeight: true, format: true, from: true, fx: true, fy: true, g1: true, g2: true, glyphName: true, glyphOrientationHorizontal: true, glyphOrientationVertical: true, glyphRef: true, gradientTransform: true, gradientUnits: true, hanging: true, horizAdvX: true, horizOriginX: true, ideographic: true, imageRendering: true, in: true, in2: true, intercept: true, k: true, k1: true, k2: true, k3: true, k4: true, kernelMatrix: true, kernelUnitLength: true, kerning: true, keyPoints: true, keySplines: true, keyTimes: true, lengthAdjust: true, letterSpacing: true, lightingColor: true, limitingConeAngle: true, local: true, markerEnd: true, markerMid: true, markerStart: true, markerHeight: true, markerUnits: true, markerWidth: true, mask: true, maskContentUnits: true, maskUnits: true, mathematical: true, mode: true, numOctaves: true, offset: true, opacity: true, operator: true, order: true, orient: true, orientation: true, origin: true, overflow: true, overlinePosition: true, overlineThickness: true, paintOrder: true, panose1: true, pathLength: true, patternContentUnits: true, patternTransform: true, patternUnits: true, pointerEvents: true, points: true, pointsAtX: true, pointsAtY: true, pointsAtZ: true, preserveAlpha: true, preserveAspectRatio: true, primitiveUnits: true, r: true, radius: true, refX: true, refY: true, renderingIntent: true, repeatCount: true, repeatDur: true, requiredExtensions: true, requiredFeatures: true, restart: true, result: true, rotate: true, rx: true, ry: true, scale: true, seed: true, shapeRendering: true, slope: true, spacing: true, specularConstant: true, specularExponent: true, speed: true, spreadMethod: true, startOffset: true, stdDeviation: true, stemh: true, stemv: true, stitchTiles: true, stopColor: true, stopOpacity: true, strikethroughPosition: true, strikethroughThickness: true, string: true, stroke: true, strokeDasharray: true, strokeDashoffset: true, strokeLinecap: true, strokeLinejoin: true, strokeMiterlimit: true, strokeOpacity: true, strokeWidth: true, surfaceScale: true, systemLanguage: true, tableValues: true, targetX: true, targetY: true, textAnchor: true, textDecoration: true, textRendering: true, textLength: true, to: true, transform: true, u1: true, u2: true, underlinePosition: true, underlineThickness: true, unicode: true, unicodeBidi: true, unicodeRange: true, unitsPerEm: true, vAlphabetic: true, vHanging: true, vIdeographic: true, vMathematical: true, values: true, vectorEffect: true, version: true, vertAdvY: true, vertOriginX: true, vertOriginY: true, viewBox: true, viewTarget: true, visibility: true, widths: true, wordSpacing: true, writingMode: true, x: true, xHeight: true, x1: true, x2: true, xChannelSelector: true, xlinkActuate: true, xlinkArcrole: true, xlinkHref: true, xlinkRole: true, xlinkShow: true, xlinkTitle: true, xlinkType: true, xmlBase: true, xmlns: true, xmlnsXlink: true, xmlLang: true, xmlSpace: true, y: true, y1: true, y2: true, yChannelSelector: true, z: true, zoomAndPan: true }; /* From DOMProperty */ 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'; var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + '\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040'; var isCustomAttribute = RegExp.prototype.test.bind(new RegExp('^(data|aria)-[' + ATTRIBUTE_NAME_CHAR + ']*$')); var hasOwnProperty = {}.hasOwnProperty; var validAttr = (function (name) { return hasOwnProperty.call(htmlProps, name) || hasOwnProperty.call(svgProps, name) || isCustomAttribute(name.toLowerCase()) || hasOwnProperty.call(reactProps, name); }); // function isTag(target) /* : %checks */{ return typeof target === 'string'; } var index$7 = isFunction; var toString$1 = Object.prototype.toString; function isFunction(fn) { var string = toString$1.call(fn); return string === '[object Function]' || typeof fn === 'function' && string !== '[object RegExp]' || typeof window !== 'undefined' && ( // IE8 and below fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt); } // /** * Creates a broadcast that can be listened to, i.e. simple event emitter * * @see https://github.com/ReactTraining/react-broadcast */ var createBroadcast = function createBroadcast(initialValue) { var listeners = []; var currentValue = initialValue; return { publish: function publish(value) { currentValue = value; listeners.forEach(function (listener) { return listener(currentValue); }); }, subscribe: function subscribe(listener) { listeners.push(listener); // Publish to this subscriber once immediately. listener(currentValue); return function () { listeners = listeners.filter(function (item) { return item !== listener; }); }; } }; }; // /* globals React$Element */ // NOTE: DO NOT CHANGE, changing this is a semver major change! var CHANNEL = '__styled-components__'; /** * Provide a theme to an entire react component tree via context and event listeners (have to do * both context and event emitter as pure components block context updates) */ var ThemeProvider = function (_Component) { inherits(ThemeProvider, _Component); function ThemeProvider() { classCallCheck(this, ThemeProvider); var _this = possibleConstructorReturn(this, (ThemeProvider.__proto__ || Object.getPrototypeOf(ThemeProvider)).call(this)); _this.getTheme = _this.getTheme.bind(_this); return _this; } createClass(ThemeProvider, [{ key: 'componentWillMount', value: function componentWillMount() { var _this2 = this; // If there is a ThemeProvider wrapper anywhere around this theme provider, merge this theme // with the outer theme if (this.context[CHANNEL]) { var subscribe = this.context[CHANNEL]; this.unsubscribeToOuter = subscribe(function (theme) { _this2.outerTheme = theme; }); } this.broadcast = createBroadcast(this.getTheme()); } }, { key: 'getChildContext', value: function getChildContext() { return _extends({}, this.context, defineProperty({}, CHANNEL, this.broadcast.subscribe)); } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { if (this.props.theme !== nextProps.theme) this.broadcast.publish(this.getTheme(nextProps.theme)); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (this.context[CHANNEL]) { this.unsubscribeToOuter(); } } // Get the theme from the props, supporting both (outerTheme) => {} as well as object notation }, { key: 'getTheme', value: function getTheme(passedTheme) { var theme = passedTheme || this.props.theme; if (index$7(theme)) { var mergedTheme = theme(this.outerTheme); if (!index$1(mergedTheme)) { throw new Error('[ThemeProvider] Please return an object from your theme function, i.e. theme={() => ({})}!'); } return mergedTheme; } if (!index$1(theme)) { throw new Error('[ThemeProvider] Please make your theme prop a plain object'); } return _extends({}, this.outerTheme, theme); } }, { key: 'render', value: function render() { if (!this.props.children) { return null; } return React__default.Children.only(this.props.children); } }]); return ThemeProvider; }(React.Component); ThemeProvider.childContextTypes = defineProperty({}, CHANNEL, React.PropTypes.func.isRequired); ThemeProvider.contextTypes = defineProperty({}, CHANNEL, React.PropTypes.func); // var AbstractStyledComponent = function (_Component) { inherits(AbstractStyledComponent, _Component); function AbstractStyledComponent() { classCallCheck(this, AbstractStyledComponent); return possibleConstructorReturn(this, (AbstractStyledComponent.__proto__ || Object.getPrototypeOf(AbstractStyledComponent)).apply(this, arguments)); } return AbstractStyledComponent; }(React.Component); AbstractStyledComponent.contextTypes = defineProperty({}, CHANNEL, React.PropTypes.func); // var _styledComponent = (function (ComponentStyle) { // eslint-disable-next-line no-undef var createStyledComponent = function createStyledComponent(target, rules, parent) { /* Handle styled(OtherStyledComponent) differently */ var isStyledComponent = AbstractStyledComponent.isPrototypeOf(target); if (!isTag(target) && isStyledComponent) { return createStyledComponent(target.target, target.rules.concat(rules), target); } var componentStyle = new ComponentStyle(rules); var ParentComponent = parent || AbstractStyledComponent; var StyledComponent = function (_ParentComponent) { inherits(StyledComponent, _ParentComponent); function StyledComponent() { classCallCheck(this, StyledComponent); var _this = possibleConstructorReturn(this, (StyledComponent.__proto__ || Object.getPrototypeOf(StyledComponent)).call(this)); _this.state = { theme: null, generatedClassName: '' }; return _this; } createClass(StyledComponent, [{ key: 'generateAndInjectStyles', value: function generateAndInjectStyles(theme, props) { var executionContext = _extends({}, props, { theme: theme }); return componentStyle.generateAndInjectStyles(executionContext); } }, { key: 'componentWillMount', value: function componentWillMount() { var _this2 = this; // If there is a theme in the context, subscribe to the event emitter. This // is necessary due to pure components blocking context updates, this circumvents // that by updating when an event is emitted if (this.context[CHANNEL]) { var subscribe = this.context[CHANNEL]; this.unsubscribe = subscribe(function (nextTheme) { // This will be called once immediately var theme = _this2.props.theme || nextTheme; var generatedClassName = _this2.generateAndInjectStyles(theme, _this2.props); _this2.setState({ theme: theme, generatedClassName: generatedClassName }); }); } else { var theme = this.props.theme || {}; var generatedClassName = this.generateAndInjectStyles(theme, this.props); this.setState({ theme: theme, generatedClassName: generatedClassName }); } } }, { key: 'componentWillReceiveProps', value: function componentWillReceiveProps(nextProps) { var _this3 = this; this.setState(function (oldState) { var theme = nextProps.theme || oldState.theme; var generatedClassName = _this3.generateAndInjectStyles(theme, nextProps); return { theme: theme, generatedClassName: generatedClassName }; }); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (this.unsubscribe) { this.unsubscribe(); } } }, { key: 'render', value: function render() { var _this4 = this; var _props = this.props, className = _props.className, children = _props.children, innerRef = _props.innerRef; var generatedClassName = this.state.generatedClassName; var propsForElement = {}; /* Don't pass through non HTML tags through to HTML elements */ Object.keys(this.props).filter(function (propName) { return !isTag(target) || validAttr(propName); }).forEach(function (propName) { propsForElement[propName] = _this4.props[propName]; }); propsForElement.className = [className, generatedClassName].filter(function (x) { return x; }).join(' '); if (innerRef) { propsForElement.ref = innerRef; delete propsForElement.innerRef; } return React.createElement(target, propsForElement, children); } }]); return StyledComponent; }(ParentComponent); StyledComponent.target = target; StyledComponent.rules = rules; StyledComponent.displayName = isTag(target) ? 'styled.' + target : 'Styled(' + target.displayName + ')'; return StyledComponent; }; return createStyledComponent; }); // // Thanks to ReactDOMFactories for this handy list! var domElements = ['a', 'abbr', 'address', 'area', 'article', 'aside', 'audio', 'b', 'base', 'bdi', 'bdo', 'big', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'cite', 'code', 'col', 'colgroup', 'data', 'datalist', 'dd', 'del', 'details', 'dfn', 'dialog', 'div', 'dl', 'dt', 'em', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'iframe', 'img', 'input', 'ins', 'kbd', 'keygen', 'label', 'legend', 'li', 'link', 'main', 'map', 'mark', 'menu', 'menuitem', 'meta', 'meter', 'nav', 'noscript', 'object', 'ol', 'optgroup', 'option', 'output', 'p', 'param', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'script', 'section', 'select', 'small', 'source', 'span', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'time', 'title', 'tr', 'track', 'u', 'ul', 'var', 'video', 'wbr', // SVG 'circle', 'clipPath', 'defs', 'ellipse', 'g', 'image', 'line', 'linearGradient', 'mask', 'path', 'pattern', 'polygon', 'polyline', 'radialGradient', 'rect', 'stop', 'svg', 'text', 'tspan']; // var _styled = (function (styledComponent) { var styled = function styled(tag) { return function (strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } return styledComponent(tag, css.apply(undefined, [strings].concat(interpolations))); }; }; // Shorthands for all valid HTML Elements domElements.forEach(function (domElement) { styled[domElement] = styled(domElement); }); return styled; }); function unwrapExports (x) { return x && x.__esModule ? x['default'] : x; } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var hash = createCommonjsModule(function (module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = doHash; // murmurhash2 via https://gist.github.com/raycmorgan/588423 function doHash(str, seed) { var m = 0x5bd1e995; var r = 24; var h = seed ^ str.length; var length = str.length; var currentIndex = 0; while (length >= 4) { var k = UInt32(str, currentIndex); k = Umul32(k, m); k ^= k >>> r; k = Umul32(k, m); h = Umul32(h, m); h ^= k; currentIndex += 4; length -= 4; } switch (length) { case 3: h ^= UInt16(str, currentIndex); h ^= str.charCodeAt(currentIndex + 2) << 16; h = Umul32(h, m); break; case 2: h ^= UInt16(str, currentIndex); h = Umul32(h, m); break; case 1: h ^= str.charCodeAt(currentIndex); h = Umul32(h, m); break; } h ^= h >>> 13; h = Umul32(h, m); h ^= h >>> 15; return h >>> 0; } function UInt32(str, pos) { return str.charCodeAt(pos++) + (str.charCodeAt(pos++) << 8) + (str.charCodeAt(pos++) << 16) + (str.charCodeAt(pos) << 24); } function UInt16(str, pos) { return str.charCodeAt(pos++) + (str.charCodeAt(pos++) << 8); } function Umul32(n, m) { n = n | 0; m = m | 0; var nlo = n & 0xffff; var nhi = n >>> 16; var res = nlo * m + ((nhi * m & 0xffff) << 16) | 0; return res; } }); var hashStr = unwrapExports(hash); // var replaceWhitespace = function replaceWhitespace(str) { return str.replace(/\s|\\n/g, ''); }; var _keyframes = (function (nameGenerator) { return function (strings) { for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { interpolations[_key - 1] = arguments[_key]; } var rules = css.apply(undefined, [strings].concat(interpolations)); var hash = hashStr(replaceWhitespace(JSON.stringify(rules))); var name = nameGenerator(hash); var keyframes = new ComponentStyle(rules, '@keyframes ' + name); keyframes.generateAndInject(); return name; }; }); /** * 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$1(string) { return string.replace(_hyphenPattern, function (_, character) { return character.toUpperCase(); }); } var camelize_1 = camelize$1; var camelize = camelize_1; var msPattern$1 = /^-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$1, 'ms-')); } var camelizeStyleName_1 = camelizeStyleName; var prefixProps = createCommonjsModule(function (module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = { "Webkit": { "transform": true, "transformOrigin": true, "transformOriginX": true, "transformOriginY": true, "backfaceVisibility": true, "perspective": true, "perspectiveOrigin": true, "transformStyle": true, "transformOriginZ": true, "animation": true, "animationDelay": true, "animationDirection": true, "animationFillMode": true, "animationDuration": true, "animationIterationCount": true, "animationName": true, "animationPlayState": true, "animationTimingFunction": true, "appearance": true, "userSelect": true, "fontKerning": true, "textEmphasisPosition": true, "textEmphasis": true, "textEmphasisStyle": true, "textEmphasisColor": true, "boxDecorationBreak": true, "clipPath": true, "maskImage": true, "maskMode": true, "maskRepeat": true, "maskPosition": true, "maskClip": true, "maskOrigin": true, "maskSize": true, "maskComposite": true, "mask": true, "maskBorderSource": true, "maskBorderMode": true, "maskBorderSlice": true, "maskBorderWidth": true, "maskBorderOutset": true, "maskBorderRepeat": true, "maskBorder": true, "maskType": true, "textDecorationStyle": true, "textDecorationSkip": true, "textDecorationLine": true, "textDecorationColor": true, "filter": true, "fontFeatureSettings": true, "breakAfter": true, "breakBefore": true, "breakInside": true, "columnCount": true, "columnFill": true, "columnGap": true, "columnRule": true, "columnRuleColor": true, "columnRuleStyle": true, "columnRuleWidth": true, "columns": true, "columnSpan": true, "columnWidth": true, "flex": true, "flexBasis": true, "flexDirection": true, "flexGrow": true, "flexFlow": true, "flexShrink": true, "flexWrap": true, "alignContent": true, "alignItems": true, "alignSelf": true, "justifyContent": true, "order": true, "transition": true, "transitionDelay": true, "transitionDuration": true, "transitionProperty": true, "transitionTimingFunction": true, "backdropFilter": true, "scrollSnapType": true, "scrollSnapPointsX": true, "scrollSnapPointsY": true, "scrollSnapDestination": true, "scrollSnapCoordinate": true, "shapeImageThreshold": true, "shapeImageMargin": true, "shapeImageOutside": true, "hyphens": true, "flowInto": true, "flowFrom": true, "regionFragment": true, "textSizeAdjust": true }, "Moz": { "appearance": true, "userSelect": true, "boxSizing": true, "textAlignLast": true, "textDecorationStyle": true, "textDecorationSkip": true, "textDecorationLine": true, "textDecorationColor": true, "tabSize": true, "hyphens": true, "fontFeatureSettings": true, "breakAfter": true, "breakBefore": true, "breakInside": true, "columnCount": true, "columnFill": true, "columnGap": true, "columnRule": true, "columnRuleColor": true, "columnRuleStyle": true, "columnRuleWidth": true, "columns": true, "columnSpan": true, "columnWidth": true }, "ms": { "flex": true, "flexBasis": false, "flexDirection": true, "flexGrow": false, "flexFlow": true, "flexShrink": false, "flexWrap": true, "alignContent": false, "alignItems": false, "alignSelf": false, "justifyContent": false, "order": false, "transform": true, "transformOrigin": true, "transformOriginX": true, "transformOriginY": true, "userSelect": true, "wrapFlow": true, "wrapThrough": true, "wrapMargin": true, "scrollSnapType": true, "scrollSnapPointsX": true, "scrollSnapPointsY": true, "scrollSnapDestination": true, "scrollSnapCoordinate": true, "touchAction": true, "hyphens": true, "flowInto": true, "flowFrom": true, "breakBefore": true, "breakAfter": true, "breakInside": true, "regionFragment": true, "gridTemplateColumns": true, "gridTemplateRows": true, "gridTemplateAreas": true, "gridTemplate": true, "gridAutoColumns": true, "gridAutoRows": true, "gridAutoFlow": true, "grid": true, "gridRowStart": true, "gridColumnStart": true, "gridRowEnd": true, "gridRow": true, "gridColumn": true, "gridColumnEnd": true, "gridColumnGap": true, "gridRowGap": true, "gridArea": true, "gridGap": true, "textSizeAdjust": true } }; module.exports = exports["default"]; }); var capitalizeString = createCommonjsModule(function (module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); // helper to capitalize strings exports.default = function (str) { return str.charAt(0).toUpperCase() + str.slice(1); }; module.exports = exports["default"]; }); var isPrefixedProperty = createCommonjsModule(function (module, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (property) { return property.match(/^(Webkit|Moz|O|ms)/) !== null; }; module.exports = exports["default"]; }); var sortPrefixedStyle_1 = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = sortPrefixedStyle; var _isPrefixedProperty = isPrefixedProperty; var _isPrefixedProperty2 = _interopRequireDefault(_isPrefixedProperty); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function sortPrefixedStyle(style) { return Object.keys(style).sort(function (left, right) { if ((0, _isPrefixedProperty2.default)(left) && !(0, _isPrefixedProperty2.default)(right)) { return -1; } else if (!(0, _isPrefixedProperty2.default)(left) && (0, _isPrefixedProperty2.default)(right)) { return 1; } return 0; }).reduce(function (sortedStyle, prop) { sortedStyle[prop] = style[prop]; return sortedStyle; }, {}); } module.exports = exports['default']; }); var position_1 = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = position; function position(property, value) { if (property === 'position' && value === 'sticky') { return { position: ['-webkit-sticky', 'sticky'] }; } } module.exports = exports['default']; }); var joinPrefixedValue = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); 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; } // returns a style object with a single concated prefixed value string exports.default = function (property, value) { var replacer = arguments.length <= 2 || arguments[2] === undefined ? function (prefix, value) { return prefix + value; } : arguments[2]; return _defineProperty({}, property, ['-webkit-', '-moz-', ''].map(function (prefix) { return replacer(prefix, value); })); }; module.exports = exports['default']; }); var isPrefixedValue = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = function (value) { if (Array.isArray(value)) value = value.join(','); return value.match(/-webkit-|-moz-|-ms-/) !== null; }; module.exports = exports['default']; }); var calc_1 = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = calc; var _joinPrefixedValue = joinPrefixedValue; var _joinPrefixedValue2 = _interopRequireDefault(_joinPrefixedValue); var _isPrefixedValue = isPrefixedValue; var _isPrefixedValue2 = _interopRequireDefault(_isPrefixedValue); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function calc(property, value) { if (typeof value === 'string' && !(0, _isPrefixedValue2.default)(value) && value.indexOf('calc(') > -1) { return (0, _joinPrefixedValue2.default)(property, value, function (prefix, value) { return value.replace(/calc\(/g, prefix + 'calc('); }); } } module.exports = exports['default']; }); var cursor_1 = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = cursor; var _joinPrefixedValue = joinPrefixedValue; var _joinPrefixedValue2 = _interopRequireDefault(_joinPrefixedValue); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var values = { 'zoom-in': true, 'zoom-out': true, grab: true, grabbing: true }; function cursor(property, value) { if (property === 'cursor' && values[value]) { return (0, _joinPrefixedValue2.default)(property, value); } } module.exports = exports['default']; }); var flex_1 = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = flex; var values = { flex: true, 'inline-flex': true }; function flex(property, value) { if (property === 'display' && values[value]) { return { display: ['-webkit-box', '-moz-box', '-ms-' + value + 'box', '-webkit-' + value, value] }; } } module.exports = exports['default']; }); var sizing_1 = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = sizing; var _joinPrefixedValue = joinPrefixedValue; var _joinPrefixedValue2 = _interopRequireDefault(_joinPrefixedValue); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var properties = { maxHeight: true, maxWidth: true, width: true, height: true, columnWidth: true, minWidth: true, minHeight: true }; var values = { 'min-content': true, 'max-content': true, 'fill-available': true, 'fit-content': true, 'contain-floats': true }; function sizing(property, value) { if (properties[property] && values[value]) { return (0, _joinPrefixedValue2.default)(property, value); } } module.exports = exports['default']; }); var gradient_1 = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = gradient; var _joinPrefixedValue = joinPrefixedValue; var _joinPrefixedValue2 = _interopRequireDefault(_joinPrefixedValue); var _isPrefixedValue = isPrefixedValue; var _isPrefixedValue2 = _interopRequireDefault(_isPrefixedValue); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var values = /linear-gradient|radial-gradient|repeating-linear-gradient|repeating-radial-gradient/; function gradient(property, value) { if (typeof value === 'string' && !(0, _isPrefixedValue2.default)(value) && value.match(values) !== null) { return (0, _joinPrefixedValue2.default)(property, value); } } module.exports = exports['default']; }); var uppercasePattern = /[A-Z]/g; var msPattern$2 = /^ms-/; var cache = {}; function hyphenateStyleName$2(string) { return string in cache ? cache[string] : cache[string] = string.replace(uppercasePattern, '-$&').toLowerCase().replace(msPattern$2, '-ms-'); } var index$8 = hyphenateStyleName$2; var transition_1 = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = transition; var _hyphenateStyleName = index$8; var _hyphenateStyleName2 = _interopRequireDefault(_hyphenateStyleName); var _capitalizeString = capitalizeString; var _capitalizeString2 = _interopRequireDefault(_capitalizeString); var _isPrefixedValue = isPrefixedValue; var _isPrefixedValue2 = _interopRequireDefault(_isPrefixedValue); var _prefixProps = prefixProps; var _prefixProps2 = _interopRequireDefault(_prefixProps); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var properties = { transition: true, transitionProperty: true, WebkitTransition: true, WebkitTransitionProperty: true }; function transition(property, value) { // also check for already prefixed transitions if (typeof value === 'string' && properties[property]) { var _ref2; var outputValue = prefixValue(value); var webkitOutput = outputValue.split(/,(?![^()]*(?:\([^()]*\))?\))/g).filter(function (value) { return value.match(/-moz-|-ms-/) === null; }).join(','); // if the property is already prefixed if (property.indexOf('Webkit') > -1) { return _defineProperty({}, property, webkitOutput); } return _ref2 = {}, _defineProperty(_ref2, 'Webkit' + (0, _capitalizeString2.default)(property), webkitOutput), _defineProperty(_ref2, property, outputValue), _ref2; } } function prefixValue(value) { if ((0, _isPrefixedValue2.default)(value)) { return value; } // only split multi values, not cubic beziers var multipleValues = value.split(/,(?![^()]*(?:\([^()]*\))?\))/g); // iterate each single value and check for transitioned properties // that need to be prefixed as well multipleValues.forEach(function (val, index) { multipleValues[index] = Object.keys(_prefixProps2.default).reduce(function (out, prefix) { var dashCasePrefix = '-' + prefix.toLowerCase() + '-'; Object.keys(_prefixProps2.default[prefix]).forEach(function (prop) { var dashCaseProperty = (0, _hyphenateStyleName2.default)(prop); if (val.indexOf(dashCaseProperty) > -1 && dashCaseProperty !== 'order') { // join all prefixes and create a new value out = val.replace(dashCaseProperty, dashCasePrefix + dashCaseProperty) + ',' + out; } }); return out; }, val); }); return multipleValues.join(','); } module.exports = exports['default']; }); var flexboxIE_1 = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = flexboxIE; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var alternativeValues = { 'space-around': 'distribute', 'space-between': 'justify', 'flex-start': 'start', 'flex-end': 'end' }; var alternativeProps = { alignContent: 'msFlexLinePack', alignSelf: 'msFlexItemAlign', alignItems: 'msFlexAlign', justifyContent: 'msFlexPack', order: 'msFlexOrder', flexGrow: 'msFlexPositive', flexShrink: 'msFlexNegative', flexBasis: 'msPreferredSize' }; function flexboxIE(property, value) { if (alternativeProps[property]) { return _defineProperty({}, alternativeProps[property], alternativeValues[value] || value); } } module.exports = exports['default']; }); var flexboxOld_1 = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = flexboxOld; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; }return obj; } var alternativeValues = { 'space-around': 'justify', 'space-between': 'justify', 'flex-start': 'start', 'flex-end': 'end', 'wrap-reverse': 'multiple', wrap: 'multiple' }; var alternativeProps = { alignItems: 'WebkitBoxAlign', justifyContent: 'WebkitBoxPack', flexWrap: 'WebkitBoxLines' }; function flexboxOld(property, value) { if (property === 'flexDirection' && typeof value === 'string') { return { WebkitBoxOrient: value.indexOf('column') > -1 ? 'vertical' : 'horizontal', WebkitBoxDirection: value.indexOf('reverse') > -1 ? 'reverse' : 'normal' }; } if (alternativeProps[property]) { return _defineProperty({}, alternativeProps[property], alternativeValues[value] || value); } } module.exports = exports['default']; }); var prefixAll_1 = createCommonjsModule(function (module, exports) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = prefixAll; var _prefixProps = prefixProps; var _prefixProps2 = _interopRequireDefault(_prefixProps); var _capitalizeString = capitalizeString; var _capitalizeString2 = _interopRequireDefault(_capitalizeString); var _sortPrefixedStyle = sortPrefixedStyle_1; var _sortPrefixedStyle2 = _interopRequireDefault(_sortPrefixedStyle); var _position = position_1; var _position2 = _interopRequireDefault(_position); var _calc = calc_1; var _calc2 = _interopRequireDefault(_calc); var _cursor = cursor_1; var _cursor2 = _interopRequireDefault(_cursor); var _flex = flex_1; var _flex2 = _interopRequireDefault(_flex); var _sizing = sizing_1; var _sizing2 = _interopRequireDefault(_sizing); var _gradient = gradient_1; var _gradient2 = _interopRequireDefault(_gradient); var _transition = transition_1; var _transition2 = _interopRequireDefault(_transition); var _flexboxIE = flexboxIE_1; var _flexboxIE2 = _interopRequireDefault(_flexboxIE); var _flexboxOld = flexboxOld_1; var _flexboxOld2 = _interopRequireDefault(_flexboxOld); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // special flexbox specifications var plugins = [_position2.default, _calc2.default, _cursor2.default, _sizing2.default, _gradient2.default, _transition2.default, _flexboxIE2.default, _flexboxOld2.default, _flex2.default]; /** * Returns a prefixed version of the style object using all vendor prefixes * @param {Object} styles - Style object that gets prefixed properties added * @returns {Object} - Style object with prefixed properties and values */ function prefixAll(styles) { Object.keys(styles).forEach(function (property) { var value = styles[property]; if (value instanceof Object && !Array.isArray(value)) { // recurse through nested style objects styles[property] = prefixAll(value); } else { Object.keys(_prefixProps2.default).forEach(function (prefix) { var properties = _prefixProps2.default[prefix]; // add prefixes if needed if (properties[property]) { styles[prefix + (0, _capitalizeString2.default)(property)] = value; } }); } }); Object.keys(styles).forEach(function (property) { [].concat(styles[property]).forEach(function (value, index) { // resolve every special plugins plugins.forEach(function (plugin) { return assignStyles(styles, plugin(property, value)); }); }); }); return (0, _sortPrefixedStyle2.default)(styles); } function assignStyles(base) { var extend = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; Object.keys(extend).forEach(function (property) { var baseValue = base[property]; if (Array.isArray(baseValue)) { [].concat(extend[property]).forEach(function (value) { var valueIndex = baseValue.indexOf(value); if (valueIndex > -1) { base[property].splice(valueIndex, 1); } base[property].push(value); }); } else { base[property] = extend[property]; } }); } module.exports = exports['default']; }); var _static = prefixAll_1; // // eslint-disable-next-line var autoprefix = (function (root) { root.walkDecls(function (decl) { /* No point even checking custom props */ if (/^--/.test(decl.prop)) return; var objStyle = defineProperty({}, camelizeStyleName_1(decl.prop), decl.value); var prefixed = _static(objStyle); Object.keys(prefixed).reverse().forEach(function (newProp) { var newVals = prefixed[newProp]; var newValArray = Array.isArray(newVals) ? newVals : [newVals]; newValArray.forEach(function (newVal) { decl.cloneBefore({ prop: hyphenateStyleName_1(newProp), value: newVal }); }); }); decl.remove(); }); }); // /* ComponentStyle is all the CSS-specific stuff, not the React-specific stuff. */ var _ComponentStyle = (function (nameGenerator) { var inserted = {}; var ComponentStyle = function () { function ComponentStyle(rules) { classCallCheck(this, ComponentStyle); this.rules = rules; if (!styleSheet.injected) styleSheet.inject(); this.insertedRule = styleSheet.insert(''); } /* * Flattens a rule set into valid CSS * Hashes it, wraps the whole chunk in a ._hashName {} * Parses that with PostCSS then runs PostCSS-Nested on it * Returns the hash to be injected on render() * */ createClass(ComponentStyle, [{ key: 'generateAndInjectStyles', value: function generateAndInjectStyles(executionContext) { var flatCSS = flatten(this.rules, executionContext).join('').replace(/^\s*\/\/.*$/gm, ''); // replace JS comments var hash = hashStr(flatCSS); if (!inserted[hash]) { var selector = nameGenerator(hash); inserted[hash] = selector; var root = safeParse('.' + selector + ' { ' + flatCSS + ' }'); process$2(root); autoprefix(root); this.insertedRule.appendRule(root.toResult().css); } return inserted[hash]; } }]); return ComponentStyle; }(); return ComponentStyle; }); // /* globals ReactClass */ var withTheme = (function (Component$$1) { var _class, _temp2; return _temp2 = _class = function (_React$Component) { inherits(_class, _React$Component); function _class() { var _ref; var _temp, _this, _ret; classCallCheck(this, _class); for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return _ret = (_temp = (_this = possibleConstructorReturn(this, (_ref = _class.__proto__ || Object.getPrototypeOf(_class)).call.apply(_ref, [this].concat(args))), _this), _this.state = {}, _temp), possibleConstructorReturn(_this, _ret); } createClass(_class, [{ key: 'componentWillMount', value: function componentWillMount() { var _this2 = this; if (!this.context[CHANNEL]) { throw new Error('[withTheme] Please use ThemeProvider to be able to use withTheme'); } var subscribe = this.context[CHANNEL]; this.unsubscribe = subscribe(function (theme) { _this2.setState({ theme: theme }); }); } }, { key: 'componentWillUnmount', value: function componentWillUnmount() { if (typeof this.unsubscribe === 'function') this.unsubscribe(); } }, { key: 'render', value: function render() { var theme = this.state.theme; return React__default.createElement(Component$$1, _extends({ theme: theme }, this.props)); } }]); return _class; }(React__default.Component), _class.contextTypes = defineProperty({}, CHANNEL, React__default.PropTypes.func), _temp2; }); // /* Import singletons */ /* Import singleton constructors */ /* Import components */ /* Import Higher Order Components */ /* Instantiate singletons */ var keyframes = _keyframes(generateAlphabeticName); var styled = _styled(_styledComponent(_ComponentStyle(generateAlphabeticName))); exports['default'] = styled; exports.css = css; exports.keyframes = keyframes; exports.injectGlobal = injectGlobal; exports.ThemeProvider = ThemeProvider; exports.withTheme = withTheme; Object.defineProperty(exports, '__esModule', { value: true }); })));
src/utils/griddleConnect.js
ttrentham/Griddle
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; /// This method appends options onto existing connect parameters export const mergeConnectParametersWithOptions = ( originalConnect, newOptions ) => { const [ mapStateFromProps, mapDispatchFromProps, mergeProps, options ] = originalConnect; return [ mapStateFromProps, mapDispatchFromProps, mergeProps, { ...options, ...newOptions } ]; }; const griddleConnect = (...connectOptions) => OriginalComponent => class extends React.Component { static contextTypes = { storeKey: PropTypes.string }; constructor(props, context) { super(props, context); const newOptions = mergeConnectParametersWithOptions(connectOptions, { storeKey: context.storeKey }); this.ConnectedComponent = connect(...newOptions)(OriginalComponent); } render() { return <this.ConnectedComponent {...this.props} />; } }; export { griddleConnect as connect };
src/Components/Input.spec.js
michaelmilessmith/pizza-requirement-calculator
import React from 'react' import { shallow } from 'enzyme' import { Input } from './Input' describe('<Input/>', () => { it('has an input for number of people and number of slices', () => { const wrapper = shallow(<Input />) expect(wrapper.find('input[type="number"]').length).toBe(2) }) it('raises an event when the number of people value changes', () => { const onChange = jest.fn() const wrapper = shallow(<Input onPeopleChange={onChange} />) wrapper .find('#number-of-people') .first() .simulate('change', { target: { value: '7' } }) expect(onChange).toHaveBeenCalledTimes(1) }) it('raises an event when the number of slices value changes', () => { const onChange = jest.fn() const wrapper = shallow(<Input onSlicesChange={onChange} />) wrapper .find('#number-of-slices') .first() .simulate('change', { target: { value: '7' } }) expect(onChange).toHaveBeenCalledTimes(1) }) it('raises an event when the bogof value changes', () => { const onChange = jest.fn() const wrapper = shallow(<Input onBogofChange={onChange} />) wrapper .find('#bogof') .first() .simulate('change', { target: { value: 'true' } }) expect(onChange).toHaveBeenCalledTimes(1) }) })
fiddles/react/fiddle-0008-ListComponent/src/index.js
bradyhouse/house
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));